Exemplo n.º 1
0
int error(const char *msg, int fatal)
{
    char buf[200];
    int x, y, button;

    Curses_clear_window(PROMPT_WINDOW);
    Curses_write_window(PROMPT_WINDOW, 1, 1, "LOCATION:\n");
    Curses_write_window(PROMPT_WINDOW, 1, 12, G_location());
    Curses_write_window(PROMPT_WINDOW, 2, 1, "MAPSET:\n");
    Curses_write_window(PROMPT_WINDOW, 2, 12, G_location());

    Beep();
    if (fatal)
	sprintf(buf, _("ERROR: %s"), msg);
    else
	sprintf(buf, _("WARNING: %s (click mouse to continue)"), msg);
    Menu_msg(buf);

    if (fatal)
	quit(1);

    Mouse_pointer(&x, &y, &button);
    Curses_clear_window(PROMPT_WINDOW);

    return 0;
}
Exemplo n.º 2
0
void print_shell(const struct Map_info *Map)
{
    if (Vect_maptype(Map) & (GV_FORMAT_OGR | GV_FORMAT_OGR_DIRECT)) {
	fprintf(stdout, "ogr_layer=%s\n",
		Vect_get_ogr_layer_name(Map));
	fprintf(stdout, "ogr_dsn=%s\n",
		Vect_get_ogr_dsn_name(Map));
    }
    else {
	fprintf(stdout, "name=%s\n",
		Vect_get_name(Map));
	fprintf(stdout, "mapset=%s\n",
		Vect_get_mapset(Map));
    }
    
    fprintf(stdout, "location=%s\n",
	    G_location());
    fprintf(stdout, "database=%s\n",
	    G_gisdbase());
    fprintf(stdout, "title=%s\n",
	    Vect_get_map_name(Map));
    fprintf(stdout, "scale=1:%d\n",
	    Vect_get_scale(Map));
    
    if (Vect_maptype(Map) & (GV_FORMAT_OGR | GV_FORMAT_OGR_DIRECT)) {	
	fprintf(stdout, "format=%s,%s\n",
		Vect_maptype_info(Map), Vect_get_ogr_format_info(Map));
    }
    else {
	fprintf(stdout, "format=%s\n",
		Vect_maptype_info(Map));
    }

    fprintf(stdout, "creator=%s\n",
	    Vect_get_person(Map));
    fprintf(stdout, "organization=%s\n",
	    Vect_get_organization(Map));
    fprintf(stdout, "source_date=%s\n",
	    Vect_get_map_date(Map));
    fprintf(stdout, "level=%d\n", 
	    Vect_level(Map));
    
    if (Vect_level(Map) > 0) {
	fprintf(stdout, "num_dblinks=%d\n",
		Vect_get_num_dblinks(Map));
    }

    fprintf(stdout, "projection=%s\n",
	    Vect_get_proj_name(Map));
    if (G_projection() == PROJECTION_UTM) {
	fprintf(stdout, "zone=%d\n",
		Vect_get_zone(Map));
    }
    fprintf(stdout, "digitization_threshold=%f\n",
	    Vect_get_thresh(Map));
    fprintf(stdout, "comment=%s\n",
	    Vect_get_comment(Map));
}
Exemplo n.º 3
0
int display_title(View * view)
{
    View *title;
    char left[100], center[100];
    int size;

    *left = 0;
    *center = 0;

    if (view->cell.configured) {
	sprintf(center, "%s (mag %.1f)",
		view->cell.name, magnification(view));
    }

    if (view == VIEW_MAP1) {
	sprintf(left, "%s", G_location());
	title = VIEW_TITLE1;
    }
    else if (view == VIEW_MAP1_ZOOM) {
	title = VIEW_TITLE1_ZOOM;
    }

    if (view == VIEW_MAP2) {
	sprintf(left, "%s", G_location());
	title = VIEW_TITLE2;
    }
    else if (view == VIEW_MAP2_ZOOM) {
	title = VIEW_TITLE2_ZOOM;
    }

    Erase_view(title);
    R_standard_color(WHITE);
    size = title->nrows - 4;
    R_text_size(size, size);
    Text(left, title->top, title->bottom, title->left, title->right, 2);
    if (*center) {
	R_standard_color(YELLOW);
	Text(center, title->top, title->bottom,
	     (title->left + title->right - Text_width(center)) / 2,
	     title->right, 2);
    }

    return 0;
}
Exemplo n.º 4
0
static int error(char *camera, char *msga, char *msgb)
{
    char buf[100];

    sprintf(buf, "%s camera file [%s] in [%s %s] %s",
	    msga, camera, G_location(), G_mapset(), msgb);
    G_warning("%s", buf);

    return 0;
}
Exemplo n.º 5
0
/*!
 * \brief Get current location path
 *
 *  \param
 *  \return char* to location path
 */
char *G__location_path(void)
{
    const char *name = G_location();
    const char *base = G_gisdbase();
    char *location = G_malloc(strlen(base) + strlen(name) + 2);

    sprintf(location, "%s/%s", base, name);

    return location;
}
Exemplo n.º 6
0
Arquivo: mapset.c Projeto: caomw/grass
/*!
  \brief Get current mapset UNIX-like path (internal use only)
  
  Allocated buffer should be freed by G_free(). See also
  G_mapset_path().
  
  \todo Support also Windows-like path (?)
  
  \return buffer with mapset path
*/
char *G__mapset_path(void)
{
    const char *mapset = G__mapset();
    const char *location = G_location();
    const char *base = G_gisdbase();
    
    char *mapset_path = G_malloc(strlen(base) + strlen(location) +
                                 strlen(mapset) + 3);

    sprintf(mapset_path, "%s/%s/%s", base, location, mapset);

    return mapset_path;
}
Exemplo n.º 7
0
char *
G__location_path()
{
    char *location = 0;
    char *base;
    char *name;

    name      = G_location();
    base      = G_gisdbase();
    location  = G_malloc (strlen (base) + strlen (name) + 2);
    sprintf (location, "%s/%s", base, name);

    return location;
}
Exemplo n.º 8
0
static int do_report(FILE * fd)
{
    char buf[100];
    int n;
    int width;

    fprintf(fd, "LOCATION: %-20s GROUP: %-20s MAPSET: %s\n\n",
	    G_location(), group.name, G_mapset());
    fprintf(fd, "%15sAnalysis of control point registration\n\n", "");
    fprintf(fd, "%s   %s\n", LHEAD1, RHEAD1);
    fprintf(fd, "%s   %s\n", LHEAD2, RHEAD2);

    FMT1(buf, 0.0, 0.0, 0.0);
    width = strlen(buf);

    for (n = 0; n < group.points.count; n++) {
	FMT0(buf, n + 1);
	fprintf(fd, "%s", buf);
	if (group.equation_stat > 0 && group.points.status[n] > 0) {
	    FMT1(buf, xres[n], yres[n], gnd[n]);
	    fprintf(fd, "%s", buf);
	}
	else if (group.points.status[n] > 0)
	    printcentered(fd, "?", width);
	else
	    printcentered(fd, "not used", width);
	FMT2(buf,
	     group.points.e1[n],
	     group.points.n1[n], group.points.e2[n], group.points.n2[n]);
	fprintf(fd, "   %s\n", buf);
    }
    fprintf(fd, "\n");
    if (group.equation_stat < 0)
	fprintf(fd, "Poorly place control points\n");
    else if (group.equation_stat == 0)
	fprintf(fd, "No active control points\n");
    else
	fprintf(fd,
		"Overall rms error: %.2f                %s Transformation\n",
		rms, order_msg);

    return 0;
}
Exemplo n.º 9
0
int do_map_header(char *date)
{
    char temp[100];

    /* set color and font */
    set_ps_color(&hdr.color);
    fontsize = (double)hdr.fontsize;
    fprintf(PS.fp, "(%s) FN %.1f SF\n", hdr.font, fontsize);

    /* set start of first line */
    dy = 1.2 * fontsize;
    y = 72.0 * (PS.page_height - PS.top_marg) - fontsize - 1.5;

    if (hdr.fp == NULL) {

	if (PS.celltitle[0]) {
	    fprintf(PS.fp, "/t (TITLE:  %s) def\n", PS.celltitle);
	    fprintf(PS.fp, "t SW pop %.1f XS D2 t exch %.1f MS\n",
		    72 * PS.page_width, y);
	    y -= dy;
	}
	strcpy(temp, G_myname());
	G_strip(temp);
	if (*temp == 0)
	    strcpy(temp, G_location());
	fprintf(PS.fp, "/t (LOCATION:  %s) def\n", temp);
	fprintf(PS.fp, "t SW pop %.1f XS D2 t exch %.1f MS\n",
		72 * PS.page_width, y);
	y -= 0.25 * dy;
	if (PS.min_y > y)
	    PS.min_y = y;
	return 0;
    }

    x = 72.0 * PS.left_marg + 1.5;
    read_header_file(date);
    y -= 0.25 * dy;
    if (PS.min_y > y)
	PS.min_y = y;

    return 0;
}
Exemplo n.º 10
0
void prn_header(void)
{
    int i, len;
    char buf[1024], *titles, *label;
    char *mask;
    FILE *fd;

    if (output == NULL)
	fd = stdout;
    else if ((fd = fopen(output, "w")) == NULL) {
	G_fatal_error(_("Cannot open file <%s> to write header"), output);
	return;
    }

    /* print header */
    fprintf(fd, "\t\t\t%s\n", title);
    sprintf(buf, "LOCATION: %s\t\t\t\t%s", G_location(), G_date());
    fprintf(fd, "%s\n", buf);
    if ((mask = maskinfo()))
	sprintf(buf, "MASK: %s", mask);

    fprintf(fd, "%s\n", buf);
    fprintf(fd, "MAPS: ");
    label = "MAP";
    len = strlen(label);

    for (i = 0; i < nlayers; i++) {
	titles = Rast_get_cats_title(&(layers[i].labels));
	if (titles)
	    G_strip(titles);
	if (titles == NULL || *titles == 0)
	    titles = "(untitled)";
	sprintf(buf, "%*s%-*s%d = %s (%s in %s)", i * 6, "", len, label,
		i + 1, titles, layers[i].name, layers[i].mapset);
	fprintf(fd, "%s\n", buf);
    }

    if (output != NULL)
	fclose(fd);
}
Exemplo n.º 11
0
int G__make_mapset(const char *gisdbase_name, const char *location_name,
		   const char *mapset_name)
{
    char path[GPATH_MAX];
    struct Cell_head default_window;

    /* Get location */
    if (location_name == NULL)
	location_name = G_location();

    /* Get GISDBASE */
    if (gisdbase_name == NULL)
	gisdbase_name = G_gisdbase();

    /* TODO: Should probably check that user specified location and gisdbase are valid */

    /* Make the mapset. */
    sprintf(path, "%s/%s/%s", gisdbase_name, location_name, mapset_name);
    if (G_mkdir(path) != 0)
	return -1;

    G__create_alt_env();

    /* Get PERMANENT default window */
    G__setenv("GISDBASE", gisdbase_name);
    G__setenv("LOCATION", location_name);
    G__setenv("MAPSET", "PERMANENT");
    G_get_default_window(&default_window);

    /* Change to the new mapset */
    G__setenv("MAPSET", mapset_name);

    /* Copy default window/regions to new mapset */
    G__put_window(&default_window, "", "WIND");

    /* And switch back to original environment */
    G__switch_env();

    return 0;
}
Exemplo n.º 12
0
void GRASS_EXPORT QgsGrass::init( void )
{
  // Warning!!!
  // G_set_error_routine() once called from plugin
  // is not valid in provider -> call it always

  // Set error function
  G_set_error_routine( &error_routine );

  if ( initialized )
    return;

  QSettings settings;

  // Is it active mode ?
  if ( getenv( "GISRC" ) )
  {
    active = true;
    // Store default values
    defaultGisdbase = G_gisdbase();
    defaultLocation = G_location();
    defaultMapset = G_mapset();
  }
  else
  {
    active = false;
  }

  // Don't use GISRC file and read/write GRASS variables (from location G_VAR_GISRC) to memory only.
  G_set_gisrc_mode( G_GISRC_MODE_MEMORY );

  // Init GRASS libraries (required)
  G_no_gisinit();  // Doesn't check write permissions for mapset compare to G_gisinit("libgrass++");

  // I think that mask should not be used in QGIS as it can only confuses people,
  // anyway, I don't think anybody is using MASK
  G_suppress_masking();

  // Set program name
  G_set_program_name( "QGIS" );

  // Require GISBASE to be set. This should point to the location of
  // the GRASS installation. The GRASS libraries use it to know
  // where to look for things.

  // Look first to see if GISBASE env var is already set.
  // This is set when QGIS is run from within GRASS
  // or when set explicitly by the user.
  // This value should always take precedence.
#if WIN32
  QString gisBase = getenv( "WINGISBASE" ) ? getenv( "WINGISBASE" ) : getenv( "GISBASE" );
  gisBase = shortPath( gisBase );
#else
  QString gisBase = getenv( "GISBASE" );
#endif
  QgsDebugMsg( QString( "GRASS gisBase from GISBASE env var is: %1" ).arg( gisBase ) );
  if ( !isValidGrassBaseDir( gisBase ) )
  {
    // Look for gisbase in QSettings
    gisBase = settings.value( "/GRASS/gisbase", "" ).toString();
    QgsDebugMsg( QString( "GRASS gisBase from QSettings is: %1" ).arg( gisBase ) );
  }

  if ( !isValidGrassBaseDir( gisBase ) )
  {
    // Erase gisbase from settings because it does not exists
    settings.setValue( "/GRASS/gisbase", "" );

#ifdef WIN32
    // Use the applicationDirPath()/grass
    gisBase = shortPath( QCoreApplication::applicationDirPath() + "/grass" );
    QgsDebugMsg( QString( "GRASS gisBase = %1" ).arg( gisBase ) );
#else
    // Use the location specified --with-grass during configure
    gisBase = GRASS_BASE;
    QgsDebugMsg( QString( "GRASS gisBase from configure is: %1" ).arg( gisBase ) );
#endif
  }

  bool userGisbase = false;
  bool valid = false;
  while ( !( valid = isValidGrassBaseDir( gisBase ) ) )
  {

    // ask user if he wants to specify GISBASE
    QMessageBox::StandardButton res = QMessageBox::warning( 0, QObject::tr( "GRASS plugin" ),
                                      QObject::tr( "QGIS couldn't find your GRASS installation.\n"
                                                   "Would you like to specify path (GISBASE) to your GRASS installation?" ),
                                      QMessageBox::Ok | QMessageBox::Cancel );

    if ( res != QMessageBox::Ok )
    {
      userGisbase = false;
      break;
    }

    // XXX Need to subclass this and add explantory message above to left side
    userGisbase = true;
    // For Mac, GISBASE folder may be inside GRASS bundle. Use Qt file dialog
    // since Mac native dialog doesn't allow user to browse inside bundles.
    gisBase = QFileDialog::getExistingDirectory(
                0, QObject::tr( "Choose GRASS installation path (GISBASE)" ), gisBase,
                QFileDialog::DontUseNativeDialog );
    if ( gisBase == QString::null )
    {
      // User pressed cancel. No GRASS for you!
      userGisbase = false;
      break;
    }
#if defined(WIN32)
    gisBase = shortPath( gisBase );
#endif
  }

  if ( !valid )
  {
    // warn user
    QMessageBox::information( 0, QObject::tr( "GRASS plugin" ),
                              QObject::tr( "GRASS data won't be available if GISBASE is not specified." ) );
  }

  if ( userGisbase )
  {
    settings.setValue( "/GRASS/gisbase", gisBase );
  }

  QgsDebugMsg( QString( "Valid GRASS gisBase is: %1" ).arg( gisBase ) );
  putEnv( "GISBASE", gisBase );

  // Add path to GRASS modules
#ifdef WIN32
  QString sep = ";";
#else
  QString sep = ":";
#endif
  QString path = gisBase + "/bin";
  path.append( sep + gisBase + "/scripts" );
  path.append( sep +  QgsApplication::pkgDataPath() + "/grass/scripts/" );

  // On windows the GRASS libraries are in
  // QgsApplication::prefixPath(), we have to add them
  // to PATH to enable running of GRASS modules
  // and database drivers
#ifdef WIN32
  // It seems that QgsApplication::prefixPath()
  // is not initialized at this point
  path.append( sep + shortPath( QCoreApplication::applicationDirPath() ) );

  // Add path to MSYS bin
  // Warning: MSYS sh.exe will translate this path to '/bin'
  if ( QFileInfo( QCoreApplication::applicationDirPath() + "/msys/bin/" ).isDir() )
    path.append( sep + shortPath( QCoreApplication::applicationDirPath() + "/msys/bin/" ) );
#endif

  QString p = getenv( "PATH" );
  path.append( sep + p );

  QgsDebugMsg( QString( "set PATH: %1" ).arg( path ) );
  putEnv( "PATH", path );

  // Set PYTHONPATH
  QString pythonpath = gisBase + "/etc/python";
  QString pp = getenv( "PYTHONPATH" );
  pythonpath.append( sep + pp );
  QgsDebugMsg( QString( "set PYTHONPATH: %1" ).arg( pythonpath ) );
  putEnv( "PYTHONPATH", pythonpath );

  // Set GRASS_PAGER if not set, it is necessary for some
  // modules printing to terminal, e.g. g.list
  // We use 'cat' because 'more' is not present in MSYS (Win)
  // and it doesn't work well in built in shell (Unix/Mac)
  // and 'less' is not user friendly (for example user must press
  // 'q' to quit which is definitely difficult for normal user)
  // Also scroling can be don in scrollable window in both
  // MSYS terminal and built in shell.
  if ( !getenv( "GRASS_PAGER" ) )
  {
    QString pager;
    QStringList pagers;
    //pagers << "more" << "less" << "cat"; // se notes above
    pagers << "cat";

    for ( int i = 0; i < pagers.size(); i++ )
    {
      int state;

      QProcess p;
      p.start( pagers.at( i ) );
      p.waitForStarted();
      state = p.state();
      p.write( "\004" ); // Ctrl-D
      p.closeWriteChannel();
      p.waitForFinished( 1000 );
      p.kill();

      if ( state == QProcess::Running )
      {
        pager = pagers.at( i );
        break;
      }
    }

    if ( pager.length() > 0 )
    {
      putEnv( "GRASS_PAGER", pager );
    }
  }

  initialized = 1;
}
Exemplo n.º 13
0
int rectify(char *name, char *mapset, struct cache *ebuffer,
            double aver_z, char *result, char *interp_method)
{
    struct Cell_head cellhd;
    int ncols, nrows;
    int row, col;
    double row_idx, col_idx;
    int infd, outfd;
    RASTER_MAP_TYPE map_type;
    int cell_size;
    void *trast, *tptr;
    double n1, e1, z1;
    double nx, ex, nx1, ex1, zx1;
    struct cache *ibuffer;

    select_current_env();
    Rast_get_cellhd(name, mapset, &cellhd);

    /* open the file to be rectified
     * set window to cellhd first to be able to read file exactly
     */
    Rast_set_input_window(&cellhd);
    infd = Rast_open_old(name, mapset);
    map_type = Rast_get_map_type(infd);
    cell_size = Rast_cell_size(map_type);

    ibuffer = readcell(infd, seg_mb_img, 0);

    Rast_close(infd);		/* (pmx) 17 april 2000 */

    G_message(_("Rectify <%s@%s> (location <%s>)"),
	      name, mapset, G_location());
    select_target_env();
    G_set_window(&target_window);
    G_message(_("into  <%s@%s> (location <%s>) ..."),
	      result, G_mapset(), G_location());

    nrows = target_window.rows;
    ncols = target_window.cols;

    if (strcmp(interp_method, "nearest") != 0) {
	map_type = DCELL_TYPE;
	cell_size = Rast_cell_size(map_type);
    }

    /* open the result file into target window
     * this open must be first since we change the window later
     * raster maps open for writing are not affected by window changes
     * but those open for reading are
     */

    outfd = Rast_open_new(result, map_type);
    trast = Rast_allocate_output_buf(map_type);

    for (row = 0; row < nrows; row++) {
	n1 = target_window.north - (row + 0.5) * target_window.ns_res;

	G_percent(row, nrows, 2);

	Rast_set_null_value(trast, ncols, map_type);
	tptr = trast;
	for (col = 0; col < ncols; col++) {
	    DCELL *zp = CPTR(ebuffer, row, col);

	    e1 = target_window.west + (col + 0.5) * target_window.ew_res;
	    
	    /* if target cell has no elevation, set to aver_z */
	    if (Rast_is_d_null_value(zp)) {
		G_warning(_("No elevation available at row = %d, col = %d"), row, col);
		z1 = aver_z;
	    }
	    else
		z1 = *zp;

	    /* target coordinates e1, n1 to photo coordinates ex1, nx1 */
	    I_ortho_ref(e1, n1, z1, &ex1, &nx1, &zx1, &group.camera_ref,
			group.XC, group.YC, group.ZC, group.M);

	    G_debug(5, "\t\tAfter ortho ref (photo cords): ex = %f \t nx =  %f",
		    ex1, nx1);

	    /* photo coordinates ex1, nx1 to image coordinates ex, nx */
	    I_georef(ex1, nx1, &ex, &nx, group.E21, group.N21, 1);

	    G_debug(5, "\t\tAfter geo ref: ex = %f \t nx =  %f", ex, nx);

	    /* convert to row/column indices of source raster */
	    row_idx = (cellhd.north - nx) / cellhd.ns_res;
	    col_idx = (ex - cellhd.west) / cellhd.ew_res;

	    /* resample data point */
	    interpolate(ibuffer, tptr, map_type, &row_idx, &col_idx, &cellhd);

	    tptr = G_incr_void_ptr(tptr, cell_size);
	}
	Rast_put_row(outfd, trast, map_type);
    }
    G_percent(1, 1, 1);

    Rast_close(outfd);		/* (pmx) 17 april 2000 */
    G_free(trast);

    close(ibuffer->fd);
    release_cache(ibuffer);

    Rast_get_cellhd(result, G_mapset(), &cellhd);

    if (cellhd.proj == 0) {	/* x,y imagery */
	cellhd.proj = target_window.proj;
	cellhd.zone = target_window.zone;
    }

    if (target_window.proj != cellhd.proj) {
	cellhd.proj = target_window.proj;
	G_warning(_("Raster map <%s@%s>: projection don't match current settings"),
		  name, mapset);
    }

    if (target_window.zone != cellhd.zone) {
	cellhd.zone = target_window.zone;
	G_warning(_("Raster map <%s@%s>: zone don't match current settings"),
		  name, mapset);
    }

    select_current_env();

    return 1;
}
Exemplo n.º 14
0
static int output(char *line, char *date)
{
    char text[1024];
    char fmt[30];
    char *buf;

    buf = line;
    *text = 0;
    while (*buf) {
	if (*buf == '%') {
	    buf++;
	    if (*buf == '%')
		strcat(text, "%");
	    else if (*buf == 'n') {
		if (*text)
		    show_text(x, y, text);
		y -= dy;
		return 0;
	    }
	    else if (*buf == '_') {
		fprintf(PS.fp, "BW ");
		draw_line(x, y + 0.2 * fontsize,
			  72.0 * (PS.page_width - PS.right_marg),
			  y + 0.2 * fontsize);
		y -= dy;
		set_ps_color(&hdr.color);
		return 0;
	    }
	    else {
		buf = get_format(buf, fmt);
		append('s', fmt);
		switch (*buf) {
		case 'd':
		    apply(date, fmt, text);
		    break;
		case 'l':
		    apply(G_location(), fmt, text);
		    break;
		case 'L':
		    apply(G_myname(), fmt, text);
		    break;
		case 'c':
		    if (PS.cell_fd >= 0) {
			char name[100];

			sprintf(name, "<%s> in mapset <%s>",
				PS.cell_name, PS.cell_mapset);
			apply(name, fmt, text);
		    }
		    else
			apply("none", fmt, text);
		    break;
		case 'm':
		    apply(G_mapset(), fmt, text);
		    break;
		case 'u':
		    apply(G_whoami(), fmt, text);
		    break;
		case 'x':
		    apply(G_mask_info(), fmt, text);
		    break;
		case 0:
		    continue;
		}
	    }
	}
	else
	    append(*buf, text);
	buf++;
    }
    if (*text)
	show_text(x, y, text);
    y -= dy;

    return 0;
}
Exemplo n.º 15
0
/*!
   \brief Delete vector map including attribute tables

   \param map vector map name

   \return -1 error
   \return 0 success
 */
int Vect_delete(const char *map)
{
    int i, n, ret;
    struct Map_info Map;
    struct field_info *Fi;
    char buf[GPATH_MAX];
    DIR *dir;
    struct dirent *ent;
    const char *tmp;
    char xname[GNAME_MAX], xmapset[GMAPSET_MAX];

    G_debug(3, "Delete vector '%s'", map);

    /* remove mapset from fully qualified name */
    if (G_name_is_fully_qualified(map, xname, xmapset)) {
	map = xname;
    }

    if (map == NULL || strlen(map) == 0) {
	G_warning(_("Invalid vector map name <%s>"), map ? map : "null");
	return -1;
    }

    sprintf(buf, "%s/%s/%s/%s/%s/%s", G_gisdbase(), G_location(),
	    G_mapset(), GV_DIRECTORY, map, GV_DBLN_ELEMENT);

    G_debug(1, "dbln file: %s", buf);

    if (access(buf, F_OK) == 0) {
	/* Open input */
	Vect_set_open_level(1);	/* Topo not needed */
	ret = Vect_open_old_head(&Map, map, G_mapset());
	if (ret < 1) {
	    G_warning(_("Unable to open header file for vector map <%s>"),
		      map);
	    return -1;
	}

	/* Delete all tables, NOT external (OGR) */
	if (Map.format == GV_FORMAT_NATIVE) {

	    n = Vect_get_num_dblinks(&Map);
	    for (i = 0; i < n; i++) {
		Fi = Vect_get_dblink(&Map, i);
		if (Fi == NULL) {
		    G_warning(_("Database connection not defined for layer %d"),
			      Map.dblnk->field[i].number);
		    Vect_close(&Map);
		    return -1;
		}
		G_debug(3, "Delete drv:db:table '%s:%s:%s'", Fi->driver,
			Fi->database, Fi->table);

		ret = db_table_exists(Fi->driver, Fi->database, Fi->table);
		if (ret == -1) {
		    G_warning(_("Unable to find table <%s> linked to vector map <%s>"),
			      Fi->table, map);
		    Vect_close(&Map);
		    return -1;
		}

		if (ret == 1) {
		    ret =
			db_delete_table(Fi->driver, Fi->database, Fi->table);
		    if (ret == DB_FAILED) {
			G_warning(_("Unable to delete table <%s>"),
				  Fi->table);
			Vect_close(&Map);
			return -1;
		    }
		}
		else {
		    G_warning(_("Table <%s> linked to vector map <%s> does not exist"),
			      Fi->table, map);
		}
	    }
	}
	Vect_close(&Map);
    }

    /* Delete all files from vector/name directory */
    sprintf(buf, "%s/%s/vector/%s", G_location_path(), G_mapset(), map);
    G_debug(3, "opendir '%s'", buf);
    dir = opendir(buf);
    if (dir == NULL) {
	G_warning(_("Unable to open directory '%s'"), buf);
	return -1;
    }

    while ((ent = readdir(dir))) {
	G_debug(3, "file = '%s'", ent->d_name);
	if ((strcmp(ent->d_name, ".") == 0) ||
	    (strcmp(ent->d_name, "..") == 0))
	    continue;
	sprintf(buf, "%s/%s/vector/%s/%s", G_location_path(), G_mapset(), map,
		ent->d_name);
	G_debug(3, "delete file '%s'", buf);
	ret = unlink(buf);
	if (ret == -1) {
	    G_warning(_("Unable to delete file '%s'"), buf);
	    closedir(dir);
	    return -1;
	}
    }
    closedir(dir);

    /* NFS can create .nfsxxxxxxxx files for those deleted 
     *  -> we have to move the directory to ./tmp before it is deleted */
    sprintf(buf, "%s/%s/vector/%s", G_location_path(), G_mapset(), map);

    tmp = G_tempfile();

    G_debug(3, "rename '%s' to '%s'", buf, tmp);
    ret = rename(buf, tmp);

    if (ret == -1) {
	G_warning(_("Unable to rename directory '%s' to '%s'"), buf, tmp);
	return -1;
    }

    G_debug(3, "remove directory '%s'", tmp);
    /* Warning: remove() fails on Windows */
    ret = rmdir(tmp);
    if (ret == -1) {
	G_warning(_("Unable to remove directory '%s'"), tmp);
	return -1;
    }

    return 0;
}
Exemplo n.º 16
0
void print_info(const struct Map_info *Map)
{
    int i;
    char line[100];
    char tmp1[100], tmp2[100];

    struct bound_box box;
    
    divider('+');
    if (Vect_maptype(Map) & (GV_FORMAT_OGR | GV_FORMAT_OGR_DIRECT)) {
	/* for OGR format print also datasource and layer */
	sprintf(line, "%-17s%s", _("OGR layer:"),
		Vect_get_ogr_layer_name(Map));
	printline(line);
	sprintf(line, "%-17s%s", _("OGR datasource:"),
		Vect_get_ogr_dsn_name(Map));
	printline(line);
    }
    else {
	sprintf(line, "%-17s%s", _("Name:"),
		Vect_get_name(Map));
	printline(line);
	sprintf(line, "%-17s%s", _("Mapset:"),
		Vect_get_mapset(Map));
	printline(line);
    }

    sprintf(line, "%-17s%s", _("Location:"),
	    G_location());
    printline(line);
    sprintf(line, "%-17s%s", _("Database:"),
	    G_gisdbase());
    printline(line);
    sprintf(line, "%-17s%s", _("Title:"),
	    Vect_get_map_name(Map));
    printline(line);
    sprintf(line, "%-17s1:%d", _("Map scale:"),
	    Vect_get_scale(Map));
    printline(line);
    
    if (Vect_maptype(Map) & (GV_FORMAT_OGR | GV_FORMAT_OGR_DIRECT)) {
	sprintf(line, "%-17s%s (%s)", _("Map format:"),
		Vect_maptype_info(Map), Vect_get_ogr_format_info(Map));
    }
    else {
	sprintf(line, "%-17s%s", _("Map format:"),
		Vect_maptype_info(Map));
    }
    
    printline(line);
    sprintf(line, "%-17s%s", _("Name of creator:"),
	    Vect_get_person(Map));
    printline(line);
    sprintf(line, "%-17s%s", _("Organization:"),
	    Vect_get_organization(Map));
    printline(line);
    sprintf(line, "%-17s%s", _("Source date:"),
	    Vect_get_map_date(Map));
    printline(line);
    
    divider('|');
    
    sprintf(line, "  %s: %s (%s: %i)",
	    _("Type of map"), _("vector"), _("level"), Vect_level(Map));
    
    printline(line);
    
    if (Vect_level(Map) > 0) {
	printline("");
	sprintf(line,
		"  %-24s%-9d       %-22s%-9d",
		_("Number of points:"), 
		Vect_get_num_primitives(Map, GV_POINT),
		_("Number of centroids:"),
		Vect_get_num_primitives(Map, GV_CENTROID));
	printline(line);
	sprintf(line,
		"  %-24s%-9d       %-22s%-9d",
		_("Number of lines:"),
		Vect_get_num_primitives(Map, GV_LINE),
		_("Number of boundaries:"),
		Vect_get_num_primitives(Map, GV_BOUNDARY));
	printline(line);
	sprintf(line,
		"  %-24s%-9d       %-22s%-9d",
		_("Number of areas:"),
		Vect_get_num_areas(Map),
		_("Number of islands:"),
		Vect_get_num_islands(Map));
	printline(line);
	if (Vect_is_3d(Map)) {
	    sprintf(line,
		    "  %-24s%-9d       %-22s%-9d",
		    _("Number of faces:"),
		    Vect_get_num_primitives(Map, GV_FACE),
		    _("Number of kernels:"),
		    Vect_get_num_primitives(Map, GV_KERNEL));
	    printline(line);
	    sprintf(line,
		    "  %-24s%-9d       %-22s%-9d",
		    _("Number of volumes:"),
		    Vect_get_num_volumes(Map),
		    _("Number of holes:"),
		    Vect_get_num_holes(Map));
	    printline(line);
	}
	printline("");
	
	sprintf(line, "  %-24s%s",
		_("Map is 3D:"),
		Vect_is_3d(Map) ? _("Yes") : _("No"));
	printline(line);
	sprintf(line, "  %-24s%-9d",
		_("Number of dblinks:"),
		Vect_get_num_dblinks(Map));
	printline(line);
    }
    
    printline("");
    /* this differs from r.info in that proj info IS taken from the map here, not the location settings */
    /* Vect_get_proj_name() and _zone() are typically unset?! */
    if (G_projection() == PROJECTION_UTM)
	sprintf(line, "  %s: %s (%s %d)",
		_("Projection:"),
		Vect_get_proj_name(Map),
		_("zone"), Vect_get_zone(Map));
    else
	sprintf(line, "  %s: %s",
		_("Projection"),
		Vect_get_proj_name(Map));
    
    printline(line);
    printline("");
    
    Vect_get_map_box(Map, &box);
    
    G_format_northing(box.N, tmp1, G_projection());
    G_format_northing(box.S, tmp2, G_projection());
    sprintf(line, "              %c: %17s    %c: %17s",
	    'N', tmp1, 'S', tmp2);
    printline(line);
    
    G_format_easting(box.E, tmp1, G_projection());
    G_format_easting(box.W, tmp2, G_projection());
    sprintf(line, "              %c: %17s    %c: %17s",
	    'E', tmp1, 'W', tmp2);
    printline(line);
    
    if (Vect_is_3d(Map)) {
	format_double(box.B, tmp1);
	format_double(box.T, tmp2);
	sprintf(line, "              %c: %17s    %c: %17s",
		'B', tmp1, 'T', tmp2);
	printline(line);
    }
    printline("");

    format_double(Vect_get_thresh(Map), tmp1);
    sprintf(line, "  %s: %s", _("Digitization threshold"), tmp1);
    printline(line);
    sprintf(line, "  %s:", _("Comment"));
    printline(line);
    sprintf(line, "    %s", Vect_get_comment(Map));
    printline(line);
    divider('+');
    fprintf(stdout, "\n");
}
Exemplo n.º 17
0
int main(int argc, char *argv[])
{
    struct Option *group, *mapset, *loc;
    struct GModule *module;
    struct Flag *c;
    char t_mapset[GMAPSET_MAX], t_location[GMAPSET_MAX];
    char group_name[GNAME_MAX], mapset_name[GMAPSET_MAX];

    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("imagery"));
    G_add_keyword(_("map management"));
    module->description =
	_("Targets an imagery group to a GRASS location and mapset.");

    group = G_define_standard_option(G_OPT_I_GROUP);
    group->gisprompt = "any,group,group";

    loc = G_define_option();
    loc->key = "location";
    loc->type = TYPE_STRING;
    loc->required = NO;
    loc->description = _("Name of imagery target location");

    mapset = G_define_option();
    mapset->key = "mapset";
    mapset->type = TYPE_STRING;
    mapset->required = NO;
    mapset->description = _("Name of target mapset");

    c = G_define_flag();
    c->key = 'c';
    c->description =
	_("Set current location and mapset as target for imagery group");

    if (G_parser(argc, argv))
	exit(EXIT_FAILURE);


    /* check if current mapset:  (imagery libs are very lacking in this dept)
       - abort if not,
       - remove @mapset part if it is
     */
    if (G_name_is_fully_qualified(group->answer, group_name, mapset_name)) {
	if (strcmp(mapset_name, G_mapset()))
	    G_fatal_error(_("Group must exist in the current mapset"));
    }
    else {
	strcpy(group_name, group->answer);	/* FIXME for buffer overflow (have the parser check that?) */
    }

    /* if no setting options are given, print the current target info */
    if (!c->answer && !mapset->answer && !loc->answer) {

	if (I_get_target(group_name, t_location, t_mapset))
	    G_message(_("Group <%s> targeted for location [%s], mapset [%s]"),
		      group_name, t_location, t_mapset);
	else
	    G_message(_("Group <%s> has no target"), group_name);

	exit(EXIT_SUCCESS);
    }

    /* error if -c is specified with other options, or options are incomplete */
    if ((c->answer && (mapset->answer || loc->answer)) ||
	(!c->answer && (!mapset->answer || !loc->answer)))
	G_fatal_error(_("Use either the Current Mapset and "
			"Location Flag (-c)\n OR\n manually enter the variables"));

    if (c->answer) {
	/* point group target to current mapset and location */
	I_put_target(group_name, G_location(), G_mapset());
	G_message(_("Group <%s> targeted for location [%s], mapset [%s]"),
		  group_name, G_location(), G_mapset());
    }
    else {
	/* point group target to specified mapset and location */

	/* TODO: check if it is in current mapset and strip off @mapset part, if present */

	I_put_target(group_name, loc->answer, mapset->answer);
	G_message(_("Group <%s> targeted for location [%s], mapset [%s]"),
		  group_name, loc->answer, mapset->answer);
    }

    G_done_msg(" ");
    exit(EXIT_SUCCESS);
}
Exemplo n.º 18
0
int main(int argc, char *argv[])
{
    char group[INAME_LEN], extension[INAME_LEN];
    int order;			/* ADDED WITH CRS MODIFICATIONS */
    char *ipolname;		/* name of interpolation method */
    int method;
    int n, i, m, k = 0;
    int got_file = 0, target_overwrite = 0;
    char *overstr;
    struct Cell_head cellhd;

    struct Option *grp,         /* imagery group */
     *val,                      /* transformation order */
     *ifile,			/* input files */
     *ext,			/* extension */
     *tres,			/* target resolution */
     *mem,			/* amount of memory for cache */
     *interpol;			/* interpolation method:
				   nearest neighbor, bilinear, cubic */
    struct Flag *c, *a;
    struct GModule *module;

    G_gisinit(argv[0]);

    module = G_define_module();
    module->keywords = _("imagery, rectify");
    module->description =
	_("Rectifies an image by computing a coordinate "
	  "transformation for each pixel in the image based on the "
	  "control points.");

    grp = G_define_standard_option(G_OPT_I_GROUP);

    ifile = G_define_standard_option(G_OPT_R_INPUTS);
    ifile->required = NO;

    ext = G_define_option();
    ext->key = "extension";
    ext->type = TYPE_STRING;
    ext->required = YES;
    ext->multiple = NO;
    ext->description = _("Output raster map(s) suffix");

    val = G_define_option();
    val->key = "order";
    val->type = TYPE_INTEGER;
    val->required = YES;
    val->description = _("Rectification polynom order (1-3)");

    tres = G_define_option();
    tres->key = "res";
    tres->type = TYPE_DOUBLE;
    tres->required = NO;
    tres->description = _("Target resolution (ignored if -c flag used)");

    mem = G_define_option();
    mem->key = "memory";
    mem->type = TYPE_DOUBLE;
    mem->key_desc = "memory in MB";
    mem->required = NO;
    mem->answer = "300";
    mem->description = _("Amount of memory to use in MB");

    ipolname = make_ipol_list();

    interpol = G_define_option();
    interpol->key = "method";
    interpol->type = TYPE_STRING;
    interpol->required = NO;
    interpol->answer = "nearest";
    interpol->options = ipolname;
    interpol->description = _("Interpolation method to use");

    c = G_define_flag();
    c->key = 'c';
    c->description =
	_("Use current region settings in target location (def.=calculate smallest area)");

    a = G_define_flag();
    a->key = 'a';
    a->description = _("Rectify all raster maps in group");

    if (G_parser(argc, argv))
	exit(EXIT_FAILURE);

    /* get the method */
    for (method = 0; (ipolname = menu[method].name); method++)
	if (strcmp(ipolname, interpol->answer) == 0)
	    break;

    if (!ipolname)
	G_fatal_error(_("<%s=%s> unknown %s"),
		      interpol->key, interpol->answer, interpol->key);
    interpolate = menu[method].method;

    G_strip(grp->answer);
    strcpy(group, grp->answer);
    strcpy(extension, ext->answer);
    order = atoi(val->answer);

    seg_mb = NULL;
    if (mem->answer) {
	if (atoi(mem->answer) > 0)
	    seg_mb = mem->answer;
    }

    if (!ifile->answers)
	a->answer = 1;		/* force all */

    /* Find out how many files on command line */
    if (!a->answer) {
	for (m = 0; ifile->answers[m]; m++) {
	    k = m;
	}
	k++;
    }

    if (order < 1 || order > MAXORDER)
	G_fatal_error(_("Invalid order (%d); please enter 1 to %d"), order,
		      MAXORDER);

    /* determine the number of files in this group */
    if (I_get_group_ref(group, &ref) <= 0)
	G_fatal_error(_("Group <%s> does not exist"), grp->answer);

    if (ref.nfiles <= 0) {
	G_important_message(_("Group <%s> contains no raster maps; run i.group"),
			    grp->answer);
	exit(EXIT_SUCCESS);
    }

    ref_list = (int *)G_malloc(ref.nfiles * sizeof(int));

    if (a->answer) {
	for (n = 0; n < ref.nfiles; n++) {
	    ref_list[n] = 1;
	}
    }
    else {
	char xname[GNAME_MAX], xmapset[GMAPSET_MAX], *name, *mapset;

	for (n = 0; n < ref.nfiles; n++)
		ref_list[n] = 0;

	for (m = 0; m < k; m++) {
	    got_file = 0;
	    if (G__name_is_fully_qualified(ifile->answers[m], xname, xmapset)) {
		name = xname;
		mapset = xmapset;
	    }
	    else {
		name = ifile->answers[m];
		mapset = NULL;
	    }

	    got_file = 0;
	    for (n = 0; n < ref.nfiles; n++) {
		if (mapset) {
		    if (strcmp(name, ref.file[n].name) == 0 &&
		        strcmp(mapset, ref.file[n].mapset) == 0) {
			got_file = 1;
			ref_list[n] = 1;
			break;
		    }
		}
		else {
		    if (strcmp(name, ref.file[n].name) == 0) {
			got_file = 1;
			ref_list[n] = 1;
			break;
		    }
		}
	    }
	    if (got_file == 0)
		err_exit(ifile->answers[m], group);
	}
    }

    /* read the control points for the group */
    get_control_points(group, order);

    /* get the target */
    get_target(group);

    /* Check the GRASS_OVERWRITE environment variable */
    if ((overstr = getenv("GRASS_OVERWRITE")))  /* OK ? */
	target_overwrite = atoi(overstr);

    if (!target_overwrite) {
	/* check if output exists in target location/mapset */
	char result[GNAME_MAX];
	
	select_target_env();
	for (i = 0; i < ref.nfiles; i++) {
	    if (!ref_list[i])
		continue;

	    strcpy(result, ref.file[i].name);
	    strcat(result, extension);
	    
	    if (G_legal_filename(result) < 0)
		G_fatal_error(_("Extension <%s> is illegal"), extension);
		
	    if (G_find_cell(result, G_mapset())) {
		G_warning(_("The following raster map already exists in"));
		G_warning(_("target LOCATION %s, MAPSET %s:"),
			  G_location(), G_mapset());
		G_warning("<%s>", result);
		G_fatal_error(_("Orthorectification cancelled."));
	    }
	}
	
	select_current_env();
    }
    else
	G_debug(1, "Overwriting OK");

    /* do not use current region in target location */
    if (!c->answer) {
	double res = -1;
	
	if (tres->answer) {
	    if (!((res = atof(tres->answer)) > 0))
		G_warning(_("Target resolution must be > 0, ignored"));
	}
	/* Calculate smallest region */
	if (a->answer) {
	    if (G_get_cellhd(ref.file[0].name, ref.file[0].mapset, &cellhd) <
		0)
		G_fatal_error(_("Unable to read header of raster map <%s>"),
			      ref.file[0].name);
	}
	else {
	    if (G_get_cellhd(ifile->answers[0], ref.file[0].mapset, &cellhd) <
		0)
		G_fatal_error(_("Unable to read header of raster map <%s>"),
			      ifile->answers[0]);
	}
	georef_window(&cellhd, &target_window, order, res);
    }

    G_verbose_message(_("Using region: N=%f S=%f, E=%f W=%f"), target_window.north,
	      target_window.south, target_window.east, target_window.west);

    exec_rectify(order, extension, interpol->answer);

    G_done_msg(" ");

    exit(EXIT_SUCCESS);
}
Exemplo n.º 19
0
void print_info(const struct Map_info *Map)
{
    int i, map_type;
    char line[1024];
    char timebuff[256];
    struct TimeStamp ts;
    int time_ok, first_time_ok, second_time_ok;
    struct bound_box box;
    char tmp1[1024], tmp2[1024];
    
    time_ok = first_time_ok = second_time_ok = FALSE;
    map_type = Vect_maptype(Map);
    
    /* Check the Timestamp */
    time_ok = G_read_vector_timestamp(Vect_get_name(Map), NULL, "", &ts);

    /* Check for valid entries, show none if no timestamp available */
    if (time_ok == TRUE) {
        if (ts.count > 0)
            first_time_ok = TRUE;
        if (ts.count > 1)
            second_time_ok = TRUE;
    }

    divider('+');
    sprintf(line, "%-17s%s", _("Name:"),
            Vect_get_name(Map));
    printline(line);
    sprintf(line, "%-17s%s", _("Mapset:"),
            Vect_get_mapset(Map));
    printline(line);
    
    sprintf(line, "%-17s%s", _("Location:"),
            G_location());
    printline(line);
    sprintf(line, "%-17s%s", _("Database:"),
            G_gisdbase());
    printline(line);

    sprintf(line, "%-17s%s", _("Title:"),
            Vect_get_map_name(Map));
    printline(line);
    sprintf(line, "%-17s1:%d", _("Map scale:"),
            Vect_get_scale(Map));
    printline(line);

    sprintf(line, "%-17s%s", _("Name of creator:"),
            Vect_get_person(Map));
    printline(line);
    sprintf(line, "%-17s%s", _("Organization:"),
            Vect_get_organization(Map));
    printline(line);
    sprintf(line, "%-17s%s", _("Source date:"),
            Vect_get_map_date(Map));
    printline(line);

    /* This shows the TimeStamp (if present) */
    if (time_ok  == TRUE && (first_time_ok || second_time_ok)) {
        G_format_timestamp(&ts, timebuff);
        sprintf(line, "%-17s%s", _("Timestamp (first layer): "), timebuff);
        printline(line);
    }
    else {
        strcpy(line, _("Timestamp (first layer): none"));
        printline(line);
    }
    
    divider('|');
    
    if (map_type == GV_FORMAT_OGR ||
        map_type == GV_FORMAT_OGR_DIRECT) {
        sprintf(line, "%-17s%s (%s)", _("Map format:"),
                Vect_maptype_info(Map), Vect_get_finfo_format_info(Map));
        printline(line);
        
        /* for OGR format print also datasource and layer */
        sprintf(line, "%-17s%s", _("OGR layer:"),
                Vect_get_finfo_layer_name(Map));
        printline(line);
        sprintf(line, "%-17s%s", _("OGR datasource:"),
                Vect_get_finfo_dsn_name(Map));
        printline(line);
        sprintf(line, "%-17s%s", _("Feature type:"),
                Vect_get_finfo_geometry_type(Map));
        printline(line);
    }
    else if (map_type == GV_FORMAT_POSTGIS) {
        int topo_format;
        char *toposchema_name, *topogeom_column;
        int topo_geo_only;

        const struct Format_info *finfo;

        finfo = Vect_get_finfo(Map);
        
        sprintf(line, "%-17s%s (%s)", _("Map format:"),
                Vect_maptype_info(Map), Vect_get_finfo_format_info(Map));
        printline(line);
        
        /* for PostGIS format print also datasource and layer */
        sprintf(line, "%-17s%s", _("DB table:"),
                Vect_get_finfo_layer_name(Map));
        printline(line);
        sprintf(line, "%-17s%s", _("DB name:"),
                Vect_get_finfo_dsn_name(Map));
        printline(line);

        sprintf(line, "%-17s%s", _("Geometry column:"),
                finfo->pg.geom_column);
        printline(line);

        sprintf(line, "%-17s%s", _("Feature type:"),
                Vect_get_finfo_geometry_type(Map));
        printline(line);


        
        topo_format = Vect_get_finfo_topology_info(Map,
                                                   &toposchema_name, &topogeom_column,
                                                   &topo_geo_only);
        if (topo_format == GV_TOPO_POSTGIS) {
            sprintf(line, "%-17s%s (%s %s%s)", _("Topology:"), "PostGIS",
                    _("schema:"), toposchema_name,
                    topo_geo_only ? ", topo-geo-only: yes" : "");
            printline(line);

            sprintf(line, "%-17s%s", _("Topology column:"),
                    topogeom_column);
        }
        else
            sprintf(line, "%-17s%s", _("Topology:"), "pseudo (simple features)");
        
        printline(line);
    }
    else {
        sprintf(line, "%-17s%s", _("Map format:"),
                Vect_maptype_info(Map));
        printline(line);
    }
    

    divider('|');
    
    sprintf(line, "  %s: %s (%s: %i)",
            _("Type of map"), _("vector"), _("level"), Vect_level(Map));
    printline(line);
    
    if (Vect_level(Map) > 0) {
        printline("");
        sprintf(line,
                "  %-24s%-9d       %-22s%-9d",
                _("Number of points:"), 
                Vect_get_num_primitives(Map, GV_POINT),
                _("Number of centroids:"),
                Vect_get_num_primitives(Map, GV_CENTROID));
        printline(line);
        sprintf(line,
                "  %-24s%-9d       %-22s%-9d",
                _("Number of lines:"),
                Vect_get_num_primitives(Map, GV_LINE),
                _("Number of boundaries:"),
                Vect_get_num_primitives(Map, GV_BOUNDARY));
        printline(line);
        sprintf(line,
                "  %-24s%-9d       %-22s%-9d",
                _("Number of areas:"),
                Vect_get_num_areas(Map),
                _("Number of islands:"),
                Vect_get_num_islands(Map));
        printline(line);
        if (Vect_is_3d(Map)) {
            sprintf(line,
                    "  %-24s%-9d       %-22s%-9d",
                    _("Number of faces:"),
                    Vect_get_num_primitives(Map, GV_FACE),
                    _("Number of kernels:"),
                    Vect_get_num_primitives(Map, GV_KERNEL));
            printline(line);
            sprintf(line,
                    "  %-24s%-9d       %-22s%-9d",
                    _("Number of volumes:"),
                    Vect_get_num_volumes(Map),
                    _("Number of holes:"),
                    Vect_get_num_holes(Map));
            printline(line);
        }
        printline("");

        sprintf(line, "  %-24s%s",
                _("Map is 3D:"),
                Vect_is_3d(Map) ? _("Yes") : _("No"));
        printline(line);
        sprintf(line, "  %-24s%-9d",
                _("Number of dblinks:"),
                Vect_get_num_dblinks(Map));
        printline(line);
    }

    printline("");
    /* this differs from r.info in that proj info IS taken from the map here, not the location settings */
    /* Vect_get_proj_name() and _zone() are typically unset?! */
    if (G_projection() == PROJECTION_UTM) {
        int utm_zone;

        utm_zone = Vect_get_zone(Map);
        if (utm_zone < 0 || utm_zone > 60)
            strcpy(tmp1, _("invalid"));
        else if (utm_zone == 0)
            strcpy(tmp1, _("unspecified"));
        else
            sprintf(tmp1, "%d", utm_zone);

        sprintf(line, "  %s: %s (%s %s)",
                _("Projection"), Vect_get_proj_name(Map),
                _("zone"), tmp1);
    }
    else
        sprintf(line, "  %s: %s",
                _("Projection"), Vect_get_proj_name(Map));

    printline(line);
    printline("");

    Vect_get_map_box(Map, &box);

    G_format_northing(box.N, tmp1, G_projection());
    G_format_northing(box.S, tmp2, G_projection());
    sprintf(line, "              %c: %17s    %c: %17s",
            'N', tmp1, 'S', tmp2);
    printline(line);
    
    G_format_easting(box.E, tmp1, G_projection());
    G_format_easting(box.W, tmp2, G_projection());
    sprintf(line, "              %c: %17s    %c: %17s",
            'E', tmp1, 'W', tmp2);
    printline(line);
    
    if (Vect_is_3d(Map)) {
        format_double(box.B, tmp1);
        format_double(box.T, tmp2);
        sprintf(line, "              %c: %17s    %c: %17s",
                'B', tmp1, 'T', tmp2);
        printline(line);
    }
    printline("");

    format_double(Vect_get_thresh(Map), tmp1);
    sprintf(line, "  %s: %s", _("Digitization threshold"), tmp1);
    printline(line);
    sprintf(line, "  %s:", _("Comment"));
    printline(line);
    sprintf(line, "    %s", Vect_get_comment(Map));
    printline(line);
    divider('+');
    fprintf(stdout, "\n");
}
Exemplo n.º 20
0
void print_shell(const struct Map_info *Map, const char *field_opt)
{
    int map_type;
    int time_ok, first_time_ok, second_time_ok;
    char timebuff[256];
    struct field_info *fi;
    struct TimeStamp ts;
        
    time_ok = first_time_ok = second_time_ok = FALSE;
    
    /* Check the Timestamp */
    time_ok = G_read_vector_timestamp(Vect_get_name(Map), NULL, "", &ts);
    
    /* Check for valid entries, show none if no timestamp available */
    if (time_ok == TRUE) {
        if (ts.count > 0)
            first_time_ok = TRUE;
        if (ts.count > 1)
            second_time_ok = TRUE;
    }

    map_type = Vect_maptype(Map);
    
    fprintf(stdout, "name=%s\n",
            Vect_get_name(Map));
    fprintf(stdout, "mapset=%s\n",
            Vect_get_mapset(Map));
    fprintf(stdout, "location=%s\n",
            G_location());
    fprintf(stdout, "database=%s\n",
            G_gisdbase());
    fprintf(stdout, "title=%s\n",
            Vect_get_map_name(Map));
    fprintf(stdout, "scale=1:%d\n",
            Vect_get_scale(Map));
    fprintf(stdout, "creator=%s\n",
            Vect_get_person(Map));
    fprintf(stdout, "organization=%s\n",
            Vect_get_organization(Map));
    fprintf(stdout, "source_date=%s\n",
            Vect_get_map_date(Map));
    /* This shows the TimeStamp (if present) */
    if (time_ok  == TRUE && (first_time_ok || second_time_ok)) {
        G_format_timestamp(&ts, timebuff);
        fprintf(stdout, "timestamp=%s\n", timebuff);
    }
    else {
        fprintf(stdout, "timestamp=none\n");
    }

    if (map_type == GV_FORMAT_OGR ||
        map_type == GV_FORMAT_OGR_DIRECT) {
        fprintf(stdout, "format=%s,%s\n",
                Vect_maptype_info(Map), Vect_get_finfo_format_info(Map));
        fprintf(stdout, "ogr_layer=%s\n",
                Vect_get_finfo_layer_name(Map));
        fprintf(stdout, "ogr_dsn=%s\n",
                Vect_get_finfo_dsn_name(Map));
        fprintf(stdout, "feature_type=%s\n",
                Vect_get_finfo_geometry_type(Map));

    }
    else if (map_type == GV_FORMAT_POSTGIS) {
        int topo_format;
        char *toposchema_name, *topogeom_column;
        const struct Format_info *finfo;

        finfo = Vect_get_finfo(Map);
        
        fprintf(stdout, "format=%s,%s\n",
                Vect_maptype_info(Map), Vect_get_finfo_format_info(Map));
        fprintf(stdout, "pg_table=%s\n",
                Vect_get_finfo_layer_name(Map));
        fprintf(stdout, "pg_dbname=%s\n",
                Vect_get_finfo_dsn_name(Map));
        fprintf(stdout, "geometry_column=%s\n",
                finfo->pg.geom_column);
        fprintf(stdout, "feature_type=%s\n",
                Vect_get_finfo_geometry_type(Map));
        topo_format = Vect_get_finfo_topology_info(Map, &toposchema_name, &topogeom_column, NULL);
        if (topo_format == GV_TOPO_POSTGIS) {
            fprintf(stdout, "pg_topo_schema=%s\n",
                    toposchema_name);
            fprintf(stdout, "pg_topo_column=%s\n",
                    topogeom_column);
        }
    }
    else {
        fprintf(stdout, "format=%s\n",
                Vect_maptype_info(Map));
    }

    fprintf(stdout, "level=%d\n", 
            Vect_level(Map));
    
    if (Vect_level(Map) > 0) {
        fprintf(stdout, "num_dblinks=%d\n",
                Vect_get_num_dblinks(Map));

        if (Vect_get_num_dblinks(Map) > 0) {
            fi = Vect_get_field2(Map, field_opt);
            if(fi != NULL) {
                fprintf(stdout, "attribute_layer_number=%i\n",fi->number);
                fprintf(stdout, "attribute_layer_name=%s\n",fi->name);
                fprintf(stdout, "attribute_database=%s\n",fi->database);
                fprintf(stdout, "attribute_database_driver=%s\n",fi->driver);
                fprintf(stdout, "attribute_table=%s\n",fi->table);
                fprintf(stdout, "attribute_primary_key=%s\n",fi->key);
            }
        }
    }

    fprintf(stdout, "projection=%s\n",
            Vect_get_proj_name(Map));
    if (G_projection() == PROJECTION_UTM) {
        fprintf(stdout, "zone=%d\n",
                Vect_get_zone(Map));
    }
    fprintf(stdout, "digitization_threshold=%f\n",
            Vect_get_thresh(Map));
    fprintf(stdout, "comment=%s\n",
            Vect_get_comment(Map));
}
Exemplo n.º 21
0
/* create the actual report */
void do_report_CELL ( char *map, char *mapset, char *sites,
					int precision, int null_flag, int uncat_flag,
					int all_flag, int quiet_flag, int skip_flag,
				  	char *logfile, int background, int gain, int show_progress) {
    	CELL *cellbuf;
	struct Cell_head region;
	GT_Row_cache_t *cache;
	unsigned long row_idx, col_idx;	
	int fd;
	unsigned long i,j,k;
	unsigned long no_sites;
	FILE *lp;	
	unsigned long nrows, ncols;
	unsigned long *share_smp = NULL; /* array that keeps percentage of sites */
	double total = 0;
	double map_total = 0;
	double kvamme_gain;
	long null_count = 0; /* keeps count of sites on NULL cells */
	long nocat_count = 0;
	/* category counts and descriptions */
	int cats;
	char **cats_description; /* category labels */
	long *cat_count; /* category counts */
	long null_count_map; /* number of NULL cells in input map */
	long nocat_count_map; /* number of cells that do not fall into the category range [0 .. n] */		
	int debug_mode = 0;		/* 1 to enable writing additional output to logfile */
	time_t systime;

	char errmsg [200];
	struct Map_info in_vect_map;
  	struct line_pnts *vect_points;
	double x,y,z;
	int n_points = 1;
	int cur_type;
	

	/* get current region */
	G_get_window (&region);
	nrows = G_window_rows ();
	ncols = G_window_cols ();	
	
	/* check logfile */
	if (logfile != NULL) {
		debug_mode = 1;	
		if ( !G_legal_filename (logfile) ) {
			delete_tmpfile (map);
			G_fatal_error ("Please specify a legal filename for the logfile.\n");
		}
		/* attempt to write to logfile */
		if ( (lp = fopen ( logfile, "w+" ) ) == NULL )	{
			delete_tmpfile (map);
			G_fatal_error ("Could not create logfile.\n");
		}
		/* we want unbuffered output for the logfile */
		setvbuf (lp,NULL,_IONBF,0);	
		fprintf (lp,"This is %s, version %.2f\n",PROGNAME, PROGVERSION);
		systime = time (NULL);
		fprintf (lp,"Started on %s",ctime(&systime));
		fprintf (lp,"\tlocation    = %s\n",G_location());
		fprintf (lp,"\tmapset      = %s\n",G_mapset());
		fprintf (lp,"\tinput map   = %s\n",map);
		fprintf (lp,"\tsample file = %s\n",sites);
	} else {		
		/* log output to stderr by default */
		lp = stderr;
	}

  	if (1 > Vect_open_old (&in_vect_map, sites, "")) {
		delete_tmpfile (map);
    		sprintf (errmsg, "Could not open input map %s.\n", sites);
    		G_fatal_error (errmsg);
  	}

	vect_points = Vect_new_line_struct ();

	if (all_flag != 1) {
		Vect_set_constraint_region (&in_vect_map, region.north, region.south, 
			region.east, region.west, 0.0, 0.0);
	}
		
	/* get total number of sampling points */
	i = 0;	
	while ((cur_type = Vect_read_next_line (&in_vect_map, vect_points, NULL) > 0)) {
		i ++;
	}

	no_sites = i; /* store this for later use */
			
	/* open raster map */
	fd = G_open_cell_old (map, G_find_cell (map, ""));
	if (fd < 0)
	{
		delete_tmpfile (map);
		G_fatal_error ("Could not open raster map for reading!\n");
	}
	/* allocate a cache and a raster buffer */
	cache = (GT_Row_cache_t *) G_malloc (sizeof (GT_Row_cache_t));
	GT_RC_open (cache, CACHESIZE, fd, CELL_TYPE);
	cellbuf = G_allocate_raster_buf (CELL_TYPE);			
	
	cats = GT_get_stats (map,mapset,&null_count_map, &nocat_count_map, show_progress);
	if ( cats < 2 ) {
		delete_tmpfile (map);
		G_fatal_error ("Input map must have at least two categories.");
	}
	
	/* get category labels and counts */
	cats_description = GT_get_labels (map,mapset);
	if (cats_description == NULL) {
		delete_tmpfile (map);
		G_fatal_error ("Could not read category labels from input map.");
	}
	cat_count = GT_get_c_counts (map,mapset, show_progress);
	if (cat_count == NULL) {
		delete_tmpfile (map);
		G_fatal_error ("Could not count categories in input map.");
	}		
	
	/* allocate a double array to hold statistics */
	share_smp = (unsigned long *) G_malloc ((signed)(cats * sizeof (unsigned long)));
	for (i = 0; i < cats; i++)
	{
		share_smp[i] = 0;
		
	}	
	
	/* count raster values under sampling points */
	i = 0;
	k = 0; /* progress counter for status display */
	
	Vect_rewind (&in_vect_map);	
	
	if ( !quiet_flag ) {
		fprintf (stdout, "Counting sample: \n");
		fflush (stdout);	
	}
	
	/* we MUST not set constraints so that no raster values outside the current region are
	   accessed, which would give an "illegal cache request" error */
	Vect_set_constraint_region (&in_vect_map, region.north, region.south, 
				     region.east, region.west, 0.0, 0.0);
	
	while ((cur_type = Vect_read_next_line (&in_vect_map, vect_points, NULL) > 0)) {	
		Vect_copy_pnts_to_xyz (vect_points, &x, &y, &z, &n_points);		
		k ++;
		if ( !quiet_flag ) {
			G_percent ((signed) k, (signed) no_sites, 1);
		}
		/* get raster row with same northing as sample and perform
		   quantification */
		row_idx = (long) G_northing_to_row (y, &region);
		col_idx = (long) G_easting_to_col (x, &region);				
				
		cellbuf = GT_RC_get (cache, (signed) row_idx);
		/* now read the raster value under the current site */
		if (G_is_c_null_value (&cellbuf[col_idx]) == 0) {
			/* site on cell within category range [0..cats] ? */
			if ( (cellbuf[col_idx] > -1) && (cellbuf[col_idx] <= cats) ) {
				share_smp [cellbuf[col_idx] ] ++;
				/* i keeps track of samples on non-null coverage only */
				/* inside the current region */
				i ++;
			} else {
				if ( uncat_flag ) {
					/* also keep count of sites on uncategorised cells? */
					i ++;
					nocat_count++;
				}
			}				
		}
		if (G_is_c_null_value (&cellbuf[col_idx]) == 1) { 
			/* got a NULL value under this site */
			if (null_flag) { /* only count this, if null flag is set */
				null_count ++;
				i ++;
			}
		}
	}
	
	Vect_close (&in_vect_map);		
	
	fprintf (lp,"\n");
	if ( background ) {
		fprintf (lp,"Distribution of categories under %lu points (%lu in region) and in input map:\n",i,no_sites);	
	} else {
		fprintf (lp,"Distribution of categories under %lu points (%lu in region):\n",i,no_sites);	
	}
	/* determine starting value for total of sites analysed */
	total = 0;
	for ( j=0; j < cats; j ++) {
		total = total + share_smp[j];
		map_total = map_total + cat_count[j];
	}
	if (null_flag) { /* add NULL values to total */	
		total = total + null_count;
		map_total = map_total + null_count_map;
	}
	if (uncat_flag) { /* add uncategorised cells to total */
		total = total + nocat_count;
		map_total = map_total + nocat_count_map;
		
	}
	
	/* Now display those values which the user has chosen */
	if ( (background) && (gain) ) {	
		fprintf (lp,"Cat.\tPts.\t(%%)\tMap\t(%%)\tGain\tDescription\n");				
	}
	if ( (background) && (!gain) ) {	
		fprintf (lp,"Cat.\tPts.\t(%%)\tMap\t(%%)\tDescription\n");		
	}
	if ( (!background) && (gain) ) {	
		fprintf (lp,"Cat.\tPts.\t(%%)\tGain\tDescription\n");
	}
	if ( (!background) && (!gain) ) {	
		fprintf (lp,"Cat.\tPts.\t(%%)\tDescription\n");
	}	
	for ( j = 0; j < cats; j ++) {
		/* if skip_flag is not set: only show categories that have count > 0 */
		if ((skip_flag == 1) || ((skip_flag == 0) && (share_smp[j] > 0))) {
			if ( (background) && (gain) ) {
				/* Kvamme's Gain = 1 - (%area/%sites) */
				kvamme_gain = gstats_gain_K(((double) share_smp[j]*(100/total)),
							    ((double) cat_count[j]*(100/map_total)));							    				
				fprintf (lp, "%lu\t%6lu\t%6.2f\t%8lu %6.2f\t%6.2f\t%s\n", j, share_smp[j], (float) share_smp[j]*(100/total),
						cat_count[j], (float) cat_count[j]*(100/map_total),
						kvamme_gain, cats_description[j]);
			} 
			if ( (background) && (!gain) ) {
				fprintf (lp, "%lu\t%6lu\t%6.2f\t%8lu %6.2f\t%s\n", j, share_smp[j], (float) share_smp[j]*(100/total),
						cat_count[j], (float) cat_count[j]*(100/map_total),
						cats_description[j]);
				
			} 			
			if ( (!background) && (gain) ) {
				kvamme_gain = 1-( (float) cat_count[j]*(100/map_total) / (float) share_smp[j]*(100/total) );
				fprintf (lp, "%lu\t%6lu\t%6.2f\t%6.2f\t%s\n", j, share_smp[j], (float) share_smp[j]*(100/total),						
						kvamme_gain, cats_description[j]);				
			} 			
			if ( (!background) && (!gain) ) {
				fprintf (lp, "%lu\t%6lu\t%6.2f\t%s\n", j, share_smp[j], (float) share_smp[j]*(100/total),
						cats_description[j]);
			} 									
		}
	}
	if (null_flag) {		
		if ( background ) {
			fprintf (lp,"NULL\t%6lu\t%6.2f\t%8lu %6.2f\n",null_count, (float) null_count * 100 / total
						,null_count_map, (float) null_count_map * 100 / map_total);
		} else {
			fprintf (lp,"NULL\t%6lu\t%6.2f\n",null_count, (float) null_count * 100 / total);
		}
	}
	if (uncat_flag) {
		if ( background ) {
			fprintf (lp,"NOCAT\t%6lu\t%6.2f\t%8lu %6.2f\n",nocat_count, (float) nocat_count * 100 / total
						,nocat_count_map, (float) nocat_count_map * 100 / map_total);
		} else {
			fprintf (lp,"NOCAT\t%6lu\t%6.2f\n",nocat_count, (float) nocat_count * 100 / total);
		}		
	}	
	if ( background) {
		fprintf (lp,"TOTAL\t%6lu\t%6.2f\t%8lu %6.2f\n",(long) total, (float) 100, (long) map_total, (float) 100);
	} else {
		fprintf (lp,"TOTAL\t%6lu\t%6.2f\n",(long) total, (float) 100);
	}
	
	/* close cache and sites file; free buffers. */
	GT_RC_close (cache);
	G_free (cellbuf);
	G_free (cache);	
}
Exemplo n.º 22
0
int main(int argc, char *argv[])
{
    int i, type, stat;
    int day, yr, Out_proj;
    int out_zone = 0;
    int overwrite;		/* overwrite output map */
    const char *mapset;
    const char *omap_name, *map_name, *iset_name, *iloc_name;
    struct pj_info info_in;
    struct pj_info info_out;
    const char *gbase;
    char date[40], mon[4];
    struct GModule *module;
    struct Option *omapopt, *mapopt, *isetopt, *ilocopt, *ibaseopt, *smax;
    struct Key_Value *in_proj_keys, *in_unit_keys;
    struct Key_Value *out_proj_keys, *out_unit_keys;
    struct line_pnts *Points, *Points2;
    struct line_cats *Cats;
    struct Map_info Map;
    struct Map_info Out_Map;
    struct bound_box src_box, tgt_box;
    int nowrap = 0, recommend_nowrap = 0;
    double lmax;
    struct
    {
	struct Flag *list;	/* list files in source location */
	struct Flag *transformz;	/* treat z as ellipsoidal height */
	struct Flag *wrap;		/* latlon output: wrap to 0,360 */
	struct Flag *no_topol;		/* do not build topology */
    } flag;

    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("vector"));
    G_add_keyword(_("projection"));
    G_add_keyword(_("transformation"));
    G_add_keyword(_("import"));
    module->description = _("Re-projects a vector map from one location to the current location.");

    /* set up the options and flags for the command line parser */

    ilocopt = G_define_standard_option(G_OPT_M_LOCATION);
    ilocopt->required = YES;
    ilocopt->label = _("Location containing input vector map");
    ilocopt->guisection = _("Source");
    
    isetopt = G_define_standard_option(G_OPT_M_MAPSET);
    isetopt->label = _("Mapset containing input vector map");
    isetopt->description = _("Default: name of current mapset");
    isetopt->guisection = _("Source");

    mapopt = G_define_standard_option(G_OPT_V_INPUT);
    mapopt->required = NO;
    mapopt->label = _("Name of input vector map to re-project");
    mapopt->description = NULL;
    mapopt->guisection = _("Source");
    
    ibaseopt = G_define_standard_option(G_OPT_M_DBASE);
    ibaseopt->label = _("Path to GRASS database of input location");
    
    smax = G_define_option();
    smax->key = "smax";
    smax->type = TYPE_DOUBLE;
    smax->required = NO;
    smax->answer = "10000";
    smax->label = _("Maximum segment length in meters in output vector map");
    smax->description = _("Increases accuracy of reprojected shapes, disable with smax=0");
    smax->guisection = _("Target");

    omapopt = G_define_standard_option(G_OPT_V_OUTPUT);
    omapopt->required = NO;
    omapopt->description = _("Name for output vector map (default: input)");
    omapopt->guisection = _("Target");

    flag.list = G_define_flag();
    flag.list->key = 'l';
    flag.list->description = _("List vector maps in input mapset and exit");

    flag.transformz = G_define_flag();
    flag.transformz->key = 'z';
    flag.transformz->description = _("3D vector maps only");
    flag.transformz->label =
	_("Assume z coordinate is ellipsoidal height and "
	  "transform if possible");
    flag.transformz->guisection = _("Target");

    flag.wrap = G_define_flag();
    flag.wrap->key = 'w';
    flag.wrap->description = _("Latlon output only, default is -180,180");
    flag.wrap->label =
	_("Disable wrapping to -180,180 for latlon output");
    flag.transformz->guisection = _("Target");

    flag.no_topol = G_define_flag();
    flag.no_topol->key = 'b';
    flag.no_topol->label = _("Do not build vector topology");
    flag.no_topol->description = _("Recommended for massive point projection");

    /* The parser checks if the map already exists in current mapset,
       we switch out the check and do it
       in the module after the parser */
    overwrite = G_check_overwrite(argc, argv);

    if (G_parser(argc, argv))
	exit(EXIT_FAILURE);

    /* start checking options and flags */
    /* set input vector map name and mapset */
    map_name = mapopt->answer;
    if (omapopt->answer)
	omap_name = omapopt->answer;
    else
	omap_name = map_name;
    if (omap_name && !flag.list->answer && !overwrite &&
	G_find_vector2(omap_name, G_mapset()))
	G_fatal_error(_("option <%s>: <%s> exists. To overwrite, use the --overwrite flag"), omapopt->key,
		      omap_name);
    if (isetopt->answer)
	iset_name = isetopt->answer;
    else
	iset_name = G_store(G_mapset());

    iloc_name = ilocopt->answer;

    if (ibaseopt->answer)
	gbase = ibaseopt->answer;
    else
	gbase = G_store(G_gisdbase());

    if (!ibaseopt->answer && strcmp(iloc_name, G_location()) == 0)
	G_fatal_error(_("Input and output locations can not be the same"));

    lmax = atof(smax->answer);
    if (lmax < 0)
	lmax = 0;

    Out_proj = G_projection();
    if (Out_proj == PROJECTION_LL && flag.wrap->answer)
	nowrap = 1;
    
    G_begin_distance_calculations();

    /* Change the location here and then come back */

    select_target_env();
    G_setenv_nogisrc("GISDBASE", gbase);
    G_setenv_nogisrc("LOCATION_NAME", iloc_name);
    stat = G_mapset_permissions(iset_name);
    
    if (stat >= 0) {		/* yes, we can access the mapset */
	/* if requested, list the vector maps in source location - MN 5/2001 */
	if (flag.list->answer) {
	    int i;
	    char **list;
	    G_verbose_message(_("Checking location <%s> mapset <%s>"),
			      iloc_name, iset_name);
	    list = G_list(G_ELEMENT_VECTOR, G_getenv_nofatal("GISDBASE"),
			  G_getenv_nofatal("LOCATION_NAME"), iset_name);
	    if (list[0]) {
		for (i = 0; list[i]; i++) {
		    fprintf(stdout, "%s\n", list[i]);
		}
		fflush(stdout);
	    }
	    else {
		G_important_message(_("No vector maps found"));
	    }
	    exit(EXIT_SUCCESS);	/* leave v.proj after listing */
	}

	if (mapopt->answer == NULL) {
	    G_fatal_error(_("Required parameter <%s> not set"), mapopt->key);
	}

	G_setenv_nogisrc("MAPSET", iset_name);
	/* Make sure map is available */
	mapset = G_find_vector2(map_name, iset_name);
	if (mapset == NULL)
	    G_fatal_error(_("Vector map <%s> in location <%s> mapset <%s> not found"),
			  map_name, iloc_name, iset_name);

	 /*** Get projection info for input mapset ***/
	in_proj_keys = G_get_projinfo();
	if (in_proj_keys == NULL)
	    exit(EXIT_FAILURE);

	/* apparently the +over switch must be set in the input projection,
	 * not the output latlon projection */
	if (Out_proj == PROJECTION_LL && nowrap == 1)
	    G_set_key_value("+over", "defined", in_proj_keys);

	in_unit_keys = G_get_projunits();
	if (in_unit_keys == NULL)
	    exit(EXIT_FAILURE);

	if (pj_get_kv(&info_in, in_proj_keys, in_unit_keys) < 0)
	    exit(EXIT_FAILURE);

	Vect_set_open_level(1);
	G_debug(1, "Open old: location: %s mapset : %s", G_location_path(),
		G_mapset());
	if (Vect_open_old(&Map, map_name, mapset) < 0)
	    G_fatal_error(_("Unable to open vector map <%s>"), map_name);
    }
    else if (stat < 0)
    {				/* allow 0 (i.e. denied permission) */
	/* need to be able to read from others */
	if (stat == 0)
	    G_fatal_error(_("Mapset <%s> in input location <%s> - permission denied"),
			  iset_name, iloc_name);
	else
	    G_fatal_error(_("Mapset <%s> in input location <%s> not found"),
			  iset_name, iloc_name);
    }

    select_current_env();

    /****** get the output projection parameters ******/
    out_proj_keys = G_get_projinfo();
    if (out_proj_keys == NULL)
	exit(EXIT_FAILURE);

    out_unit_keys = G_get_projunits();
    if (out_unit_keys == NULL)
	exit(EXIT_FAILURE);

    if (pj_get_kv(&info_out, out_proj_keys, out_unit_keys) < 0)
	exit(EXIT_FAILURE);

    G_free_key_value(in_proj_keys);
    G_free_key_value(in_unit_keys);
    G_free_key_value(out_proj_keys);
    G_free_key_value(out_unit_keys);

    if (G_verbose() == G_verbose_max()) {
	pj_print_proj_params(&info_in, &info_out);
    }

    /* Initialize the Point / Cat structure */
    Points = Vect_new_line_struct();
    Points2 = Vect_new_line_struct();
    Cats = Vect_new_cats_struct();

    /* test if latlon wrapping to -180,180 should be disabled */
    if (Out_proj == PROJECTION_LL && nowrap == 0) {
	int first = 1, counter = 0;
	double x, y;
	
	/* Cycle through all lines */
	Vect_rewind(&Map);
	while (1) {
	    type = Vect_read_next_line(&Map, Points, Cats);	/* read line */
	    if (type == 0)
		continue;		/* Dead */

	    if (type == -1)
		G_fatal_error(_("Reading input vector map"));
	    if (type == -2)
		break;
		
	    if (first && Points->n_points > 0) {
		first = 0;
		src_box.E = src_box.W = Points->x[0];
		src_box.N = src_box.S = Points->y[0];
		src_box.T = src_box.B = Points->z[0];
	    }
	    for (i = 0; i < Points->n_points; i++) {
		if (src_box.E < Points->x[i])
		    src_box.E = Points->x[i];
		if (src_box.W > Points->x[i])
		    src_box.W = Points->x[i];
		if (src_box.N < Points->y[i])
		    src_box.N = Points->y[i];
		if (src_box.S > Points->y[i])
		    src_box.S = Points->y[i];
	    }
	    counter++;
	}
	if (counter == 0) {
	    G_warning(_("Input vector map <%s> is empty"), omap_name);
	    exit(EXIT_SUCCESS);
	}
	/* NW corner */
	x = src_box.W;
	y = src_box.N;
	if (pj_do_transform(1, &x, &y, NULL,
			    &info_in, &info_out) < 0) {
	    G_fatal_error(_("Error in pj_do_transform"));
	}
	tgt_box.E = x;
	tgt_box.W = x;
	tgt_box.N = y;
	tgt_box.S = y;
	/* SW corner */
	x = src_box.W;
	y = src_box.S;
	if (pj_do_transform(1, &x, &y, NULL,
			    &info_in, &info_out) < 0) {
	    G_fatal_error(_("Error in pj_do_transform"));
	}
	if (tgt_box.W > x)
	    tgt_box.W = x;
	if (tgt_box.E < x)
	    tgt_box.E = x;
	if (tgt_box.N < y)
	    tgt_box.N = y;
	if (tgt_box.S > y)
	    tgt_box.S = y;
	/* NE corner */
	x = src_box.E;
	y = src_box.N;
	if (pj_do_transform(1, &x, &y, NULL,
			    &info_in, &info_out) < 0) {
	    G_fatal_error(_("Error in pj_do_transform"));
	}
	if (tgt_box.W > x) {
	    tgt_box.E = x + 360;
	    recommend_nowrap = 1;
	}
	if (tgt_box.N < y)
	    tgt_box.N = y;
	if (tgt_box.S > y)
	    tgt_box.S = y;
	/* SE corner */
	x = src_box.E;
	y = src_box.S;
	if (pj_do_transform(1, &x, &y, NULL,
			    &info_in, &info_out) < 0) {
	    G_fatal_error(_("Error in pj_do_transform"));
	}
	if (tgt_box.W > x) {
	    if (tgt_box.E < x + 360)
		tgt_box.E = x + 360;
	    recommend_nowrap = 1;
	}
	if (tgt_box.N < y)
	    tgt_box.N = y;
	if (tgt_box.S > y)
	    tgt_box.S = y;
    }

    G_debug(1, "Open new: location: %s mapset : %s", G_location_path(),
	    G_mapset());

    if (Vect_open_new(&Out_Map, omap_name, Vect_is_3d(&Map)) < 0)
	G_fatal_error(_("Unable to create vector map <%s>"), omap_name);

    Vect_set_error_handler_io(NULL, &Out_Map); /* register standard i/o error handler */
    
    Vect_copy_head_data(&Map, &Out_Map);
    Vect_hist_copy(&Map, &Out_Map);
    Vect_hist_command(&Out_Map);

    out_zone = info_out.zone;
    Vect_set_zone(&Out_Map, out_zone);

    /* Read and write header info */
    sprintf(date, "%s", G_date());
    sscanf(date, "%*s%s%d%*s%d", mon, &day, &yr);
    if (yr < 2000)
	yr = yr - 1900;
    else
	yr = yr - 2000;
    sprintf(date, "%s %d %d", mon, day, yr);
    Vect_set_date(&Out_Map, date);

    /* line densification works only with vector topology */
    if (Map.format != GV_FORMAT_NATIVE)
	lmax = 0;

    /* Cycle through all lines */
    Vect_rewind(&Map);
    i = 0;
    G_message(_("Reprojecting primitives ..."));
    while (TRUE) {
	++i;
	G_progress(i, 1e3);
	type = Vect_read_next_line(&Map, Points, Cats);	/* read line */
	if (type == 0)
	    continue;		/* Dead */

	if (type == -1)
	    G_fatal_error(_("Reading input vector map"));
	if (type == -2)
	    break;

	Vect_line_prune(Points);
	if (lmax > 0 && (type & GV_LINES) && Points->n_points > 1) {
	    double x1, y1, z1, x2, y2, z2;
	    double dx, dy, dz;
	    double l;
	    int i, n;

	    Vect_reset_line(Points2);
	    for (i = 0; i < Points->n_points - 1; i++) {
		x1 = Points->x[i];
		y1 = Points->y[i];
		z1 = Points->z[i];
		n = i + 1;
		x2 = Points->x[n];
		y2 = Points->y[n];
		z2 = Points->z[n];

		dx = x2 - x1;
		dy = y2 - y1;
		dz = z2 - z1;

		if (pj_do_transform(1, &x1, &y1,
				    flag.transformz->answer ? &z1 : NULL,
				    &info_in, &info_out) < 0) {
		  G_fatal_error(_("Unable to re-project vector map <%s> from <%s>"),
				Vect_get_full_name(&Map), ilocopt->answer);
		}

		if (pj_do_transform(1, &x2, &y2,
				    flag.transformz->answer ? &z2 : NULL,
				    &info_in, &info_out) < 0) {
		  G_fatal_error(_("Unable to re-project vector map <%s> from <%s>"),
				Vect_get_full_name(&Map), ilocopt->answer);
		}

		Vect_append_point(Points2, x1, y1, z1);

		l = G_distance(x1, y1, x2, y2);

		if (l > lmax) {
		    int j;
		    double x, y, z;

		    x1 = Points->x[i];
		    y1 = Points->y[i];
		    z1 = Points->z[i];

		    n = ceil(l / lmax);

		    for (j = 1; j < n; j++) {
			x = x1 + dx * j / n;
			y = y1 + dy * j / n;
			z = z1 + dz * j / n;

			if (pj_do_transform(1, &x, &y,
					    flag.transformz->answer ? &z : NULL,
					    &info_in, &info_out) < 0) {
			  G_fatal_error(_("Unable to re-project vector map <%s> from <%s>"),
					Vect_get_full_name(&Map), ilocopt->answer);
			}
			Vect_append_point(Points2, x, y, z);
		    }
		}
	    }
	    Vect_append_point(Points2, x2, y2, z2);
	    Vect_write_line(&Out_Map, type, Points2, Cats);	/* write line */
	}
	else {
	    if (pj_do_transform(Points->n_points, Points->x, Points->y,
				flag.transformz->answer ? Points->z : NULL,
				&info_in, &info_out) < 0) {
	      G_fatal_error(_("Unable to re-project vector map <%s> from <%s>"),
			    Vect_get_full_name(&Map), ilocopt->answer);
	    }

	    Vect_write_line(&Out_Map, type, Points, Cats);	/* write line */
	}
    }				/* end lines section */
    G_progress(1, 1);

    /* Copy tables */
    if (Vect_copy_tables(&Map, &Out_Map, 0))
        G_warning(_("Failed to copy attribute table to output map"));

    Vect_close(&Map);

    if (!flag.no_topol->answer)
        Vect_build(&Out_Map);
    Vect_close(&Out_Map);

    if (recommend_nowrap)
	G_important_message(_("Try to disable wrapping to -180,180 "
			      "if topological errors occurred"));

    exit(EXIT_SUCCESS);
}
Exemplo n.º 23
0
int main( int argc, char *argv[] )
{
	Shypothesis **samples; /* Data to be combined */
	unsigned int i;
	FILE *kb;
	char **groups;
	int norm = 1; /* turn on normalisation of evidence by default */
	/* these are for time keeping in the logfile */	
	time_t systime;
	clock_t proctime;
	unsigned long timeused;
	unsigned int days, hours, mins, secs;
	
	xmlDocPtr dstXMLFile;
	Sfp_struct* file_pointers;	
	
	G_gisinit ( argv[0] );		
	
	module = G_define_module ();
	module->description = "Combines evidences from a DST knowledge base";
		
	parm.file = G_define_option ();
	parm.file->key = "file";
	parm.file->type = TYPE_STRING;
	parm.file->required = YES;
	parm.file->description = "Name of the knowledge base that contains the evidence";
	
	parm.groups = G_define_option ();
	parm.groups->key = "sources";
	parm.groups->type = TYPE_STRING;
	parm.groups->required = NO;
	parm.groups->multiple = YES;
	parm.groups->description = "Evidences to be combined (default: all)";
			
	parm.type = G_define_option ();
	parm.type->key = "type";
	parm.type->type = TYPE_STRING;
	parm.type->required = NO;
	parm.type->options = "const,rast,vect";
	parm.type->answer = "rast";
	parm.type->description = "Type(s) of evidences to combine";	
	
	parm.output = G_define_option ();
	parm.output->key = "output";
	parm.output->type = TYPE_STRING;
	parm.output->required = NO;
	parm.output->answer = G_location ();
	parm.output->description = "Prefix for result maps (dflt: location name)";

	parm.vals = G_define_option ();
	parm.vals->key = "values";
	parm.vals->type = TYPE_STRING;
	parm.vals->required = NO;
	parm.vals->multiple = YES;
	parm.vals->options = "bel,pl,doubt,common,bint,woc,maxbpa,minbpa,maxsrc,minsrc";
	parm.vals->answer = "bel";
	parm.vals->description = "Dempster-Shafer values to map";

	parm.hyps = G_define_option ();
	parm.hyps->key = "hypotheses";
	parm.hyps->type = TYPE_STRING;
	parm.hyps->required = NO;
	parm.hyps->multiple = NO;
	parm.hyps->description = "Hypotheses to map (default: all)";

	parm.logfile = G_define_option ();
	parm.logfile->key = "logfile";
	parm.logfile->type = TYPE_STRING;
	parm.logfile->required = NO;
	parm.logfile->description = "Name of logfile";

	/* TODO: not implemented yet
	parm.warnings = G_define_option ();
	parm.warnings->key = "warnings";
	parm.warnings->type = TYPE_STRING;
	parm.warnings->required = NO;
	parm.warnings->description = "Name of site list to store locations of warnings." ;
	*/

	flag.norm = G_define_flag ();
	flag.norm->key = 'n';
	flag.norm->description = "Turn off normalisation";

	flag.quiet = G_define_flag ();
	flag.quiet->key = 'q';
	flag.quiet->description = "Quiet operation: no progress diplay";

	/* append output to existing logfile ? */
	flag.append = G_define_flag ();
	flag.append->key = 'a';
	flag.append->description = "Append log output to existing file";
	
	no_assigns = 0;
	
	/* INIT GLOBAL VARS */
	WOC_MIN = 0;
	WOC_MAX = 0;
	
	/* do not pause after a warning message was displayed */
	G_sleep_on_error (0);
	
	/* parse command line */
	if (G_parser (argc, argv))
	{
		exit (-1);
	}			
	
	/* check if given parameters are valid */
	if (G_legal_filename (parm.file->answer) == -1) {
		G_fatal_error ("Please provide the name of an existing DST knowledge base.\n");
	}
	
	if (G_find_file ("DST",parm.file->answer,G_mapset()) == NULL) {
		G_fatal_error ("Knowledge base does not exist in user's MAPSET!\n");
	}
	
	/* check logfile */
	if (parm.logfile->answer != NULL) {		
		if ( !G_legal_filename (parm.logfile->answer) ) {
			G_fatal_error ("Please specify a legal filename for the logfile.\n");
		}
		/* attempt to write to logfile */
		if (flag.append->answer) {
			if (fopen (parm.logfile->answer, "r") == NULL) {
				lp = fopen (parm.logfile->answer, "w+");
				if (lp == NULL) {
					G_fatal_error ("Logfile error: %s\n", strerror (errno));
				}				
			} else {
				lp = fopen (parm.logfile->answer, "a");
				if (lp == NULL) {
					G_fatal_error ("Logfile error: %s\n", strerror (errno));
				}
				fprintf (lp,"\n\n * * * * * \n\n");
			}
		} else {
			if ( (lp = fopen ( parm.logfile->answer, "w+" ) ) == NULL ) {
				G_fatal_error ("Logfile error: %s\n", strerror (errno));
			}
		}
		/* we want unbuffered output for the logfile */
		setvbuf (lp,NULL,_IONBF,0);
	} else {		
		/* log output to stderr by default */
		lp = stderr;
	}
		
	/* setup coordinate file storage, if desired */
	/* try to create a sites file to store coordinates */
	/* set 'warn' to point to the user-defined sites file */	
	/*
	warn = NULL;
	if ( parm.warnings != NULL ) {
	}
	*/
			
	/* check if we have read/write access to knowledge base */
	kb = G_fopen_old ("DST",parm.file->answer,G_mapset());
	if ( kb == NULL ) {
		G_fatal_error ("Cannot open knowledge base file for reading and writing!\n");
	}
	fclose(kb);
	
	/* start logfile */
	if ( parm.logfile->answer != NULL) {
		fprintf (lp,"This is %s, version %.2f\n",argv[0],PROGVERSION);
		systime = time (NULL);
		fprintf (lp,"Calculation started on %s\n",ctime(&systime));
	}		
		
	/* open DST file and get basic evidence group information */
	dstXMLFile = stat_XML ( parm.file->answer, &NO_SINGLETONS, &N );
	groups = get_groups_XML ( N, dstXMLFile );
	
	if ( NO_SINGLETONS == 1 ) {
		G_fatal_error ("Knowledge base does not contain any user-supplied hypotheses.\n");
	}

	if ( parm.groups->answer != NULL ) {
		/* user specified a subset of groups */
		N = check_groups ( groups );
	}
		
	if ( N < 2 ) {
		G_fatal_error ("At least two groups of evidences must be present in the knowledge base.\n");
	}				

	/* allocate memory for all samples 
	 a sample holds one double for bel, pl and bpn for each
	 piece of evidence. The number of pieces of evidence is
	 the number of possible subsets in Theta 
	 = 2^NO_SINGLETONS ! 
	
	 The number of samples is = number of groups in the XML
	 knowledge base file (N) !
	*/
	samples = (Shypothesis**) G_malloc ((N * sizeof(Shypothesis*)));
	for ( i=0; i < N; i ++ ) {
		samples[i] = (Shypothesis*) G_malloc (sizeof(Shypothesis));
	}
	
	
	/* turn off normalisation if user wants it so */
	if ( flag.norm->answer == 1 ) {
		norm = 0;
	}	
			
	/* do some type-dependant checking */
	/* and open file pointers for all the maps to read! */
	file_pointers = NULL;
	if ( !strcmp (parm.type->answer,"rast") ) {
		if ( parm.groups->answer != NULL ) {
			/* check only user-specified groups */
			file_pointers = test_rast_XML ( parm.groups->answers, dstXMLFile );			
		} else {
			/* check all groups */
			file_pointers = test_rast_XML ( groups, dstXMLFile );
		}
	}	
	
	/* read in all samples in a type-dependant manner */
	if ( parm.groups->answer != NULL ) {
		/* read only user-specified groups */
		if ( !strcmp (parm.type->answer,"const") ) {
			if ( strcmp (parm.output->answer,G_location ()) != 0) {
				G_warning ("Ignoring parameter 'output='.\n");
			}
			if ( strcmp (parm.vals->answer,"bel") !=0 ) {
				G_warning ("Ignoring parameter 'values='.\n");
			}
			if ( parm.hyps->answer != NULL ) {
				G_warning ("Ignoring parameter 'hypotheses='.\n");
			}
			do_calculations_const (samples,parm.groups->answers, norm, dstXMLFile);
		}
		if ( !strcmp (parm.type->answer,"rast") ) {
			do_calculations_rast (samples,parm.groups->answers, norm,
								  parm.output->answer, parm.vals->answers, 
								  parm.hyps->answer, flag.quiet->answer,
							      parm.logfile->answer, dstXMLFile, file_pointers );
		}			
	} else {
		/* read all groups */
		if ( !strcmp (parm.type->answer,"const") ) {
			if ( strcmp (parm.output->answer,G_location ()) != 0) {
				G_warning ("Ignoring parameter 'output='.\n");
			}
			if ( strcmp (parm.vals->answer,"bel") !=0 ) {
				G_warning ("Ignoring parameter 'values='.\n");
			}
			if ( parm.hyps->answer != NULL ) {
				G_warning ("Ignoring parameter 'hypotheses='.\n");
			}
			do_calculations_const (samples,groups, norm, dstXMLFile);
		}
		if ( !strcmp (parm.type->answer,"rast") ) {
			do_calculations_rast (samples,groups, norm,
								  parm.output->answer, parm.vals->answers, 
							      parm.hyps->answer, flag.quiet->answer,
								  parm.logfile->answer, dstXMLFile, file_pointers );
		}			
	}	
		
	/* close logfile */
	/* write processing time to logfile */
	proctime = clock ();
	timeused = (unsigned long) proctime / CLOCKS_PER_SEC;
	days = timeused / 86400;
	hours = (timeused - (days * 86400)) / 3600;
	mins = (timeused - (days * 86400) - (hours * 3600)) / 60;		
	secs = (timeused - (days * 86400) - (hours * 3600) - (mins * 60));
	systime = time (NULL);
	
	if ( parm.logfile->answer != NULL ) {
		fprintf (lp,"\nCalculation finished on %s",ctime(&systime));		
		fprintf (lp,"Processing time: %id, %ih, %im, %is\n",
				days, hours, mins, secs );
		fflush (lp);
	}
	
	for (i=0; i<N; i++) {
		G_free (groups[i]);		
	}
	G_free (groups);
	
	return (EXIT_SUCCESS);
}
Exemplo n.º 24
0
int main(int argc, char **argv)
{
    char *mapname,		/* ptr to name of output layer  */
     *setname,			/* ptr to name of input mapset  */
     *ipolname;			/* name of interpolation method */

    int fdi,			/* input map file descriptor    */
      fdo,			/* output map file descriptor   */
      method,			/* position of method in table  */
      permissions,		/* mapset permissions           */
      cell_type,		/* output celltype              */
      cell_size,		/* size of a cell in bytes      */
      row, col,			/* counters                     */
      irows, icols,		/* original rows, cols          */
      orows, ocols, have_colors,	/* Input map has a colour table */
      overwrite,		/* Overwrite                    */
      curr_proj;		/* output projection (see gis.h) */

    void *obuffer,		/* buffer that holds one output row     */
     *obufptr;			/* column ptr in output buffer  */
    struct cache *ibuffer;	/* buffer that holds the input map      */
    func interpolate;		/* interpolation routine        */

    double xcoord1, xcoord2,	/* temporary x coordinates      */
      ycoord1, ycoord2,		/* temporary y coordinates      */
      col_idx,			/* column index in input matrix */
      row_idx,			/* row index in input matrix    */
      onorth, osouth,		/* save original border coords  */
      oeast, owest, inorth, isouth, ieast, iwest;
    char north_str[30], south_str[30], east_str[30], west_str[30];

    struct Colors colr;		/* Input map colour table       */
    struct History history;

    struct pj_info iproj,	/* input map proj parameters    */
      oproj;			/* output map proj parameters   */

    struct Key_Value *in_proj_info,	/* projection information of    */
     *in_unit_info,		/* input and output mapsets     */
     *out_proj_info, *out_unit_info;

    struct GModule *module;

    struct Flag *list,		/* list files in source location */
     *nocrop,			/* don't crop output map        */
     *print_bounds,		/* print output bounds and exit */
     *gprint_bounds;		/* same but print shell style	*/

    struct Option *imapset,	/* name of input mapset         */
     *inmap,			/* name of input layer          */
     *inlocation,		/* name of input location       */
     *outmap,			/* name of output layer         */
     *indbase,			/* name of input database       */
     *interpol,			/* interpolation method:
				   nearest neighbor, bilinear, cubic */
     *memory,			/* amount of memory for cache   */
     *res;			/* resolution of target map     */
    struct Cell_head incellhd,	/* cell header of input map     */
      outcellhd;		/* and output map               */


    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("raster"));
    G_add_keyword(_("projection"));
    G_add_keyword(_("transformation"));
    module->description =
	_("Re-projects a raster map from given location to the current location.");

    inmap = G_define_standard_option(G_OPT_R_INPUT);
    inmap->description = _("Name of input raster map to re-project");
    inmap->required = NO;
    inmap->guisection = _("Source");

    inlocation = G_define_option();
    inlocation->key = "location";
    inlocation->type = TYPE_STRING;
    inlocation->required = YES;
    inlocation->description = _("Location containing input raster map");
    inlocation->gisprompt = "old,location,location";
    inlocation->key_desc = "name";

    imapset = G_define_standard_option(G_OPT_M_MAPSET);
    imapset->label = _("Mapset containing input raster map");
    imapset->description = _("default: name of current mapset");
    imapset->guisection = _("Source");

    indbase = G_define_option();
    indbase->key = "dbase";
    indbase->type = TYPE_STRING;
    indbase->required = NO;
    indbase->description = _("Path to GRASS database of input location");
    indbase->gisprompt = "old,dbase,dbase";
    indbase->key_desc = "path";
    indbase->guisection = _("Source");

    outmap = G_define_standard_option(G_OPT_R_OUTPUT);
    outmap->required = NO;
    outmap->description = _("Name for output raster map (default: same as 'input')");
    outmap->guisection = _("Target");

    ipolname = make_ipol_list();
    
    interpol = G_define_option();
    interpol->key = "method";
    interpol->type = TYPE_STRING;
    interpol->required = NO;
    interpol->answer = "nearest";
    interpol->options = ipolname;
    interpol->description = _("Interpolation method to use");
    interpol->guisection = _("Target");
    interpol->descriptions = make_ipol_desc();

    memory = G_define_option();
    memory->key = "memory";
    memory->type = TYPE_INTEGER;
    memory->required = NO;
    memory->description = _("Cache size (MiB)");

    res = G_define_option();
    res->key = "resolution";
    res->type = TYPE_DOUBLE;
    res->required = NO;
    res->description = _("Resolution of output raster map");
    res->guisection = _("Target");

    list = G_define_flag();
    list->key = 'l';
    list->description = _("List raster maps in input location and exit");

    nocrop = G_define_flag();
    nocrop->key = 'n';
    nocrop->description = _("Do not perform region cropping optimization");

    print_bounds = G_define_flag();
    print_bounds->key = 'p';
    print_bounds->description =
	_("Print input map's bounds in the current projection and exit");
    print_bounds->guisection = _("Target");
    
    gprint_bounds = G_define_flag();
    gprint_bounds->key = 'g';
    gprint_bounds->description =
	_("Print input map's bounds in the current projection and exit (shell style)");
    gprint_bounds->guisection = _("Target");

    /* The parser checks if the map already exists in current mapset,
       we switch out the check and do it
       in the module after the parser */
    overwrite = G_check_overwrite(argc, argv);

    if (G_parser(argc, argv))
	exit(EXIT_FAILURE);


    /* get the method */
    for (method = 0; (ipolname = menu[method].name); method++)
	if (strcmp(ipolname, interpol->answer) == 0)
	    break;

    if (!ipolname)
	G_fatal_error(_("<%s=%s> unknown %s"),
		      interpol->key, interpol->answer, interpol->key);
    interpolate = menu[method].method;

    mapname = outmap->answer ? outmap->answer : inmap->answer;
    if (mapname && !list->answer && !overwrite &&
	G_find_raster(mapname, G_mapset()))
	G_fatal_error(_("option <%s>: <%s> exists."), "output", mapname);

    setname = imapset->answer ? imapset->answer : G_store(G_mapset());
    if (strcmp(inlocation->answer, G_location()) == 0 &&
        (!indbase->answer || strcmp(indbase->answer, G_gisdbase()) == 0))
#if 0
	G_fatal_error(_("Input and output locations can not be the same"));
#else
	G_warning(_("Input and output locations are the same"));
#endif
    G_get_window(&outcellhd);

    if(gprint_bounds->answer && !print_bounds->answer)
	print_bounds->answer = gprint_bounds->answer;
    curr_proj = G_projection();

    /* Get projection info for output mapset */
    if ((out_proj_info = G_get_projinfo()) == NULL)
	G_fatal_error(_("Unable to get projection info of output raster map"));

    if ((out_unit_info = G_get_projunits()) == NULL)
	G_fatal_error(_("Unable to get projection units of output raster map"));

    if (pj_get_kv(&oproj, out_proj_info, out_unit_info) < 0)
	G_fatal_error(_("Unable to get projection key values of output raster map"));

    /* Change the location           */
    G__create_alt_env();
    G__setenv("GISDBASE", indbase->answer ? indbase->answer : G_gisdbase());
    G__setenv("LOCATION_NAME", inlocation->answer);

    permissions = G__mapset_permissions(setname);
    if (permissions < 0)	/* can't access mapset       */
	G_fatal_error(_("Mapset <%s> in input location <%s> - %s"),
		      setname, inlocation->answer,
		      permissions == 0 ? _("permission denied")
		      : _("not found"));

    /* if requested, list the raster maps in source location - MN 5/2001 */
    if (list->answer) {
	int i;
	char **list;
	G_verbose_message(_("Checking location <%s> mapset <%s>"),
			  inlocation->answer, setname);
	list = G_list(G_ELEMENT_RASTER, G__getenv("GISDBASE"),
		      G__getenv("LOCATION_NAME"), setname);
	for (i = 0; list[i]; i++) {
	    fprintf(stdout, "%s\n", list[i]);
	}
	fflush(stdout);
	exit(EXIT_SUCCESS);	/* leave r.proj after listing */
    }

    if (!inmap->answer)
	G_fatal_error(_("Required parameter <%s> not set"), inmap->key);

    if (!G_find_raster(inmap->answer, setname))
	G_fatal_error(_("Raster map <%s> in location <%s> in mapset <%s> not found"),
		      inmap->answer, inlocation->answer, setname);

    /* Read input map colour table */
    have_colors = Rast_read_colors(inmap->answer, setname, &colr);

    /* Get projection info for input mapset */
    if ((in_proj_info = G_get_projinfo()) == NULL)
	G_fatal_error(_("Unable to get projection info of input map"));

    if ((in_unit_info = G_get_projunits()) == NULL)
	G_fatal_error(_("Unable to get projection units of input map"));

    if (pj_get_kv(&iproj, in_proj_info, in_unit_info) < 0)
	G_fatal_error(_("Unable to get projection key values of input map"));

    G_free_key_value(in_proj_info);
    G_free_key_value(in_unit_info);
    G_free_key_value(out_proj_info);
    G_free_key_value(out_unit_info);
    if (G_verbose() > G_verbose_std())
	pj_print_proj_params(&iproj, &oproj);

    /* this call causes r.proj to read the entire map into memeory */
    Rast_get_cellhd(inmap->answer, setname, &incellhd);

    Rast_set_input_window(&incellhd);

    if (G_projection() == PROJECTION_XY)
	G_fatal_error(_("Unable to work with unprojected data (xy location)"));

    /* Save default borders so we can show them later */
    inorth = incellhd.north;
    isouth = incellhd.south;
    ieast = incellhd.east;
    iwest = incellhd.west;
    irows = incellhd.rows;
    icols = incellhd.cols;

    onorth = outcellhd.north;
    osouth = outcellhd.south;
    oeast = outcellhd.east;
    owest = outcellhd.west;
    orows = outcellhd.rows;
    ocols = outcellhd.cols;


    if (print_bounds->answer) {
	G_message(_("Input map <%s@%s> in location <%s>:"),
	    inmap->answer, setname, inlocation->answer);

	if (pj_do_proj(&iwest, &isouth, &iproj, &oproj) < 0)
	    G_fatal_error(_("Error in pj_do_proj (projection of input coordinate pair)"));
	if (pj_do_proj(&ieast, &inorth, &iproj, &oproj) < 0)
	    G_fatal_error(_("Error in pj_do_proj (projection of input coordinate pair)"));

	G_format_northing(inorth, north_str, curr_proj);
	G_format_northing(isouth, south_str, curr_proj);
	G_format_easting(ieast, east_str, curr_proj);
	G_format_easting(iwest, west_str, curr_proj);

	if(gprint_bounds->answer) {
	    fprintf(stdout, "n=%s s=%s w=%s e=%s rows=%d cols=%d\n",
		north_str, south_str, west_str, east_str, irows, icols);
	}
	else {
	    fprintf(stdout, "Source cols: %d\n", icols);
	    fprintf(stdout, "Source rows: %d\n", irows);
	    fprintf(stdout, "Local north: %s\n",  north_str);
	    fprintf(stdout, "Local south: %s\n", south_str);
	    fprintf(stdout, "Local west: %s\n", west_str);
	    fprintf(stdout, "Local east: %s\n", east_str);
	}

	/* somehow approximate local ewres, nsres ?? (use 'g.region -m' on lat/lon side) */

	exit(EXIT_SUCCESS);
    }


    /* Cut non-overlapping parts of input map */
    if (!nocrop->answer)
	bordwalk(&outcellhd, &incellhd, &oproj, &iproj);

    /* Add 2 cells on each side for bilinear/cubic & future interpolation methods */
    /* (should probably be a factor based on input and output resolution) */
    incellhd.north += 2 * incellhd.ns_res;
    incellhd.east += 2 * incellhd.ew_res;
    incellhd.south -= 2 * incellhd.ns_res;
    incellhd.west -= 2 * incellhd.ew_res;
    if (incellhd.north > inorth)
	incellhd.north = inorth;
    if (incellhd.east > ieast)
	incellhd.east = ieast;
    if (incellhd.south < isouth)
	incellhd.south = isouth;
    if (incellhd.west < iwest)
	incellhd.west = iwest;

    Rast_set_input_window(&incellhd);

    /* And switch back to original location */

    G__switch_env();

    /* Adjust borders of output map */

    if (!nocrop->answer)
	bordwalk(&incellhd, &outcellhd, &iproj, &oproj);

#if 0
    outcellhd.west = outcellhd.south = HUGE_VAL;
    outcellhd.east = outcellhd.north = -HUGE_VAL;
    for (row = 0; row < incellhd.rows; row++) {
	ycoord1 = Rast_row_to_northing((double)(row + 0.5), &incellhd);
	for (col = 0; col < incellhd.cols; col++) {
	    xcoord1 = Rast_col_to_easting((double)(col + 0.5), &incellhd);
	    pj_do_proj(&xcoord1, &ycoord1, &iproj, &oproj);
	    if (xcoord1 > outcellhd.east)
		outcellhd.east = xcoord1;
	    if (ycoord1 > outcellhd.north)
		outcellhd.north = ycoord1;
	    if (xcoord1 < outcellhd.west)
		outcellhd.west = xcoord1;
	    if (ycoord1 < outcellhd.south)
		outcellhd.south = ycoord1;
	}
    }
#endif

    if (res->answer != NULL)	/* set user defined resolution */
	outcellhd.ns_res = outcellhd.ew_res = atof(res->answer);

    G_adjust_Cell_head(&outcellhd, 0, 0);
    Rast_set_output_window(&outcellhd);

    G_message(" ");
    G_message(_("Input:"));
    G_message(_("Cols: %d (%d)"), incellhd.cols, icols);
    G_message(_("Rows: %d (%d)"), incellhd.rows, irows);
    G_message(_("North: %f (%f)"), incellhd.north, inorth);
    G_message(_("South: %f (%f)"), incellhd.south, isouth);
    G_message(_("West: %f (%f)"), incellhd.west, iwest);
    G_message(_("East: %f (%f)"), incellhd.east, ieast);
    G_message(_("EW-res: %f"), incellhd.ew_res);
    G_message(_("NS-res: %f"), incellhd.ns_res);
    G_message(" ");

    G_message(_("Output:"));
    G_message(_("Cols: %d (%d)"), outcellhd.cols, ocols);
    G_message(_("Rows: %d (%d)"), outcellhd.rows, orows);
    G_message(_("North: %f (%f)"), outcellhd.north, onorth);
    G_message(_("South: %f (%f)"), outcellhd.south, osouth);
    G_message(_("West: %f (%f)"), outcellhd.west, owest);
    G_message(_("East: %f (%f)"), outcellhd.east, oeast);
    G_message(_("EW-res: %f"), outcellhd.ew_res);
    G_message(_("NS-res: %f"), outcellhd.ns_res);
    G_message(" ");

    /* open and read the relevant parts of the input map and close it */
    G__switch_env();
    Rast_set_input_window(&incellhd);
    fdi = Rast_open_old(inmap->answer, setname);
    cell_type = Rast_get_map_type(fdi);
    ibuffer = readcell(fdi, memory->answer);
    Rast_close(fdi);

    G__switch_env();
    Rast_set_output_window(&outcellhd);

    if (strcmp(interpol->answer, "nearest") == 0) {
	fdo = Rast_open_new(mapname, cell_type);
	obuffer = (CELL *) Rast_allocate_output_buf(cell_type);
    }
    else {
	fdo = Rast_open_fp_new(mapname);
	cell_type = FCELL_TYPE;
	obuffer = (FCELL *) Rast_allocate_output_buf(cell_type);
    }

    cell_size = Rast_cell_size(cell_type);

    xcoord1 = xcoord2 = outcellhd.west + (outcellhd.ew_res / 2);
    /**/ ycoord1 = ycoord2 = outcellhd.north - (outcellhd.ns_res / 2);
    /**/ G_important_message(_("Projecting..."));
    G_percent(0, outcellhd.rows, 2);

    for (row = 0; row < outcellhd.rows; row++) {
	obufptr = obuffer;

	for (col = 0; col < outcellhd.cols; col++) {
	    /* project coordinates in output matrix to       */
	    /* coordinates in input matrix                   */
	    if (pj_do_proj(&xcoord1, &ycoord1, &oproj, &iproj) < 0)
		Rast_set_null_value(obufptr, 1, cell_type);
	    else {
		/* convert to row/column indices of input matrix */
		col_idx = (xcoord1 - incellhd.west) / incellhd.ew_res;
		row_idx = (incellhd.north - ycoord1) / incellhd.ns_res;

		/* and resample data point               */
		interpolate(ibuffer, obufptr, cell_type,
			    &col_idx, &row_idx, &incellhd);
	    }

	    obufptr = G_incr_void_ptr(obufptr, cell_size);
	    xcoord2 += outcellhd.ew_res;
	    xcoord1 = xcoord2;
	    ycoord1 = ycoord2;
	}

	Rast_put_row(fdo, obuffer, cell_type);

	xcoord1 = xcoord2 = outcellhd.west + (outcellhd.ew_res / 2);
	ycoord2 -= outcellhd.ns_res;
	ycoord1 = ycoord2;
	G_percent(row, outcellhd.rows - 1, 2);
    }

    Rast_close(fdo);

    if (have_colors > 0) {
	Rast_write_colors(mapname, G_mapset(), &colr);
	Rast_free_colors(&colr);
    }

    Rast_short_history(mapname, "raster", &history);
    Rast_command_history(&history);
    Rast_write_history(mapname, &history);

    G_done_msg(NULL);
    exit(EXIT_SUCCESS);
}
Exemplo n.º 25
0
int main(int argc, char *argv[])
{
    struct GModule *module;
    struct Option *element, *prompt;
    char *tempfile;
    char command[1024];
    FILE *fd;

    G_gisinit(argv[0]);

    module = G_define_module();
    module->keywords = _("display, map management");
    module->description =
	_("Prompts the user to select a GRASS data base file from among "
	  "files displayed in a menu on the graphics monitor.");

    element = G_define_option();
    element->key = "element";
    element->key_desc = "name,description";
    element->type = TYPE_STRING;
    element->required = YES;
    element->description = _("Database element, one word description");

    prompt = G_define_option();
    prompt->key = "prompt";
    prompt->key_desc = "message";
    prompt->type = TYPE_STRING;
    prompt->description = _("Short user prompt message");

    G_disable_interactive();
    if (G_parser(argc, argv))
	exit(EXIT_FAILURE);


    /* make sure we can do graphics */
    if (R_open_driver() != 0)
	G_fatal_error(_("No graphics device selected"));

    R_close_driver();

    tempfile = G_tempfile();
    unlink(tempfile);
    sprintf(command, "%s/etc/i.find %s %s %s %s",
	    G_gisbase(), G_location(), G_mapset(), element->answers[0],
	    tempfile);
    system(command);

    if (access(tempfile, 0) == 0) {
	if (prompt->answer) {
	    sprintf(command, "%s/etc/i.ask %s '%s'",
		    G_gisbase(), tempfile, prompt->answer);
	}
	else {
	    sprintf(command, "%s/etc/i.ask %s", G_gisbase(), tempfile);
	}
	exit(system(command));
    }
    else {
	fd = popen("d.menu tcolor=red > /dev/null", "w");
	if (fd) {
	    fprintf(fd, _("** no %s files found **\n"), element->answers[1]);
	    fprintf(fd, _("Click here to CONTINUE\n"));
	    pclose(fd);
	}
	exit(EXIT_SUCCESS);
    }
}