Esempio n. 1
0
int main(int argc, char *argv[])
{
    struct Map_info In, Out;
    static struct line_pnts *Points;
    struct line_cats *Cats;
    struct GModule *module;	/* GRASS module for parsing arguments */
    struct Option *map_in, *map_out;
    struct Option *method_opt, *afield_opt, *nfield_opt, *abcol,
                  *afcol, *ncol;
    struct Flag *add_f;
    int with_z;
    int afield, nfield, mask_type;
    dglGraph_s *graph;
    int *component, nnodes, type, i, nlines, components, max_cat;
    char buf[2000], *covered;
    char *desc;

    /* Attribute table */
    dbString sql;
    dbDriver *driver;
    struct field_info *Fi;

    /* initialize GIS environment */
    G_gisinit(argv[0]);		/* reads grass env, stores program name to G_program_name() */

    /* initialize module */
    module = G_define_module();
    G_add_keyword(_("vector"));
    G_add_keyword(_("network"));
    G_add_keyword(_("components"));
    module->description =
	_("Computes strongly and weakly connected components in the network.");

    /* Define the different options as defined in gis.h */
    map_in = G_define_standard_option(G_OPT_V_INPUT);

    afield_opt = G_define_standard_option(G_OPT_V_FIELD);
    afield_opt->key = "arc_layer";
    afield_opt->answer = "1";
    afield_opt->label = _("Arc layer");
    afield_opt->guisection = _("Cost");

    nfield_opt = G_define_standard_option(G_OPT_V_FIELD);
    nfield_opt->key = "node_layer";
    nfield_opt->answer = "2";
    nfield_opt->label = _("Node layer");
    nfield_opt->guisection = _("Cost");

    afcol = G_define_standard_option(G_OPT_DB_COLUMN);
    afcol->key = "arc_column";
    afcol->required = NO;
    afcol->description =
	_("Arc forward/both direction(s) cost column (number)");
    afcol->guisection = _("Cost");

    abcol = G_define_standard_option(G_OPT_DB_COLUMN);
    abcol->key = "arc_backward_column";
    abcol->required = NO;
    abcol->description = _("Arc backward direction cost column (number)");
    abcol->guisection = _("Cost");

    ncol = G_define_option();
    ncol->key = "node_column";
    ncol->type = TYPE_STRING;
    ncol->required = NO;
    ncol->description = _("Node cost column (number)");
    ncol->guisection = _("Cost");

    map_out = G_define_standard_option(G_OPT_V_OUTPUT);

    method_opt = G_define_option();
    method_opt->key = "method";
    method_opt->type = TYPE_STRING;
    method_opt->required = YES;
    method_opt->multiple = NO;
    method_opt->options = "weak,strong";
    desc = NULL;
    G_asprintf(&desc,
	       "weak;%s;strong;%s",
	       _("Weakly connected components"),
	       _("Strongly connected components"));
    method_opt->descriptions = desc;
    method_opt->description = _("Type of components");

    add_f = G_define_flag();
    add_f->key = 'a';
    add_f->description = _("Add points on nodes");

    /* options and flags parser */
    if (G_parser(argc, argv))
	exit(EXIT_FAILURE);
    /* TODO: make an option for this */
    mask_type = GV_LINE | GV_BOUNDARY;

    Points = Vect_new_line_struct();
    Cats = Vect_new_cats_struct();

    Vect_check_input_output_name(map_in->answer, map_out->answer,
				 G_FATAL_EXIT);

    Vect_set_open_level(2);

    if (1 > Vect_open_old(&In, map_in->answer, ""))
	G_fatal_error(_("Unable to open vector map <%s>"), map_in->answer);

    with_z = Vect_is_3d(&In);

    if (0 > Vect_open_new(&Out, map_out->answer, with_z)) {
	Vect_close(&In);
	G_fatal_error(_("Unable to create vector map <%s>"), map_out->answer);
    }

    /* parse filter option and select appropriate lines */
    afield = Vect_get_field_number(&In, afield_opt->answer);
    nfield = Vect_get_field_number(&In, nfield_opt->answer);

    if (0 != Vect_net_build_graph(&In, mask_type, afield, nfield, afcol->answer,
                                  abcol->answer, ncol->answer, 0, 2))
        G_fatal_error(_("Unable to build graph for vector map <%s>"), Vect_get_full_name(&In));

    graph = Vect_net_get_graph(&In);
    nnodes = Vect_get_num_nodes(&In);
    component = (int *)G_calloc(nnodes + 1, sizeof(int));
    covered = (char *)G_calloc(nnodes + 1, sizeof(char));
    if (!component || !covered) {
	G_fatal_error(_("Out of memory"));
	exit(EXIT_FAILURE);
    }
    /* Create table */
    Fi = Vect_default_field_info(&Out, 1, NULL, GV_1TABLE);
    Vect_map_add_dblink(&Out, 1, NULL, Fi->table, GV_KEY_COLUMN, Fi->database,
			Fi->driver);
    db_init_string(&sql);
    driver = db_start_driver_open_database(Fi->driver, Fi->database);
    if (driver == NULL)
	G_fatal_error(_("Unable to open database <%s> by driver <%s>"),
		      Fi->database, Fi->driver);

    sprintf(buf, "create table %s ( cat integer, comp integer)", Fi->table);

    db_set_string(&sql, buf);
    G_debug(2, "%s", db_get_string(&sql));

    if (db_execute_immediate(driver, &sql) != DB_OK) {
	db_close_database_shutdown_driver(driver);
	G_fatal_error(_("Unable to create table: '%s'"), db_get_string(&sql));
    }

    if (db_create_index2(driver, Fi->table, GV_KEY_COLUMN) != DB_OK)
	G_warning(_("Cannot create index"));

    if (db_grant_on_table
	(driver, Fi->table, DB_PRIV_SELECT, DB_GROUP | DB_PUBLIC) != DB_OK)
	G_fatal_error(_("Cannot grant privileges on table <%s>"), Fi->table);

    db_begin_transaction(driver);

    if (method_opt->answer[0] == 'w') {
	G_message(_("Computing weakly connected components..."));
	components = NetA_weakly_connected_components(graph, component);
    }
    else {
	G_message(_("Computing strongly connected components..."));
	components = NetA_strongly_connected_components(graph, component);
    }

    G_debug(3, "Components: %d", components);

    G_message(_("Writing output..."));

    Vect_copy_head_data(&In, &Out);
    Vect_hist_copy(&In, &Out);
    Vect_hist_command(&Out);

    nlines = Vect_get_num_lines(&In);
    max_cat = 1;
    G_percent(0, nlines, 4);
    for (i = 1; i <= nlines; i++) {
	int comp, cat;

	G_percent(i, nlines, 4);
	type = Vect_read_line(&In, Points, Cats, i);
	if (!Vect_cat_get(Cats, afield, &cat))
	    continue;
	if (type == GV_LINE || type == GV_BOUNDARY) {
	    int node1, node2;

	    Vect_get_line_nodes(&In, i, &node1, &node2);
	    if (component[node1] == component[node2]) {
		comp = component[node1];
	    }
	    else {
		continue;
	    }
	}
	else if (type == GV_POINT) {
	    int node;

	    /* Vect_get_line_nodes(&In, i, &node, NULL); */
	    node = Vect_find_node(&In, Points->x[0], Points->y[0], Points->z[0], 0, 0);
	    if (!node)
		continue;
	    comp = component[node];
	    covered[node] = 1;
	}
	else
	    continue;
	
	cat = max_cat++;
	Vect_reset_cats(Cats);
	Vect_cat_set(Cats, 1, cat);
	Vect_write_line(&Out, type, Points, Cats);
	insert_new_record(driver, Fi, &sql, cat, comp);
    }

    /*add points on nodes not covered by any point in the network */
    if (add_f->answer) {
	for (i = 1; i <= nnodes; i++)
	    if (!covered[i]) {
		Vect_reset_cats(Cats);
		Vect_cat_set(Cats, 1, max_cat);
		NetA_add_point_on_node(&In, &Out, i, Cats);
		insert_new_record(driver, Fi, &sql, max_cat++, component[i]);
	    }
    }

    db_commit_transaction(driver);
    db_close_database_shutdown_driver(driver);

    Vect_close(&In);

    Vect_build(&Out);
    Vect_close(&Out);

    G_done_msg(_("Found %d components."), components);

    exit(EXIT_SUCCESS);
}
Esempio n. 2
0
int main(int argc, char *argv[])
{
    int out_fd;
    CELL *result, *rp;
    int nrows, ncols;
    int row, col;
    struct GModule *module;
    struct Option *in_opt, *out_opt;
    struct Option *method_opt, *size_opt;
    char *mapset;
    struct Map_info In;
    double radius;
    struct ilist *List;
    struct Cell_head region;
    BOUND_BOX box;
    struct line_pnts *Points;
    struct line_cats *Cats;

    G_gisinit(argv[0]);

    module = G_define_module();
    module->keywords = _("vector, raster, aggregation");
    module->description = "Makes each cell value a "
	"function of the attribute values assigned to the vector points or centroids "
	"around it, and stores new cell values in an output raster map layer.";

    in_opt = G_define_standard_option(G_OPT_V_INPUT);
    out_opt = G_define_standard_option(G_OPT_R_OUTPUT);

    method_opt = G_define_option();
    method_opt->key = "method";
    method_opt->type = TYPE_STRING;
    method_opt->required = YES;
    method_opt->options = "count";
    method_opt->answer = "count";
    method_opt->description = "Neighborhood operation";

    size_opt = G_define_option();
    size_opt->key = "size";
    size_opt->type = TYPE_DOUBLE;
    size_opt->required = YES;
    size_opt->description = "Neighborhood diameter in map units";

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

    radius = atof(size_opt->answer) / 2;

    /* open input vector */
    if ((mapset = G_find_vector2(in_opt->answer, "")) == NULL) {
	G_fatal_error(_("Vector map <%s> not found in the current mapset"),
		      in_opt->answer);
    }

    Vect_set_open_level(2);
    Vect_open_old(&In, in_opt->answer, mapset);

    G_get_set_window(&region);
    nrows = G_window_rows();
    ncols = G_window_cols();

    result = G_allocate_raster_buf(CELL_TYPE);
    Points = Vect_new_line_struct();
    Cats = Vect_new_cats_struct();
    List = Vect_new_list();

    /*open the new cellfile */
    out_fd = G_open_raster_new(out_opt->answer, CELL_TYPE);
    if (out_fd < 0)
	G_fatal_error(_("Unable to create raster map <%s>"), out_opt->answer);

    box.T = PORT_DOUBLE_MAX;
    box.B = -PORT_DOUBLE_MAX;

    for (row = 0; row < nrows; row++) {
	double x, y;

	G_percent(row, nrows, 1);

	y = G_row_to_northing(row + 0.5, &region);
	box.N = y + radius;
	box.S = y - radius;

	G_set_null_value(result, ncols, CELL_TYPE);
	rp = result;

	for (col = 0; col < ncols; col++) {
	    int i, count;
	    CELL value;

	    x = G_col_to_easting(col + 0.5, &region);

	    box.E = x + radius;
	    box.W = x - radius;

	    Vect_select_lines_by_box(&In, &box, GV_POINTS, List);
	    G_debug(3, "  %d lines in box", List->n_values);

	    count = 0;

	    for (i = 0; i < List->n_values; i++) {
		double distance;

		Vect_read_line(&In, Points, Cats, List->value[i]);
		distance =
		    Vect_points_distance(x, y, 0.0, Points->x[0],
					 Points->y[0], 0.0, 0);

		if (distance <= radius) {
		    count++;
		}
	    }

	    if (count > 0) {
		value = count;
		G_set_raster_value_d(rp, value, CELL_TYPE);
	    }
	    rp = G_incr_void_ptr(rp, G_raster_size(CELL_TYPE));
	}

	G_put_raster_row(out_fd, result, CELL_TYPE);
    }
    G_percent(row, nrows, 1);

    Vect_close(&In);
    G_close_cell(out_fd);

    exit(EXIT_SUCCESS);
}
Esempio n. 3
0
static off_t format_l()
{
    G_fatal_error(_("Requested format is not compiled in this version"));
    return 0;
}
Esempio n. 4
0
int main(int argc, char **argv)
{
    struct GModule *module;
    struct Option *map_opt, *field_opt, *fs_opt, *vs_opt, *nv_opt, *col_opt,
	*where_opt, *file_opt;
    struct Flag *c_flag, *v_flag, *r_flag;
    dbDriver *driver;
    dbString sql, value_string;
    dbCursor cursor;
    dbTable *table;
    dbColumn *column;
    dbValue *value;
    struct field_info *Fi;
    int ncols, col, more;
    struct Map_info Map;
    char query[1024];
    struct ilist *list_lines;

    struct bound_box *min_box, *line_box;
    int i, line, area, init_box, cat;

    module = G_define_module();
    G_add_keyword(_("vector"));
    G_add_keyword(_("database"));
    G_add_keyword(_("attribute table"));
    module->description = _("Prints vector map attributes.");

    map_opt = G_define_standard_option(G_OPT_V_MAP);
    field_opt = G_define_standard_option(G_OPT_V_FIELD);

    col_opt = G_define_standard_option(G_OPT_DB_COLUMNS);

    where_opt = G_define_standard_option(G_OPT_DB_WHERE);

    fs_opt = G_define_standard_option(G_OPT_F_SEP);
    fs_opt->description = _("Output field separator");
    fs_opt->guisection = _("Format");

    vs_opt = G_define_standard_option(G_OPT_F_SEP);
    vs_opt->key = "vs";
    vs_opt->description = _("Output vertical record separator");
    vs_opt->answer = NULL;
    vs_opt->guisection = _("Format");

    nv_opt = G_define_option();
    nv_opt->key = "nv";
    nv_opt->type = TYPE_STRING;
    nv_opt->required = NO;
    nv_opt->description = _("Null value indicator");
    nv_opt->guisection = _("Format");

    file_opt = G_define_standard_option(G_OPT_F_OUTPUT); 
    file_opt->key = "file";
    file_opt->required = NO; 
    file_opt->description = 
	_("Name for output file (if omitted or \"-\" output to stdout)"); 
    
    r_flag = G_define_flag();
    r_flag->key = 'r';
    r_flag->description =
	_("Print minimal region extent of selected vector features instead of attributes");

    c_flag = G_define_flag();
    c_flag->key = 'c';
    c_flag->description = _("Do not include column names in output");
    c_flag->guisection = _("Format");

    v_flag = G_define_flag();
    v_flag->key = 'v';
    v_flag->description = _("Vertical output (instead of horizontal)");
    v_flag->guisection = _("Format");

    G_gisinit(argv[0]);

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

    /* set input vector map name and mapset */
    if (file_opt->answer && strcmp(file_opt->answer, "-") != 0) { 
	if (NULL == freopen(file_opt->answer, "w", stdout)) { 
	    G_fatal_error(_("Unable to open file <%s> for writing"), file_opt->answer); 
	} 
    } 
    
    if (r_flag->answer) {
	min_box = (struct bound_box *) G_malloc(sizeof(struct bound_box));
	G_zero((void *)min_box, sizeof(struct bound_box));

	line_box = (struct bound_box *) G_malloc(sizeof(struct bound_box));
	list_lines = Vect_new_list();
    }
    else {
      min_box = line_box = NULL;
      list_lines = NULL;
    }

    db_init_string(&sql);
    db_init_string(&value_string);

    /* open input vector */
    if (!r_flag->answer)
	Vect_open_old_head2(&Map, map_opt->answer, "", field_opt->answer);
    else {
	if (2 > Vect_open_old2(&Map, map_opt->answer, "", field_opt->answer)) {
	    Vect_close(&Map);
	    G_fatal_error(_("Unable to open vector map <%s> at topology level. "
			   "Flag '%c' requires topology level."),
			  map_opt->answer, r_flag->key);
	}
    }

    if ((Fi = Vect_get_field2(&Map, field_opt->answer)) == NULL)
	G_fatal_error(_("Database connection not defined for layer <%s>"),
		      field_opt->answer);

    driver = db_start_driver_open_database(Fi->driver, Fi->database);

    if (!driver)
	G_fatal_error(_("Unable to open database <%s> by driver <%s>"),
		      Fi->database, Fi->driver);

    if (col_opt->answer)
	sprintf(query, "SELECT %s FROM ", col_opt->answer);
    else
	sprintf(query, "SELECT * FROM ");

    db_set_string(&sql, query);
    db_append_string(&sql, Fi->table);

    if (where_opt->answer) {
	char *buf = NULL;

	buf = G_malloc((strlen(where_opt->answer) + 8));
	sprintf(buf, " WHERE %s", where_opt->answer);
	db_append_string(&sql, buf);
	G_free(buf);
    }

    if (db_open_select_cursor(driver, &sql, &cursor, DB_SEQUENTIAL) != DB_OK)
	G_fatal_error(_("Unable to open select cursor"));

    table = db_get_cursor_table(&cursor);
    ncols = db_get_table_number_of_columns(table);

    /* column names if horizontal output (ignore for -r) */
    if (!v_flag->answer && !c_flag->answer && !r_flag->answer) {
	for (col = 0; col < ncols; col++) {
	    column = db_get_table_column(table, col);
	    if (col)
		fprintf(stdout, "%s", fs_opt->answer);
	    fprintf(stdout, "%s", db_get_column_name(column));
	}
	fprintf(stdout, "\n");
    }

    init_box = 1;

    /* fetch the data */
    while (1) {
	if (db_fetch(&cursor, DB_NEXT, &more) != DB_OK)
	    G_fatal_error(_("Unable to fetch data from table <%s>"),
			  Fi->table);

	if (!more)
	    break;

	cat = -1;
	for (col = 0; col < ncols; col++) {
	    column = db_get_table_column(table, col);
	    value = db_get_column_value(column);

	    if (cat < 0 && strcmp(Fi->key, db_get_column_name(column)) == 0) {
		cat = db_get_value_int(value);
		if (r_flag->answer)
		    break;
	    }

	    if (r_flag->answer)
		continue;

	    db_convert_column_value_to_string(column, &value_string);

	    if (!c_flag->answer && v_flag->answer)
		fprintf(stdout, "%s%s", db_get_column_name(column),
			fs_opt->answer);

	    if (col && !v_flag->answer)
		fprintf(stdout, "%s", fs_opt->answer);

	    if (nv_opt->answer && db_test_value_isnull(value))
		fprintf(stdout, "%s", nv_opt->answer);
	    else
		fprintf(stdout, "%s", db_get_string(&value_string));

	    if (v_flag->answer)
		fprintf(stdout, "\n");
	}

	if (r_flag->answer) {
	    /* get minimal region extent */
	    Vect_cidx_find_all(&Map, Vect_get_field_number(&Map, field_opt->answer), -1, cat, list_lines);
	    for (i = 0; i < list_lines->n_values; i++) {
		line = list_lines->value[i];
		area = Vect_get_centroid_area(&Map, line);
		if (area > 0) {
		    if (!Vect_get_area_box(&Map, area, line_box))
			G_fatal_error(_("Unable to get bounding box of area %d"),
				      area);
		}
		else {
		    if (!Vect_get_line_box(&Map, line, line_box))
			G_fatal_error(_("Unable to get bounding box of line %d"),
				      line);
		}
		if (init_box) {
		    Vect_box_copy(min_box, line_box);
		    init_box = 0;
		}
		else {
		    Vect_box_extend(min_box, line_box);
		}
	    }
	}
	else {
	    if (!v_flag->answer)
		fprintf(stdout, "\n");
	    else if (vs_opt->answer)
		fprintf(stdout, "%s\n", vs_opt->answer);
	}
    }

    if (r_flag->answer) {
	fprintf(stdout, "n=%f\n", min_box->N);
	fprintf(stdout, "s=%f\n", min_box->S);
	fprintf(stdout, "w=%f\n", min_box->W);
	fprintf(stdout, "e=%f\n", min_box->E);
	if (Vect_is_3d(&Map)) {
	    fprintf(stdout, "t=%f\n", min_box->T);
	    fprintf(stdout, "b=%f\n", min_box->B);
	}
	fflush(stdout);

	G_free((void *)min_box);
	G_free((void *)line_box);

	Vect_destroy_list(list_lines);
    }

    db_close_cursor(&cursor);
    db_close_database_shutdown_driver(driver);
    Vect_close(&Map);

    exit(EXIT_SUCCESS);
}
Esempio n. 5
0
static int cell_draw( char *name,
                      char *mapset,
                      struct Colors *colors,
                      RASTER_MAP_TYPE data_type,
                      char *format )
{
  int cellfile;
  void *xarray;
  int row;
  int ncols, nrows;
  static unsigned char *red, *grn, *blu, *set;
  int i;
  void *ptr;
  int big_endian;
  long one = 1;
  FILE *fo;
  int raster_size;

  big_endian = !( *(( char * )( &one ) ) );

  ncols = G_window_cols();
  nrows = G_window_rows();

  /* Make sure map is available */
  if (( cellfile = G_open_cell_old( name, mapset ) ) == -1 )
    G_fatal_error(( "Unable to open raster map <%s>" ), name );

  /* Allocate space for cell buffer */
  xarray = G_allocate_raster_buf( data_type );
  red = G_malloc( ncols );
  grn = G_malloc( ncols );
  blu = G_malloc( ncols );
  set = G_malloc( ncols );

  /* some buggy C libraries require BOTH setmode() and fdopen(bin) */
#ifdef WIN32
  if ( _setmode( _fileno( stdout ), _O_BINARY ) == -1 )
    G_fatal_error( "Cannot set stdout mode" );
#endif
  // Unfortunately this is not sufficient on Windows to switch stdout to binary mode
  fo = fdopen( fileno( stdout ), "wb" );

  raster_size = G_raster_size( data_type );
  //fprintf( fo, "%d %d", data_type, raster_size );
  //exit(0);
  /* loop for array rows */
  for ( row = 0; row < nrows; row++ )
  {
    G_get_raster_row( cellfile, xarray, row, data_type );
    ptr = xarray;

    G_lookup_raster_colors( xarray, red, grn, blu, set, ncols, colors,
                            data_type );

    for ( i = 0; i < ncols; i++ )
    {
      unsigned char alpha = 255;
      //G_debug ( 0, "row = %d col = %d", row, i );
      if ( G_is_null_value( ptr, data_type ) )
      {
        alpha = 0;
      }

      if ( strcmp( format, "color" ) == 0 )
      {
        // We need data suitable for QImage 32-bpp
        // the data are stored in QImage as QRgb which is unsigned int.
        // Because it depends on byte order of the platform we have to
        // consider byte order (well, middle endian ignored)
        if ( big_endian )
        {
          // I have never tested this
          fprintf( fo, "%c%c%c%c", alpha, red[i], grn[i], blu[i] );
        }
        else
        {
          fprintf( fo, "%c%c%c%c", blu[i], grn[i], red[i], alpha );
        }
      }
      else
      {
        if ( data_type == CELL_TYPE )
        {
          //G_debug ( 0, "valx = %d", *((CELL *) ptr));
        }
        if ( G_is_null_value( ptr, data_type ) )
        {
          if ( data_type == CELL_TYPE )
          {
            int nul = -2147483647;
            fwrite( &nul , 4, 1, fo );
          }
          else if ( data_type == DCELL_TYPE )
          {
            double nul = 2.2250738585072014e-308;
            fwrite( &nul , 8, 1, fo );
          }
          else if ( data_type == FCELL_TYPE )
          {
            double nul = 1.17549435e-38F;
            fwrite( &nul , 4, 1, fo );
          }
        }
        else
        {
          fwrite( ptr, raster_size, 1, fo );
        }
      }
      ptr = G_incr_void_ptr( ptr, raster_size );
    }
  }

  G_close_cell( cellfile );
  return ( 0 );
}
Esempio n. 6
0
int main(int argc, char *argv[])
{
    struct Map_info In, Out, Error;
    struct line_pnts *Points;
    struct line_cats *Cats;
    int i, type, iter;
    struct GModule *module;	/* GRASS module for parsing arguments */
    struct Option *map_in, *map_out, *error_out, *thresh_opt, *method_opt,
	*look_ahead_opt;
    struct Option *iterations_opt, *cat_opt, *alpha_opt, *beta_opt, *type_opt;
    struct Option *field_opt, *where_opt, *reduction_opt, *slide_opt;
    struct Option *angle_thresh_opt, *degree_thresh_opt,
	*closeness_thresh_opt;
    struct Option *betweeness_thresh_opt;
    struct Flag *notab_flag, *loop_support_flag;
    int with_z;
    int total_input, total_output;	/* Number of points in the input/output map respectively */
    double thresh, alpha, beta, reduction, slide, angle_thresh;
    double degree_thresh, closeness_thresh, betweeness_thresh;
    int method;
    int look_ahead, iterations;
    int loop_support;
    int layer;
    int n_lines;
    int simplification, mask_type;
    struct cat_list *cat_list = NULL;
    char *s, *descriptions;

    /* initialize GIS environment */
    G_gisinit(argv[0]);		/* reads grass env, stores program name to G_program_name() */

    /* initialize module */
    module = G_define_module();
    G_add_keyword(_("vector"));
    G_add_keyword(_("generalization"));
    G_add_keyword(_("simplification"));
    G_add_keyword(_("smoothing"));
    G_add_keyword(_("displacement"));
    G_add_keyword(_("network generalization"));
    module->description = _("Performs vector based generalization.");

    /* Define the different options as defined in gis.h */
    map_in = G_define_standard_option(G_OPT_V_INPUT);

    field_opt = G_define_standard_option(G_OPT_V_FIELD_ALL);

    type_opt = G_define_standard_option(G_OPT_V_TYPE);
    type_opt->options = "line,boundary,area";
    type_opt->answer = "line,boundary,area";
    type_opt->guisection = _("Selection");
    
    map_out = G_define_standard_option(G_OPT_V_OUTPUT);

    error_out = G_define_standard_option(G_OPT_V_OUTPUT);
    error_out->key = "error";
    error_out->required = NO;
    error_out->description =
	_("Error map of all lines and boundaries not being generalized due to topology issues or over-simplification");

    method_opt = G_define_option();
    method_opt->key = "method";
    method_opt->type = TYPE_STRING;
    method_opt->required = YES;
    method_opt->multiple = NO;
    method_opt->options =
	"douglas,douglas_reduction,lang,reduction,reumann,boyle,sliding_averaging,distance_weighting,chaiken,hermite,snakes,network,displacement";
    descriptions = NULL;
    G_asprintf(&descriptions,
               "douglas;%s;"
               "douglas_reduction;%s;"
               "lang;%s;"
               "reduction;%s;"
               "reumann;%s;"
               "boyle;%s;"
               "sliding_averaging;%s;"
               "distance_weighting;%s;"
               "chaiken;%s;"
               "hermite;%s;"
               "snakes;%s;"
               "network;%s;"
               "displacement;%s;",
               _("Douglas-Peucker Algorithm"),
               _("Douglas-Peucker Algorithm with reduction parameter"),
               _("Lang Simplification Algorithm"),
               _("Vertex Reduction Algorithm eliminates points close to each other"),
               _("Reumann-Witkam Algorithm"),
               _("Boyle's Forward-Looking Algorithm"),
               _("McMaster's Sliding Averaging Algorithm"),
               _("McMaster's Distance-Weighting Algorithm"),
               _("Chaiken's Algorithm"),
               _("Interpolation by Cubic Hermite Splines"),
               _("Snakes method for line smoothing"),
               _("Network generalization"),
               _("Displacement of lines close to each other"));
    method_opt->descriptions = G_store(descriptions);
    
    method_opt->description = _("Generalization algorithm");

    thresh_opt = G_define_option();
    thresh_opt->key = "threshold";
    thresh_opt->type = TYPE_DOUBLE;
    thresh_opt->required = YES;
    thresh_opt->options = "0-1000000000";
    thresh_opt->description = _("Maximal tolerance value");

    look_ahead_opt = G_define_option();
    look_ahead_opt->key = "look_ahead";
    look_ahead_opt->type = TYPE_INTEGER;
    look_ahead_opt->required = NO;
    look_ahead_opt->answer = "7";
    look_ahead_opt->description = _("Look-ahead parameter");

    reduction_opt = G_define_option();
    reduction_opt->key = "reduction";
    reduction_opt->type = TYPE_DOUBLE;
    reduction_opt->required = NO;
    reduction_opt->answer = "50";
    reduction_opt->options = "0-100";
    reduction_opt->description =
	_("Percentage of the points in the output of 'douglas_reduction' algorithm");
    
    slide_opt = G_define_option();
    slide_opt->key = "slide";
    slide_opt->type = TYPE_DOUBLE;
    slide_opt->required = NO;
    slide_opt->answer = "0.5";
    slide_opt->options = "0-1";
    slide_opt->description =
	_("Slide of computed point toward the original point");

    angle_thresh_opt = G_define_option();
    angle_thresh_opt->key = "angle_thresh";
    angle_thresh_opt->type = TYPE_DOUBLE;
    angle_thresh_opt->required = NO;
    angle_thresh_opt->answer = "3";
    angle_thresh_opt->options = "0-180";
    angle_thresh_opt->description =
	_("Minimum angle between two consecutive segments in Hermite method");

    degree_thresh_opt = G_define_option();
    degree_thresh_opt->key = "degree_thresh";
    degree_thresh_opt->type = TYPE_INTEGER;
    degree_thresh_opt->required = NO;
    degree_thresh_opt->answer = "0";
    degree_thresh_opt->description =
	_("Degree threshold in network generalization");

    closeness_thresh_opt = G_define_option();
    closeness_thresh_opt->key = "closeness_thresh";
    closeness_thresh_opt->type = TYPE_DOUBLE;
    closeness_thresh_opt->required = NO;
    closeness_thresh_opt->answer = "0";
    closeness_thresh_opt->options = "0-1";
    closeness_thresh_opt->description =
	_("Closeness threshold in network generalization");

    betweeness_thresh_opt = G_define_option();
    betweeness_thresh_opt->key = "betweeness_thresh";
    betweeness_thresh_opt->type = TYPE_DOUBLE;
    betweeness_thresh_opt->required = NO;
    betweeness_thresh_opt->answer = "0";
    betweeness_thresh_opt->description =
	_("Betweeness threshold in network generalization");

    alpha_opt = G_define_option();
    alpha_opt->key = "alpha";
    alpha_opt->type = TYPE_DOUBLE;
    alpha_opt->required = NO;
    alpha_opt->answer = "1.0";
    alpha_opt->description = _("Snakes alpha parameter");

    beta_opt = G_define_option();
    beta_opt->key = "beta";
    beta_opt->type = TYPE_DOUBLE;
    beta_opt->required = NO;
    beta_opt->answer = "1.0";
    beta_opt->description = _("Snakes beta parameter");

    iterations_opt = G_define_option();
    iterations_opt->key = "iterations";
    iterations_opt->type = TYPE_INTEGER;
    iterations_opt->required = NO;
    iterations_opt->answer = "1";
    iterations_opt->description = _("Number of iterations");

    cat_opt = G_define_standard_option(G_OPT_V_CATS);
    cat_opt->guisection = _("Selection");
    
    where_opt = G_define_standard_option(G_OPT_DB_WHERE);
    where_opt->guisection = _("Selection");

    loop_support_flag = G_define_flag();
    loop_support_flag->key = 'l';
    loop_support_flag->label = _("Disable loop support");
    loop_support_flag->description = _("Do not modify end points of lines forming a closed loop");

    notab_flag = G_define_standard_flag(G_FLG_V_TABLE);
    notab_flag->description = _("Do not copy attributes");
    notab_flag->guisection = _("Attributes");
    
    /* options and flags parser */
    if (G_parser(argc, argv))
	exit(EXIT_FAILURE);

    thresh = atof(thresh_opt->answer);
    look_ahead = atoi(look_ahead_opt->answer);
    alpha = atof(alpha_opt->answer);
    beta = atof(beta_opt->answer);
    reduction = atof(reduction_opt->answer);
    iterations = atoi(iterations_opt->answer);
    slide = atof(slide_opt->answer);
    angle_thresh = atof(angle_thresh_opt->answer);
    degree_thresh = atof(degree_thresh_opt->answer);
    closeness_thresh = atof(closeness_thresh_opt->answer);
    betweeness_thresh = atof(betweeness_thresh_opt->answer);

    mask_type = type_mask(type_opt);
    G_debug(3, "Method: %s", method_opt->answer);

    s = method_opt->answer;

    if (strcmp(s, "douglas") == 0)
	method = DOUGLAS;
    else if (strcmp(s, "lang") == 0)
	method = LANG;
    else if (strcmp(s, "reduction") == 0)
	method = VERTEX_REDUCTION;
    else if (strcmp(s, "reumann") == 0)
	method = REUMANN;
    else if (strcmp(s, "boyle") == 0)
	method = BOYLE;
    else if (strcmp(s, "distance_weighting") == 0)
	method = DISTANCE_WEIGHTING;
    else if (strcmp(s, "chaiken") == 0)
	method = CHAIKEN;
    else if (strcmp(s, "hermite") == 0)
	method = HERMITE;
    else if (strcmp(s, "snakes") == 0)
	method = SNAKES;
    else if (strcmp(s, "douglas_reduction") == 0)
	method = DOUGLAS_REDUCTION;
    else if (strcmp(s, "sliding_averaging") == 0)
	method = SLIDING_AVERAGING;
    else if (strcmp(s, "network") == 0)
	method = NETWORK;
    else if (strcmp(s, "displacement") == 0) {
	method = DISPLACEMENT;
	/* we can displace only the lines */
	mask_type = GV_LINE;
    }
    else {
	G_fatal_error(_("Unknown method"));
	exit(EXIT_FAILURE);
    }


    /* simplification or smoothing? */
    switch (method) {
    case DOUGLAS:
    case DOUGLAS_REDUCTION:
    case LANG:
    case VERTEX_REDUCTION:
    case REUMANN:
	simplification = 1;
	break;
    default:
	simplification = 0;
	break;
    }


    Points = Vect_new_line_struct();
    Cats = Vect_new_cats_struct();

    Vect_check_input_output_name(map_in->answer, map_out->answer,
				 G_FATAL_EXIT);

    Vect_set_open_level(2);

    if (Vect_open_old2(&In, map_in->answer, "", field_opt->answer) < 1)
	G_fatal_error(_("Unable to open vector map <%s>"), map_in->answer);

    if (Vect_get_num_primitives(&In, mask_type) == 0) {
	G_warning(_("No lines found in input map <%s>"), map_in->answer);
	Vect_close(&In);
	exit(EXIT_SUCCESS);
    }
    with_z = Vect_is_3d(&In);

    if (0 > Vect_open_new(&Out, map_out->answer, with_z)) {
	Vect_close(&In);
	G_fatal_error(_("Unable to create vector map <%s>"), map_out->answer);
    }

    if (error_out->answer) {
        if (0 > Vect_open_new(&Error, error_out->answer, with_z)) {
	    Vect_close(&In);
	    G_fatal_error(_("Unable to create error vector map <%s>"), error_out->answer);
        }
    }


    Vect_copy_head_data(&In, &Out);
    Vect_hist_copy(&In, &Out);
    Vect_hist_command(&Out);

    total_input = total_output = 0;

    layer = Vect_get_field_number(&In, field_opt->answer);
    /* parse filter options */
    if (layer > 0)
	cat_list = Vect_cats_set_constraint(&In, layer, 
			      where_opt->answer, cat_opt->answer);

    if (method == DISPLACEMENT) {
	/* modifies only lines, all other features including boundaries are preserved */
	/* options where, cats, and layer are respected */
	G_message(_("Displacement..."));
	snakes_displacement(&In, &Out, thresh, alpha, beta, 1.0, 10.0,
			    iterations, cat_list, layer);
    }

    /* TODO: rearrange code below. It's really messy */
    if (method == NETWORK) {
	/* extracts lines of selected type, all other features are discarded */
	/* options where, cats, and layer are ignored */
	G_message(_("Network generalization..."));
	total_output =
	    graph_generalization(&In, &Out, mask_type, degree_thresh, 
	                         closeness_thresh, betweeness_thresh);
    }

    /* copy tables here because method == NETWORK is complete and 
     * tables for Out may be needed for parse_filter_options() below */
    if (!notab_flag->answer) {
	if (method == NETWORK)
	    copy_tables_by_cats(&In, &Out);
	else
	    Vect_copy_tables(&In, &Out, -1);
    }
    else if (where_opt->answer && method < NETWORK) {
	G_warning(_("Attributes are needed for 'where' option, copying table"));
	Vect_copy_tables(&In, &Out, -1);
    }

    /* smoothing/simplification */
    if (method < NETWORK) {
	/* modifies only lines of selected type, all other features are preserved */
	int not_modified_boundaries = 0, n_oversimplified = 0;
	struct line_pnts *APoints;  /* original Points */

	set_topo_debug();

	Vect_copy_map_lines(&In, &Out);
	Vect_build_partial(&Out, GV_BUILD_CENTROIDS);

	G_message("-----------------------------------------------------");
	G_message(_("Generalization (%s)..."), method_opt->answer);
	G_message(_("Using threshold: %g %s"), thresh, G_database_unit_name(1));
	G_percent_reset();

	APoints = Vect_new_line_struct();

	n_lines = Vect_get_num_lines(&Out);
	for (i = 1; i <= n_lines; i++) {
	    int after = 0;

	    G_percent(i, n_lines, 1);

	    type = Vect_read_line(&Out, APoints, Cats, i);

	    if (!(type & GV_LINES) || !(mask_type & type))
		continue;

	    if (layer > 0) {
		if ((type & GV_LINE) &&
		    !Vect_cats_in_constraint(Cats, layer, cat_list))
		    continue;
		else if ((type & GV_BOUNDARY)) {
		    int do_line = 0;
		    int left, right;
		    
		    do_line = Vect_cats_in_constraint(Cats, layer, cat_list);

		    if (!do_line) {
			
			/* check if any of the centroids is selected */
			Vect_get_line_areas(&Out, i, &left, &right);
			if (left < 0)
			    left = Vect_get_isle_area(&Out, abs(left));
			if (right < 0)
			    right = Vect_get_isle_area(&Out, abs(right));

			if (left > 0) {
			    Vect_get_area_cats(&Out, left, Cats);
			    do_line = Vect_cats_in_constraint(Cats, layer, cat_list);
			}
			
			if (!do_line && right > 0) {
			    Vect_get_area_cats(&Out, right, Cats);
			    do_line = Vect_cats_in_constraint(Cats, layer, cat_list);
			}
		    }
		    if (!do_line)
			continue;
		}
	    }

	    Vect_line_prune(APoints);

	    if (APoints->n_points < 2)
		/* Line of length zero, delete if boundary ? */
		continue;

	    total_input += APoints->n_points;

	    /* copy points */
	    Vect_reset_line(Points);
	    Vect_append_points(Points, APoints, GV_FORWARD);
	    
	    loop_support = 0;
	    if (!loop_support_flag->answer) {
		int n1, n2;

		Vect_get_line_nodes(&Out, i, &n1, &n2);
		if (n1 == n2) {
		    if (Vect_get_node_n_lines(&Out, n1) == 2) {
			if (abs(Vect_get_node_line(&Out, n1, 0)) == i &&
			    abs(Vect_get_node_line(&Out, n1, 1)) == i)
			    loop_support = 1;
		    }
		}
	    }
		
	    for (iter = 0; iter < iterations; iter++) {
		switch (method) {
		case DOUGLAS:
		    douglas_peucker(Points, thresh, with_z);
		    break;
		case DOUGLAS_REDUCTION:
		    douglas_peucker_reduction(Points, thresh, reduction,
					      with_z);
		    break;
		case LANG:
		    lang(Points, thresh, look_ahead, with_z);
		    break;
		case VERTEX_REDUCTION:
		    vertex_reduction(Points, thresh, with_z);
		    break;
		case REUMANN:
		    reumann_witkam(Points, thresh, with_z);
		    break;
		case BOYLE:
		    boyle(Points, look_ahead, loop_support, with_z);
		    break;
		case SLIDING_AVERAGING:
		    sliding_averaging(Points, slide, look_ahead, loop_support, with_z);
		    break;
		case DISTANCE_WEIGHTING:
		    distance_weighting(Points, slide, look_ahead, loop_support, with_z);
		    break;
		case CHAIKEN:
		    chaiken(Points, thresh, loop_support, with_z);
		    break;
		case HERMITE:
		    hermite(Points, thresh, angle_thresh, loop_support, with_z);
		    break;
		case SNAKES:
		    snakes(Points, alpha, beta, loop_support, with_z);
		    break;
		}
	    }

	    if (loop_support == 0) { 
		/* safety check, BUG in method if not passed */
		if (APoints->x[0] != Points->x[0] || 
		    APoints->y[0] != Points->y[0] ||
		    APoints->z[0] != Points->z[0])
		    G_fatal_error(_("Method '%s' did not preserve first point"), method_opt->answer);
		    
		if (APoints->x[APoints->n_points - 1] != Points->x[Points->n_points - 1] || 
		    APoints->y[APoints->n_points - 1] != Points->y[Points->n_points - 1] ||
		    APoints->z[APoints->n_points - 1] != Points->z[Points->n_points - 1])
		    G_fatal_error(_("Method '%s' did not preserve last point"), method_opt->answer);
	    }
	    else {
		/* safety check, BUG in method if not passed */
		if (Points->x[0] != Points->x[Points->n_points - 1] || 
		    Points->y[0] != Points->y[Points->n_points - 1] ||
		    Points->z[0] != Points->z[Points->n_points - 1])
		    G_fatal_error(_("Method '%s' did not preserve loop"), method_opt->answer);
	    }

	    Vect_line_prune(Points);

	    /* oversimplified line */
	    if (Points->n_points < 2) {
		after = APoints->n_points;
		n_oversimplified++;
                if (error_out->answer)
		    Vect_write_line(&Error, type, APoints, Cats);
	    }
	    /* check for topology corruption */
	    else if (type == GV_BOUNDARY) {
		if (!check_topo(&Out, i, APoints, Points, Cats)) {
		    after = APoints->n_points;
		    not_modified_boundaries++;
                    if (error_out->answer)
		        Vect_write_line(&Error, type, APoints, Cats);
		}
		else
		    after = Points->n_points;
	    }
	    else {
		/* type == GV_LINE */
		Vect_rewrite_line(&Out, i, type, Points, Cats);
		after = Points->n_points;
	    }

	    total_output += after;
	}
	if (not_modified_boundaries > 0)
	    G_warning(_("%d boundaries were not modified because modification would damage topology"),
		      not_modified_boundaries);
	if (n_oversimplified > 0)
	    G_warning(_("%d lines/boundaries were not modified due to over-simplification"),
		      n_oversimplified);
	G_message("-----------------------------------------------------");

	/* make sure that clean topo is built at the end */
	Vect_build_partial(&Out, GV_BUILD_NONE);
        if (error_out->answer)
	    Vect_build_partial(&Error, GV_BUILD_NONE);
    }

    Vect_build(&Out);
    if (error_out->answer)
        Vect_build(&Error);

    Vect_close(&In);
    Vect_close(&Out);
    if (error_out->answer)
        Vect_close(&Error);

    G_message("-----------------------------------------------------");
    if (total_input != 0 && total_input != total_output)
	G_done_msg(_("Number of vertices for selected features %s from %d to %d (%d%% remaining)"),
                   simplification ? _("reduced") : _("changed"), 
                   total_input, total_output,
                   (total_output * 100) / total_input);
    else
        G_done_msg(" ");

    exit(EXIT_SUCCESS);
}
Esempio n. 7
0
/*--------------------------------------------------------------------*/
int main(int argc, char *argv[])
{
    /* Variable declarations */
    int nsply, nsplx, nrows, ncols, nsplx_adj, nsply_adj;
    int nsubregion_col, nsubregion_row, subregion_row, subregion_col;
    int subregion = 0, nsubregions = 0;
    int last_row, last_column, grid, bilin, ext, flag_auxiliar, cross;	/* booleans */
    double stepN, stepE, lambda, mean;
    double N_extension, E_extension, edgeE, edgeN;

    const char *mapset, *drv, *db, *vector, *map;
    char table_name[GNAME_MAX], title[64];
    char xname[GNAME_MAX], xmapset[GMAPSET_MAX];

    int dim_vect, nparameters, BW;
    int *lineVect;		/* Vector restoring primitive's ID */
    double *TN, *Q, *parVect;	/* Interpolating and least-square vectors */
    double **N, **obsVect;	/* Interpolation and least-square matrix */

    SEGMENT out_seg, mask_seg;
    const char *out_file, *mask_file;
    int out_fd, mask_fd;
    double seg_size;
    int seg_mb, segments_in_memory;
    int have_mask;

    /* Structs declarations */
    int raster;
    struct Map_info In, In_ext, Out;
    struct History history;

    struct GModule *module;
    struct Option *in_opt, *in_ext_opt, *out_opt, *out_map_opt, *stepE_opt,
               *stepN_opt, *lambda_f_opt, *type_opt, *dfield_opt, *col_opt, *mask_opt,
               *memory_opt, *solver, *error, *iter;
    struct Flag *cross_corr_flag, *spline_step_flag;

    struct Reg_dimens dims;
    struct Cell_head elaboration_reg, original_reg;
    struct bound_box general_box, overlap_box, original_box;

    struct Point *observ;
    struct line_cats *Cats;
    dbCatValArray cvarr;

    int with_z;
    int nrec, ctype = 0;
    struct field_info *Fi;
    dbDriver *driver, *driver_cats;

    /*----------------------------------------------------------------*/
    /* Options declarations */
    module = G_define_module();
    G_add_keyword(_("vector"));
    G_add_keyword(_("surface"));
    G_add_keyword(_("interpolation"));
    G_add_keyword(_("LIDAR"));
    module->description =
        _("Performs bicubic or bilinear spline interpolation with Tykhonov regularization.");

    cross_corr_flag = G_define_flag();
    cross_corr_flag->key = 'c';
    cross_corr_flag->description =
        _("Find the best Tykhonov regularizing parameter using a \"leave-one-out\" cross validation method");

    spline_step_flag = G_define_flag();
    spline_step_flag->key = 'e';
    spline_step_flag->label = _("Estimate point density and distance");
    spline_step_flag->description =
        _("Estimate point density and distance for the input vector points within the current region extends and quit");

    in_opt = G_define_standard_option(G_OPT_V_INPUT);
    in_opt->label = _("Name of input vector point map");

    dfield_opt = G_define_standard_option(G_OPT_V_FIELD);
    dfield_opt->guisection = _("Settings");

    col_opt = G_define_standard_option(G_OPT_DB_COLUMN);
    col_opt->required = NO;
    col_opt->label =
        _("Name of the attribute column with values to be used for approximation");
    col_opt->description = _("If not given and input is 3D vector map then z-coordinates are used.");
    col_opt->guisection = _("Settings");

    in_ext_opt = G_define_standard_option(G_OPT_V_INPUT);
    in_ext_opt->key = "sparse_input";
    in_ext_opt->required = NO;
    in_ext_opt->label =
        _("Name of input vector map with sparse points");

    out_opt = G_define_standard_option(G_OPT_V_OUTPUT);
    out_opt->required = NO;
    out_opt->guisection = _("Outputs");

    out_map_opt = G_define_standard_option(G_OPT_R_OUTPUT);
    out_map_opt->key = "raster_output";
    out_map_opt->required = NO;
    out_map_opt->guisection = _("Outputs");

    mask_opt = G_define_standard_option(G_OPT_R_INPUT);
    mask_opt->key = "mask";
    mask_opt->label = _("Raster map to use for masking (applies to raster output only)");
    mask_opt->description = _("Only cells that are not NULL and not zero are interpolated");
    mask_opt->required = NO;

    stepE_opt = G_define_option();
    stepE_opt->key = "ew_step";
    stepE_opt->type = TYPE_DOUBLE;
    stepE_opt->required = NO;
    stepE_opt->answer = "4";
    stepE_opt->description =
        _("Length of each spline step in the east-west direction");
    stepE_opt->guisection = _("Settings");

    stepN_opt = G_define_option();
    stepN_opt->key = "ns_step";
    stepN_opt->type = TYPE_DOUBLE;
    stepN_opt->required = NO;
    stepN_opt->answer = "4";
    stepN_opt->description =
        _("Length of each spline step in the north-south direction");
    stepN_opt->guisection = _("Settings");

    type_opt = G_define_option();
    type_opt->key = "method";
    type_opt->description = _("Spline interpolation algorithm");
    type_opt->type = TYPE_STRING;
    type_opt->options = "bilinear,bicubic";
    type_opt->answer = "bilinear";
    type_opt->guisection = _("Settings");
    G_asprintf((char **) &(type_opt->descriptions),
               "bilinear;%s;bicubic;%s",
               _("Bilinear interpolation"),
               _("Bicubic interpolation"));

    lambda_f_opt = G_define_option();
    lambda_f_opt->key = "lambda_i";
    lambda_f_opt->type = TYPE_DOUBLE;
    lambda_f_opt->required = NO;
    lambda_f_opt->description = _("Tykhonov regularization parameter (affects smoothing)");
    lambda_f_opt->answer = "0.01";
    lambda_f_opt->guisection = _("Settings");

    solver = N_define_standard_option(N_OPT_SOLVER_SYMM);
    solver->options = "cholesky,cg";
    solver->answer = "cholesky";

    iter = N_define_standard_option(N_OPT_MAX_ITERATIONS);

    error = N_define_standard_option(N_OPT_ITERATION_ERROR);

    memory_opt = G_define_option();
    memory_opt->key = "memory";
    memory_opt->type = TYPE_INTEGER;
    memory_opt->required = NO;
    memory_opt->answer = "300";
    memory_opt->label = _("Maximum memory to be used (in MB)");
    memory_opt->description = _("Cache size for raster rows");

    /*----------------------------------------------------------------*/
    /* Parsing */
    G_gisinit(argv[0]);
    if (G_parser(argc, argv))
        exit(EXIT_FAILURE);

    vector = out_opt->answer;
    map = out_map_opt->answer;

    if (vector && map)
        G_fatal_error(_("Choose either vector or raster output, not both"));

    if (!vector && !map && !cross_corr_flag->answer)
        G_fatal_error(_("No raster or vector or cross-validation output"));

    if (!strcmp(type_opt->answer, "linear"))
        bilin = P_BILINEAR;
    else
        bilin = P_BICUBIC;

    stepN = atof(stepN_opt->answer);
    stepE = atof(stepE_opt->answer);
    lambda = atof(lambda_f_opt->answer);

    flag_auxiliar = FALSE;

    drv = db_get_default_driver_name();
    if (!drv) {
        if (db_set_default_connection() != DB_OK)
            G_fatal_error(_("Unable to set default DB connection"));
        drv = db_get_default_driver_name();
    }
    db = db_get_default_database_name();
    if (!db)
        G_fatal_error(_("No default DB defined"));

    /* Set auxiliary table's name */
    if (vector) {
        if (G_name_is_fully_qualified(out_opt->answer, xname, xmapset)) {
            sprintf(table_name, "%s_aux", xname);
        }
        else
            sprintf(table_name, "%s_aux", out_opt->answer);
    }

    /* Something went wrong in a previous v.surf.bspline execution */
    if (db_table_exists(drv, db, table_name)) {
        /* Start driver and open db */
        driver = db_start_driver_open_database(drv, db);
        if (driver == NULL)
            G_fatal_error(_("No database connection for driver <%s> is defined. Run db.connect."),
                          drv);
        db_set_error_handler_driver(driver);

        if (P_Drop_Aux_Table(driver, table_name) != DB_OK)
            G_fatal_error(_("Old auxiliary table could not be dropped"));
        db_close_database_shutdown_driver(driver);
    }

    /* Open input vector */
    if ((mapset = G_find_vector2(in_opt->answer, "")) == NULL)
        G_fatal_error(_("Vector map <%s> not found"), in_opt->answer);

    Vect_set_open_level(1);	/* WITHOUT TOPOLOGY */
    if (1 > Vect_open_old(&In, in_opt->answer, mapset))
        G_fatal_error(_("Unable to open vector map <%s> at the topological level"),
                      in_opt->answer);

    bspline_field = 0; /* assume 3D input */
    bspline_column = col_opt->answer;

    with_z = !bspline_column && Vect_is_3d(&In);

    if (Vect_is_3d(&In)) {
        if (!with_z)
            G_verbose_message(_("Input is 3D: using attribute values instead of z-coordinates for approximation"));
        else
            G_verbose_message(_("Input is 3D: using z-coordinates for approximation"));
    }
    else { /* 2D */
        if (!bspline_column)
            G_fatal_error(_("Input vector map is 2D. Parameter <%s> required."), col_opt->key);
    }

    if (!with_z) {
        bspline_field = Vect_get_field_number(&In, dfield_opt->answer);
    }

    /* Estimate point density and mean distance for current region */
    if (spline_step_flag->answer) {
        double dens, dist;
        if (P_estimate_splinestep(&In, &dens, &dist) == 0) {
            fprintf(stdout, _("Estimated point density: %.4g"), dens);
            fprintf(stdout, _("Estimated mean distance between points: %.4g"), dist);
        }
        else {
            fprintf(stdout, _("No points in current region"));
        }

        Vect_close(&In);
        exit(EXIT_SUCCESS);
    }

    /*----------------------------------------------------------------*/
    /* Cross-correlation begins */
    if (cross_corr_flag->answer) {
        G_debug(1, "CrossCorrelation()");
        cross = cross_correlation(&In, stepE, stepN);

        if (cross != TRUE)
            G_fatal_error(_("Cross validation didn't finish correctly"));
        else {
            G_debug(1, "Cross validation finished correctly");

            Vect_close(&In);

            G_done_msg(_("Cross validation finished for ew_step = %f and ns_step = %f"), stepE, stepN);
            exit(EXIT_SUCCESS);
        }
    }

    /* Open input ext vector */
    ext = FALSE;
    if (in_ext_opt->answer) {
        ext = TRUE;
        G_message(_("Vector map <%s> of sparse points will be interpolated"),
                  in_ext_opt->answer);

        if ((mapset = G_find_vector2(in_ext_opt->answer, "")) == NULL)
            G_fatal_error(_("Vector map <%s> not found"), in_ext_opt->answer);

        Vect_set_open_level(1);	/* WITHOUT TOPOLOGY */
        if (1 > Vect_open_old(&In_ext, in_ext_opt->answer, mapset))
            G_fatal_error(_("Unable to open vector map <%s> at the topological level"),
                          in_opt->answer);
    }

    /* Open output map */
    /* vector output */
    if (vector && !map) {
        if (strcmp(drv, "dbf") == 0)
            G_fatal_error(_("Sorry, the <%s> driver is not compatible with "
                            "the vector output of this module. "
                            "Try with raster output or another driver."), drv);

        Vect_check_input_output_name(in_opt->answer, out_opt->answer,
                                     G_FATAL_EXIT);
        grid = FALSE;

        if (0 > Vect_open_new(&Out, out_opt->answer, WITH_Z))
            G_fatal_error(_("Unable to create vector map <%s>"),
                          out_opt->answer);

        /* Copy vector Head File */
        if (ext == FALSE) {
            Vect_copy_head_data(&In, &Out);
            Vect_hist_copy(&In, &Out);
        }
        else {
            Vect_copy_head_data(&In_ext, &Out);
            Vect_hist_copy(&In_ext, &Out);
        }
        Vect_hist_command(&Out);

        G_verbose_message(_("Points in input vector map <%s> will be interpolated"),
                          vector);
    }


    /* read z values from attribute table */
    if (bspline_field > 0) {
        G_message(_("Reading values from attribute table..."));
        db_CatValArray_init(&cvarr);
        Fi = Vect_get_field(&In, bspline_field);
        if (Fi == NULL)
            G_fatal_error(_("Cannot read layer info"));

        driver_cats = db_start_driver_open_database(Fi->driver, Fi->database);
        /*G_debug (0, _("driver=%s db=%s"), Fi->driver, Fi->database); */

        if (driver_cats == NULL)
            G_fatal_error(_("Unable to open database <%s> by driver <%s>"),
                          Fi->database, Fi->driver);
        db_set_error_handler_driver(driver_cats);

        nrec =
            db_select_CatValArray(driver_cats, Fi->table, Fi->key,
                                  col_opt->answer, NULL, &cvarr);
        G_debug(3, "nrec = %d", nrec);

        ctype = cvarr.ctype;
        if (ctype != DB_C_TYPE_INT && ctype != DB_C_TYPE_DOUBLE)
            G_fatal_error(_("Column type not supported"));

        if (nrec < 0)
            G_fatal_error(_("Unable to select data from table"));

        G_verbose_message(_("%d records selected from table"), nrec);

        db_close_database_shutdown_driver(driver_cats);
    }

    /*----------------------------------------------------------------*/
    /* Interpolation begins */
    G_debug(1, "Interpolation()");

    /* Open driver and database */
    driver = db_start_driver_open_database(drv, db);
    if (driver == NULL)
        G_fatal_error(_("No database connection for driver <%s> is defined. "
                        "Run db.connect."), drv);
    db_set_error_handler_driver(driver);

    /* Create auxiliary table */
    if (vector) {
        if ((flag_auxiliar = P_Create_Aux4_Table(driver, table_name)) == FALSE) {
            P_Drop_Aux_Table(driver, table_name);
            G_fatal_error(_("Interpolation: Creating table: "
                            "It was impossible to create table <%s>."),
                          table_name);
        }
        /* db_create_index2(driver, table_name, "ID"); */
        /* sqlite likes that ??? */
        db_close_database_shutdown_driver(driver);
        driver = db_start_driver_open_database(drv, db);
    }

    /* raster output */
    raster = -1;
    Rast_set_fp_type(DCELL_TYPE);
    if (!vector && map) {
        grid = TRUE;
        raster = Rast_open_fp_new(out_map_opt->answer);

        G_verbose_message(_("Cells for raster map <%s> will be interpolated"),
                          map);
    }

    /* Setting regions and boxes */
    G_debug(1, "Interpolation: Setting regions and boxes");
    G_get_window(&original_reg);
    G_get_window(&elaboration_reg);
    Vect_region_box(&original_reg, &original_box);
    Vect_region_box(&elaboration_reg, &overlap_box);
    Vect_region_box(&elaboration_reg, &general_box);

    nrows = Rast_window_rows();
    ncols = Rast_window_cols();

    /* Alloc raster matrix */
    have_mask = 0;
    out_file = mask_file = NULL;
    out_fd = mask_fd = -1;
    if (grid == TRUE) {
        int row;
        DCELL *drastbuf;

        seg_mb = atoi(memory_opt->answer);
        if (seg_mb < 3)
            G_fatal_error(_("Memory in MB must be >= 3"));

        if (mask_opt->answer)
            seg_size = sizeof(double) + sizeof(char);
        else
            seg_size = sizeof(double);

        seg_size = (seg_size * SEGSIZE * SEGSIZE) / (1 << 20);
        segments_in_memory = seg_mb / seg_size + 0.5;
        G_debug(1, "%d %dx%d segments held in memory", segments_in_memory, SEGSIZE, SEGSIZE);

        out_file = G_tempfile();
        out_fd = creat(out_file, 0666);
        if (Segment_format(out_fd, nrows, ncols, SEGSIZE, SEGSIZE, sizeof(double)) != 1)
            G_fatal_error(_("Can not create temporary file"));
        close(out_fd);

        out_fd = open(out_file, 2);
        if (Segment_init(&out_seg, out_fd, segments_in_memory) != 1)
            G_fatal_error(_("Can not initialize temporary file"));

        /* initialize output */
        G_message(_("Initializing output..."));

        drastbuf = Rast_allocate_buf(DCELL_TYPE);
        Rast_set_d_null_value(drastbuf, ncols);
        for (row = 0; row < nrows; row++) {
            G_percent(row, nrows, 2);
            Segment_put_row(&out_seg, drastbuf, row);
        }
        G_percent(row, nrows, 2);

        if (mask_opt->answer) {
            int row, col, maskfd;
            DCELL dval, *drastbuf;
            char mask_val;

            G_message(_("Load masking map"));

            mask_file = G_tempfile();
            mask_fd = creat(mask_file, 0666);
            if (Segment_format(mask_fd, nrows, ncols, SEGSIZE, SEGSIZE, sizeof(char)) != 1)
                G_fatal_error(_("Can not create temporary file"));
            close(mask_fd);

            mask_fd = open(mask_file, 2);
            if (Segment_init(&mask_seg, mask_fd, segments_in_memory) != 1)
                G_fatal_error(_("Can not initialize temporary file"));

            maskfd = Rast_open_old(mask_opt->answer, "");
            drastbuf = Rast_allocate_buf(DCELL_TYPE);

            for (row = 0; row < nrows; row++) {
                G_percent(row, nrows, 2);
                Rast_get_d_row(maskfd, drastbuf, row);
                for (col = 0; col < ncols; col++) {
                    dval = drastbuf[col];
                    if (Rast_is_d_null_value(&dval) || dval == 0)
                        mask_val = 0;
                    else
                        mask_val = 1;

                    Segment_put(&mask_seg, &mask_val, row, col);
                }
            }

            G_percent(row, nrows, 2);
            G_free(drastbuf);
            Rast_close(maskfd);

            have_mask = 1;
        }
    }

    /*------------------------------------------------------------------
      | Subdividing and working with tiles:
      | Each original region will be divided into several subregions.
      | Each one will be overlaped by its neighbouring subregions.
      | The overlapping is calculated as a fixed OVERLAP_SIZE times
      | the largest spline step plus 2 * edge
      ----------------------------------------------------------------*/

    /* Fixing parameters of the elaboration region */
    P_zero_dim(&dims);		/* Set dim struct to zero */

    nsplx_adj = NSPLX_MAX;
    nsply_adj = NSPLY_MAX;
    if (stepN > stepE)
        dims.overlap = OVERLAP_SIZE * stepN;
    else
        dims.overlap = OVERLAP_SIZE * stepE;
    P_get_edge(bilin, &dims, stepE, stepN);
    P_set_dim(&dims, stepE, stepN, &nsplx_adj, &nsply_adj);

    G_verbose_message(_("Adjusted EW splines %d"), nsplx_adj);
    G_verbose_message(_("Adjusted NS splines %d"), nsply_adj);

    /* calculate number of subregions */
    edgeE = dims.ew_size - dims.overlap - 2 * dims.edge_v;
    edgeN = dims.sn_size - dims.overlap - 2 * dims.edge_h;

    N_extension = original_reg.north - original_reg.south;
    E_extension = original_reg.east - original_reg.west;

    nsubregion_col = ceil(E_extension / edgeE) + 0.5;
    nsubregion_row = ceil(N_extension / edgeN) + 0.5;

    if (nsubregion_col < 0)
        nsubregion_col = 0;
    if (nsubregion_row < 0)
        nsubregion_row = 0;

    nsubregions = nsubregion_row * nsubregion_col;

    /* Creating line and categories structs */
    Cats = Vect_new_cats_struct();
    Vect_cat_set(Cats, 1, 0);

    subregion_row = 0;
    elaboration_reg.south = original_reg.north;
    last_row = FALSE;

    while (last_row == FALSE) {	/* For each subregion row */
        subregion_row++;
        P_set_regions(&elaboration_reg, &general_box, &overlap_box, dims,
                      GENERAL_ROW);

        if (elaboration_reg.north > original_reg.north) {	/* First row */

            P_set_regions(&elaboration_reg, &general_box, &overlap_box, dims,
                          FIRST_ROW);
        }

        if (elaboration_reg.south <= original_reg.south) {	/* Last row */

            P_set_regions(&elaboration_reg, &general_box, &overlap_box, dims,
                          LAST_ROW);
            last_row = TRUE;
        }

        nsply =
            ceil((elaboration_reg.north -
                  elaboration_reg.south) / stepN) + 0.5;
        G_debug(1, "Interpolation: nsply = %d", nsply);
        /*
        if (nsply > NSPLY_MAX)
            nsply = NSPLY_MAX;
        */
        elaboration_reg.east = original_reg.west;
        last_column = FALSE;
        subregion_col = 0;

        /* TODO: process each subregion using its own thread (via OpenMP or pthreads) */
        /*     I'm not sure about pthreads, but you can tell OpenMP to start all at the
        	same time and it will keep num_workers supplied with the next job as free
        	cpus become available */
        while (last_column == FALSE) {	/* For each subregion column */
            int npoints = 0;
            /* needed for sparse points interpolation */
            int npoints_ext, *lineVect_ext = NULL;
            double **obsVect_ext;	/*, mean_ext = .0; */
            struct Point *observ_ext;

            subregion_col++;
            subregion++;
            if (nsubregions > 1)
                G_message(_("Processing subregion %d of %d..."), subregion, nsubregions);

            P_set_regions(&elaboration_reg, &general_box, &overlap_box, dims,
                          GENERAL_COLUMN);

            if (elaboration_reg.west < original_reg.west) {	/* First column */

                P_set_regions(&elaboration_reg, &general_box, &overlap_box,
                              dims, FIRST_COLUMN);
            }

            if (elaboration_reg.east >= original_reg.east) {	/* Last column */

                P_set_regions(&elaboration_reg, &general_box, &overlap_box,
                              dims, LAST_COLUMN);
                last_column = TRUE;
            }
            nsplx =
                ceil((elaboration_reg.east -
                      elaboration_reg.west) / stepE) + 0.5;
            G_debug(1, "Interpolation: nsplx = %d", nsplx);
            /*
            if (nsplx > NSPLX_MAX)
            nsplx = NSPLX_MAX;
            */
            G_debug(1, "Interpolation: (%d,%d): subregion bounds",
                    subregion_row, subregion_col);
            G_debug(1, "Interpolation: \t\tNORTH:%.2f\t",
                    elaboration_reg.north);
            G_debug(1, "Interpolation: WEST:%.2f\t\tEAST:%.2f",
                    elaboration_reg.west, elaboration_reg.east);
            G_debug(1, "Interpolation: \t\tSOUTH:%.2f",
                    elaboration_reg.south);

#ifdef DEBUG_SUBREGIONS
            fprintf(stdout, "B 5\n");
            fprintf(stdout, " %.11g %.11g\n", elaboration_reg.east, elaboration_reg.north);
            fprintf(stdout, " %.11g %.11g\n", elaboration_reg.west, elaboration_reg.north);
            fprintf(stdout, " %.11g %.11g\n", elaboration_reg.west, elaboration_reg.south);
            fprintf(stdout, " %.11g %.11g\n", elaboration_reg.east, elaboration_reg.south);
            fprintf(stdout, " %.11g %.11g\n", elaboration_reg.east, elaboration_reg.north);
            fprintf(stdout, "C 1 1\n");
            fprintf(stdout, " %.11g %.11g\n", (elaboration_reg.west + elaboration_reg.east) / 2,
                    (elaboration_reg.south + elaboration_reg.north) / 2);
            fprintf(stdout, " 1 %d\n", subregion);
#endif



            /* reading points in interpolation region */
            dim_vect = nsplx * nsply;
            observ_ext = NULL;
            if (grid == FALSE && ext == TRUE) {
                observ_ext =
                    P_Read_Vector_Region_Map(&In_ext,
                                             &elaboration_reg,
                                             &npoints_ext, dim_vect,
                                             1);
            }
            else
                npoints_ext = 1;

            if (grid == TRUE && have_mask) {
                /* any unmasked cells in general region ? */
                mean = 0;
                observ_ext =
                    P_Read_Raster_Region_masked(&mask_seg, &original_reg,
                                                original_box, general_box,
                                                &npoints_ext, dim_vect, mean);
            }

            observ = NULL;
            if (npoints_ext > 0) {
                observ =
                    P_Read_Vector_Region_Map(&In, &elaboration_reg, &npoints,
                                             dim_vect, bspline_field);
            }
            else
                npoints = 1;

            G_debug(1,
                    "Interpolation: (%d,%d): Number of points in <elaboration_box> is %d",
                    subregion_row, subregion_col, npoints);
            if (npoints > 0)
                G_verbose_message(_("%d points found in this subregion"), npoints);
            /* only interpolate if there are any points in current subregion */
            if (npoints > 0 && npoints_ext > 0) {
                int i;

                nparameters = nsplx * nsply;
                BW = P_get_BandWidth(bilin, nsply);

                /* Least Squares system */
                N = G_alloc_matrix(nparameters, BW);	/* Normal matrix */
                TN = G_alloc_vector(nparameters);	/* vector */
                parVect = G_alloc_vector(nparameters);	/* Parameters vector */
                obsVect = G_alloc_matrix(npoints, 3);	/* Observation vector */
                Q = G_alloc_vector(npoints);	/* "a priori" var-cov matrix */
                lineVect = G_alloc_ivector(npoints);	/*  */

                for (i = 0; i < npoints; i++) {	/* Setting obsVect vector & Q matrix */
                    double dval;

                    Q[i] = 1;	/* Q=I */
                    lineVect[i] = observ[i].lineID;
                    obsVect[i][0] = observ[i].coordX;
                    obsVect[i][1] = observ[i].coordY;

                    /* read z coordinates from attribute table */
                    if (bspline_field > 0) {
                        int cat, ival, ret;

                        cat = observ[i].cat;
                        if (cat < 0)
                            continue;

                        if (ctype == DB_C_TYPE_INT) {
                            ret =
                                db_CatValArray_get_value_int(&cvarr, cat,
                                                             &ival);
                            obsVect[i][2] = ival;
                            observ[i].coordZ = ival;
                        }
                        else {	/* DB_C_TYPE_DOUBLE */
                            ret =
                                db_CatValArray_get_value_double(&cvarr, cat,
                                                                &dval);
                            obsVect[i][2] = dval;
                            observ[i].coordZ = dval;
                        }
                        if (ret != DB_OK) {
                            G_warning(_("Interpolation: (%d,%d): No record for point (cat = %d)"),
                                      subregion_row, subregion_col, cat);
                            continue;
                        }
                    }
                    /* use z coordinates of 3D vector */
                    else {
                        obsVect[i][2] = observ[i].coordZ;
                    }
                }

                /* Mean calculation for every point */
                mean = P_Mean_Calc(&elaboration_reg, observ, npoints);

                G_debug(1, "Interpolation: (%d,%d): mean=%lf",
                        subregion_row, subregion_col, mean);

                G_free(observ);

                for (i = 0; i < npoints; i++)
                    obsVect[i][2] -= mean;

                /* Bilinear interpolation */
                if (bilin) {
                    G_debug(1,
                            "Interpolation: (%d,%d): Bilinear interpolation...",
                            subregion_row, subregion_col);
                    normalDefBilin(N, TN, Q, obsVect, stepE, stepN, nsplx,
                                   nsply, elaboration_reg.west,
                                   elaboration_reg.south, npoints,
                                   nparameters, BW);
                    nCorrectGrad(N, lambda, nsplx, nsply, stepE, stepN);
                }
                /* Bicubic interpolation */
                else {
                    G_debug(1,
                            "Interpolation: (%d,%d): Bicubic interpolation...",
                            subregion_row, subregion_col);
                    normalDefBicubic(N, TN, Q, obsVect, stepE, stepN, nsplx,
                                     nsply, elaboration_reg.west,
                                     elaboration_reg.south, npoints,
                                     nparameters, BW);
                    nCorrectGrad(N, lambda, nsplx, nsply, stepE, stepN);
                }

                if(G_strncasecmp(solver->answer, "cg", 2) == 0)
                    G_math_solver_cg_sband(N, parVect, TN, nparameters, BW, atoi(iter->answer), atof(error->answer));
                else
                    G_math_solver_cholesky_sband(N, parVect, TN, nparameters, BW);


                G_free_matrix(N);
                G_free_vector(TN);
                G_free_vector(Q);

                if (grid == TRUE) {	/* GRID INTERPOLATION ==> INTERPOLATION INTO A RASTER */
                    G_debug(1, "Interpolation: (%d,%d): Regular_Points...",
                            subregion_row, subregion_col);

                    if (!have_mask) {
                        P_Regular_Points(&elaboration_reg, &original_reg, general_box,
                                         overlap_box, &out_seg, parVect,
                                         stepN, stepE, dims.overlap, mean,
                                         nsplx, nsply, nrows, ncols, bilin);
                    }
                    else {
                        P_Sparse_Raster_Points(&out_seg,
                                               &elaboration_reg, &original_reg,
                                               general_box, overlap_box,
                                               observ_ext, parVect,
                                               stepE, stepN,
                                               dims.overlap, nsplx, nsply,
                                               npoints_ext, bilin, mean);
                    }
                }
                else {		/* OBSERVATION POINTS INTERPOLATION */
                    if (ext == FALSE) {
                        G_debug(1, "Interpolation: (%d,%d): Sparse_Points...",
                                subregion_row, subregion_col);
                        P_Sparse_Points(&Out, &elaboration_reg, general_box,
                                        overlap_box, obsVect, parVect,
                                        lineVect, stepE, stepN,
                                        dims.overlap, nsplx, nsply, npoints,
                                        bilin, Cats, driver, mean,
                                        table_name);
                    }
                    else {	/* FLAG_EXT == TRUE */

                        /* done that earlier */
                        /*
                        int npoints_ext, *lineVect_ext = NULL;
                        double **obsVect_ext;
                        struct Point *observ_ext;

                        observ_ext =
                            P_Read_Vector_Region_Map(&In_ext,
                        			     &elaboration_reg,
                        			     &npoints_ext, dim_vect,
                        			     1);
                        */

                        obsVect_ext = G_alloc_matrix(npoints_ext, 3);	/* Observation vector_ext */
                        lineVect_ext = G_alloc_ivector(npoints_ext);

                        for (i = 0; i < npoints_ext; i++) {	/* Setting obsVect_ext vector & Q matrix */
                            obsVect_ext[i][0] = observ_ext[i].coordX;
                            obsVect_ext[i][1] = observ_ext[i].coordY;
                            obsVect_ext[i][2] = observ_ext[i].coordZ - mean;
                            lineVect_ext[i] = observ_ext[i].lineID;
                        }

                        G_free(observ_ext);

                        G_debug(1, "Interpolation: (%d,%d): Sparse_Points...",
                                subregion_row, subregion_col);
                        P_Sparse_Points(&Out, &elaboration_reg, general_box,
                                        overlap_box, obsVect_ext, parVect,
                                        lineVect_ext, stepE, stepN,
                                        dims.overlap, nsplx, nsply,
                                        npoints_ext, bilin, Cats, driver,
                                        mean, table_name);

                        G_free_matrix(obsVect_ext);
                        G_free_ivector(lineVect_ext);
                    }		/* END FLAG_EXT == TRUE */
                }		/* END GRID == FALSE */
                G_free_vector(parVect);
                G_free_matrix(obsVect);
                G_free_ivector(lineVect);
            }
            else {
                if (observ)
                    G_free(observ);
                if (observ_ext)
                    G_free(observ_ext);
                if (npoints == 0)
                    G_warning(_("No data within this subregion. "
                                "Consider increasing spline step values."));
            }
        }			/*! END WHILE; last_column = TRUE */
    }				/*! END WHILE; last_row = TRUE */

    G_verbose_message(_("Writing output..."));
    /* Writing the output raster map */
    if (grid == TRUE) {
        int row, col;
        DCELL *drastbuf, dval;


        if (have_mask) {
            Segment_release(&mask_seg);	/* release memory  */
            close(mask_fd);
            unlink(mask_file);
        }

        drastbuf = Rast_allocate_buf(DCELL_TYPE);
        for (row = 0; row < nrows; row++) {
            G_percent(row, nrows, 2);
            for (col = 0; col < ncols; col++) {
                Segment_get(&out_seg, &dval, row, col);
                drastbuf[col] = dval;
            }
            Rast_put_d_row(raster, drastbuf);
        }

        Rast_close(raster);

        Segment_release(&out_seg);	/* release memory  */
        close(out_fd);
        unlink(out_file);
        /* set map title */
        sprintf(title, "%s interpolation with Tykhonov regularization",
                type_opt->answer);
        Rast_put_cell_title(out_map_opt->answer, title);
        /* write map history */
        Rast_short_history(out_map_opt->answer, "raster", &history);
        Rast_command_history(&history);
        Rast_write_history(out_map_opt->answer, &history);
    }
    /* Writing to the output vector map the points from the overlapping zones */
    else if (flag_auxiliar == TRUE) {
        if (ext == FALSE)
            P_Aux_to_Vector(&In, &Out, driver, table_name);
        else
            P_Aux_to_Vector(&In_ext, &Out, driver, table_name);

        /* Drop auxiliary table */
        G_debug(1, "%s: Dropping <%s>", argv[0], table_name);
        if (P_Drop_Aux_Table(driver, table_name) != DB_OK)
            G_fatal_error(_("Auxiliary table could not be dropped"));
    }

    db_close_database_shutdown_driver(driver);

    Vect_close(&In);
    if (ext != FALSE)
        Vect_close(&In_ext);
    if (vector)
        Vect_close(&Out);

    G_done_msg(" ");

    exit(EXIT_SUCCESS);
}				/*END MAIN */
Esempio n. 8
0
int main(int argc, char *argv[])
{
    struct GModule *module;
    int Out_proj;
    int out_stat;
    int old_zone, old_proj;
    int i;
    int stat;
    char cmnd2[500];
    char proj_out[20], proj_name[50], set_name[20];
    char path[1024], buffa[1024], buffb[1024], answer[200], answer1[200];
    char answer2[200], buff[1024];
    char tmp_buff[20], *buf;

    struct Key_Value *old_proj_keys, *out_proj_keys, *in_unit_keys;
    double aa, e2;
    double f;
    FILE *FPROJ;
    int exist = 0;
    char spheroid[100];
    int j, k, sph_check;
    struct Cell_head cellhd;
    char datum[100], dat_ellps[100], dat_params[100];
    struct proj_parm *proj_parms;

    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("general"));
    G_add_keyword(_("projection"));
    module->description =
	_("Interactively reset the location's projection settings.");

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


    if (strcmp(G_mapset(), "PERMANENT") != 0)
	G_fatal_error(_("You must be in the PERMANENT mapset to run g.setproj"));

	/***
         * no longer necessary, table is a static struct 
	 * init_unit_table();
        ***/
    sprintf(set_name, "PERMANENT");
    G_file_name(path, "", PROJECTION_FILE, set_name);

    /* get the output projection parameters, if existing */
    /* Check for ownership here */
    stat = G__mapset_permissions(set_name);
    if (stat == 0) {
	G_fatal_error(_("PERMANENT: permission denied"));
    }
    G_get_default_window(&cellhd);
    if (-1 == G_set_window(&cellhd))
	G_fatal_error(_("Current region cannot be set"));

    if (G_get_set_window(&cellhd) == -1)
	G_fatal_error(_("Retrieving and setting region failed"));

    Out_proj = cellhd.proj;
    old_zone = cellhd.zone;
    old_proj = cellhd.proj;

    if (access(path, 0) == 0) {
	exist = 1;
	FPROJ = fopen(path, "r");
	old_proj_keys = G_fread_key_value(FPROJ);
	fclose(FPROJ);
	buf = G_find_key_value("name", old_proj_keys);
	fprintf(stderr,
		"\nWARNING: A projection file already exists for this location\n(Filename '%s')\n",
		path);
	fprintf(stderr,
		"\nThis file contains all the parameters for the location's projection:\n  %s\n",
		buf);
	fprintf(stderr,
		"\n    Overriding this information implies that the old projection parameters\n"
		"    were incorrect.  If you change the parameters, all existing data will\n"
		"    be interpreted differently by the projection software.\n%c%c%c",
		7, 7, 7);
	fprintf(stderr,
		"    GRASS will not re-project your data automatically.\n\n");

	if (!G_yes
	    (_("Would you still like to change some of the parameters?"),
	     0)) {
	    G_message(_("The projection information will not be updated"));
	    leave(SP_NOCHANGE);
	}
    }
    out_proj_keys = G_create_key_value();

    if (exist) {
	buf = G_find_key_value("zone", old_proj_keys);
	if (buf != NULL)
	    sscanf(buf, "%d", &zone);
	if (zone != old_zone) {
	    G_warning(_("Zone in default geographic region definition: %d\n"
			" is different from zone in PROJ_INFO file: %d"),
		      old_zone, zone);
	    old_zone = zone;
	}
    }
    switch (Out_proj) {
    case 0:			/* No projection/units */
	if (!exist) {
	    /* leap frog over code, and just make sure we remove the file */
	    G_warning(_("XY-location cannot be projected"));
	    goto write_file;
	    break;
	}
    case PROJECTION_UTM:
	if (!exist) {
	    sprintf(proj_name, "%s", G__projection_name(PROJECTION_UTM));
	    sprintf(proj_out, "utm");
	    break;
	}
    case PROJECTION_SP:
	if (!exist) {
	    sprintf(proj_name, "%s", G__projection_name(PROJECTION_SP));
	    sprintf(proj_out, "stp");
	    break;
	}
    case PROJECTION_LL:
	if (!exist) {
	    sprintf(proj_name, "%s", G__projection_name(PROJECTION_LL));
	    sprintf(proj_out, "ll");
	    break;
	}
    case PROJECTION_OTHER:
	if (G_ask_proj_name(proj_out, proj_name) < 0)
	    leave(SP_NOCHANGE);

	if (G_strcasecmp(proj_out, "LL") == 0)
	    Out_proj = PROJECTION_LL;
	else if (G_strcasecmp(proj_out, "UTM") == 0)
	    Out_proj = PROJECTION_UTM;
	else if (G_strcasecmp(proj_out, "STP") == 0)
	    Out_proj = PROJECTION_SP;
	break;
    default:
	G_fatal_error(_("Unknown projection"));
    }
    cellhd.proj = Out_proj;

    proj_parms = get_proj_parms(proj_out);
    if (!proj_parms)
	G_fatal_error(_("Projection %s is not specified in the file 'proj-parms.table'"),
		      proj_out);

    G_set_key_value("name", proj_name, out_proj_keys);

    sph_check = 0;
    if (G_yes
	(_("Do you wish to specify a geodetic datum for this location?"),
	 1)) {
	char lbuf[100], lbufa[100];

	if (exist &&
	    (G_get_datumparams_from_projinfo(old_proj_keys, lbuf, lbufa) ==
	     2)) {
	    G_strip(lbuf);
	    if ((i = G_get_datum_by_name(lbuf)) > 0) {
		G_message(_("The current datum is %s (%s)"),
			  G_datum_name(i), G_datum_description(i));
		if (G_yes
		    (_("Do you wish to change the datum (or datum transformation parameters)?"),
		     0))
		    sph_check = ask_datum(datum, dat_ellps, dat_params);
		else {
		    sprintf(datum, lbuf);
		    sprintf(dat_params, lbufa);
		    sprintf(dat_ellps, G_datum_ellipsoid(i));
		    sph_check = 1;
		    G_message(_("The datum information has not been changed"));
		}
	    }
	    else
		sph_check = ask_datum(datum, dat_ellps, dat_params);

	}
	else
	    sph_check = ask_datum(datum, dat_ellps, dat_params);
    }

    if (sph_check > 0) {
	char *paramkey, *paramvalue;

	/* write out key/value pairs to out_proj_keys */
	if (G_strcasecmp(datum, "custom") != 0)
	    G_set_key_value("datum", datum, out_proj_keys);
	/*        G_set_key_value("datumparams", dat_params, out_proj_keys); */
	paramkey = strtok(dat_params, "=");
	paramvalue = dat_params + strlen(paramkey) + 1;
	G_set_key_value(paramkey, paramvalue, out_proj_keys);
	sprintf(spheroid, "%s", dat_ellps);
    }
    else {

/*****************   GET spheroid  **************************/

	if (Out_proj != PROJECTION_SP) {	/* some projections have 
						 * fixed spheroids */
	    if (G_strcasecmp(proj_out, "ALSK") == 0 ||
		G_strcasecmp(proj_out, "GS48") == 0 ||
		G_strcasecmp(proj_out, "GS50") == 0) {
		sprintf(spheroid, "%s", "clark66");
		G_set_key_value("ellps", spheroid, out_proj_keys);
		sph_check = 1;
	    }
	    else if (G_strcasecmp(proj_out, "LABRD") == 0 ||
		     G_strcasecmp(proj_out, "NZMG") == 0) {
		sprintf(spheroid, "%s", "international");
		G_set_key_value("ellps", spheroid, out_proj_keys);
		sph_check = 1;
	    }
	    else if (G_strcasecmp(proj_out, "SOMERC") == 0) {
		sprintf(spheroid, "%s", "bessel");
		G_set_key_value("ellps", spheroid, out_proj_keys);
		sph_check = 1;
	    }
	    else if (G_strcasecmp(proj_out, "OB_TRAN") == 0) {
		/* Hard coded to use "Equidistant Cylincrical"
		 * until g.setproj has been changed to run
		 * recurively, to allow input of options for
		 * a second projection, MHu991010 */
		G_set_key_value("o_proj", "eqc", out_proj_keys);
		sph_check = 2;
	    }
	    else {
		if (exist &&
		    (buf =
		     G_find_key_value("ellps", old_proj_keys)) != NULL) {
		    strcpy(spheroid, buf);
		    G_strip(spheroid);
		    if (G_get_spheroid_by_name(spheroid, &aa, &e2, &f)) {
			/* if legal ellips. exist, ask wether or not to change it */
			G_message(_("The current ellipsoid is %s"), spheroid);
			if (G_yes
			    (_("Do you want to change ellipsoid parameter?"),
			     0))
			    sph_check = G_ask_ellipse_name(spheroid);
			else {
			    G_message(_("The ellipse information has not been changed"));
			    sph_check = 1;
			}
		    }		/* the val is legal */
		    else
			sph_check = G_ask_ellipse_name(spheroid);
		}
		else
		    sph_check = G_ask_ellipse_name(spheroid);
	    }
	}

	if (sph_check > 0) {
	    if (sph_check == 2) {	/* ask radius */
		if (exist) {
		    buf = G_find_key_value("a", old_proj_keys);
		    if ((buf != NULL) && (sscanf(buf, "%lf", &radius) == 1)) {
			G_message(_("The radius is currently %f"), radius);
			if (G_yes(_("Do you want to change the radius?"), 0))
			    radius =
				prompt_num_double(_("Enter radius for the sphere in meters"),
						  RADIUS_DEF, 1);
		    }
		}
		else
		    radius =
			prompt_num_double(_("Enter radius for the sphere in meters"),
					  RADIUS_DEF, 1);
	    }			/* end ask radius */
	}
    }

/*** END get spheroid  ***/


    /* create the PROJ_INFO & PROJ_UNITS files, if required */
    if (G_strcasecmp(proj_out, "LL") == 0) ;
    else if (G_strcasecmp(proj_out, "STP") == 0)
	get_stp_proj(buffb);
    else if (sph_check != 2) {
	G_strip(spheroid);
	if (G_get_spheroid_by_name(spheroid, &aa, &e2, &f) == 0)
	    G_fatal_error(_("Invalid input ellipsoid"));
    }

  write_file:
    /*
     **  NOTE   the program will (hopefully) never exit abnormally
     **  after this point.  Thus we know the file will be completely
     **  written out once it is opened for write 
     */
    if (exist) {
	sprintf(buff, "%s~", path);
	G_rename_file(path, buff);
    }
    if (Out_proj == 0)
	goto write_units;

    /*
     **   Include MISC parameters for PROJ_INFO
     */
    if (G_strcasecmp(proj_out, "STP") == 0) {
	for (i = 0; i < strlen(buffb); i++)
	    if (buffb[i] == ' ')
		buffb[i] = '\t';
	sprintf(cmnd2, "%s\t\n", buffb);
	for (i = 0; i < strlen(cmnd2); i++) {
	    j = k = 0;
	    if (cmnd2[i] == '+') {
		while (cmnd2[++i] != '=')
		    buffa[j++] = cmnd2[i];
		buffa[j] = 0;
		while (cmnd2[++i] != '\t' && cmnd2[i] != '\n' &&
		       cmnd2[i] != 0)
		    buffb[k++] = cmnd2[i];
		buffb[k] = 0;
		G_set_key_value(buffa, buffb, out_proj_keys);
	    }
	}
    }
    else if (G_strcasecmp(proj_out, "LL") == 0) {
	G_set_key_value("proj", "ll", out_proj_keys);
	G_set_key_value("ellps", spheroid, out_proj_keys);
    }
    else {
	if (sph_check != 2) {
	    G_set_key_value("proj", proj_out, out_proj_keys);
	    G_set_key_value("ellps", spheroid, out_proj_keys);
	    sprintf(tmp_buff, "%.10f", aa);
	    G_set_key_value("a", tmp_buff, out_proj_keys);
	    sprintf(tmp_buff, "%.10f", e2);
	    G_set_key_value("es", tmp_buff, out_proj_keys);
	    sprintf(tmp_buff, "%.10f", f);
	    G_set_key_value("f", tmp_buff, out_proj_keys);
	}
	else {
	    G_set_key_value("proj", proj_out, out_proj_keys);
	    /* G_set_key_value ("ellps", "sphere", out_proj_keys); */
	    sprintf(tmp_buff, "%.10f", radius);
	    G_set_key_value("a", tmp_buff, out_proj_keys);
	    G_set_key_value("es", "0.0", out_proj_keys);
	    G_set_key_value("f", "0.0", out_proj_keys);
	}

	for (i = 0;; i++) {
	    struct proj_parm *parm = &proj_parms[i];
	    struct proj_desc *desc;

	    if (!parm->name)
		break;

	    desc = get_proj_desc(parm->name);
	    if (!desc)
		break;

	    if (parm->ask) {
		if (G_strcasecmp(desc->type, "bool") == 0) {
		    if (G_yes((char *)desc->desc, 0)) {
			G_set_key_value(desc->key, "defined", out_proj_keys);
			if (G_strcasecmp(parm->name, "SOUTH") == 0)
			    cellhd.zone = -abs(cellhd.zone);
		    }
		}
		else if (G_strcasecmp(desc->type, "lat") == 0) {
		    double val;

		    while (!get_LL_stuff(parm, desc, 1, &val)) ;
		    sprintf(tmp_buff, "%.10f", val);
		    G_set_key_value(desc->key, tmp_buff, out_proj_keys);
		}
		else if (G_strcasecmp(desc->type, "lon") == 0) {
		    double val;

		    while (!get_LL_stuff(parm, desc, 0, &val)) ;
		    sprintf(tmp_buff, "%.10f", val);
		    G_set_key_value(desc->key, tmp_buff, out_proj_keys);
		}
		else if (G_strcasecmp(desc->type, "float") == 0) {
		    double val;

		    while (!get_double(parm, desc, &val)) ;
		    sprintf(tmp_buff, "%.10f", val);
		    G_set_key_value(desc->key, tmp_buff, out_proj_keys);
		}
		else if (G_strcasecmp(desc->type, "int") == 0) {
		    int val;

		    while (!get_int(parm, desc, &val)) ;
		    sprintf(tmp_buff, "%d", val);
		    G_set_key_value(desc->key, tmp_buff, out_proj_keys);
		}
		else if (G_strcasecmp(desc->type, "zone") == 0) {
		    if ((Out_proj == PROJECTION_UTM) && (old_zone != 0)) {
			G_message(_("The UTM zone is now set to %d"),
				  old_zone);
			if (!G_yes
			    (_("Do you want to change the UTM zone?"), 0)) {
			    G_message(_("UTM zone information has not been updated"));
			    zone = old_zone;
			    break;
			}
			else {
			    G_message(_("But if you change zone, all the existing "
				       "data will be interpreted by projection software. "
				       "GRASS will not automatically re-project or even "
				       "change the headers for existing maps."));
			    if (!G_yes
				(_("Would you still like to change the UTM zone?"),
				 0)) {
				zone = old_zone;
				break;
			    }
			}
		    }		/* UTM */

		    while (!get_zone()) ;

		    sprintf(tmp_buff, "%d", zone);
		    G_set_key_value("zone", tmp_buff, out_proj_keys);
		    cellhd.zone = zone;
		}
	    }
	    else if (parm->def_exists) {
		/* don't ask, use the default */

		if (G_strcasecmp(desc->type, "float") == 0 ||
		    G_strcasecmp(desc->type, "lat") == 0 ||
		    G_strcasecmp(desc->type, "lon") == 0) {
		    sprintf(tmp_buff, "%.10f", parm->deflt);
		    G_set_key_value(desc->key, tmp_buff, out_proj_keys);
		}
		else if (G_strcasecmp(desc->type, "int") == 0) {
		    sprintf(tmp_buff, "%d", (int)parm->deflt);
		    G_set_key_value(desc->key, tmp_buff, out_proj_keys);
		}
	    }
	}			/* for OPTIONS */
    }

    /* create the PROJ_INFO & PROJ_UNITS files, if required */

    G_write_key_value_file(path, out_proj_keys, &out_stat);
    if (out_stat != 0) {
	G_fatal_error(_("Error writing PROJ_INFO file <%s>"), path);
    }

    G_free_key_value(out_proj_keys);
    if (exist)
	G_free_key_value(old_proj_keys);

  write_units:
    G_file_name(path, "", UNIT_FILE, set_name);

    /* if we got this far, the user
     ** already affirmed to write over old info
     ** so if units file is here, remove it.
     */
    if (access(path, 0) == 0) {
	sprintf(buff, "%s~", path);
	G_rename_file(path, buff);
    }
    if (Out_proj == 0)
	leave(0);

    {
	in_unit_keys = G_create_key_value();

	switch (Out_proj) {
	case PROJECTION_UTM:
	    G_set_key_value("unit", "meter", in_unit_keys);
	    G_set_key_value("units", "meters", in_unit_keys);
	    G_set_key_value("meters", "1.0", in_unit_keys);
	    break;
	case PROJECTION_SP:
	    for (;;) {

		do {
		    fprintf(stderr, "\nSpecify the correct units to use:\n");
		    fprintf(stderr, "Enter the corresponding number\n");
		    fprintf(stderr,
			    "1.\tUS Survey Foot (Default for State Plane 1927)\n");
		    fprintf(stderr, "2.\tInternational Foot\n");
		    fprintf(stderr, "3.\tMeter\n");
		    fprintf(stderr, ">");
		} while (!G_gets(answer));

		G_strip(answer);
		if (strcmp(answer, "1") == 0) {
		    G_set_key_value("unit", "USfoot", in_unit_keys);
		    G_set_key_value("units", "USfeet", in_unit_keys);
		    G_set_key_value("meters", "0.30480060960121920243",
				    in_unit_keys);
		    break;
		}
		else if (strcmp(answer, "2") == 0) {
		    G_set_key_value("unit", "foot", in_unit_keys);
		    G_set_key_value("units", "feet", in_unit_keys);
		    G_set_key_value("meters", "0.3048", in_unit_keys);
		    break;
		}
		else if (strcmp(answer, "3") == 0) {
		    G_set_key_value("unit", "meter", in_unit_keys);
		    G_set_key_value("units", "meters", in_unit_keys);
		    G_set_key_value("meters", "1.0", in_unit_keys);
		    break;
		}
		else
		    fprintf(stderr, "\nInvalid Entry (number 1 - 3)\n");
	    }
	    break;
	case PROJECTION_LL:
	    G_set_key_value("unit", "degree", in_unit_keys);
	    G_set_key_value("units", "degrees", in_unit_keys);
	    G_set_key_value("meters", "1.0", in_unit_keys);
	    break;
	default:
	    if (G_strcasecmp(proj_out, "LL") != 0) {
		fprintf(stderr, _("Enter plural form of units [meters]: "));
		G_gets(answer);
		if (strlen(answer) == 0) {
		    G_set_key_value("unit", "meter", in_unit_keys);
		    G_set_key_value("units", "meters", in_unit_keys);
		    G_set_key_value("meters", "1.0", in_unit_keys);
		}
		else {
		    const struct proj_unit *unit;

		    G_strip(answer);
		    unit = get_proj_unit(answer);
		    if (unit) {
#ifdef FOO
			if (G_strcasecmp(proj_out, "STP") == 0 &&
			    !strcmp(answer, "feet")) {
			    fprintf(stderr,
				    "%cPROJECTION 99 State Plane cannot be in FEET.\n",
				    7);
			    remove(path);	/* remove file */
			    leave(SP_FATAL);
			}
#endif
			G_set_key_value("unit", unit->unit, in_unit_keys);
			G_set_key_value("units", unit->units, in_unit_keys);
			sprintf(buffb, "%.10f", unit->fact);
			G_set_key_value("meters", buffb, in_unit_keys);
		    }
		    else {
			double unit_fact;

			while (1) {
			    fprintf(stderr, _("Enter singular for unit: "));
			    G_gets(answer1);
			    G_strip(answer1);
			    if (strlen(answer1) > 0)
				break;
			}
			while (1) {
			    fprintf(stderr,
				    _("Enter conversion factor from %s to meters: "),
				    answer);
			    G_gets(answer2);
			    G_strip(answer2);
			    if (!
				(strlen(answer2) == 0 ||
				 (1 != sscanf(answer2, "%lf", &unit_fact))))
				break;
			}
			G_set_key_value("unit", answer1, in_unit_keys);
			G_set_key_value("units", answer, in_unit_keys);
			sprintf(buffb, "%.10f", unit_fact);
			G_set_key_value("meters", buffb, in_unit_keys);
		    }
		}
	    }
	    else {
		G_set_key_value("unit", "degree", in_unit_keys);
		G_set_key_value("units", "degrees", in_unit_keys);
		G_set_key_value("meters", "1.0", in_unit_keys);
	    }
	}			/* switch */

	G_write_key_value_file(path, in_unit_keys, &out_stat);
	if (out_stat != 0)
	    G_fatal_error(_("Error writing into UNITS output file <%s>"),
			  path);

	G_free_key_value(in_unit_keys);
    }				/* if */

    if (G__put_window(&cellhd, "", "DEFAULT_WIND") < 0)
	G_fatal_error(_("Unable to write to DEFAULT_WIND region file"));
    fprintf(stderr,
	    _("\nProjection information has been recorded for this location\n\n"));
    if ((old_zone != zone) | (old_proj != cellhd.proj)) {
	G_message(_("The geographic region information in WIND is now obsolete"));
	G_message(_("Run g.region -d to update it"));
    }
    leave(0);
}
Esempio n. 9
0
int main( int argc, char **argv )
{
  struct GModule *module;
  struct Option *info_opt, *rast_opt, *vect_opt, *coor_opt, *north_opt, *south_opt, *east_opt, *west_opt, *rows_opt, *cols_opt;
  struct Cell_head window;

  /* Initialize the GIS calls */
  G_gisinit( argv[0] );

  module = G_define_module();
  module->description = ( "Get info about locations,mapsets,maps" );

  info_opt = G_define_option();
  info_opt->key = "info";
  info_opt->type = TYPE_STRING;
  info_opt->description = "info key";
  info_opt->options = "proj,window,size,query,info,colors,stats";

  rast_opt = G_define_standard_option( G_OPT_R_INPUT );
  rast_opt->key = "rast";
  rast_opt->required = NO;

  vect_opt = G_define_standard_option( G_OPT_V_INPUT );
  vect_opt->key = "vect";
  vect_opt->required = NO;

  coor_opt = G_define_option();
  coor_opt->key = "coor";
  coor_opt->type = TYPE_DOUBLE;
  coor_opt->multiple = YES;

  north_opt = G_define_option();
  north_opt->key = "north";
  north_opt->type = TYPE_STRING;

  south_opt = G_define_option();
  south_opt->key = "south";
  south_opt->type = TYPE_STRING;

  east_opt = G_define_option();
  east_opt->key = "east";
  east_opt->type = TYPE_STRING;

  west_opt = G_define_option();
  west_opt->key = "west";
  west_opt->type = TYPE_STRING;

  rows_opt = G_define_option();
  rows_opt->key = "rows";
  rows_opt->type = TYPE_INTEGER;

  cols_opt = G_define_option();
  cols_opt->key = "cols";
  cols_opt->type = TYPE_INTEGER;

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


  if ( strcmp( "proj", info_opt->answer ) == 0 )
  {
    G_get_window( &window );
    /* code from g.proj */
    if ( window.proj != PROJECTION_XY )
    {
      struct Key_Value *projinfo, *projunits;
      char *wkt;
      projinfo = G_get_projinfo();
      projunits = G_get_projunits();
      wkt = GPJ_grass_to_wkt( projinfo, projunits, 0, 0 );
      fprintf( stdout, "%s", wkt );
    }
  }
  else if ( strcmp( "window", info_opt->answer ) == 0 )
  {
    if ( rast_opt->answer )
    {
      G_get_cellhd( rast_opt->answer, "", &window );
      fprintf( stdout, "%f,%f,%f,%f", window.west, window.south, window.east, window.north );
    }
    else if ( vect_opt->answer )
    {
      G_fatal_error( "Not yet supported" );
    }
  }
  // raster width and height
  else if ( strcmp( "size", info_opt->answer ) == 0 )
  {
    if ( rast_opt->answer )
    {
      G_get_cellhd( rast_opt->answer, "", &window );
      fprintf( stdout, "%d,%d", window.cols, window.rows );
    }
    else if ( vect_opt->answer )
    {
      G_fatal_error( "Not yet supported" );
    }
  }
  // raster information
  else if ( strcmp( "info", info_opt->answer ) == 0 )
  {
    struct FPRange range;
    double zmin, zmax;

    // Data type
    RASTER_MAP_TYPE raster_type = G_raster_map_type( rast_opt->answer, "" );
    fprintf( stdout, "TYPE:%d\n", raster_type );

    // Statistics
    if ( G_read_fp_range( rast_opt->answer, "", &range ) < 0 )
    {
      G_fatal_error(( "Unable to read range file" ) );
    }
    G_get_fp_range_min_max( &range, &zmin, &zmax );
    fprintf( stdout, "MIN_VALUE:%.17e\n", zmin );
    fprintf( stdout, "MAX_VALUE:%.17e\n", zmax );
  }
  else if ( strcmp( "colors", info_opt->answer ) == 0 )
  {
    // Color table
    struct Colors colors;
    int i, ccount;
    if ( G_read_colors( rast_opt->answer, "", &colors ) == 1 )
    {
      //int maxcolor;
      //CELL min, max;

      //G_get_color_range ( &min, &max, &colors);
      ccount = G_colors_count( &colors );
      for ( i = ccount - 1; i >= 0; i-- )
      {
        DCELL val1, val2;
        unsigned char r1, g1, b1, r2, g2, b2;

        G_get_f_color_rule( &val1, &r1, &g1, &b1, &val2, &r2, &g2, &b2, &colors, i );
        fprintf( stdout, "%.17e %.17e %d %d %d %d %d %d\n", val1, val2, r1, g1, b1, r2, g2, b2 );
      }
    }
  }

  else if ( strcmp( "query", info_opt->answer ) == 0 )
  {
    double x, y;
    int row, col;
    //x = atof( coor_opt->answers[0] );
    //y = atof( coor_opt->answers[1] );
    if ( rast_opt->answer )
    {
      int fd;
      RASTER_MAP_TYPE rast_type;
      DCELL *dcell;
      CELL *cell;
      char buff[101];
      G_get_cellhd( rast_opt->answer, "", &window );
      G_set_window( &window );
      fd = G_open_cell_old( rast_opt->answer, "" );
      // wait for coords from stdin
      while ( fgets( buff, 100, stdin ) != 0 )
      {
        if ( sscanf( buff, "%lf%lf", &x, &y ) != 2 )
        {
          fprintf( stdout, "value:error\n" );
        }
        else
        {
          col = ( int ) G_easting_to_col( x, &window );
          row = ( int ) G_northing_to_row( y, &window );
          if ( col == window.cols )
            col--;
          if ( row == window.rows )
            row--;

          if ( col < 0 || col > window.cols || row < 0 || row > window.rows )
          {
            //fprintf( stdout, "value:out\n" );
            fprintf( stdout, "value:nan\n" );
          }
          else
          {
            void *ptr;
            double val;

#if defined(GRASS_VERSION_MAJOR) && defined(GRASS_VERSION_MINOR) && \
    ( ( GRASS_VERSION_MAJOR == 6 && GRASS_VERSION_MINOR > 2 ) || GRASS_VERSION_MAJOR > 6 )
            rast_type = G_get_raster_map_type( fd );
#else
            rast_type = G_raster_map_type( rast_opt->answer, "" );
#endif
            cell = G_allocate_c_raster_buf();
            dcell = G_allocate_d_raster_buf();

            if ( rast_type == CELL_TYPE )
            {
#if GRASS_VERSION_MAJOR < 7
              if ( G_get_c_raster_row( fd, cell, row ) < 0 )
              {
                G_fatal_error(( "Unable to read raster map <%s> row %d" ),
                              rast_opt->answer, row );
              }
#else
              G_get_c_raster_row( fd, cell, row );
#endif
              val = cell[col];
              ptr = &( cell[col] );
            }
            else
            {
#if GRASS_VERSION_MAJOR < 7
              if ( G_get_d_raster_row( fd, dcell, row ) < 0 )
              {
                G_fatal_error(( "Unable to read raster map <%s> row %d" ),
                              rast_opt->answer, row );
              }
#else
              G_get_d_raster_row( fd, dcell, row );
#endif
              val = dcell[col];
              ptr = &( dcell[col] );
            }
            if ( G_is_null_value( ptr, rast_type ) )
            {
              fprintf( stdout, "value:nan\n" );
            }
            else
            {
              fprintf( stdout, "value:%f\n", val );
            }
          }
        }
        fflush( stdout );
      }
      G_close_cell( fd );
    }
    else if ( vect_opt->answer )
    {
      G_fatal_error( "Not yet supported" );
    }
  }
  else if ( strcmp( "stats", info_opt->answer ) == 0 )
  {
    if ( rast_opt->answer )
    {
      int fd;
      RASTER_MAP_TYPE rast_type;
      DCELL *dcell;
      CELL *cell;
      int ncols, nrows;
      int row, col;
      void *ptr;
      double val;
      double min = DBL_MAX;
      double max = -DBL_MAX;
      double sum = 0; // sum of values
      int count = 0; // count of non null values
      double mean = 0;
      double squares_sum = 0; // sum of squares
      double stdev = 0; // standard deviation

      G_get_cellhd( rast_opt->answer, "", &window );
      window.north = atof( north_opt->answer );
      window.south = atof( south_opt->answer );
      window.east = atof( east_opt->answer );
      window.west = atof( west_opt->answer );
      window.rows = ( int ) atoi( rows_opt->answer );
      window.cols = ( int ) atoi( cols_opt->answer );

      G_set_window( &window );
      fd = G_open_cell_old( rast_opt->answer, "" );

      ncols = G_window_cols();
      nrows = G_window_rows();

#if defined(GRASS_VERSION_MAJOR) && defined(GRASS_VERSION_MINOR) && \
    ( ( GRASS_VERSION_MAJOR == 6 && GRASS_VERSION_MINOR > 2 ) || GRASS_VERSION_MAJOR > 6 )
      rast_type = G_get_raster_map_type( fd );
#else
      rast_type = G_raster_map_type( rast_opt->answer, "" );
#endif
      cell = G_allocate_c_raster_buf();
      dcell = G_allocate_d_raster_buf();

      // Calc stats is very slow for large rasters -> prefer optimization for speed over
      // code length and readability (which is not currently true)
      for ( row = 0; row < nrows; row++ )
      {
        if ( rast_type == CELL_TYPE )
        {
#if GRASS_VERSION_MAJOR < 7
          if ( G_get_c_raster_row( fd, cell, row ) < 0 )
          {
            G_fatal_error(( "Unable to read raster map <%s> row %d" ),
                          rast_opt->answer, row );
          }
#else
          G_get_c_raster_row( fd, cell, row );
#endif
        }
        else
        {
#if GRASS_VERSION_MAJOR < 7
          if ( G_get_d_raster_row( fd, dcell, row ) < 0 )
          {
            G_fatal_error(( "Unable to read raster map <%s> row %d" ),
                          rast_opt->answer, row );
          }
#else
          G_get_d_raster_row( fd, dcell, row );
#endif
        }

        for ( col = 0; col < ncols; col++ )
        {
          if ( rast_type == CELL_TYPE )
          {
            val = cell[col];
            ptr = &( cell[col] );
          }
          else
          {
            val = dcell[col];
            ptr = &( dcell[col] );
          }
          if ( ! G_is_null_value( ptr, rast_type ) )
          {
            if ( val < min ) min = val;
            if ( val > max ) max = val;
            sum += val;
            count++;
            squares_sum += pow( val, 2 );
          }
        }
      }
      mean = count > 0 ? sum / count : 0;
      squares_sum -= count * pow( mean, 2 );
      stdev = sqrt( squares_sum / ( count - 1 ) );

      fprintf( stdout, "MIN:%.17e\n", min );
      fprintf( stdout, "MAX:%.17e\n", max );
      fprintf( stdout, "SUM:%.17e\n", sum );
      fprintf( stdout, "MEAN:%.17e\n", mean );
      fprintf( stdout, "COUNT:%d\n", count );
      fprintf( stdout, "STDEV:%.17e\n", stdev );
      fprintf( stdout, "SQSUM:%.17e\n", squares_sum );

      G_close_cell( fd );
    }
    else if ( vect_opt->answer )
    {
      G_fatal_error( "Not yet supported" );
    }
  }

  exit( EXIT_SUCCESS );
}
Esempio n. 10
0
int main(int argc, char **argv)
{
    struct band B[3];
    int row;
    int next_row;
    int overlay;
    struct Cell_head window;
    struct GModule *module;
    struct Flag *flag_n;
    int i;

    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("display"));
    G_add_keyword(_("graphics"));
    G_add_keyword(_("raster"));
    G_add_keyword("RGB");
    module->description =
	_("Displays three user-specified raster maps "
	  "as red, green, and blue overlays in the active graphics frame.");

    flag_n = G_define_flag();
    flag_n->key = 'n';
    flag_n->description = _("Make null cells opaque");
    flag_n->guisection = _("Null cells");
    
    for (i = 0; i < 3; i++) {
	char buff[80];

	sprintf(buff, _("Name of raster map to be used for <%s>"),
		color_names[i]);

	B[i].opt = G_define_standard_option(G_OPT_R_MAP);
	B[i].opt->key = G_store(color_names[i]);
	B[i].opt->description = G_store(buff);
    }

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

    /* Do screen initializing stuff */
    D_open_driver();
    
    overlay = !flag_n->answer;

    D_setup(0);
    D_set_overlay_mode(overlay);

    for (i = 0; i < 3; i++) {
	/* Get name of layer to be used */
	char *name = B[i].opt->answer;

	/* Make sure map is available */
	B[i].file = Rast_open_old(name, "");

	B[i].type = Rast_get_map_type(B[i].file);

	/* Reading color lookup table */
	if (Rast_read_colors(name, "", &B[i].colors) == -1)
	    G_fatal_error(_("Color file for <%s> not available"), name);

	B[i].array = Rast_allocate_buf(B[i].type);
    }

    /* read in current window */
    G_get_window(&window);

    D_raster_draw_begin();

    next_row = 0;
    for (row = 0; row < window.rows;) {
	G_percent(row, window.rows, 5);

	for (i = 0; i < 3; i++)
	    Rast_get_row(B[i].file, B[i].array, row, B[i].type);

	if (row == next_row)
	    next_row = D_draw_raster_RGB(next_row,
					 B[0].array, B[1].array, B[2].array,
					 &B[0].colors, &B[1].colors,
					 &B[2].colors, B[0].type, B[1].type,
					 B[2].type);
	else if (next_row > 0)
	    row = next_row;
	else
	    break;
    }
    G_percent(window.rows, window.rows, 5);
    D_raster_draw_end();
    
    D_save_command(G_recreate_command());
    D_close_driver();

    /* Close the raster maps */
    for (i = 0; i < 3; i++)
	Rast_close(B[i].file);

    exit(EXIT_SUCCESS);
}
Esempio n. 11
0
int main(int argc, char **argv)
{
    MELEMENT *rowlist;
    SHORT nrows, ncols;
    SHORT datarows;
    int npoints;
    struct GModule *module;
    struct History history;
    struct
    {
	struct Option *input, *output, *npoints;
    } parm;
    struct
    {
	struct Flag *e;
    } flag;
    int n, fd, maskfd;

    /* Initialize the GIS calls                                     */
    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("raster"));
    G_add_keyword(_("surface"));
    G_add_keyword(_("interpolation"));
    G_add_keyword(_("IDW"));
    module->description =
	_("Surface interpolation utility for raster map.");

    parm.input = G_define_standard_option(G_OPT_R_INPUT);

    parm.output = G_define_standard_option(G_OPT_R_OUTPUT);

    parm.npoints = G_define_option();
    parm.npoints->key = "npoints";
    parm.npoints->type = TYPE_INTEGER;
    parm.npoints->required = NO;
    parm.npoints->description = _("Number of interpolation points");
    parm.npoints->answer = "12";

    flag.e = G_define_flag();
    flag.e->key = 'e';
    flag.e->description = _("Output is the interpolation error");

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

    if (sscanf(parm.npoints->answer, "%d", &n) != 1 || n <= 0)
	G_fatal_error(_("Illegal value for '%s' (%s)"), parm.npoints->key,
		      parm.npoints->answer);

    npoints = n;
    error_flag = flag.e->answer;
    input = parm.input->answer;
    output = parm.output->answer;

    /*  Get database window parameters                              */
    G_get_window(&window);

    /*  find number of rows and columns in window                   */
    nrows = Rast_window_rows();
    ncols = Rast_window_cols();

    /* create distance squared or latitude lookup tables */
    /* initialize function pointers */
    lookup_and_function_ptrs(nrows, ncols);

    /*  allocate buffers for row i/o                                */
    cell = Rast_allocate_c_buf();
    if ((maskfd = Rast_maskfd()) >= 0 || error_flag) {	/* apply mask to output */
	if (error_flag)		/* use input as mask when -e option chosen */
	    maskfd = Rast_open_old(input, "");
	mask = Rast_allocate_c_buf();
    }
    else
	mask = NULL;

    /*  Open input cell layer for reading                           */
    fd = Rast_open_old(input, "");

    /* Store input data in array-indexed doubly-linked lists and close input file */
    rowlist = row_lists(nrows, ncols, &datarows, &n, fd, cell);
    Rast_close(fd);
    if (npoints > n)
	npoints = n;


    /* open cell layer for writing output              */
    fd = Rast_open_c_new(output);

    /* call the interpolation function                              */
    interpolate(rowlist, nrows, ncols, datarows, npoints, fd, maskfd);

    /* free allocated memory */
    free_row_lists(rowlist, nrows);
    G_free(rowlook);
    G_free(collook);
    if (ll)
	free_dist_params();
    Rast_close(fd);
    /* writing history file */
    Rast_short_history(output, "raster", &history);
    Rast_command_history(&history);
    Rast_write_history(output, &history);

    G_done_msg(" ");
    
    exit(EXIT_SUCCESS);
}
Esempio n. 12
0
int main(int argc, char **argv)
{
    struct GModule *module;
    struct Option *opt1, *opt2;
    struct Flag *mapcoords;
    int R, G, B, color = 0;

    /* Initialize the GIS calls */
    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("display"));
    G_add_keyword(_("cartography"));
    module->description =
	_("Program for generating and displaying simple graphics on the "
	  "display monitor.");

    opt1 = G_define_option();
    opt1->key = "input";
    opt1->type = TYPE_STRING;
    opt1->required = NO;
    opt1->description = _("Name of file containing graphics commands, "
			  "if not given reads from standard input");
    opt1->gisprompt = "old_file,file,input";

    opt2 = G_define_option();
    opt2->key = "color";
    opt2->type = TYPE_STRING;
    opt2->required = NO;
    opt2->description = _("Color to draw with, either a standard GRASS color "
			  "or R:G:B triplet");
    opt2->answer = DEFAULT_FG_COLOR;
    opt2->gisprompt = "old_color,color,color";

    mapcoords = G_define_flag();
    mapcoords->key = 'm';
    mapcoords->description = _("Coordinates are given in map units");

    /* Check command line */
    if (G_parser(argc, argv))
	exit(EXIT_FAILURE);

    /* default font scaling: 5% of active frame */
    hsize = vsize = 5.;

    if (opt1->answer != NULL) {
	if ((infile = fopen(opt1->answer, "r")) == NULL)
	    G_fatal_error(_("Graph file <%s> not found"), opt1->answer);
    }
    else
	infile = stdin;

    /* open graphics window */
    if (D_open_driver() != 0)
	G_fatal_error(_("No graphics device selected. "
			"Use d.mon to select graphics device."));
    
    /* Parse and select color */
    if (opt2->answer != NULL) {
	color = G_str_to_color(opt2->answer, &R, &G, &B);

	if (color == 0)
	    G_fatal_error(_("[%s]: No such color"), opt2->answer);

	if (color == 1) {
	    D_RGB_color(R, G, B);
	    set_last_color(R, G, B, RGBA_COLOR_OPAQUE);
	}
	else			/* (color==2) is "none" */
	    set_last_color(0, 0, 0, RGBA_COLOR_NONE);
    }

    if (mapcoords->answer) {
	mapunits = TRUE;
	D_setup(0);
    }
    else {
	D_setup2(0, 0, 100, 0, 0, 100);
	mapunits = FALSE;
    }

    /* Do the graphics */
    set_graph_stuff();
    set_text_size();
    graphics(infile);

    D_save_command(G_recreate_command());
    D_close_driver();

    exit(EXIT_SUCCESS);
}
Esempio n. 13
0
int start_mon(const char *name, const char *output, int select,
	      const char *width, const char *height, const char *bgcolor,
	      int truecolor)
{
    const char *curr_mon;
    char *env_name, *env_value, *cmd_value;
    char *tempfile, buf[1024];
    int env_fd;
    
    curr_mon = G__getenv("MONITOR");
    if (curr_mon && strcmp(curr_mon, name) == 0 && check_mon(curr_mon))
	G_fatal_error(_("Monitor <%s> already running"), name);
    
    tempfile = G_tempfile();

    env_name = env_value = NULL;
    G_asprintf(&env_name, "MONITOR_%s_ENVFILE", name);
    G_asprintf(&env_value, "%s.env", tempfile);
    G_setenv(env_name, env_value);
    env_fd = creat(env_value, 0666);
    if (env_fd < 0)
	G_fatal_error(_("Unable to create file '%s'"), env_value);
    if (width) {
	sprintf(buf, "GRASS_WIDTH=%s\n", width);
	write(env_fd, buf, strlen(buf));
    }
    if (height) {
	sprintf(buf, "GRASS_HEIGHT=%s\n", height);
	write(env_fd, buf, strlen(buf));
    }
    if (bgcolor) {
	if (strcmp(bgcolor, "none") == 0)
	    sprintf(buf, "GRASS_TRANSPARENT=TRUE\n");
	else
	    sprintf(buf, "GRASS_BACKGROUNDCOLOR=%s\n", bgcolor);
	write(env_fd, buf, strlen(buf));
    }
    if (truecolor) {
	sprintf(buf, "GRASS_TRUECOLOR=TRUE\n");
	write(env_fd, buf, strlen(buf));
    }
    close(env_fd);

    cmd_value = NULL;
    G_asprintf(&env_name, "MONITOR_%s_CMDFILE", name);
    G_asprintf(&cmd_value, "%s.cmd", tempfile);
    G_setenv(env_name, cmd_value);
    close(creat(cmd_value, 0666));

    G_verbose_message(_("Staring monitor <%s> with env file '%s'"), name, env_value);
    
    G_debug(1, "start: name=%s ", name);
    G_debug(3, "       envfile = %s", env_value);
    G_debug(3, "       cmdfile = %s", cmd_value);
    
    if (select)
	G_setenv("MONITOR", name);
    
    if (strncmp(name, "wx", 2) == 0) /* use G_strncasecmp() instead */
	start_wx(name, tempfile, env_value, cmd_value, 
		 width, height);
    else
	start(name, output);
    
    return 0;
}
Esempio n. 14
0
int main(int argc, char *argv[])
{
    char *terrainmap, *seedmap, *lakemap, *mapset;
    int rows, cols, in_terran_fd, out_fd, lake_fd, row, col, pases, pass;
    int lastcount, curcount, start_col = 0, start_row = 0;
    double east, north, area = 0, volume = 0;
    FCELL **in_terran, **out_water, water_level, max_depth = 0, min_depth = 0;
    FCELL water_window[3][3];
    struct Option *tmap_opt, *smap_opt, *wlvl_opt, *lake_opt, *sdxy_opt;
    struct Flag *negative_flag, *overwrite_flag;
    struct GModule *module;
    struct Colors colr;
    struct Cell_head window;
    struct History history;

    G_gisinit(argv[0]);
    
    module = G_define_module();
    module->keywords = _("raster, hydrology");
    module->description = _("Fills lake at given point to given level.");

    tmap_opt = G_define_option();
    tmap_opt->key = "dem";
    tmap_opt->key_desc = "name";
    tmap_opt->description = _("Name of terrain raster map (DEM)");
    tmap_opt->type = TYPE_STRING;
    tmap_opt->gisprompt = "old,cell,raster";
    tmap_opt->required = YES;

    wlvl_opt = G_define_option();
    wlvl_opt->key = "wl";
    wlvl_opt->description = _("Water level");
    wlvl_opt->type = TYPE_DOUBLE;
    wlvl_opt->required = YES;

    lake_opt = G_define_option();
    lake_opt->key = "lake";
    lake_opt->key_desc = "name";
    lake_opt->description = _("Name for output raster map with lake");
    lake_opt->type = TYPE_STRING;
    lake_opt->gisprompt = "new,cell,raster";
    lake_opt->required = NO;

    sdxy_opt = G_define_option();
    sdxy_opt->key = "xy";
    sdxy_opt->description = _("Seed point coordinates");
    sdxy_opt->type = TYPE_DOUBLE;
    sdxy_opt->key_desc = "east,north";
    sdxy_opt->required = NO;
    sdxy_opt->multiple = NO;

    smap_opt = G_define_option();
    smap_opt->key = "seed";
    smap_opt->key_desc = "name";
    smap_opt->description =
	_("Name of raster map with given starting point(s) (at least 1 cell > 0)");
    smap_opt->type = TYPE_STRING;
    smap_opt->gisprompt = "old,cell,raster";
    smap_opt->required = NO;

    negative_flag = G_define_flag();
    negative_flag->key = 'n';
    negative_flag->description =
	_("Use negative depth values for lake raster map");

    overwrite_flag = G_define_flag();
    overwrite_flag->key = 'o';
    overwrite_flag->description =
	_("Overwrite seed map with result (lake) map");

    if (G_parser(argc, argv))	/* Returns 0 if successful, non-zero otherwise */
	exit(EXIT_FAILURE);

    if (smap_opt->answer && sdxy_opt->answer)
	G_fatal_error(_("Both seed map and coordinates cannot be specified"));

    if (!smap_opt->answer && !sdxy_opt->answer)
	G_fatal_error(_("Seed map or seed coordinates must be set!"));

    if (sdxy_opt->answer && !lake_opt->answer)
	G_fatal_error(_("Seed coordinates and output map lake= must be set!"));

    if (lake_opt->answer && overwrite_flag->answer)
	G_fatal_error(_("Both lake and overwrite cannot be specified"));

    if (!lake_opt->answer && !overwrite_flag->answer)
	G_fatal_error(_("Output lake map or overwrite flag must be set!"));

    terrainmap = tmap_opt->answer;
    seedmap = smap_opt->answer;
    sscanf(wlvl_opt->answer, "%f", &water_level);
    lakemap = lake_opt->answer;

    /* If lakemap is set, write to it, else is set overwrite flag and we should write to seedmap. */
    if (lakemap) {
	lake_fd = G_open_raster_new(lakemap, 1);
	if (lake_fd < 0)
	    G_fatal_error(_("Unable to create raster map <%s>"), lakemap);
    }

    rows = G_window_rows();
    cols = G_window_cols();

    /* If we use x,y as seed... */
    if (sdxy_opt->answer) {
	G_get_window(&window);
	east = window.east;
	north = window.north;

	G_scan_easting(sdxy_opt->answers[0], &east, G_projection());
	G_scan_northing(sdxy_opt->answers[1], &north, G_projection());
	start_col = (int)G_easting_to_col(east, &window);
	start_row = (int)G_northing_to_row(north, &window);

	if (start_row < 0 || start_row > rows ||
	    start_col < 0 || start_col > cols)
	    G_fatal_error(_("Seed point outside the current region"));
    }

    /* Open terran map */
    mapset = G_find_cell2(terrainmap, "");
    if (mapset == NULL)
	G_fatal_error(_("Raster map <%s> not found"), terrainmap);

    in_terran_fd = G_open_cell_old(terrainmap, mapset);
    if (in_terran_fd < 0)
	G_fatal_error(_("Unable to open raster map <%s>"),
		      G_fully_qualified_name(terrainmap, mapset));

    /* Open seed map */
    if (smap_opt->answer) {
	mapset = G_find_cell2(seedmap, "");
	if (mapset == NULL)
	    G_fatal_error(_("Raster map <%s> not found"), seedmap);

	out_fd = G_open_cell_old(seedmap, mapset);
	if (out_fd < 0)
	    G_fatal_error(_("Unable to open raster map <%s>"),
			  G_fully_qualified_name(seedmap, mapset));
    }

    /* Pointers to rows. Row = ptr to 'col' size array. */
    in_terran = (FCELL **) G_malloc(rows * sizeof(FCELL *));
    out_water = (FCELL **) G_malloc(rows * sizeof(FCELL *));
    if (in_terran == NULL || out_water == NULL)
	G_fatal_error(_("G_malloc: out of memory"));


    G_debug(1, "Loading maps...");
    /* foo_rows[row] == array with data (2d array). */
    for (row = 0; row < rows; row++) {
	in_terran[row] = (FCELL *) G_malloc(cols * sizeof(FCELL));
	out_water[row] = (FCELL *) G_calloc(cols, sizeof(FCELL));

	/* In newly created space load data from file. */
	if (G_get_f_raster_row(in_terran_fd, in_terran[row], row) != 1)
	    G_fatal_error(_("Unable to read raster map <%s> row %d"),
			  terrainmap, row);

	if (smap_opt->answer)
	    if (G_get_f_raster_row(out_fd, out_water[row], row) != 1)
		G_fatal_error(_("Unable to read raster map <%s> row %d"),
			      seedmap, row);

	G_percent(row + 1, rows, 5);
    }

    /* Set seed point */
    if (sdxy_opt->answer)
	/* Check is water level higher than seed point */
	if (in_terran[start_row][start_col] >= water_level)
	    G_fatal_error(_("Given water level at seed point is below earth surface. "
			   "Increase water level or move seed point."));
    out_water[start_row][start_col] = 1;

    /* Close seed map for reading. */
    if (smap_opt->answer)
	G_close_cell(out_fd);

    /* Open output map for writing. */
    if (lakemap) {
	out_fd = lake_fd;
    }
    else {
	out_fd = G_open_raster_new(seedmap, 1);
	if (out_fd < 0)
	    G_fatal_error(_("Unable to create raster map <%s>"), seedmap);
    }

    /* More pases are renudant. Real pases count is controled by altered cell count. */
    pases = (int)(rows * cols) / 2;

    G_debug(1,
	    "Starting lake filling at level of %8.4f in %d passes. Percent done:",
	    water_level, pases);

    lastcount = 0;

    for (pass = 0; pass < pases; pass++) {
	G_debug(3, "Pass: %d", pass);
	curcount = 0;
	/* Move from left upper corner to right lower corner. */
	for (row = 0; row < rows; row++) {
	    for (col = 0; col < cols; col++) {
		/* Loading water data into window. */
		load_window_values(out_water, water_window, rows, cols, row,
				   col);

		/* Cheking presence of water. */
		if (is_near_water(water_window) == 1) {
		    if (in_terran[row][col] < water_level) {
			out_water[row][col] =
			    water_level - in_terran[row][col];
			curcount++;
		    }
		    else {
			out_water[row][col] = 0;	/* Cell is higher than water level -> NULL. */
		    }
		}
	    }
	}
	if (curcount == lastcount)
	    break;		/* We done. */
	lastcount = curcount;
	curcount = 0;
	/* Move backwards - from lower right corner to upper left corner. */
	for (row = rows - 1; row >= 0; row--) {
	    for (col = cols - 1; col >= 0; col--) {
		load_window_values(out_water, water_window, rows, cols, row,
				   col);

		if (is_near_water(water_window) == 1) {
		    if (in_terran[row][col] < water_level) {
			out_water[row][col] =
			    water_level - in_terran[row][col];
			curcount++;
		    }
		    else {
			out_water[row][col] = 0;
		    }
		}
	    }
	}
	G_percent(pass + 1, pases, 10);
	if (curcount == lastcount)
	    break;		/* We done. */
	lastcount = curcount;
    }				/*pases */

    G_percent(pases, pases, 10);	/* Show 100%. */

    save_map(out_water, out_fd, rows, cols, negative_flag->answer, &min_depth,
	     &max_depth, &area, &volume);

    G_message(_("Lake depth from %f to %f"), min_depth, max_depth);
    G_message(_("Lake area %f square meters"), area);
    G_message(_("Lake volume %f cubic meters"), volume);
    G_warning(_("Volume is correct only if lake depth (terrain raster map) is in meters"));

    /* Close all files. Lake map gets written only now. */
    G_close_cell(in_terran_fd);
    G_close_cell(out_fd);

    /* Add blue color gradient from light bank to dark depth */
    G_init_colors(&colr);
    if (negative_flag->answer == 1) {
	G_add_f_raster_color_rule(&max_depth, 0, 240, 255,
				  &min_depth, 0, 50, 170, &colr);
    }
    else {
	G_add_f_raster_color_rule(&min_depth, 0, 240, 255,
				  &max_depth, 0, 50, 170, &colr);
    }

    if (G_write_colors(lakemap, G_mapset(), &colr) != 1)
	G_fatal_error(_("Unable to read color file of raster map <%s>"),
		      lakemap);

    G_short_history(lakemap, "raster", &history);
    G_command_history(&history);
    G_write_history(lakemap, &history);

    return EXIT_SUCCESS;
}
Esempio n. 15
0
int describe(char *name, char *mapset, int compact, char *no_data_str,
	     int range, int windowed, int nsteps, int as_int, int skip_nulls)
{
    int fd;
    struct Cell_stats statf;
    CELL *buf, *b;
    int nrows, ncols;
    int row, col;
    struct Cell_head window;
    CELL negmin = 0, negmax = 0, zero = 0, posmin = 0, posmax = 0;
    CELL null = 0;
    RASTER_MAP_TYPE map_type;
    struct Quant q;
    struct FPRange r;
    DCELL dmin, dmax;
    int (*get_row) ();

    if (windowed) {
	get_row = G_get_c_raster_row;
    }
    else {
	char msg[100];

	if (G_get_cellhd(name, mapset, &window) < 0) {
	    sprintf(msg, "can't get cell header for [%s] in [%s]", name,
		    mapset);
	    G_fatal_error(msg);
	}
	G_set_window(&window);
	get_row = G_get_c_raster_row_nomask;
    }
    fd = G_open_cell_old(name, mapset);
    if (fd < 0)
	return 0;

    map_type = G_get_raster_map_type(fd);
    if (as_int)
	map_type = CELL_TYPE;	/* read as int */

    /* allocate the cell buffer */
    buf = G_allocate_cell_buf();

    if (map_type != CELL_TYPE && range)
	/* this will make it report fp range */
    {
	range = 0;
	nsteps = 1;
    }

    /* start the cell stats */
    if (!range) {
	G_init_cell_stats(&statf);
    }
    else {
	zero = 0;
	negmin = 0;
	negmax = 0;
	posmin = 0;
	posmax = 0;
	null = 0;
	dmin = 0.0;
	dmax = 0.0;
    }

    /* set up quantization rules */
    if (map_type != CELL_TYPE) {
	G_quant_init(&q);
	G_read_fp_range(name, mapset, &r);
	G_get_fp_range_min_max(&r, &dmin, &dmax);
	G_quant_add_rule(&q, dmin, dmax, 1, nsteps);
	G_set_quant_rules(fd, &q);
    }

    nrows = G_window_rows();
    ncols = G_window_cols();

    G_verbose_message("Reading [%s in %s] ...", name, mapset);
    for (row = 0; row < nrows; row++) {
	G_percent(row, nrows, 2);
	if ((*get_row) (fd, b = buf, row) < 0)
	    break;
	if (range) {
	    for (col = ncols; col-- > 0; b++) {
		if (G_is_c_null_value(b))
		    null = 1;
		else if (*b == 0)
		    zero = 1;
		else if (*b < 0) {
		    if (!negmin)
			negmin = negmax = *b;
		    else if (*b > negmax)
			negmax = *b;
		    else if (*b < negmin)
			negmin = *b;
		}
		else {
		    if (!posmin)
			posmin = posmax = *b;
		    else if (*b > posmax)
			posmax = *b;
		    else if (*b < posmin)
			posmin = *b;
		}
	    }
	}
	else
	    G_update_cell_stats(buf, ncols, &statf);
    }
    G_percent(nrows, nrows, 2);
    G_close_cell(fd);
    G_free(buf);

    if (range) {
	if (compact)
	    compact_range_list(negmin, negmax, zero, posmin, posmax, null,
			       no_data_str, skip_nulls);
	else
	    range_list(negmin, negmax, zero, posmin, posmax, null,
		       no_data_str, skip_nulls);
    }
    else {
	G_rewind_cell_stats(&statf);

	if (compact)
	    compact_list(&statf, dmin, dmax, no_data_str, skip_nulls,
			 map_type, nsteps);
	else
	    long_list(&statf, dmin, dmax, no_data_str, skip_nulls, map_type,
		      nsteps);

	G_free_cell_stats(&statf);
    }
    return 1;
}
Esempio n. 16
0
int main(int argc, char *argv[])
{
    char buf[512];
    FILE *fd;
    long old_min, old_max;
    long new_min, new_max;
    long new_delta, old_delta;
    long value, first, prev;
    long cat;
    float divisor;
    char *old_name;
    char *new_name;
    char *mapset;
    struct GModule *module;
    struct
    {
	struct Option *input, *from, *output, *to, *title;
    } parm;

    /* please, remove before GRASS 7 released */
    struct
    {
	struct Flag *quiet;
    } flag;

    G_gisinit(argv[0]);

    module = G_define_module();
    module->keywords = _("raster, rescale");
    module->description =
	_("Rescales the range of category values " "in a raster map layer.");

    /* Define the different options */

    parm.input = G_define_option();
    parm.input->key = "input";
    parm.input->type = TYPE_STRING;
    parm.input->required = YES;
    parm.input->gisprompt = "old,cell,raster";
    parm.input->description = _("The name of the raster map to be rescaled");

    parm.from = G_define_option();
    parm.from->key = "from";
    parm.from->key_desc = "min,max";
    parm.from->type = TYPE_INTEGER;
    parm.from->required = NO;
    parm.from->description =
	_("The input data range to be rescaled (default: full range of input map)");

    parm.output = G_define_option();
    parm.output->key = "output";
    parm.output->type = TYPE_STRING;
    parm.output->required = YES;
    parm.output->gisprompt = "new,cell,raster";
    parm.output->description = _("The resulting raster map name");

    parm.to = G_define_option();
    parm.to->key = "to";
    parm.to->key_desc = "min,max";
    parm.to->type = TYPE_INTEGER;
    parm.to->required = YES;
    parm.to->description = _("The output data range");

    parm.title = G_define_option();
    parm.title->key = "title";
    parm.title->key_desc = "\"phrase\"";
    parm.title->type = TYPE_STRING;
    parm.title->required = NO;
    parm.title->description = _("Title for new raster map");

    /* please, remove before GRASS 7 released */
    flag.quiet = G_define_flag();
    flag.quiet->key = 'q';
    flag.quiet->description = _("Quietly");

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

    /* please, remove before GRASS 7 released */
    if (flag.quiet->answer) {
	putenv("GRASS_VERBOSE=0");
	G_warning(_("The '-q' flag is superseded and will be removed "
		    "in future. Please use '--quiet' instead."));
    }

    old_name = parm.input->answer;
    new_name = parm.output->answer;

    mapset = G_find_cell(old_name, "");
    if (mapset == NULL) {
	sprintf(buf, "%s - not found\n", old_name);
	G_fatal_error(buf);
    }
    if (G_legal_filename(new_name) < 0) {
	sprintf(buf, "%s - illegal map name\n", new_name);
	G_fatal_error(buf);
    }

    if (parm.from->answer) {
	sscanf(parm.from->answers[0], "%ld", &old_min);
	sscanf(parm.from->answers[1], "%ld", &old_max);

    }
    else
	get_range(old_name, mapset, &old_min, &old_max);
    if (old_min > old_max) {
	value = old_min;	/* swap */
	old_min = old_max;
	old_max = value;
    }

    sscanf(parm.to->answers[0], "%ld", &new_min);
    sscanf(parm.to->answers[1], "%ld", &new_max);
    if (new_min > new_max) {
	value = new_min;	/* swap */
	new_min = new_max;
	new_max = value;
    }

    G_message(_("Rescale %s[%ld,%ld] to %s[%ld,%ld]"),
	      old_name, old_min, old_max, new_name, new_min, new_max);

    sprintf(buf, "r.reclass input=\"%s\" output=\"%s\" title=\"", old_name,
	    new_name);
    if (parm.title->answer)
	strcat(buf, parm.title->answer);
    else {
	strcat(buf, "rescale of ");
	strcat(buf, old_name);
    }
    strcat(buf, "\"");

    fd = popen(buf, "w");
    old_delta = old_max - old_min;
    new_delta = new_max - new_min;
    divisor = (float)new_delta / (float)old_delta;

    prev = new_min;
    first = old_min;
    for (cat = old_min; cat <= old_max; cat++) {
	value = (int)(divisor * (cat - old_min) + new_min + .5);
	if (value != prev) {
	    fprintf(fd, "%ld thru %ld = %ld %ld", first, cat - 1, prev,
		    first);
	    if (cat - 1 != first)
		fprintf(fd, " thru %ld", cat - 1);
	    fprintf(fd, "\n");
	    prev = value;
	    first = cat;
	}
    }
    fprintf(fd, "%ld thru %ld = %ld %ld", first, cat - 1, prev, first);
    if (cat - 1 != first)
	fprintf(fd, " thru %ld", cat - 1);
    fprintf(fd, "\n");

    pclose(fd);
    exit(EXIT_SUCCESS);
}
Esempio n. 17
0
int main(int argc, char **argv)
{
    struct Cell_head window;
    struct Categories cats;
    struct GModule *module;
    struct Option *opt1, *opt2, *opt3;
    struct Flag *fancy_mode, *simple_mode, *draw;
    char *tmpfile;
    FILE *fp;

    /* Initialize the GIS calls */
    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("display"));
    G_add_keyword(_("cartography"));
    module->description =
	_("Create a TITLE for a raster map in a form suitable "
	  "for display with d.text.");

    opt1 = G_define_standard_option(G_OPT_R_MAP);

    opt2 = G_define_option();
    opt2->key = "color";
    opt2->type = TYPE_STRING;
    opt2->answer = DEFAULT_FG_COLOR;
    opt2->required = NO;
    opt2->gisprompt = "old_color,color,color";
    opt2->description = _("Sets the text color");

    opt3 = G_define_option();
    opt3->key = "size";
    opt3->type = TYPE_DOUBLE;
    opt3->answer = "4.0";
    opt3->options = "0-100";
    opt3->description =
	_("Sets the text size as percentage of the frame's height");

    draw = G_define_flag();
    draw->key = 'd';
    draw->description = _("Draw title on current display");

    fancy_mode = G_define_flag();
    fancy_mode->key = 'f';
    fancy_mode->description = _("Do a fancier title");

    /* currently just title, but it doesn't have to be /that/ simple */
    simple_mode = G_define_flag();
    simple_mode->key = 's';
    simple_mode->description = _("Do a simple title");


    /* Check command line */
    if (G_parser(argc, argv))
	exit(EXIT_FAILURE);


    map_name = opt1->answer;

    color = opt2->answer;

    if (opt3->answer != NULL)
	sscanf(opt3->answer, "%f", &size);

    type = fancy_mode->answer ? FANCY : NORMAL;

    if (fancy_mode->answer && simple_mode->answer)
	G_fatal_error(_("Title can be fancy or simple, not both"));

    if (!strlen(map_name))
	G_fatal_error(_("No map name given"));

    Rast_get_cellhd(map_name, "", &window);

    if (Rast_read_cats(map_name, "", &cats) == -1)
	G_fatal_error(_("Unable to read category file of raster map <%s>"),
		      map_name);


    if (draw->answer) {
	tmpfile = G_convert_dirseps_to_host(G_tempfile());
	if (!(fp = fopen(tmpfile, "w")))
	    G_fatal_error(_("Unable to open temporary file <%s>"), tmpfile);
    }
    else
	fp = stdout;


    if (type == NORMAL)
	normal(&window, &cats, simple_mode->answer, fp);
    else
	fancy(&window, &cats, fp);


    if (draw->answer) {
	char inarg[GPATH_MAX];
	fclose(fp);
	sprintf(inarg, "input=%s", tmpfile);
	G_spawn("d.text", "d.text", inarg, NULL);
	unlink(tmpfile);
	/* note a tmp file will remain, created by d.text so it can survive d.redraw */
    }

    exit(EXIT_SUCCESS);
}
Esempio n. 18
0
int write_line(PAD_ENT_HDR adenhd, int type, int level)
{
    int i, l;
    double x, y, z, r, ang;

    adSeekLayer(dwghandle, adenhd->entlayerobjhandle, Layer);

    /* Transformation, go up through all levels of transformation */
    /* not sure what is the right order of transformation */
    for (l = level; l >= 0; l--) {
	for (i = 0; i < Points->n_points; i++) {
	    /* scale */
	    x = Points->x[i] * Trans[l].xscale;
	    y = Points->y[i] * Trans[l].yscale;
	    z = Points->z[i] * Trans[l].zscale;
	    /* rotate */
	    r = sqrt(x * x + y * y);
	    ang = atan2(y, x) + Trans[l].rotang;
	    x = r * cos(ang);
	    y = r * sin(ang);
	    /* move */
	    x += Trans[l].dx;
	    y += Trans[l].dy;
	    z += Trans[l].dz;
	    Points->x[i] = x;
	    Points->y[i] = y;
	    Points->z[i] = z;
	}
    }

    Vect_reset_cats(Cats);
    Vect_cat_set(Cats, 1, cat);
    Vect_write_line(&Map, type, Points, Cats);

    /* Cat */
    sprintf(buf, "insert into %s values ( %d", Fi->table, cat);
    db_set_string(&sql, buf);

    /* Entity name */
    getEntTypeName(adenhd, buf2);
    sprintf(buf, ", '%s'", buf2);
    db_append_string(&sql, buf);

    /* Color */
    sprintf(buf, ", %d", adenhd->entcolor);
    db_append_string(&sql, buf);

    /* Weight */
    sprintf(buf, ", %d", adenhd->lineweight);
    db_append_string(&sql, buf);

    /* Layer name */
    if (!Layer->purgedflag && Layer->name != NULL) {
	db_set_string(&str, Layer->name);
	db_double_quote_string(&str);
	sprintf(buf, ", '%s'", db_get_string(&str));
    }
    else {
	sprintf(buf, ", ''");
    }
    db_append_string(&sql, buf);

    /* Block name */
    if (Block != NULL) {
	db_set_string(&str, Block);
	db_double_quote_string(&str);
    }
    else {
	db_set_string(&str, "");
    }
    sprintf(buf, ", '%s'", db_get_string(&str));
    db_append_string(&sql, buf);

    /* Text */
    if (Txt != NULL) {
	db_set_string(&str, Txt);
	db_double_quote_string(&str);
    }
    else {
	db_set_string(&str, "");
    }
    sprintf(buf, ", '%s'", db_get_string(&str));
    db_append_string(&sql, buf);

    db_append_string(&sql, ")");
    G_debug(3, db_get_string(&sql));

    if (db_execute_immediate(driver, &sql) != DB_OK) {
	db_close_database(driver);
	db_shutdown_driver(driver);
	G_fatal_error("Cannot insert new row: %s", db_get_string(&sql));
    }

    cat++;
    return 0;
}
Esempio n. 19
0
int main(int argc, char *argv[])
{

    struct GModule *module;
    struct Option *coord, *out_file, *min, *max, *mult;
    struct Flag *flag;
    int *int_buf;
    struct Cell_head w;
    struct History history;
    int cellfile;
    double east, north, pt[2], cur[2], row, col, fmult;
    double fmin, fmax;
    int binary;

    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("raster"));
    G_add_keyword(_("buffer"));
    G_add_keyword(_("geometry"));
    G_add_keyword(_("circle"));
    module->description =
	_("Creates a raster map containing concentric "
	  "rings around a given point.");

    out_file = G_define_standard_option(G_OPT_R_OUTPUT);

    coord = G_define_standard_option(G_OPT_M_COORDS);
    coord->required = YES;
    coord->description = _("The coordinate of the center (east,north)");

    min = G_define_option();
    min->key = "min";
    min->type = TYPE_DOUBLE;
    min->required = NO;
    min->description = _("Minimum radius for ring/circle map (in meters)");

    max = G_define_option();
    max->key = "max";
    max->type = TYPE_DOUBLE;
    max->required = NO;
    max->description = _("Maximum radius for ring/circle map (in meters)");

    mult = G_define_option();
    mult->key = "multiplier";
    mult->type = TYPE_DOUBLE;
    mult->required = NO;
    mult->description = _("Data value multiplier");

    flag = G_define_flag();
    flag->key = 'b';
    flag->description = _("Generate binary raster map");

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

    G_scan_easting(coord->answers[0], &east, G_projection());
    G_scan_northing(coord->answers[1], &north, G_projection());
    pt[0] = east;
    pt[1] = north;

    fmult = 1.0;

    if (min->answer)
	sscanf(min->answer, "%lf", &fmin);
    else
	fmin = 0;

    if (max->answer)
	sscanf(max->answer, "%lf", &fmax);
    else
	fmax = HUGE_VAL;

    if (fmin > fmax)
	G_fatal_error(_("Please specify a radius in which min < max"));

    if (mult->answer)
	if (1 != sscanf(mult->answer, "%lf", &fmult))
	    fmult = 1.0;

    /* nonsense test */
    if (flag->answer && (!min->answer && !max->answer))
	G_fatal_error(_("Please specify min and/or max radius when "
			"using the binary flag"));

    if (flag->answer)
	binary = 1;		/* generate binary pattern only, useful for MASK */
    else
	binary = 0;

    G_get_set_window(&w);

    cellfile = Rast_open_c_new(out_file->answer);

    int_buf = (int *)G_malloc(w.cols * sizeof(int));
    {
	int c;

	for (row = 0; row < w.rows; row++) {
	    G_percent(row, w.rows, 2);
	    cur[1] = Rast_row_to_northing(row + 0.5, &w);
	    for (col = 0; col < w.cols; col++) {
		c = col;
		cur[0] = Rast_col_to_easting(col + 0.5, &w);
		int_buf[c] =
		    (int)(distance(pt, cur, fmin, fmax, binary) * fmult);
		if (int_buf[c] == 0)
		    Rast_set_null_value(&int_buf[c], 1, CELL_TYPE);
	    }
	    Rast_put_row(cellfile, int_buf, CELL_TYPE);

	}
    }
    G_free(int_buf);
    Rast_close(cellfile);
    Rast_short_history(out_file->answer, "raster", &history);
    Rast_command_history(&history);
    Rast_write_history(out_file->answer, &history);

    G_done_msg(_("Raster map <%s> created."),
	       out_file->answer);
    
    return (EXIT_SUCCESS);
}
Esempio n. 20
0
/* data preparations, sigma, shear, etc. */
int grad_check(void)
{
    int k, l;
    double zx, zy, zd2, zd4, sinsl;
    double cc, cmul2;
    double sheer;
    double vsum = 0.;
    double vmax = 0.;
    double chsum = 0.;
    double zmin = 1.e12;
    double zmax = -1.e12;
    double zd2min = 1.e12;
    double zd2max = -1.e12;
    double smin = 1.e12;
    double smax = -1.e12;
    double infmin = 1.e12;
    double infmax = -1.e12;
    double sigmax = -1.e12;
    double cchezmax = -1.e12;
    double rhow = 1000.;
    double gacc = 9.81;
    double hh = 1.;
    double deltaw = 1.e12;

    sisum = 0.;
    infsum = 0.;
    cmul2 = rhow * gacc;

    for (k = 0; k < my; k++) {
	for (l = 0; l < mx; l++) {
	    if (zz[k][l] != UNDEF) {
		zx = v1[k][l];
		zy = v2[k][l];
		zd2 = zx * zx + zy * zy;
		sinsl = sqrt(zd2) / sqrt(zd2 + 1);	/* sin(terrain slope) */
		/* Computing MIN */
		zd2 = sqrt(zd2);
		zd2min = amin1(zd2min, zd2);
		/* Computing MAX */
		zd2max = amax1(zd2max, zd2);
		zd4 = sqrt(zd2);	/* ^.25 */
		if (cchez[k][l] != 0.) {
		    cchez[k][l] = 1. / cchez[k][l];	/* 1/n */
		}
		else {
		    G_fatal_error(_("Zero value in Mannings n"));
		}
		if (zd2 == 0.) {
		    v1[k][l] = 0.;
		    v2[k][l] = 0.;
		    slope[k][l] = 0.;
		}
		else {
		    if (wdepth)
			hh = pow(gama[k][l], 2. / 3.);
		    /* hh = 1 if there is no water depth input */
		    v1[k][l] = (double)hh *cchez[k][l] * zx / zd4;
		    v2[k][l] = (double)hh *cchez[k][l] * zy / zd4;

		    slope[k][l] =
			sqrt(v1[k][l] * v1[k][l] + v2[k][l] * v2[k][l]);
		}
		if (wdepth) {
		    sheer = (double)(cmul2 * gama[k][l] * sinsl);	/* shear stress */
		    /* if critical shear stress >= shear then all zero */
		    if ((sheer <= tau[k][l]) || (ct[k][l] == 0.)) {
			si[k][l] = 0.;
			sigma[k][l] = 0.;
		    }
		    else {
			si[k][l] = (double)(dc[k][l] * (sheer - tau[k][l]));
			sigma[k][l] = (double)(dc[k][l] / ct[k][l]) * (sheer - tau[k][l]) / (pow(sheer, 1.5));	/* rill erosion=1.5, sheet = 1.1 */
		    }
		}
		sisum += si[k][l];
		smin = amin1(smin, si[k][l]);
		smax = amax1(smax, si[k][l]);
		if (inf) {
		    infsum += inf[k][l];
		    infmin = amin1(infmin, inf[k][l]);
		    infmax = amax1(infmax, inf[k][l]);
		}
		vmax = amax1(vmax, slope[k][l]);
		vsum += slope[k][l];
		chsum += cchez[k][l];
		zmin = amin1(zmin, (double)zz[k][l]);
		zmax = amax1(zmax, (double)zz[k][l]);	/* not clear were needed */
		if (wdepth)
		    sigmax = amax1(sigmax, sigma[k][l]);
		cchezmax = amax1(cchezmax, cchez[k][l]);
		/* saved sqrt(sinsl)*cchez to cchez array for output */
		cchez[k][l] *= sqrt(sinsl);
	    }			/* DEFined area */
	}
    }
    if (inf != NULL && smax < infmax)
	G_warning(_("Infiltration exceeds the rainfall rate everywhere! No overland flow."));

    cc = (double)mx *my;

    si0 = sisum / cc;
    vmean = vsum / cc;
    chmean = chsum / cc;

    if (inf)
	infmean = infsum / cc;

    if (wdepth)
	deltaw = 0.8 / (sigmax * vmax);	/*time step for sediment */
    deltap = 0.25 * sqrt(stepx * stepy) / vmean;	/*time step for water */

    if (deltaw > deltap)
	timec = 4.;
    else
	timec = 1.25;

    miter = (int)(timesec / (deltap * timec));	/* number of iterations = number of cells to pass */
    iterout = (int)(iterout / (deltap * timec));	/* number of cells to pass for time series output */

    fprintf(stderr, "\n");
    G_message(_("Min elevation \t= %.2f m\nMax elevation \t= %.2f m\n"), zmin,
	      zmax);
    G_message(_("Mean Source Rate (rainf. excess or sediment) \t= %f m/s or kg/m2s \n"),
	      si0);
    G_message(_("Mean flow velocity \t= %f m/s\n"), vmean);
    G_message(_("Mean Mannings \t= %f\n"), 1.0 / chmean);

    deltap = amin1(deltap, deltaw);

    G_message(_("Number of iterations \t= %d cells\n"), miter);
    G_message(_("Time step \t= %.2f s\n"), deltap);
    if (wdepth) {
	G_message(_("Sigmax \t= %f\nMax velocity \t= %f m/s\n"), sigmax,
		  vmax);
	G_message(_("Time step used \t= %.2f s\n"), deltaw);
    }
    /*    if (wdepth) deltap = 0.1; 
     *    deltap for sediment is ar. average deltap and deltaw */
    /*    if (wdepth) deltap = (deltaw+deltap)/2.; 
     *    deltap for sediment is ar. average deltap and deltaw */


    /*! For each cell (k,l) compute the length s=(v1,v2) of the path 
     *  that the particle will travel per one time step
     *  \f$ s(k,l)=v(k,l)*dt \f$, [m]=[m/s]*[s]
     *  give warning if there is a cell that will lead to path longer than 2 cells 
     *
     *  if running erosion, compute sediment transport capacity for each cell si(k,l)
     *  \f$
     * T({\bf r})=K_t({\bf r}) \bigl[\tau({\bf r})\bigr]^p
     * =K_t({\bf r}) \bigl[\rho_w\, g h({\bf r}) \sin \beta ({\bf r}) \bigr]^p
     * \f$
     * [kg/ms]=...
     */
    for (k = 0; k < my; k++) {
	for (l = 0; l < mx; l++) {
	    if (zz[k][l] != UNDEF) {
		v1[k][l] *= deltap;
		v2[k][l] *= deltap;
		/*if(v1[k][l]*v1[k][l]+v2[k][l]*v2[k][l] > cellsize, warning, napocitaj
		 *ak viac ako 10%a*/
		/* THIS IS CORRECT SOLUTION currently commented out */
		if (inf)
		    inf[k][l] *= timesec;
		if (wdepth)
		    gama[k][l] = 0.;
		if (et) {
		    if (sigma[k][l] == 0. || slope[k][l] == 0.)
			si[k][l] = 0.;
		    else
			/* temp for transp. cap. erod */
			si[k][l] = si[k][l] / (slope[k][l] * sigma[k][l]);
		}
	    }			/* DEFined area */
	}
    }

    /*! compute transport capacity limted erosion/deposition et 
     *   as a divergence of sediment transport capacity
     *   \f$
     D_T({\bf r})= \nabla\cdot {\bf T}({\bf r})
     *   \f$
     */
    if (et) {
	erod(si);		/* compute divergence of t.capc */
	if (output_et() != 1)
	    G_fatal_error(_("Unable to write et file"));
    }

    /*! compute the inversion operator and store it in sigma - note that after this
     *   sigma does not store the first order reaction coefficient but the operator
     *   WRITE the equation here
     */
    if (wdepth) {
	for (k = 0; k < my; k++) {
	    for (l = 0; l < mx; l++) {
		if (zz[k][l] != UNDEF) {
		    /* get back from temp */
		    if (et)
			si[k][l] = si[k][l] * slope[k][l] * sigma[k][l];
		    if (sigma[k][l] != 0.)
			/* rate of weight loss - w=w*sigma ,
			 * vaha prechadzky po n-krokoch je sigma^n */

			/*!!!!! not clear what's here :-\ !!!!!*/

			sigma[k][l] =
			    exp(-sigma[k][l] * deltap * slope[k][l]);
		    /* if(sigma[k][l]<0.5) warning, napocitaj, 
		     * ak vacsie ako 50% skonci, zmensi deltap)*/
		}
	    }			/*DEFined area */
	}
    }
    return 1;
}
Esempio n. 21
0
int E_edit_fp_cats(const char *name, struct Categories *cats)
{
    long incr;
    long atnum;
    long startcat;
    long endcat;
    char buff[NLINES][60];
    char next[20];
    char next_line[80];
    char title[80];
    char msg1[80];
    char msg2[80];
    int line, ncats;
    size_t lab_len;
    DCELL max_val[NLINES], min_val[NLINES];
    DCELL dmin, dmax;
    CELL tmp_cell;
    struct Categories old_cats;
    struct FPRange fp_range;

    if (G_read_fp_range(name, G_mapset(), &fp_range) < 0)
	G_fatal_error("can't read the floating point range for %s", name);

    G_get_fp_range_min_max(&fp_range, &dmin, &dmax);
    /* first save old cats */
    G_copy_raster_cats(&old_cats, cats);

    G_init_raster_cats(old_cats.title, cats);
    G_free_raster_cats(cats);

    ncats = old_cats.ncats;
    V_clear();

    if (!ncats)
	sprintf(msg1, "There are no predefined fp ranges to label");
    else
	sprintf(msg1, "There are %d predefined fp ranges to label", ncats);
    sprintf(msg2, "Enter the number of fp ranges you want to label");

    V_line(1, msg1);
    V_line(2, msg2);
    V_ques(&ncats, 'l', 2, 48, 5);
    V_line(16, next_line);
    *next_line = 0;
    V_intrpt_ok();

    if (!V_call())
	return -1;

    *title = 0;
    if (old_cats.title != NULL)
	strcpy(title, old_cats.title);

    startcat = 0;
    sprintf(msg1, "The fp data in map %s ranges from %f to %f", name, dmin,
	    dmax);
    sprintf(msg2, "[%s] ENTER NEW CATEGORY NAMES FOR THESE CATEGORIES", name);

    while (1) {
	V_clear();
	V_line(0, msg1);
	V_line(1, msg2);
	V_line(3, "TITLE: ");
	V_line(4, "FP RANGE           NEW CATEGORY NAME");

	V_ques(title, 's', 2, 8, 60);

	endcat = startcat + NLINES <= ncats ? startcat + NLINES : ncats;

	line = 6;
	for (incr = startcat; incr < endcat; incr++) {
	    atnum = incr - startcat;
	    if (incr < old_cats.ncats) {
		/* if editing existing range label */
		lab_len = strlen(old_cats.labels[incr]);
		if (lab_len > 58)
		    lab_len = 58;
		strncpy(buff[atnum], old_cats.labels[incr], lab_len);
		buff[atnum][lab_len] = 0;
		G_quant_get_ith_rule(&old_cats.q, incr, &min_val[atnum],
				     &max_val[atnum], &tmp_cell, &tmp_cell);
	    }
	    else {
		/* adding new range label */
		strcpy(buff[atnum], "");
		max_val[atnum] = min_val[atnum] = 0;
	    }

	    V_ques(&min_val[atnum], 'd', line, 1, 8);
	    V_const("-", 's', line, 9, 1);
	    V_ques(&max_val[atnum], 'd', line, 10, 8);
	    V_ques(buff[atnum], 's', line, 19, 58);
	    line++;
	}

	line += 2;
	*next = 0;
	if (endcat >= ncats)
	    strcpy(next, "end");
	else
	    sprintf(next, "%ld", endcat);
	sprintf(next_line, "%*s%*s  (of %d)", 41,
		"Next range number ('end' to end): ", 5, "", ncats);
	V_line(line, next_line);
	V_ques(next, 's', line, 41, 5);

	V_intrpt_ok();
	if (!V_call())
	    return -1;

	/* store new category name in structure */
	for (incr = startcat; incr < endcat; incr++) {
	    atnum = incr - startcat;
	    G_strip(buff[atnum]);

	    /* adding new range label */
	    if (!(strcmp(buff[atnum], "") == 0 &&
		  min_val[atnum] == 0. && max_val[atnum] == 0.))
		G_set_d_raster_cat(&min_val[atnum], &max_val[atnum],
				   buff[atnum], cats);
	}

	if (*next == 0)
	    break;
	if (strcmp(next, "end") == 0)
	    break;
	if (sscanf(next, "%ld", &endcat) != 1)
	    continue;

	if (endcat < 0)
	    endcat = 0;

	if (endcat > ncats) {
	    endcat = ncats - NLINES + 1;
	    if (endcat < 0)
		endcat = 0;
	}
	startcat = endcat;
    }

    G_strip(title);
    cats->title = G_store(title);
    /* since label pointers in old_cats point to the old allocated strings,
       and cats now has all the newly allocated strings, it never reuses
       old ones, we need to free them */

    return (1);
}
Esempio n. 22
0
/* Read all input maps and input values into memory ************************ */
int input_data(void)
{
    int rows = my, cols = mx; /* my and mx are global variables */
    double unitconv = 0.0000002;	/* mm/hr to m/s */
    int if_rain = 0;

    G_debug(1, "Running MAR 2011 version, started modifications on 20080211");
    G_debug(1, "Reading input data");
    
    /* Elevation and gradients are mandatory */
    zz = read_float_raster_map(rows, cols, elevin, 1.0);
    v1 = read_double_raster_map(rows, cols, dxin, 1.0);
    v2 = read_double_raster_map(rows, cols, dyin, 1.0);

    /* Update elevation map */
    copy_matrix_undef_double_to_float_values(rows, cols, v1, zz);
    copy_matrix_undef_double_to_float_values(rows, cols, v2, zz);

    /* Manning surface roughnes: read map or use a single value */
    if(manin != NULL) {
    	cchez = read_float_raster_map(rows, cols, manin, 1.0);
     } else if(manin_val >= 0.0) { /* If no value set its set to -999.99 */
	cchez = create_float_matrix(rows, cols, manin_val);
    }else{
        G_fatal_error(_("Raster map <%s> not found, and manin_val undefined, choose one to be allowed to process"), manin);
    }
       
    /* Rain: read rain map or use a single value for all cells */
    if (rain != NULL) {
	si = read_double_raster_map(rows, cols, rain, unitconv);
	if_rain = 1;
    } else if(rain_val >= 0.0) { /* If no value set its set to -999.99 */
	si = create_double_matrix(rows, cols, rain_val * unitconv);
	if_rain = 1;
    } else{
	si = create_double_matrix(rows, cols, (double)UNDEF);
	if_rain = 0;
    }

    /* Update elevation map */
    copy_matrix_undef_double_to_float_values(rows, cols, si, zz);

    /* Load infiltration and traps if rain is present */
    if(if_rain == 1) {
	/* Infiltration: read map or use a single value */
        if (infil != NULL) {
            inf = read_double_raster_map(rows, cols, infil, unitconv);
        } else if(infil_val >= 0.0) { /* If no value set its set to -999.99 */
	    inf = create_double_matrix(rows, cols, infil_val * unitconv);
        } else{
	    inf = create_double_matrix(rows, cols, (double)UNDEF);
        }

   	/* Traps */
        if (traps != NULL)
            trap = read_float_raster_map(rows, cols, traps, 1.0);
	else
	    trap = create_float_matrix(rows, cols, (double)UNDEF);
    }

    if (detin != NULL) {
    	 dc = read_float_raster_map(rows, cols, detin, 1.0);
         copy_matrix_undef_float_values(rows, cols, dc, zz);
    }

    if (tranin != NULL) {
    	 ct = read_float_raster_map(rows, cols, tranin, 1.0);
         copy_matrix_undef_float_values(rows, cols, ct, zz);
    }

    if (tauin != NULL) {
    	 tau = read_float_raster_map(rows, cols, tauin, 1.0);
         copy_matrix_undef_float_values(rows, cols, tau, zz);
    }

    if (wdepth != NULL) {
        gama = read_double_raster_map(rows, cols, wdepth, 1.0);
        copy_matrix_undef_double_to_float_values(rows, cols, gama, zz);
    }
    
    /* Array for gradient checking */
    slope = create_double_matrix(rows, cols, 0.0);
    
    /* Create the observation points and open the logfile */
    create_observation_points();

  return 1;
}
Esempio n. 23
0
int avl_add(avl_tree * root, const generic_cell k, const long n)
{

    avl_node *p = NULL;
    avl_node *node_temp = NULL;
    avl_node *critical = NULL;

    int d = 0;
    int pos1 = 0, pos2 = 0;
    int rotation = 0;



    if ((root == NULL) || (*root == NULL)) {
	G_fatal_error("\navl.c: avl_add: param NULL");
	return AVL_ERR;
    }


    /* search position where insert the new node */
    node_temp = avl_individua(*root, k, &p, &d);

    if (node_temp != NULL) {
	node_temp->counter = node_temp->counter + n;
	return AVL_PRES;
    }

    node_temp = avl_make(k, n);
    if (node_temp == NULL) {
	G_fatal_error("\navl.c:  avl_add: create node error");
	return AVL_ERR;
    }


    /* link the new node */
    node_temp->father = p;

    if (d == -1) {
	p->left_child = node_temp;
    }
    else {
	if (d == 1) {
	    p->right_child = node_temp;
	}
	else {
	    G_free(node_temp);
	    G_fatal_error("avl.c: avl_add: new node position unknown");
	    return AVL_ERR;
	}
    }

    /* if it's necessary balance the tree */
    critical = critical_node(node_temp, &pos1, &pos2, NULL);
    if (critical == NULL)
	return AVL_ADD;
    rotation = (pos1 * 10) + pos2;

    switch (rotation) {
    case AVL_SS:
	avl_rotation_ll(critical);
	break;
    case AVL_SD:
	avl_rotation_lr(critical);
	break;
    case AVL_DS:
	avl_rotation_rl(critical);
	break;
    case AVL_DD:
	avl_rotation_rr(critical);
	break;
    default:
	G_fatal_error("avl, avl_add: balancing error\n");
	return AVL_ERR;
    }

    /* if after rotation the root is changed modufy the pointer to the root */
    while ((*root)->father != NULL)
	*root = (*root)->father;

    return AVL_ADD;
}
Esempio n. 24
0
int main(int argc, char *argv[])
{
    struct GModule *module;
    struct Option *in_opt, *out_opt, *feature_opt, *column_name;
    struct Flag *smooth_flg, *value_flg, *z_flg, *no_topol;
    int feature;


    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("raster"));
    G_add_keyword(_("conversion"));
    G_add_keyword(_("geometry"));
    G_add_keyword(_("vectorization"));
    module->description = _("Converts a raster map into a vector map.");

    in_opt = G_define_standard_option(G_OPT_R_INPUT);

    out_opt = G_define_standard_option(G_OPT_V_OUTPUT);
    
    feature_opt = G_define_standard_option(G_OPT_V_TYPE);
    feature_opt->required = YES;
    feature_opt->multiple = NO;
    feature_opt->options = "point,line,area";
    feature_opt->answer = NULL;

    column_name = G_define_standard_option(G_OPT_DB_COLUMN);
    column_name->label = _("Name of attribute column to store value");
    column_name->description = _("Name must be SQL compliant");
    column_name->answer = "value";

    smooth_flg = G_define_flag();
    smooth_flg->key = 's';
    smooth_flg->description = _("Smooth corners of area features");

    value_flg = G_define_flag();
    value_flg->key = 'v';
    value_flg->description =
	_("Use raster values as categories instead of unique sequence (CELL only)");
    value_flg->guisection = _("Attributes");

    z_flg = G_define_flag();
    z_flg->key = 'z';
    z_flg->label = _("Write raster values as z coordinate");
    z_flg->description = _("Table is not created. "
			   "Currently supported only for points.");
    z_flg->guisection = _("Attributes");

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

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

    feature = Vect_option_to_types(feature_opt);
    smooth_flag = (smooth_flg->answer) ? SMOOTH : NO_SMOOTH;
    value_flag = value_flg->answer;

    if (z_flg->answer && (feature != GV_POINT))
	G_fatal_error(_("z flag is supported only for points"));

    /* Open files */
    input_fd = Rast_open_old(in_opt->answer, "");

    data_type = Rast_get_map_type(input_fd);
    data_size = Rast_cell_size(data_type);
    G_get_window(&cell_head);

    if (value_flag && data_type != CELL_TYPE) {
	G_warning(_("Raster is not CELL, '-v' flag ignored, raster values will be written to the table."));
	value_flag = 0;
    }

    if (z_flg->answer)
	Vect_open_new(&Map, out_opt->answer, 1);
    else
	Vect_open_new(&Map, out_opt->answer, 0);

    Vect_hist_command(&Map);

    Cats = Vect_new_cats_struct();

    /* Open category labels */
    if (data_type == CELL_TYPE) {
	if (0 == Rast_read_cats(in_opt->answer, "", &RastCats))
	    has_cats = 1;
    }
    else
	has_cats = 0;

    db_init_string(&sql);
    db_init_string(&label);

    /* Create table */
    if ((feature & (GV_AREA | GV_POINT | GV_LINE)) &&
	(!value_flag || (value_flag && has_cats)) && !(z_flg->answer)) {
	char buf[1000];

	Fi = Vect_default_field_info(&Map, 1, NULL, GV_1TABLE);
	Vect_map_add_dblink(&Map, 1, NULL, Fi->table, GV_KEY_COLUMN, Fi->database,
			    Fi->driver);

	driver =
	    db_start_driver_open_database(Fi->driver,
					  Vect_subst_var(Fi->database, &Map));
	if (driver == NULL)
	    G_fatal_error(_("Unable to open database <%s> by driver <%s>"),
			  Fi->database, Fi->driver);

	/* Create new table */
	db_zero_string(&sql);
	sprintf(buf, "create table %s ( cat integer", Fi->table);
	db_append_string(&sql, buf);

	if (!value_flag) {	/* add value to the table */
	    if (data_type == CELL_TYPE) {
		db_append_string(&sql, ", ");
		db_append_string(&sql, column_name->answer);
		db_append_string(&sql, " integer");
	    } else {
		db_append_string(&sql, ",");
		db_append_string(&sql, column_name->answer);
		db_append_string(&sql, " double precision");
	    }
	}

	if (has_cats) {
	    int i, len;
	    int clen = 0;

	    /* Get maximum column length */
	    for (i = 0; i < RastCats.ncats; i++) {
		len = strlen(RastCats.labels[i]);
		if (len > clen)
		    clen = len;
	    }
	    clen += 10;

	    sprintf(buf, ", label varchar(%d)", clen);
	    db_append_string(&sql, buf);
	}

	db_append_string(&sql, ")");

	G_debug(3, db_get_string(&sql));

	if (db_execute_immediate(driver, &sql) != DB_OK)
	    G_fatal_error(_("Unable to create table: %s"),
			  db_get_string(&sql));

	if (db_create_index2(driver, Fi->table, GV_KEY_COLUMN) != DB_OK)
	    G_warning(_("Unable to create index"));

	if (db_grant_on_table
	    (driver, Fi->table, DB_PRIV_SELECT,
	     DB_GROUP | DB_PUBLIC) != DB_OK)
	    G_fatal_error(_("Unable to grant privileges on table <%s>"),
			  Fi->table);

	db_begin_transaction(driver);

    }
    else {
	driver = NULL;
    }

    /* init variables for lines and areas */
    first_read = 1;
    last_read = 0;
    direction = FORWARD;
    row_length = cell_head.cols;
    n_rows = cell_head.rows;
    row_count = 0;

    if (feature == GV_LINE) {
	alloc_lines_bufs(row_length + 2);
	extract_lines();
    }
    else if (feature == GV_AREA) {
	alloc_areas_bufs(row_length + 2);
	extract_areas();
    }
    else {			/* GV_POINT */

	extract_points(z_flg->answer);
    }

    Rast_close(input_fd);

    if (!no_topol->answer)
	Vect_build(&Map);


    /* insert cats and optionally labels if raster cats were used */
    if (driver && value_flag) {
	char buf[1000];
	int c, i, cat, fidx, ncats, lastcat, tp, id;

	fidx = Vect_cidx_get_field_index(&Map, 1);
	if (fidx >= 0) {
	    ncats = Vect_cidx_get_num_cats_by_index(&Map, fidx);
	    lastcat = -1;

	    for (c = 0; c < ncats; c++) {
		Vect_cidx_get_cat_by_index(&Map, fidx, c, &cat, &tp, &id);

		if (lastcat == cat)
		    continue;

		/* find label, slow -> TODO faster */
		db_set_string(&label, "");
		for (i = 0; i < RastCats.ncats; i++) {
		    if (cat == (int)RastCats.q.table[i].dLow) {	/* cats are in dLow/High not in cLow/High !!! */
			db_set_string(&label, RastCats.labels[i]);
			db_double_quote_string(&label);
			break;
		    }
		}
		G_debug(3, "cat = %d label = %s", cat, db_get_string(&label));

		sprintf(buf, "insert into %s values ( %d, '%s')", Fi->table,
			cat, db_get_string(&label));
		db_set_string(&sql, buf);
		G_debug(3, db_get_string(&sql));

		if (db_execute_immediate(driver, &sql) != DB_OK)
		    G_fatal_error(_("Unable to insert into table: %s"),
				  db_get_string(&sql));

		lastcat = cat;
	    }
	}
    }

    if (has_cats)
	Rast_free_cats(&RastCats);

    if (driver != NULL) {
	db_commit_transaction(driver);
	db_close_database_shutdown_driver(driver);
    }

    Vect_close(&Map);
    G_done_msg(" ");

    exit(EXIT_SUCCESS);
}
Esempio n. 25
0
int main( int argc, char **argv )
{
  char *mapset;
  char *name;
  struct GModule *module;
  struct Option *map;
  struct Option *win;
  struct Option *format;
  struct Cell_head window;
  RASTER_MAP_TYPE raster_type;

  /* Initialize the GIS calls */
  G_gisinit( argv[0] );

  module = G_define_module();
  module->keywords = ( "display, raster" );
  module->description = ( "Output raster map layers in a format suitable for display in QGIS" );

  map = G_define_standard_option( G_OPT_R_MAP );
  map->description = ( "Raster map to be displayed" );

  format = G_define_option();
  format->key = "format";
  format->type = TYPE_STRING;
  format->description = "format";
  format->options = "color,value";

  win = G_define_option();
  win->key = "window";
  win->type = TYPE_DOUBLE;
  win->multiple = YES;
  win->description = "xmin,ymin,xmax,ymax,ncols,nrows";

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

  name = map->answer;

  /* Make sure map is available */
  mapset = G_find_cell2( name, "" );
  if ( mapset == NULL )
    G_fatal_error(( "Raster map <%s> not found" ), name );

  /* It can happen that GRASS data set is 'corrupted' and zone differs in WIND and
   * cellhd, and G_open_cell_old fails, so it is better to read window from map */
  /* G_get_window( &window ); */
  G_get_cellhd( name, mapset, &window );
  window.west = atof( win->answers[0] );
  window.south = atof( win->answers[1] );
  window.east = atof( win->answers[2] );
  window.north = atof( win->answers[3] );
  window.cols = atoi( win->answers[4] );
  window.rows = atoi( win->answers[5] );
  G_adjust_Cell_head( &window, 1, 1 );
  G_set_window( &window );

  raster_type = G_raster_map_type( name, "" );

  display( name, mapset, raster_type, format->answer );

  exit( EXIT_SUCCESS );
}
Esempio n. 26
0
/* return: 0 OK, -1 error */
int dig_read_cidx_head(GVFILE * fp, struct Plus_head *plus)
{
    unsigned char buf[5];
    int i, byte_order;

    dig_rewind(fp);

    /* bytes 1 - 5 */
    if (0 >= dig__fread_port_C(buf, 5, fp))
	return (-1);
    plus->cidx_Version_Major = buf[0];
    plus->cidx_Version_Minor = buf[1];
    plus->cidx_Back_Major = buf[2];
    plus->cidx_Back_Minor = buf[3];
    byte_order = buf[4];

    G_debug(3,
	    "Cidx header: file version %d.%d , supported from GRASS version %d.%d",
	    plus->cidx_Version_Major, plus->cidx_Version_Minor,
	    plus->cidx_Back_Major, plus->cidx_Back_Minor);

    G_debug(3, "  byte order %d", byte_order);

    /* check version numbers */
    if (plus->cidx_Version_Major > GV_CIDX_VER_MAJOR ||
	plus->cidx_Version_Minor > GV_CIDX_VER_MINOR) {
	/* The file was created by GRASS library with higher version than this one */

	if (plus->cidx_Back_Major > GV_CIDX_VER_MAJOR ||
	    plus->cidx_Back_Minor > GV_CIDX_VER_MINOR) {
	    /* This version of GRASS lib is lower than the oldest which can read this format */
	    G_debug(1, "Category index format version %d.%d",
		    plus->cidx_Version_Major, plus->cidx_Version_Minor);
	    G_fatal_error
		("This version of GRASS (%d.%d) is too old to read this category index format."
		 " Try to rebuild topology or upgrade GRASS to at least version %d.",
		 GRASS_VERSION_MAJOR, GRASS_VERSION_MINOR, GRASS_VERSION_MAJOR + 1);
	    return (-1);
	}

	G_warning
	    ("Your GRASS version does not fully support category index format %d.%d of the vector."
	     " Consider to rebuild topology or upgrade GRASS.",
	     plus->cidx_Version_Major, plus->cidx_Version_Minor);
    }

    dig_init_portable(&(plus->cidx_port), byte_order);
    dig_set_cur_port(&(plus->cidx_port));

    /* bytes 6 - 9 : header size */
    if (0 >= dig__fread_port_L(&(plus->cidx_head_size), 1, fp))
	return (-1);
    G_debug(3, "  header size %ld", plus->cidx_head_size);

    /* Body of header - info about all fields */
    /* Number of fields */
    if (0 >= dig__fread_port_I(&(plus->n_cidx), 1, fp))
	return (-1);

    /* alloc space */
    plus->a_cidx = plus->n_cidx;
    plus->cidx =
	(struct Cat_index *)G_malloc(plus->a_cidx * sizeof(struct Cat_index));

    for (i = 0; i < plus->n_cidx; i++) {
	int t;
	struct Cat_index *ci;

	ci = &(plus->cidx[i]);
	ci->cat = NULL;
	ci->a_cats = 0;

	/* Field number */
	if (0 >= dig__fread_port_I(&(ci->field), 1, fp))
	    return (-1);

	/* Number of categories */
	if (0 >= dig__fread_port_I(&(ci->n_cats), 1, fp))
	    return (-1);

	/* Number of unique categories */
	if (0 >= dig__fread_port_I(&(ci->n_ucats), 1, fp))
	    return (-1);

	/* Number of types */
	if (0 >= dig__fread_port_I(&(ci->n_types), 1, fp))
	    return (-1);

	/* Types */
	for (t = 0; t < ci->n_types; t++) {
	    int rtype;

	    /* type */
	    if (0 >= dig__fread_port_I(&rtype, 1, fp))
		return (-1);
	    ci->type[t][0] = dig_type_from_store(rtype);

	    /* number of items */
	    if (0 >= dig__fread_port_I(&(ci->type[t][1]), 1, fp))
		return (-1);
	}

	/* Offset */
	if (0 >= dig__fread_port_L(&(ci->offset), 1, fp))
	    return (0);
    }

    if (dig_fseek(fp, plus->cidx_head_size, SEEK_SET) == -1)
	return (-1);

    return (0);
}
Esempio n. 27
0
/*!
  \brief Read Plus_head from file

  \param fp pointer to gvfile structure
  \param[in,out] ptr pointer to Plus_head structure

  \return -1 error
  \return  0 OK 
*/
int dig_Rd_Plus_head(struct gvfile * fp, struct Plus_head *ptr)
{
    unsigned char buf[5];
    int byte_order;

    dig_rewind(fp);

    /* bytes 1 - 5 */
    if (0 >= dig__fread_port_C((char *)buf, 5, fp))
	return (-1);
    ptr->version.topo.major = buf[0];
    ptr->version.topo.minor = buf[1];
    ptr->version.topo.back_major = buf[2];
    ptr->version.topo.back_minor = buf[3];
    byte_order = buf[4];

    G_debug(2,
	    "Topo header: file version %d.%d , supported from GRASS version %d.%d",
	    ptr->version.topo.major, ptr->version.topo.minor, ptr->version.topo.back_major,
	    ptr->version.topo.back_minor);

    G_debug(2, "  byte order %d", byte_order);

    /* check version numbers */
    if (ptr->version.topo.major > GV_TOPO_VER_MAJOR ||
	ptr->version.topo.minor > GV_TOPO_VER_MINOR) {
	/* The file was created by GRASS library with higher version than this one */

	if (ptr->version.topo.back_major > GV_TOPO_VER_MAJOR ||
	    ptr->version.topo.back_minor > GV_TOPO_VER_MINOR) {
	    /* This version of GRASS lib is lower than the oldest which can read this format */
	    G_debug(1, "Topology format version %d.%d",
		    ptr->version.topo.major, ptr->version.topo.minor);
	    G_fatal_error
		(_("This version of GRASS (%d.%d) is too old to read this topology format."
		 " Try to rebuild topology or upgrade GRASS to at least version %d."),
		 GRASS_VERSION_MAJOR, GRASS_VERSION_MINOR, GRASS_VERSION_MAJOR + 1);
	    return (-1);
	}

	G_warning(_("Your GRASS version does not fully support topology format %d.%d of the vector."
		    " Consider to rebuild topology or upgrade GRASS."),
		  ptr->version.topo.major, ptr->version.topo.minor);
    }
    if (ptr->version.topo.major < GV_TOPO_VER_MAJOR ||
	(ptr->version.topo.major == GV_TOPO_VER_MAJOR &&
	 ptr->version.topo.minor < GV_TOPO_VER_MINOR)) {
	/* The file was created by GRASS library with lower version than this one */

	/* This version of GRASS lib can not read this old format */
	G_warning(_("Old topology format version %d.%d is not supported by this release."
		    " Try to rebuild topology using v.build or v.build.all module."),
		  ptr->version.topo.major, ptr->version.topo.minor);
	return (-1);
    }

    /* init Port_info structure and set as default */
    dig_init_portable(&(ptr->port), byte_order);
    dig_set_cur_port(&(ptr->port));

    /* bytes 6 - 9 : header size */
    if (0 >= dig__fread_port_L(&(ptr->head_size), 1, fp))
	return (-1);
    G_debug(2, "  header size %ld", ptr->head_size);

    /* determine required offset size from header size */
    /* this is not safe in case new fields get added in later versions */
    /* better: add a new field with off_t_size after byte_order? */
    if (ptr->head_size >= 142 + 32) /* keep in sync with dig_Wr_Plus_head() */
	ptr->off_t_size = 8;
    else
	ptr->off_t_size = 4;

    if (sizeof(off_t) < ptr->off_t_size) {
	G_warning(_("Vector exceeds supported file size limit"));
	return (-1);
    }

    G_debug(2, "topo off_t size = %d", ptr->off_t_size);

    /* byte 10 : dimension 2D or 3D */
    if (0 >= dig__fread_port_C((char *)buf, 1, fp))
	return (-1);
    ptr->with_z = buf[0];
    G_debug(2, "  with_z %d", ptr->with_z);

    /* bytes 11 - 58 : bound box */
    if (0 >= dig__fread_port_D(&(ptr->box.N), 1, fp))
	return (-1);
    if (0 >= dig__fread_port_D(&(ptr->box.S), 1, fp))
	return (-1);
    if (0 >= dig__fread_port_D(&(ptr->box.E), 1, fp))
	return (-1);
    if (0 >= dig__fread_port_D(&(ptr->box.W), 1, fp))
	return (-1);
    if (0 >= dig__fread_port_D(&(ptr->box.T), 1, fp))
	return (-1);
    if (0 >= dig__fread_port_D(&(ptr->box.B), 1, fp))
	return (-1);

    /* bytes 59 - 86 : number of structures */
    if (0 >= dig__fread_port_P(&(ptr->n_nodes), 1, fp))
	return (-1);
    if (0 >= dig__fread_port_P(&(ptr->n_edges), 1, fp))
	return (-1);
    if (0 >= dig__fread_port_P(&(ptr->n_lines), 1, fp))
	return (-1);
    if (0 >= dig__fread_port_P(&(ptr->n_areas), 1, fp))
	return (-1);
    if (0 >= dig__fread_port_P(&(ptr->n_isles), 1, fp))
	return (-1);
    if (0 >= dig__fread_port_P(&(ptr->n_volumes), 1, fp))
	return (-1);
    if (0 >= dig__fread_port_P(&(ptr->n_holes), 1, fp))
	return (-1);

    /* bytes 87 - 110 : number of line types */
    if (0 >= dig__fread_port_P(&(ptr->n_plines), 1, fp))
	return (-1);
    if (0 >= dig__fread_port_P(&(ptr->n_llines), 1, fp))
	return (-1);
    if (0 >= dig__fread_port_P(&(ptr->n_blines), 1, fp))
	return (-1);
    if (0 >= dig__fread_port_P(&(ptr->n_clines), 1, fp))
	return (-1);
    if (0 >= dig__fread_port_P(&(ptr->n_flines), 1, fp))
	return (-1);
    if (0 >= dig__fread_port_P(&(ptr->n_klines), 1, fp))
	return (-1);

    /* bytes 111 - 138 : Offset */
    if (0 >= dig__fread_port_O(&(ptr->Node_offset), 1, fp, ptr->off_t_size))
	return (-1);
    if (0 >= dig__fread_port_O(&(ptr->Edge_offset), 1, fp, ptr->off_t_size))
	return (-1);
    if (0 >= dig__fread_port_O(&(ptr->Line_offset), 1, fp, ptr->off_t_size))
	return (-1);
    if (0 >= dig__fread_port_O(&(ptr->Area_offset), 1, fp, ptr->off_t_size))
	return (-1);
    if (0 >= dig__fread_port_O(&(ptr->Isle_offset), 1, fp, ptr->off_t_size))
	return (-1);
    if (0 >= dig__fread_port_O(&(ptr->Volume_offset), 1, fp, ptr->off_t_size))
	return (-1);
    if (0 >= dig__fread_port_O(&(ptr->Hole_offset), 1, fp, ptr->off_t_size))
	return (-1);

    /* bytes 139 - 142 : Coor size and time */
    if (0 >= dig__fread_port_O(&(ptr->coor_size), 1, fp, ptr->off_t_size))
	return (-1);

    G_debug(2, "  coor size %"PRI_OFF_T, ptr->coor_size);

    dig_fseek(fp, ptr->head_size, SEEK_SET);

    return (0);
}
Esempio n. 28
0
/*!
 * \brief Check input and output file names.
 *
 * Check: 
 *  1) output is legal map name,
 *  2) if can find input map, and
 *  3) if input was found in current mapset, check if input != output.
 *
 * \param input input map name
 * \param output output map name
 * \param error error type: G_FATAL_EXIT, G_FATAL_PRINT, G_FATAL_RETURN
 *
 * \return 0 OK
 * \return 1 error
 */
int G_check_input_output_name(const char *input, const char *output,
			      int error)
{
    const char *mapset;

    if (output == NULL)
	return 0;		/* don't die on undefined parameters */
    if (G_legal_filename(output) == -1) {
	if (error == G_FATAL_EXIT) {
	    G_fatal_error(_("Output raster map name <%s> is not valid map name"),
			  output);
	}
	else if (error == G_FATAL_PRINT) {
	    G_warning(_("Output raster map name <%s> is not valid map name"),
		      output);
	    return 1;
	}
	else {			/* G_FATAL_RETURN */
	    return 1;
	}
    }

    mapset = G_find_raster2(input, "");

    if (mapset == NULL) {
	if (error == G_FATAL_EXIT) {
	    G_fatal_error(_("Raster map <%s> not found"), input);
	}
	else if (error == G_FATAL_PRINT) {
	    G_warning(_("Raster map <%s> not found"), input);
	    return 1;
	}
	else {			/* G_FATAL_RETURN */
	    return 1;
	}
    }

    if (strcmp(mapset, G_mapset()) == 0) {
	char nm[1000], ms[1000];
	const char *in;

	if (G_name_is_fully_qualified(input, nm, ms)) {
	    in = nm;
	}
	else {
	    in = input;
	}

	if (strcmp(in, output) == 0) {
	    if (error == G_FATAL_EXIT) {
		G_fatal_error(_("Output raster map <%s> is used as input"),
			      output);
	    }
	    else if (error == G_FATAL_PRINT) {
		G_warning(_("Output raster map <%s> is used as input"),
			  output);
		return 1;
	    }
	    else {		/* G_FATAL_RETURN */
		return 1;
	    }
	}
    }

    return 0;
}
Esempio n. 29
0
int main(int argc, char *argv[])
{
    int line_color;
    int text_color;
    double lon1, lat1, lon2, lat2;
    char *deftcolor;
    struct GModule *module;
    struct
    {
	struct Option *lcolor, *tcolor, *coor;
    } parm;

    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("display"));
    G_add_keyword(_("distance"));
    module->description =
	_("Displays a geodesic line, tracing the shortest distance "
	"between two geographic points along a great circle, in "
	"a longitude/latitude data set.");

    parm.coor = G_define_option();
    parm.coor->key = "coor";
    parm.coor->key_desc = "lon1,lat1,lon2,lat2";
    parm.coor->type = TYPE_STRING;
    parm.coor->required = YES;
    parm.coor->description = _("Starting and ending coordinates");

    parm.lcolor = G_define_option();
    parm.lcolor->key = "lcolor";
    parm.lcolor->type = TYPE_STRING;
    parm.lcolor->required = NO;
    parm.lcolor->description = _("Line color");
    parm.lcolor->gisprompt = "old_color,color,color";
    parm.lcolor->answer = DEFAULT_FG_COLOR;

    parm.tcolor = G_define_option();
    parm.tcolor->key = "tcolor";
    parm.tcolor->type = TYPE_STRING;
    parm.tcolor->required = NO;
    parm.tcolor->description = _("Text color or \"none\"");
    parm.tcolor->gisprompt = "old_color,color,color";

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


    if (G_projection() != PROJECTION_LL)
	G_fatal_error(_("Location is not %s"), G__projection_name(PROJECTION_LL));

    if (parm.coor->answers[0] == NULL)
	G_fatal_error(_("No coordinates given"));

    if (!G_scan_easting(parm.coor->answers[0], &lon1, G_projection()))
	G_fatal_error(_("%s - illegal longitude"), parm.coor->answers[0]);

    if (!G_scan_northing(parm.coor->answers[1], &lat1, G_projection()))
	G_fatal_error(_("%s - illegal longitude"), parm.coor->answers[1]);

    if (!G_scan_easting(parm.coor->answers[2], &lon2, G_projection()))
	G_fatal_error(_("%s - illegal longitude"), parm.coor->answers[2]);

    if (!G_scan_northing(parm.coor->answers[3], &lat2, G_projection()))
	G_fatal_error(_("%s - illegal longitude"), parm.coor->answers[3]);


    if (D_open_driver() != 0)
      	G_fatal_error(_("No graphics device selected. "
			"Use d.mon to select graphics device."));
    
    line_color = D_translate_color(parm.lcolor->answer);
    if (!line_color)
	line_color = D_translate_color(parm.lcolor->answer =
				       DEFAULT_FG_COLOR);

    if (strcmp(parm.lcolor->answer, DEFAULT_FG_COLOR) == 0)
	deftcolor = "red";
    else
	deftcolor = DEFAULT_FG_COLOR;

    if (parm.tcolor->answer == NULL)
	text_color = D_translate_color(deftcolor);
    else if (strcmp(parm.tcolor->answer, "none") == 0)
	text_color = -1;
    else
	text_color = D_translate_color(parm.tcolor->answer);

    plot(lon1, lat1, lon2, lat2, line_color, text_color);
    
    D_save_command(G_recreate_command());
    D_close_driver();

    exit(EXIT_SUCCESS);
}
Esempio n. 30
0
int draw_n_arrow(double east, double north, double fontsize,
		 char *n_arrow_num, double line_width)
{
    double x_pos, y_pos;
    double t, b, l, r;
    double tt, tb, tl, tr; /* text box*/

    SYMBOL *Symb;
    RGBA_Color *line_color, *fill_color;
    int R, G, B;
    double x0, y0;
    char icon[64];
    double symbol_size;


    /* Establish text size */
    if (fontsize > 0)
	D_text_size(fontsize, fontsize);

    D_setup_unity(0);
    D_get_src(&t, &b, &l, &r);

    x_pos = east * (r - l) / 100.;
    y_pos = (100. - north) * (b - t) / 100.;

    if (line_width > 0)
	D_line_width(line_width);

    if (fontsize > 0) {
    	/* draw the "N" */
    	D_get_text_box("N", &tt, &tb, &tl, &tr);
    	D_use_color(fg_color);

    	/* positions manually tuned */
    	switch (n_arrow_num[0]) {
    	case '1':
    	    D_pos_abs(x_pos - (tr + tl) / 2, y_pos - 45);
    	    D_text("N");
    	    break;
    	case '3':
    	    D_pos_abs(x_pos - (tr + tl) / 2, y_pos - 60);
    	    D_text("N");
    	    break;
    	case '4':
    	    D_pos_abs(x_pos - (tr + tl) / 2, y_pos - 45);
    	    D_text("N");
    	    break;
    	case '7':
    	    D_pos_abs(x_pos - (tr + tl) / 2, y_pos - 70);
    	    D_text("N");
    	    break;
    	case '9':
	case 'f':
    	    D_pos_abs(x_pos - (tr + tl) / 2, y_pos - 55);
    	    D_text("N");
	    break;
    	case 'b':
    	    D_pos_abs(x_pos - (tr + tl) / 2, y_pos - 48.5);
    	    D_text("N");
    	    break;
    	case '2':
    	case '5':
    	case '6':
    	case '8':
    	    break;
    	default:
    	    G_fatal_error(_("Could not parse symbol"));
    	}
    }

    /* display the north arrow symbol */
    line_color = G_malloc(sizeof(RGBA_Color));
    fill_color = G_malloc(sizeof(RGBA_Color));

    if (D_color_number_to_RGB(fg_color, &R, &G, &B) == 0)
    	/* fall back to black on failure */
    	G_str_to_color(DEFAULT_FG_COLOR, &R, &G, &B);
    line_color->r = (unsigned char)R;
    line_color->g = (unsigned char)G;
    line_color->b = (unsigned char)B;
    line_color->a = RGBA_COLOR_OPAQUE;

    if (D_color_number_to_RGB(bg_color, &R, &G, &B) == 0)
    	/* fall back to black on failure */
    	G_str_to_color(DEFAULT_FG_COLOR, &R, &G, &B);
    fill_color->r = (unsigned char)R;
    fill_color->g = (unsigned char)G;
    fill_color->b = (unsigned char)B;
    fill_color->a = RGBA_COLOR_OPAQUE;

    if (n_arrow_num[0] == '2' || n_arrow_num[0] == '9')
    	fill_color->a = RGBA_COLOR_TRANSPARENT;

    /* sizes manually tuned */
    switch (n_arrow_num[0]) {
    case '1':
    	symbol_size = 35.;
    	break;
    case '2':
    	symbol_size = 19.;
    	break;
    case '3':
    	symbol_size = 20.;
    	break;
    case '4':
    	symbol_size = 15.;
    	break;
    case '5':
    case '6':
    	symbol_size = 14.;
    	break;
    case '7':
    	symbol_size = 23.;
    	break;
    case '8':
    case '9':
    	symbol_size = 17.;
    	break;
    case 'b':
    	symbol_size = 80.;
    	break;
    case 'f':
    	symbol_size = 100.;
    	break;
    default:
    	G_fatal_error(_("Could not parse symbol"));
    }

    x0 = D_d_to_u_col(x_pos);
    y0 = D_d_to_u_row(y_pos);

    if (n_arrow_num[0] == 'b')
	strcpy(icon, "n_arrows/basic_compass");
    else if (n_arrow_num[0] == 'f')
	strcpy(icon, "n_arrows/fancy_compass");
    else {
	strcpy(icon, "n_arrows/n_arrow");
	strncat(icon, n_arrow_num, 32);
    }

    Symb = S_read(icon);

    if(!Symb)
    	G_fatal_error(_("Could not read symbol \"%s\""), icon);

    S_stroke(Symb, symbol_size, 0.0, 0);
    D_symbol(Symb, x0, y0, line_color, fill_color);


    if (line_width > 0)
	D_line_width(0);

    G_free(Symb);
    G_free(line_color);
    G_free(fill_color);

    return 0;
}