int main(int argc, char *argv[]) { int i; int print_flag = 0; int flat_flag; int set_flag; double x; int ival; int row_flag = 0, col_flag = 0; struct Cell_head window, temp_window; const char *value; const char *name; const char *mapset; char **rast_ptr, **vect_ptr; struct GModule *module; struct { struct Flag *update, *print, *gprint, *flprint, *lprint, *eprint, *nangle, *center, *res_set, *dist_res, *dflt, *z, *savedefault, *bbox, *gmt_style, *wms_style; } flag; struct { struct Option *north, *south, *east, *west, *top, *bottom, *res, *nsres, *ewres, *res3, *tbres, *rows, *cols, *save, *region, *raster, *raster3d, *align, *zoom, *vect; } parm; G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("general")); G_add_keyword(_("settings")); module->description = _("Manages the boundary definitions for the " "geographic region."); /* flags */ flag.dflt = G_define_flag(); flag.dflt->key = 'd'; flag.dflt->description = _("Set from default region"); flag.dflt->guisection = _("Existing"); flag.savedefault = G_define_flag(); flag.savedefault->key = 's'; flag.savedefault->label = _("Save as default region"); flag.savedefault->description = _("Only possible from the PERMANENT mapset"); flag.savedefault->guisection = _("Existing"); flag.print = G_define_flag(); flag.print->key = 'p'; flag.print->description = _("Print the current region"); flag.print->guisection = _("Print"); flag.lprint = G_define_flag(); flag.lprint->key = 'l'; flag.lprint->description = _("Print the current region in lat/long " "using the current ellipsoid/datum"); flag.lprint->guisection = _("Print"); flag.eprint = G_define_flag(); flag.eprint->key = 'e'; flag.eprint->description = _("Print the current region extent"); flag.eprint->guisection = _("Print"); flag.center = G_define_flag(); flag.center->key = 'c'; flag.center->description = _("Print the current region map center coordinates"); flag.center->guisection = _("Print"); flag.gmt_style = G_define_flag(); flag.gmt_style->key = 't'; flag.gmt_style->description = _("Print the current region in GMT style"); flag.gmt_style->guisection = _("Print"); flag.wms_style = G_define_flag(); flag.wms_style->key = 'w'; flag.wms_style->description = _("Print the current region in WMS style"); flag.wms_style->guisection = _("Print"); flag.dist_res = G_define_flag(); flag.dist_res->key = 'm'; flag.dist_res->description = _("Print region resolution in meters (geodesic)"); flag.dist_res->guisection = _("Print"); flag.nangle = G_define_flag(); flag.nangle->key = 'n'; flag.nangle->label = _("Print the convergence angle (degrees CCW)"); flag.nangle->description = _("The difference between the projection's grid north and true north, " "measured at the center coordinates of the current region."); flag.nangle->guisection = _("Print"); flag.z = G_define_flag(); flag.z->key = '3'; flag.z->description = _("Print also 3D settings"); flag.z->guisection = _("Print"); flag.bbox = G_define_flag(); flag.bbox->key = 'b'; flag.bbox->description = _("Print the maximum bounding box in lat/long on WGS84"); flag.bbox->guisection = _("Print"); flag.gprint = G_define_flag(); flag.gprint->key = 'g'; flag.gprint->description = _("Print in shell script style"); flag.gprint->guisection = _("Print"); flag.flprint = G_define_flag(); flag.flprint->key = 'f'; flag.flprint->description = _("Print in shell script style, but in one line (flat)"); flag.flprint->guisection = _("Print"); flag.res_set = G_define_flag(); flag.res_set->key = 'a'; flag.res_set->description = _("Align region to resolution (default = align to bounds, " "works only for 2D resolution)"); flag.res_set->guisection = _("Bounds"); flag.update = G_define_flag(); flag.update->key = 'u'; flag.update->description = _("Do not update the current region"); flag.update->guisection = _("Effects"); /* parameters */ parm.region = G_define_standard_option(G_OPT_M_REGION); parm.region->description = _("Set current region from named region"); parm.region->guisection = _("Existing"); parm.raster = G_define_standard_option(G_OPT_R_MAP); parm.raster->key = "raster"; parm.raster->required = NO; parm.raster->multiple = YES; parm.raster->description = _("Set region to match raster map(s)"); parm.raster->guisection = _("Existing"); parm.raster3d = G_define_standard_option(G_OPT_R3_MAP); parm.raster3d->key = "raster_3d"; parm.raster3d->required = NO; parm.raster3d->multiple = NO; parm.raster3d->description = _("Set region to match 3D raster map(s) (both 2D and 3D " "values)"); parm.raster3d->guisection = _("Existing"); parm.vect = G_define_standard_option(G_OPT_V_MAP); parm.vect->key = "vector"; parm.vect->required = NO; parm.vect->multiple = YES; parm.vect->label = _("Set region to match vector map(s)"); parm.vect->description = NULL; parm.vect->guisection = _("Existing"); parm.north = G_define_option(); parm.north->key = "n"; parm.north->key_desc = "value"; parm.north->required = NO; parm.north->multiple = NO; parm.north->type = TYPE_STRING; parm.north->description = _("Value for the northern edge"); parm.north->guisection = _("Bounds"); parm.south = G_define_option(); parm.south->key = "s"; parm.south->key_desc = "value"; parm.south->required = NO; parm.south->multiple = NO; parm.south->type = TYPE_STRING; parm.south->description = _("Value for the southern edge"); parm.south->guisection = _("Bounds"); parm.east = G_define_option(); parm.east->key = "e"; parm.east->key_desc = "value"; parm.east->required = NO; parm.east->multiple = NO; parm.east->type = TYPE_STRING; parm.east->description = _("Value for the eastern edge"); parm.east->guisection = _("Bounds"); parm.west = G_define_option(); parm.west->key = "w"; parm.west->key_desc = "value"; parm.west->required = NO; parm.west->multiple = NO; parm.west->type = TYPE_STRING; parm.west->description = _("Value for the western edge"); parm.west->guisection = _("Bounds"); parm.top = G_define_option(); parm.top->key = "t"; parm.top->key_desc = "value"; parm.top->required = NO; parm.top->multiple = NO; parm.top->type = TYPE_STRING; parm.top->description = _("Value for the top edge"); parm.top->guisection = _("Bounds"); parm.bottom = G_define_option(); parm.bottom->key = "b"; parm.bottom->key_desc = "value"; parm.bottom->required = NO; parm.bottom->multiple = NO; parm.bottom->type = TYPE_STRING; parm.bottom->description = _("Value for the bottom edge"); parm.bottom->guisection = _("Bounds"); parm.rows = G_define_option(); parm.rows->key = "rows"; parm.rows->key_desc = "value"; parm.rows->required = NO; parm.rows->multiple = NO; parm.rows->type = TYPE_INTEGER; parm.rows->description = _("Number of rows in the new region"); parm.rows->guisection = _("Resolution"); parm.cols = G_define_option(); parm.cols->key = "cols"; parm.cols->key_desc = "value"; parm.cols->required = NO; parm.cols->multiple = NO; parm.cols->type = TYPE_INTEGER; parm.cols->description = _("Number of columns in the new region"); parm.cols->guisection = _("Resolution"); parm.res = G_define_option(); parm.res->key = "res"; parm.res->key_desc = "value"; parm.res->required = NO; parm.res->multiple = NO; parm.res->type = TYPE_STRING; parm.res->description = _("2D grid resolution (north-south and east-west)"); parm.res->guisection = _("Resolution"); parm.res3 = G_define_option(); parm.res3->key = "res3"; parm.res3->key_desc = "value"; parm.res3->required = NO; parm.res3->multiple = NO; parm.res3->type = TYPE_STRING; parm.res3->description = _("3D grid resolution (north-south, east-west and top-bottom)"); parm.res3->guisection = _("Resolution"); parm.nsres = G_define_option(); parm.nsres->key = "nsres"; parm.nsres->key_desc = "value"; parm.nsres->required = NO; parm.nsres->multiple = NO; parm.nsres->type = TYPE_STRING; parm.nsres->description = _("North-south 2D grid resolution"); parm.nsres->guisection = _("Resolution"); parm.ewres = G_define_option(); parm.ewres->key = "ewres"; parm.ewres->key_desc = "value"; parm.ewres->required = NO; parm.ewres->multiple = NO; parm.ewres->type = TYPE_STRING; parm.ewres->description = _("East-west 2D grid resolution"); parm.ewres->guisection = _("Resolution"); parm.tbres = G_define_option(); parm.tbres->key = "tbres"; parm.tbres->key_desc = "value"; parm.tbres->required = NO; parm.tbres->multiple = NO; parm.tbres->type = TYPE_STRING; parm.tbres->description = _("Top-bottom 3D grid resolution"); parm.tbres->guisection = _("Resolution"); parm.zoom = G_define_option(); parm.zoom->key = "zoom"; parm.zoom->key_desc = "name"; parm.zoom->required = NO; parm.zoom->multiple = NO; parm.zoom->type = TYPE_STRING; parm.zoom->description = _("Shrink region until it meets non-NULL data from this raster map"); parm.zoom->gisprompt = "old,cell,raster"; parm.zoom->guisection = _("Bounds"); parm.align = G_define_option(); parm.align->key = "align"; parm.align->key_desc = "name"; parm.align->required = NO; parm.align->multiple = NO; parm.align->type = TYPE_STRING; parm.align->description = _("Adjust region cells to cleanly align with this raster map"); parm.align->gisprompt = "old,cell,raster"; parm.align->guisection = _("Bounds"); parm.save = G_define_option(); parm.save->key = "save"; parm.save->key_desc = "name"; parm.save->required = NO; parm.save->multiple = NO; parm.save->type = TYPE_STRING; parm.save->description = _("Save current region settings in named region file"); parm.save->gisprompt = "new,windows,region"; parm.save->guisection = _("Effects"); G_option_required(flag.dflt, flag.savedefault, flag.print, flag.lprint, flag.eprint, flag.center, flag.gmt_style, flag.wms_style, flag.dist_res, flag.nangle, flag. z, flag.bbox, flag.gprint, flag.res_set, flag.update, parm.region, parm.raster, parm.raster3d, parm.vect, parm.north, parm.south, parm.east, parm.west, parm.top, parm.bottom, parm.rows, parm.cols, parm.res, parm.res3, parm.nsres, parm.ewres, parm.tbres, parm.zoom, parm.align, parm.save, NULL); if (G_parser(argc, argv)) exit(EXIT_FAILURE); G_get_default_window(&window); set_flag = !flag.update->answer; flat_flag = flag.flprint->answer; if (flag.print->answer) print_flag |= PRINT_REG; if (flag.gprint->answer) print_flag |= PRINT_SH; if (flag.lprint->answer) print_flag |= PRINT_LL; if (flag.eprint->answer) print_flag |= PRINT_EXTENT; if (flag.center->answer) print_flag |= PRINT_CENTER; if (flag.gmt_style->answer) print_flag |= PRINT_GMT; if (flag.wms_style->answer) print_flag |= PRINT_WMS; if (flag.nangle->answer) print_flag |= PRINT_NANGLE; if (flag.dist_res->answer) print_flag |= PRINT_METERS; if (flag.z->answer) print_flag |= PRINT_3D; if (flag.bbox->answer) print_flag |= PRINT_MBBOX; if (print_flag == PRINT_METERS) print_flag |= PRINT_SH; if (print_flag == PRINT_SH || print_flag & PRINT_3D || print_flag == PRINT_METERS + PRINT_SH) { print_flag |= PRINT_REG; } if (!flag.dflt->answer) G_get_window(&window); /* region= */ if ((name = parm.region->answer)) { mapset = G_find_file2("windows", name, ""); if (!mapset) G_fatal_error(_("Region <%s> not found"), name); G_get_element_window(&window, "windows", name, mapset); } /* raster= */ if (parm.raster->answer) { int first = 0; rast_ptr = parm.raster->answers; for (; *rast_ptr != NULL; rast_ptr++) { char rast_name[GNAME_MAX]; strcpy(rast_name, *rast_ptr); mapset = G_find_raster2(rast_name, ""); if (!mapset) G_fatal_error(_("Raster map <%s> not found"), rast_name); Rast_get_cellhd(rast_name, mapset, &temp_window); if (!first) { window = temp_window; first = 1; } else { window.north = (window.north > temp_window.north) ? window.north : temp_window.north; window.south = (window.south < temp_window.south) ? window.south : temp_window.south; window.east = (window.east > temp_window.east) ? window.east : temp_window.east; window.west = (window.west < temp_window.west) ? window.west : temp_window.west; } } G_adjust_Cell_head3(&window, 0, 0, 0); } /* raster3d= */ if ((name = parm.raster3d->answer)) { RASTER3D_Region win; if ((mapset = G_find_raster3d(name, "")) == NULL) G_fatal_error(_("3D raster map <%s> not found"), name); if (Rast3d_read_region_map(name, mapset, &win) < 0) G_fatal_error(_("Unable to read header of 3D raster map <%s@%s>"), name, mapset); Rast3d_region_to_cell_head(&win, &window); } /* vector= */ if (parm.vect->answer) { int first = 0; vect_ptr = parm.vect->answers; for (; *vect_ptr != NULL; vect_ptr++) { struct Map_info Map; struct bound_box box; char vect_name[GNAME_MAX]; struct Cell_head map_window; strcpy(vect_name, *vect_ptr); mapset = G_find_vector2(vect_name, ""); if (!mapset) G_fatal_error(_("Vector map <%s> not found"), vect_name); temp_window = window; Vect_set_open_level(2); if (2 > Vect_open_old_head(&Map, vect_name, mapset)) G_fatal_error(_("Unable to open vector map <%s> on topological level"), vect_name); Vect_get_map_box(&Map, &box); map_window = window; map_window.north = box.N; map_window.south = box.S; map_window.west = box.W; map_window.east = box.E; map_window.top = box.T; map_window.bottom = box.B; if (!first) { window = map_window; first = 1; } else { window.north = (window.north > map_window.north) ? window.north : map_window.north; window.south = (window.south < map_window.south) ? window.south : map_window.south; window.east = (window.east > map_window.east) ? window.east : map_window.east; window.west = (window.west < map_window.west) ? window.west : map_window.west; if (map_window.top > window.top) window.top = map_window.top; if (map_window.bottom < window.bottom) window.bottom = map_window.bottom; } if (window.north == window.south) { window.north = window.north + 0.5 * temp_window.ns_res; window.south = window.south - 0.5 * temp_window.ns_res; } if (window.east == window.west) { window.west = window.west - 0.5 * temp_window.ew_res; window.east = window.east + 0.5 * temp_window.ew_res; } if (window.top == window.bottom) { window.bottom = (window.bottom - 0.5 * temp_window.tb_res); window.top = (window.top + 0.5 * temp_window.tb_res); } if (flag.res_set->answer) Rast_align_window(&window, &temp_window); Vect_close(&Map); } } /* n= */ if ((value = parm.north->answer)) { if ((i = nsew(value, "n+", "n-", "s+"))) { if (!G_scan_resolution(value + 2, &x, window.proj)) die(parm.north); switch (i) { case 1: window.north += x; break; case 2: window.north -= x; break; case 3: window.north = window.south + x; break; } } else if (G_scan_northing(value, &x, window.proj)) window.north = x; else die(parm.north); } /* s= */ if ((value = parm.south->answer)) { if ((i = nsew(value, "s+", "s-", "n-"))) { if (!G_scan_resolution(value + 2, &x, window.proj)) die(parm.south); switch (i) { case 1: window.south += x; break; case 2: window.south -= x; break; case 3: window.south = window.north - x; break; } } else if (G_scan_northing(value, &x, window.proj)) window.south = x; else die(parm.south); } /* e= */ if ((value = parm.east->answer)) { if ((i = nsew(value, "e+", "e-", "w+"))) { if (!G_scan_resolution(value + 2, &x, window.proj)) die(parm.east); switch (i) { case 1: window.east += x; break; case 2: window.east -= x; break; case 3: window.east = window.west + x; break; } } else if (G_scan_easting(value, &x, window.proj)) window.east = x; else die(parm.east); } /* w= */ if ((value = parm.west->answer)) { if ((i = nsew(value, "w+", "w-", "e-"))) { if (!G_scan_resolution(value + 2, &x, window.proj)) die(parm.west); switch (i) { case 1: window.west += x; break; case 2: window.west -= x; break; case 3: window.west = window.east - x; break; } } else if (G_scan_easting(value, &x, window.proj)) window.west = x; else die(parm.west); } /* t= */ if ((value = parm.top->answer)) { if ((i = nsew(value, "t+", "t-", "b+"))) { if (sscanf(value + 2, "%lf", &x) != 1) die(parm.top); switch (i) { case 1: window.top += x; break; case 2: window.top -= x; break; case 3: window.top = window.bottom + x; break; } } else if (sscanf(value, "%lf", &x) == 1) window.top = x; else die(parm.top); } /* b= */ if ((value = parm.bottom->answer)) { if ((i = nsew(value, "b+", "b-", "t-"))) { if (sscanf(value + 2, "%lf", &x) != 1) die(parm.bottom); switch (i) { case 1: window.bottom += x; break; case 2: window.bottom -= x; break; case 3: window.bottom = window.top - x; break; } } else if (sscanf(value, "%lf", &x) == 1) window.bottom = x; else die(parm.bottom); } /* res= */ if ((value = parm.res->answer)) { if (!G_scan_resolution(value, &x, window.proj)) die(parm.res); window.ns_res = x; window.ew_res = x; if (flag.res_set->answer) { window.north = ceil(window.north / x) * x; window.south = floor(window.south / x) * x; window.east = ceil(window.east / x) * x; window.west = floor(window.west / x) * x; } } /* res3= */ if ((value = parm.res3->answer)) { if (!G_scan_resolution(value, &x, window.proj)) die(parm.res); window.ns_res3 = x; window.ew_res3 = x; window.tb_res = x; } /* nsres= */ if ((value = parm.nsres->answer)) { if (!G_scan_resolution(value, &x, window.proj)) die(parm.nsres); window.ns_res = x; if (flag.res_set->answer) { window.north = ceil(window.north / x) * x; window.south = floor(window.south / x) * x; } } /* ewres= */ if ((value = parm.ewres->answer)) { if (!G_scan_resolution(value, &x, window.proj)) die(parm.ewres); window.ew_res = x; if (flag.res_set->answer) { window.east = ceil(window.east / x) * x; window.west = floor(window.west / x) * x; } } /* tbres= */ if ((value = parm.tbres->answer)) { if (sscanf(value, "%lf", &x) != 1) die(parm.tbres); window.tb_res = x; if (flag.res_set->answer) { window.top = ceil(window.top / x) * x; window.bottom = floor(window.bottom / x) * x; } } /* rows= */ if ((value = parm.rows->answer)) { if (sscanf(value, "%i", &ival) != 1) die(parm.rows); window.rows = ival; row_flag = 1; } /* cols= */ if ((value = parm.cols->answer)) { if (sscanf(value, "%i", &ival) != 1) die(parm.cols); window.cols = ival; col_flag = 1; } /* zoom= */ if ((name = parm.zoom->answer)) { mapset = G_find_raster2(name, ""); if (!mapset) G_fatal_error(_("Raster map <%s> not found"), name); zoom(&window, name, mapset); } /* align= */ if ((name = parm.align->answer)) { mapset = G_find_raster2(name, ""); if (!mapset) G_fatal_error(_("Raster map <%s> not found"), name); Rast_get_cellhd(name, mapset, &temp_window); Rast_align_window(&window, &temp_window); } /* save= */ if ((name = parm.save->answer)) { temp_window = window; G_adjust_Cell_head3(&temp_window, 0, 0, 0); if (G_put_element_window(&temp_window, "windows", name) < 0) G_fatal_error(_("Unable to set region <%s>"), name); } G_adjust_Cell_head3(&window, row_flag, col_flag, 0); if (set_flag) { if (G_put_window(&window) < 0) G_fatal_error(_("Unable to update current region")); } if (flag.savedefault->answer) { if (strcmp(G_mapset(), "PERMANENT") == 0) { G_put_element_window(&window, "", "DEFAULT_WIND"); } else { G_fatal_error(_("Unable to change default region. " "The current mapset is not <PERMANENT>.")); } } /* / flag.savedefault->answer */ if (print_flag) print_window(&window, print_flag, flat_flag); exit(EXIT_SUCCESS); }
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); }
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); }
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); }
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); }
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); }
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); }
int main(int argc, char **argv) { struct GModule *module; struct Option *opt1, *opt2, *opt3; struct Flag *flag1, *flag2; G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("display")); G_add_keyword(_("settings")); module->description = _("Selects the font in which text will be displayed " "on the user's graphics monitor."); opt1 = G_define_option(); opt1->key = "font"; opt1->type = TYPE_STRING; opt1->required = NO; opt1->answer = "romans"; opt1->description = _("Choose new current font"); opt2 = G_define_standard_option(G_OPT_F_INPUT); opt2->key = "path"; opt2->required = NO; opt2->description = _("Path to Freetype-compatible font including file name"); opt2->gisprompt = "old,font,file"; opt3 = G_define_option(); opt3->key = "charset"; opt3->type = TYPE_STRING; opt3->required = NO; opt3->answer = "UTF-8"; opt3->description = _("Character encoding"); flag1 = G_define_flag(); flag1->key = 'l'; flag1->description = _("List fonts"); flag2 = G_define_flag(); flag2->key = 'v'; flag2->description = _("List fonts verbosely"); if (G_parser(argc, argv)) exit(EXIT_FAILURE); /* load the font */ D_open_driver(); if (flag1->answer) { /* List font names */ print_font_list(stdout, 0); D_close_driver(); exit(EXIT_SUCCESS); } if (flag2->answer) { /* List fonts verbosely */ print_font_list(stdout, 1); D_close_driver(); exit(EXIT_SUCCESS); } if (opt2->answer) { /* Full path to freetype font */ struct stat info; /* Check a valid filename has been supplied */ if (stat(opt2->answer, &info) != 0) G_fatal_error(_("Unable to access font path %s: %s"), opt2->answer, strerror(errno)); if (!S_ISREG(info.st_mode)) G_fatal_error(_("Font path %s is not a file"), opt2->answer); else D_font(opt2->answer); } else if (opt1->answer) { /* Font name from fontcap */ int i = 0; /* Check the fontname given is valid */ read_freetype_fonts(0); while (i < num_fonts) { if (strcmp(opt1->answer, fonts[i]) == 0) { D_font(opt1->answer); break; } i++; } if (i >= num_fonts) G_fatal_error(_("Font name <%s> is invalid. Check font name or consider running 'g.mkfontcap'"), opt1->answer); } if (opt3->answer) /* Set character encoding */ D_encoding(opt3->answer); /* add this command to the list */ D_close_driver(); exit(EXIT_SUCCESS); }
int main(int argc, char *argv[]) { struct GModule *module; struct GParams *params; int i, ret; int red, grn, blu; float size; double vp_height, z_exag; /* calculated viewpoint height, z-exag */ int width, height; /* output image size */ char *output_name; nv_data data; struct render_window *offscreen; /* initialize GRASS */ G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("visualization")); G_add_keyword(_("graphics")); G_add_keyword(_("raster")); G_add_keyword(_("vector")); G_add_keyword(_("raster3d")); module->label = _("Creates a 3D rendering of GIS data."); module->description = _("Renders surfaces (raster data), " "2D/3D vector data, and " "volumes (3D raster data) in 3D."); params = (struct GParams *)G_malloc(sizeof(struct GParams)); /* define options, call G_parser() */ parse_command(argc, argv, params); /* check parameters consistency */ check_parameters(params); width = atoi(params->size->answers[0]); height = atoi(params->size->answers[1]); G_asprintf(&output_name, "%s.%s", params->output->answer, params->format->answer); GS_libinit(); GVL_libinit(); GS_set_swap_func(swap_gl); /* define render window */ offscreen = Nviz_new_render_window(); Nviz_init_render_window(offscreen); if (Nviz_create_render_window(offscreen, NULL, width, height) == -1) G_fatal_error(_("Unable to render data")); Nviz_make_current_render_window(offscreen); /* initialize nviz data */ Nviz_init_data(&data); /* define default attributes for map objects */ Nviz_set_surface_attr_default(); /* set background color */ Nviz_set_bgcolor(&data, Nviz_color_from_str(params->bgcolor->answer)); /* init view, lights */ Nviz_init_view(&data); /* load raster maps (surface topography) & set attributes (map/constant) */ load_rasters(params, &data); /* set draw mode of loaded surfaces */ surface_set_draw_mode(params); /* load line vector maps */ if (params->vlines->answer) { load_vlines(params, &data); /* set attributes of 2d lines */ vlines_set_attrb(params); } /* load point vector maps */ if (params->vpoints->answer) { load_vpoints(params, &data); /* set attributes for points */ vpoints_set_attrb(params); } /* load volumes */ if (params->volume->answer) { load_rasters3d(params, &data); } /* define isosurfaces for displaying volumes */ if (params->isosurf_level->answer) { add_isosurfs(params, &data); } /* define slices for displaying volumes */ if (params->slice->answer) { add_slices(params, &data); } /* focus on loaded data */ Nviz_set_focus_map(MAP_OBJ_UNDEFINED, -1); /* define view point */ if (params->exag->answer) { z_exag = atof(params->exag->answer); } else { z_exag = Nviz_get_exag(); G_verbose_message(_("Vertical exaggeration not given, using calculated " "value %.0f"), z_exag); } Nviz_change_exag(&data, z_exag); if (params->height->answer) { vp_height = atof(params->height->answer); } else { double min, max; Nviz_get_exag_height(&vp_height, &min, &max); G_verbose_message(_("Viewpoint height not given, using calculated " "value %.0f"), vp_height); } Nviz_set_viewpoint_height(vp_height); Nviz_set_viewpoint_position(atof(params->pos->answers[0]), atof(params->pos->answers[1])); Nviz_set_viewpoint_twist(atoi(params->twist->answer)); Nviz_set_viewpoint_persp(atoi(params->persp->answer)); if (params->focus->answer) { Nviz_set_focus(&data, atof(params->focus->answers[0]), atof(params->focus->answers[1]), atof(params->focus->answers[2])); } /* set lights */ Nviz_set_light_position(&data, 1, atof(params->light_pos->answers[0]), atof(params->light_pos->answers[1]), atof(params->light_pos->answers[2]), 0.0); Nviz_set_light_bright(&data, 1, atoi(params->light_bright->answer) / 100.0); if (G_str_to_color(params->light_color->answer, &red, &grn, &blu) != 1) { red = grn = blu = 255; } Nviz_set_light_color(&data, 1, red, grn, blu); Nviz_set_light_ambient(&data, 1, atof(params->light_ambient->answer) / 100.0); /* define fringes */ if (params->fringe->answer) { int nw, ne, sw, se; i = 0; nw = ne = sw = se = 0; while (params->fringe->answers[i]) { const char *edge = params->fringe->answers[i++]; if (strcmp(edge, "nw") == 0) nw = 1; else if (strcmp(edge, "ne") == 0) ne = 1; else if (strcmp(edge, "sw") == 0) sw = 1; else if (strcmp(edge, "se") == 0) se = 1; } Nviz_new_fringe(&data, -1, Nviz_color_from_str(params->fringe_color->answer), atof(params->fringe_elev->answer), nw, ne, sw, se); } /* draw north arrow */ if (params->north_arrow->answer) { if (!params->north_arrow_size->answer) size = Nviz_get_longdim(&data) / 8.; else size = atof(params->north_arrow_size->answer); Nviz_set_arrow(&data, atoi(params->north_arrow->answers[0]), atoi(params->north_arrow->answers[1]), size, Nviz_color_from_str(params->north_arrow_color-> answer)); Nviz_draw_arrow(&data); } GS_clear(data.bgcolor); /* cutting planes */ if (params->cplane->answer) draw_cplane(params, &data); /* draw */ Nviz_draw_all(&data); /* write to image */ ret = 0; if (strcmp(params->format->answer, "ppm") == 0) ret = write_img(output_name, FORMAT_PPM); if (strcmp(params->format->answer, "tif") == 0) ret = write_img(output_name, FORMAT_TIF); if (!ret) G_fatal_error(_("Unsupported output format")); G_done_msg(_("File <%s> created."), output_name); Nviz_destroy_data(&data); Nviz_destroy_render_window(offscreen); G_free((void *)output_name); G_free((void *)params); exit(EXIT_SUCCESS); }
int main(int argc, char *argv[]) { /* variables */ DCELL *data_buf; CELL *clump_buf; CELL i, max; int row, col, rows, cols; int out_mode, use_MASK, *n, *e; long int *count; int fd_data, fd_clump; const char *datamap, *clumpmap, *centroidsmap; double avg, vol, total_vol, east, north, *sum; struct Cell_head window; struct Map_info *fd_centroids; struct line_pnts *Points; struct line_cats *Cats; struct field_info *Fi; char buf[DB_SQL_MAX]; dbString sql; dbDriver *driver; struct GModule *module; struct { struct Option *input, *clump, *centroids, *output; } opt; struct { struct Flag *report; } flag; /* define parameters and flags */ G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("raster")); G_add_keyword(_("volume")); G_add_keyword(_("clumps")); module->label = _("Calculates the volume of data \"clumps\"."); module->description = _("Optionally produces a GRASS vector points map " "containing the calculated centroids of these clumps."); opt.input = G_define_standard_option(G_OPT_R_INPUT); opt.input->description = _("Name of input raster map representing data that will be summed within clumps"); opt.clump = G_define_standard_option(G_OPT_R_INPUT); opt.clump->key = "clump"; opt.clump->required = NO; opt.clump->label = _("Name of input clump raster map"); opt.clump->description = _("Preferably the output of r.clump. " "If no clump map is given than MASK is used."); opt.centroids = G_define_standard_option(G_OPT_V_OUTPUT); opt.centroids->key = "centroids"; opt.centroids->required = NO; opt.centroids->description = _("Name for output vector points map to contain clump centroids"); opt.output = G_define_standard_option(G_OPT_F_OUTPUT); opt.output->required = NO; opt.output->label = _("Name for output file to hold the report"); opt.output->description = _("If no output file given report is printed to standard output"); flag.report = G_define_flag(); flag.report->key = 'f'; flag.report->description = _("Generate unformatted report (items separated by colon)"); if (G_parser(argc, argv)) exit(EXIT_FAILURE); /* get arguments */ datamap = opt.input->answer; clumpmap = NULL; if (opt.clump->answer) clumpmap = opt.clump->answer; centroidsmap = NULL; fd_centroids = NULL; Points = NULL; Cats = NULL; driver = NULL; if (opt.centroids->answer) { centroidsmap = opt.centroids->answer; fd_centroids = G_malloc(sizeof(struct Map_info)); } out_mode = (!flag.report->answer); /* * see if MASK or a separate "clumpmap" raster map is to be used * -- it must(!) be one of those two choices. */ use_MASK = 0; if (!clumpmap) { clumpmap = "MASK"; use_MASK = 1; if (!G_find_raster2(clumpmap, G_mapset())) G_fatal_error(_("No MASK found. If no clump map is given than the MASK is required. " "You need to define a clump raster map or create a MASK by r.mask command.")); G_important_message(_("No clump map given, using MASK")); } /* open input and clump raster maps */ fd_data = Rast_open_old(datamap, ""); fd_clump = Rast_open_old(clumpmap, use_MASK ? G_mapset() : ""); /* initialize vector map (for centroids) if needed */ if (centroidsmap) { if (Vect_open_new(fd_centroids, centroidsmap, WITHOUT_Z) < 0) G_fatal_error(_("Unable to create vector map <%s>"), centroidsmap); Points = Vect_new_line_struct(); Cats = Vect_new_cats_struct(); /* initialize data structures */ Vect_append_point(Points, 0., 0., 0.); Vect_cat_set(Cats, 1, 1); } /* initialize output file */ if (opt.output->answer && strcmp(opt.output->answer, "-") != 0) { if (freopen(opt.output->answer, "w", stdout) == NULL) { perror(opt.output->answer); exit(EXIT_FAILURE); } } /* initialize data accumulation arrays */ max = Rast_get_max_c_cat(clumpmap, use_MASK ? G_mapset() : ""); sum = (double *)G_malloc((max + 1) * sizeof(double)); count = (long int *)G_malloc((max + 1) * sizeof(long int)); G_zero(sum, (max + 1) * sizeof(double)); G_zero(count, (max + 1) * sizeof(long int)); data_buf = Rast_allocate_d_buf(); clump_buf = Rast_allocate_c_buf(); /* get window size */ G_get_window(&window); rows = window.rows; cols = window.cols; /* now get the data -- first pass */ for (row = 0; row < rows; row++) { G_percent(row, rows, 2); Rast_get_d_row(fd_data, data_buf, row); Rast_get_c_row(fd_clump, clump_buf, row); for (col = 0; col < cols; col++) { i = clump_buf[col]; if (i > max) G_fatal_error(_("Invalid category value %d (max=%d): row=%d col=%d"), i, max, row, col); if (i < 1) { G_debug(3, "row=%d col=%d: zero or negs ignored", row, col); continue; /* ignore zeros and negs */ } if (Rast_is_d_null_value(&data_buf[col])) { G_debug(3, "row=%d col=%d: NULL ignored", row, col); continue; } sum[i] += data_buf[col]; count[i]++; } } G_percent(1, 1, 1); /* free some buffer space */ G_free(data_buf); G_free(clump_buf); /* data lists for centroids of clumps */ e = (int *)G_malloc((max + 1) * sizeof(int)); n = (int *)G_malloc((max + 1) * sizeof(int)); i = centroids(fd_clump, e, n, 1, max); /* close raster maps */ Rast_close(fd_data); Rast_close(fd_clump); /* got everything, now do output */ if (centroidsmap) { G_message(_("Creating vector point map <%s>..."), centroidsmap); /* set comment */ sprintf(buf, _("From '%s' on raster map <%s> using clumps from <%s>"), argv[0], datamap, clumpmap); Vect_set_comment(fd_centroids, buf); /* create attribute table */ Fi = Vect_default_field_info(fd_centroids, 1, NULL, GV_1TABLE); driver = db_start_driver_open_database(Fi->driver, Vect_subst_var(Fi->database, fd_centroids)); if (driver == NULL) { G_fatal_error(_("Unable to open database <%s> by driver <%s>"), Vect_subst_var(Fi->database, fd_centroids), Fi->driver); } db_set_error_handler_driver(driver); db_begin_transaction(driver); db_init_string(&sql); sprintf(buf, "create table %s (cat integer, volume double precision, " "average double precision, sum double precision, count integer)", Fi->table); db_set_string(&sql, buf); Vect_map_add_dblink(fd_centroids, 1, NULL, Fi->table, GV_KEY_COLUMN, Fi->database, Fi->driver); G_debug(3, "%s", db_get_string(&sql)); if (db_execute_immediate(driver, &sql) != DB_OK) { G_fatal_error(_("Unable to create table: %s"), db_get_string(&sql)); } } /* print header */ if (out_mode) { fprintf(stdout, _("\nVolume report on data from <%s> using clumps on <%s> raster map"), datamap, clumpmap); fprintf(stdout, "\n\n"); fprintf(stdout, _("Category Average Data # Cells Centroid Total\n")); fprintf(stdout, _("Number in clump Total in clump Easting Northing Volume")); fprintf(stdout, "\n%s\n", SEP); } total_vol = 0.0; /* print output, write centroids */ for (i = 1; i <= max; i++) { if (count[i]) { avg = sum[i] / (double)count[i]; vol = sum[i] * window.ew_res * window.ns_res; total_vol += vol; east = window.west + (e[i] + 0.5) * window.ew_res; north = window.north - (n[i] + 0.5) * window.ns_res; if (fd_centroids) { /* write centroids if requested */ Points->x[0] = east; Points->y[0] = north; Cats->cat[0] = i; Vect_write_line(fd_centroids, GV_POINT, Points, Cats); sprintf(buf, "insert into %s values (%d, %f, %f, %f, %ld)", Fi->table, i, vol, avg, sum[i], count[i]); db_set_string(&sql, buf); if (db_execute_immediate(driver, &sql) != DB_OK) G_fatal_error(_("Cannot insert new row: %s"), db_get_string(&sql)); } if (out_mode) fprintf(stdout, "%8d%10.2f%10.0f %7ld %10.2f %10.2f %16.2f\n", i, avg, sum[i], count[i], east, north, vol); else fprintf(stdout, "%d:%.2f:%.0f:%ld:%.2f:%.2f:%.2f\n", i, avg, sum[i], count[i], east, north, vol); } } /* write centroid attributes and close the map*/ if (fd_centroids) { db_commit_transaction(driver); Vect_close(fd_centroids); } /* print total value */ if (total_vol > 0.0 && out_mode) { fprintf(stdout, "%s\n", SEP); fprintf(stdout, "%60s = %14.2f", _("Total Volume"), total_vol); fprintf(stdout, "\n"); } exit(EXIT_SUCCESS); }
/** * The main function controls the program flow. */ int main(int argc, char *argv[]) { struct params p; label_t *labels; int n_labels, i; struct GModule *module; FILE *labelf; srand((unsigned int)time(NULL)); G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("vector")); G_add_keyword(_("paint labels")); module->description = _("Create optimally placed labels for vector map(s)"); /* parse options and flags */ p.map = G_define_standard_option(G_OPT_V_MAP); p.type = G_define_standard_option(G_OPT_V_TYPE); p.type->options = "point,line,area"; p.type->answer = "point,line,area"; p.layer = G_define_standard_option(G_OPT_V_FIELD); p.column = G_define_option(); p.column->key = "column"; p.column->type = TYPE_STRING; p.column->required = YES; p.column->description = _("Name of attribute column to be used for labels"); p.labels = G_define_option(); p.labels->key = "labels"; p.labels->description = _("Name for new paint-label file"); p.labels->type = TYPE_STRING; p.labels->required = YES; p.labels->key_desc = "name"; p.font = G_define_option(); p.font->key = "font"; p.font->type = TYPE_STRING; p.font->required = YES; p.font->description = _("Name of TrueType font (as listed in the fontcap)"); p.font->guisection = _("Font"); p.font->gisprompt = "font"; p.size = G_define_option(); p.size->key = "size"; p.size->description = _("Label size (in map-units)"); p.size->type = TYPE_DOUBLE; p.size->answer = "100"; p.size->guisection = _("Font"); p.isize = G_define_option(); p.isize->key = "isize"; p.isize->description = _("Icon size of point features (in map-units)"); p.isize->type = TYPE_DOUBLE; p.isize->answer = "10"; p.charset = G_define_option(); p.charset->key = "charset"; p.charset->type = TYPE_STRING; p.charset->required = NO; p.charset->answer = DEFAULT_CHARSET; p.charset->description = "Character encoding (default: " DEFAULT_CHARSET ")"; p.color = G_define_option(); p.color->key = "color"; p.color->description = _("Text color"); p.color->type = TYPE_STRING; p.color->answer = "black"; p.color->options = "aqua,black,blue,brown,cyan,gray,green,grey,indigo," "magenta,orange,purple,red,violet,white,yellow"; p.color->guisection = _("Colors"); p.hlcolor = G_define_option(); p.hlcolor->key = "hcolor"; p.hlcolor->description = _("Highlight color for text"); p.hlcolor->type = TYPE_STRING; p.hlcolor->answer = "none"; p.hlcolor->options = "none,aqua,black,blue,brown,cyan,gray,green,grey,indigo," "magenta,orange,purple,red,violet,white,yellow"; p.hlcolor->guisection = _("Colors"); p.hlwidth = G_define_option(); p.hlwidth->key = "hwidth"; p.hlwidth->description = _("Width of highlight coloring"); p.hlwidth->type = TYPE_DOUBLE; p.hlwidth->answer = "0"; p.hlwidth->guisection = _("Colors"); p.bgcolor = G_define_option(); p.bgcolor->key = "background"; p.bgcolor->description = _("Background color"); p.bgcolor->type = TYPE_STRING; p.bgcolor->answer = "none"; p.bgcolor->options = "none,aqua,black,blue,brown,cyan,gray,green,grey,indigo," "magenta,orange,purple,red,violet,white,yellow"; p.bgcolor->guisection = _("Colors"); p.opaque = G_define_option(); p.opaque->key = "opaque"; p.opaque->description = _("Opaque to vector (only relevant if background color is selected)"); p.opaque->type = TYPE_STRING; p.opaque->answer = "yes"; p.opaque->options = "yes,no"; p.opaque->key_desc = "yes|no"; p.opaque->guisection = _("Colors"); p.bocolor = G_define_option(); p.bocolor->key = "border"; p.bocolor->description = _("Border color"); p.bocolor->type = TYPE_STRING; p.bocolor->answer = "none"; p.bocolor->options = "none,aqua,black,blue,brown,cyan,gray,green,grey,indigo," "magenta,orange,purple,red,violet,white,yellow"; p.bocolor->guisection = _("Colors"); p.bowidth = G_define_option(); p.bowidth->key = "width"; p.bowidth->description = _("Border width (only for ps.map output)"); p.bowidth->type = TYPE_DOUBLE; p.bowidth->answer = "0"; p.bowidth->guisection = _("Colors"); if (G_parser(argc, argv)) exit(EXIT_FAILURE); /* initialize labels (get text from database, and get features) */ labels = labels_init(&p, &n_labels); /* start algorithm */ /* 1. candidate position generation */ label_candidates(labels, n_labels); /* 2. position evaluation */ label_candidate_overlap(labels, n_labels); /* 3. position selection */ simulate_annealing(labels, n_labels, &p); /* write lables to file */ fprintf(stderr, "Writing labels to file: ..."); labelf = G_fopen_new("paint/labels", p.labels->answer); for (i = 0; i < n_labels; i++) { if (labels[i].n_candidates > 0) { print_label(labelf, &labels[i], &p); } G_percent(i, (n_labels - 1), 1); } fclose(labelf); return EXIT_SUCCESS; }
/* ************************************************************************* */ int main(int argc, char *argv[]) { struct GModule *module = NULL; N_solute_transport_data2d *data = NULL; N_geom_data *geom = NULL; N_les *les = NULL; N_les_callback_2d *call = NULL; struct Cell_head region; double error, sor; char *solver; int x, y, stat, i, maxit = 1; double loops = 1; N_array_2d *xcomp = NULL; N_array_2d *ycomp = NULL; N_array_2d *hc_x = NULL; N_array_2d *hc_y = NULL; N_array_2d *phead = NULL; double time_step, cfl, length, time_loops, time_sum; /* Initialize GRASS */ G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("raster")); G_add_keyword(_("hydrology")); G_add_keyword(_("solute transport")); module->description = _("Numerical calculation program for transient, confined and unconfined " "solute transport in two dimensions"); /* Get parameters from user */ set_params(); if (G_parser(argc, argv)) exit(EXIT_FAILURE); /* Make sure that the current projection is not lat/long */ if ((G_projection() == PROJECTION_LL)) G_fatal_error(_("Lat/Long location is not supported by %s. Please reproject map first."), G_program_name()); /*Set the maximum iterations */ sscanf(param.maxit->answer, "%i", &(maxit)); /*Set the calculation error break criteria */ sscanf(param.error->answer, "%lf", &(error)); sscanf(param.sor->answer, "%lf", &(sor)); /*number of loops*/ sscanf(param.loops->answer, "%lf", &(loops)); /*Set the solver */ solver = param.solver->answer; if (strcmp(solver, G_MATH_SOLVER_DIRECT_LU) == 0 && !param.full_les->answer) G_fatal_error(_("The direct LU solver do not work with sparse matrices")); if (strcmp(solver, G_MATH_SOLVER_DIRECT_GAUSS) == 0 && !param.full_les->answer) G_fatal_error(_("The direct Gauss solver do not work with sparse matrices")); /*get the current region */ G_get_set_window(®ion); /*allocate the geometry structure for geometry and area calculation */ geom = N_init_geom_data_2d(®ion, geom); /*Set the function callback to the groundwater flow function */ call = N_alloc_les_callback_2d(); N_set_les_callback_2d_func(call, (*N_callback_solute_transport_2d)); /*solute_transport 2d */ /*Allocate the groundwater flow data structure */ data = N_alloc_solute_transport_data2d(geom->cols, geom->rows); /*Set the stabilizing scheme*/ if (strncmp("full", param.stab->answer, 4) == 0) { data->stab = N_UPWIND_FULL; } if (strncmp("exp", param.stab->answer, 3) == 0) { data->stab = N_UPWIND_EXP; } /*the dispersivity lengths*/ sscanf(param.al->answer, "%lf", &(data->al)); sscanf(param.at->answer, "%lf", &(data->at)); /*Set the calculation time */ sscanf(param.dt->answer, "%lf", &(data->dt)); /*read all input maps into the memory and take care of the * null values.*/ N_read_rast_to_array_2d(param.c->answer, data->c); N_convert_array_2d_null_to_zero(data->c); N_read_rast_to_array_2d(param.c->answer, data->c_start); N_convert_array_2d_null_to_zero(data->c_start); N_read_rast_to_array_2d(param.status->answer, data->status); N_convert_array_2d_null_to_zero(data->status); N_read_rast_to_array_2d(param.diff_x->answer, data->diff_x); N_convert_array_2d_null_to_zero(data->diff_x); N_read_rast_to_array_2d(param.diff_y->answer, data->diff_y); N_convert_array_2d_null_to_zero(data->diff_y); N_read_rast_to_array_2d(param.q->answer, data->q); N_convert_array_2d_null_to_zero(data->q); N_read_rast_to_array_2d(param.nf->answer, data->nf); N_convert_array_2d_null_to_zero(data->nf); N_read_rast_to_array_2d(param.cs->answer, data->cs); N_convert_array_2d_null_to_zero(data->cs); N_read_rast_to_array_2d(param.top->answer, data->top); N_convert_array_2d_null_to_zero(data->top); N_read_rast_to_array_2d(param.bottom->answer, data->bottom); N_convert_array_2d_null_to_zero(data->bottom); N_read_rast_to_array_2d(param.r->answer, data->R); N_convert_array_2d_null_to_zero(data->R); if(param.cin->answer) { N_read_rast_to_array_2d(param.cin->answer, data->cin); N_convert_array_2d_null_to_zero(data->cin); } /*initiate the values for velocity calculation*/ hc_x = N_alloc_array_2d(geom->cols, geom->rows, 1, DCELL_TYPE); hc_x = N_read_rast_to_array_2d(param.hc_x->answer, hc_x); N_convert_array_2d_null_to_zero(hc_x); hc_y = N_alloc_array_2d(geom->cols, geom->rows, 1, DCELL_TYPE); hc_y = N_read_rast_to_array_2d(param.hc_y->answer, hc_y); N_convert_array_2d_null_to_zero(hc_y); phead = N_alloc_array_2d(geom->cols, geom->rows, 1, DCELL_TYPE); phead = N_read_rast_to_array_2d(param.phead->answer, phead); N_convert_array_2d_null_to_zero(phead); /* Set the inactive values to zero, to assure a no flow boundary */ for (y = 0; y < geom->rows; y++) { for (x = 0; x < geom->cols; x++) { stat = (int)N_get_array_2d_d_value(data->status, x, y); if (stat == N_CELL_INACTIVE) { /*only inactive cells */ N_put_array_2d_d_value(data->diff_x, x, y, 0); N_put_array_2d_d_value(data->diff_y, x, y, 0); N_put_array_2d_d_value(data->cs, x, y, 0); N_put_array_2d_d_value(data->q, x, y, 0); } } } /*compute the velocities */ N_math_array_2d(hc_x, data->nf, hc_x, N_ARRAY_DIV); N_math_array_2d(hc_y, data->nf, hc_y, N_ARRAY_DIV); N_compute_gradient_field_2d(phead, hc_x, hc_y, geom, data->grad); /*Now compute the dispersivity tensor*/ N_calc_solute_transport_disptensor_2d(data); /***************************************/ /*the Courant-Friedrichs-Lewy criteria */ /*Compute the correct time step */ if (geom->dx > geom->dy) length = geom->dx; else length = geom->dy; if (fabs(data->grad->max) > fabs(data->grad->min)) { cfl = (double)data->dt * fabs(data->grad->max) / length; time_step = 1*length / fabs(data->grad->max); } else { cfl = (double)data->dt * fabs(data->grad->min) / length; time_step = 1*length / fabs(data->grad->min); } G_message(_("The Courant-Friedrichs-Lewy criteria is %g it should be within [0:1]"), cfl); G_message(_("The largest stable time step is %g"), time_step); /*Set the number of inner loops and the time step*/ if (data->dt > time_step && param.cfl->answer) { /*safe the user time step */ time_sum = data->dt; time_loops = data->dt / time_step; time_loops = floor(time_loops) + 1; data->dt = data->dt / time_loops; G_message(_("Number of inner loops is %g"), time_loops); G_message(_("Time step for each loop %g"), data->dt); } else { if(data->dt > time_step) G_warning(_("The time step is to large: %gs. The largest time step should be of size %gs."), data->dt, time_step); time_loops = loops; data->dt = data->dt / loops; } N_free_array_2d(phead); N_free_array_2d(hc_x); N_free_array_2d(hc_y); /*Compute for each time step*/ for (i = 0; i < time_loops; i++) { G_message(_("Time step %i with time sum %g"), i + 1, (i + 1)*data->dt); /*assemble the linear equation system and solve it */ les = create_solve_les(geom, data, call, solver, maxit, error, sor); /* copy the result into the c array for output */ copy_result(data->status, data->c_start, les->x, ®ion, data->c, 1); N_convert_array_2d_null_to_zero(data->c_start); if (les) N_free_les(les); /*Set the start array*/ N_copy_array_2d(data->c, data->c_start); /*Set the transmission boundary*/ N_calc_solute_transport_transmission_2d(data); } /*write the result to the output file */ N_write_array_2d_to_rast(data->c, param.output->answer); /*Compute the the velocity field if required and write the result into three rast maps */ if (param.vector_x->answer || param.vector_y->answer) { xcomp = N_alloc_array_2d(geom->cols, geom->rows, 1, DCELL_TYPE); ycomp = N_alloc_array_2d(geom->cols, geom->rows, 1, DCELL_TYPE); N_compute_gradient_field_components_2d(data->grad, xcomp, ycomp); if (param.vector_x->answer) N_write_array_2d_to_rast(xcomp, param.vector_x->answer); if (param.vector_y->answer) N_write_array_2d_to_rast(ycomp, param.vector_y->answer); if (xcomp) N_free_array_2d(xcomp); if (ycomp) N_free_array_2d(ycomp); } if (data) N_free_solute_transport_data2d(data); if (geom) N_free_geom_data(geom); if (call) G_free(call); return (EXIT_SUCCESS); }
int main(int argc, char *argv[]) { int *fd; char **names; char **ptr; char *name; /* flags */ int raw_data; int with_coordinates; int with_xy; int with_percents; int with_counts; int with_areas; int with_labels; /* printf format */ char fmt[20]; int dp; struct Range range; struct FPRange fp_range; struct Quant q; CELL min, max, null_set = 0; DCELL dmin, dmax; struct GModule *module; struct { struct Flag *A; /* print averaged values instead of intervals */ struct Flag *a; /* area */ struct Flag *c; /* cell counts */ struct Flag *p; /* percents */ struct Flag *l; /* with labels */ struct Flag *q; /* quiet */ struct Flag *n; /* Suppress reporting of any NULLs */ struct Flag *N; /* Suppress reporting of NULLs when all values are NULL */ struct Flag *one; /* one cell per line */ struct Flag *x; /* with row/col */ struct Flag *g; /* with east/north */ struct Flag *i; /* use quant rules for fp map, i.e. read it as int */ struct Flag *r; /* raw output: when nsteps option is used, report indexes of ranges instead of ranges themselves; when -C (cats) option is used reports indexes of fp ranges = ind. of labels */ struct Flag *C; /* report stats for labeled ranges in cats files */ } flag; struct { struct Option *cell; struct Option *fs; struct Option *nv; struct Option *output; struct Option *nsteps; /* divide data range into nsteps and report stats for these ranges: only for fp maps NOTE: when -C flag is used, and there are explicit fp ranges in cats or when the map is int, nsteps is ignored */ } option; G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("raster")); G_add_keyword(_("statistics")); module->description = _("Generates area statistics for raster map layers."); /* Define the different options */ option.cell = G_define_standard_option(G_OPT_R_INPUTS); option.output = G_define_standard_option(G_OPT_F_OUTPUT); option.output->required = NO; option.output->description = _("Name for output file (if omitted or \"-\" output to stdout)"); option.fs = G_define_standard_option(G_OPT_F_SEP); option.fs->key_desc = "character|space|tab"; option.fs->answer = "space"; option.fs->description = _("Output field separator"); option.nv = G_define_option(); option.nv->key = "nv"; option.nv->type = TYPE_STRING; option.nv->required = NO; option.nv->multiple = NO; option.nv->answer = "*"; option.nv->description = _("String representing no data cell value"); option.nsteps = G_define_option(); option.nsteps->key = "nsteps"; option.nsteps->type = TYPE_INTEGER; option.nsteps->required = NO; option.nsteps->multiple = NO; option.nsteps->answer = "255"; option.nsteps->description = _("Number of fp subranges to collect stats from"); /* Define the different flags */ flag.one = G_define_flag(); flag.one->key = '1'; flag.one->description = _("One cell (range) per line"); flag.A = G_define_flag(); flag.A->key = 'A'; flag.A->description = _("Print averaged values instead of intervals"); flag.A->guisection = _("Print"); flag.a = G_define_flag(); flag.a->key = 'a'; flag.a->description = _("Print area totals"); flag.a->guisection = _("Print"); flag.c = G_define_flag(); flag.c->key = 'c'; flag.c->description = _("Print cell counts"); flag.c->guisection = _("Print"); flag.p = G_define_flag(); flag.p->key = 'p'; flag.p->description = _("Print APPROXIMATE percents (total percent may not be 100%)"); flag.p->guisection = _("Print"); flag.l = G_define_flag(); flag.l->key = 'l'; flag.l->description = _("Print category labels"); flag.l->guisection = _("Print"); flag.g = G_define_flag(); flag.g->key = 'g'; flag.g->description = _("Print grid coordinates (east and north)"); flag.g->guisection = _("Print"); flag.x = G_define_flag(); flag.x->key = 'x'; flag.x->description = _("Print x and y (column and row)"); flag.x->guisection = _("Print"); flag.r = G_define_flag(); flag.r->key = 'r'; flag.r->description = _("Print raw indexes of fp ranges (fp maps only)"); flag.r->guisection = _("Print"); flag.n = G_define_flag(); flag.n->key = 'n'; flag.n->description = _("Suppress reporting of any NULLs"); flag.N = G_define_flag(); flag.N->key = 'N'; flag.N->description = _("Suppress reporting of NULLs when all values are NULL"); flag.C = G_define_flag(); flag.C->key = 'C'; flag.C->description = _("Report for cats fp ranges (fp maps only)"); flag.i = G_define_flag(); flag.i->key = 'i'; flag.i->description = _("Read fp map as integer (use map's quant rules)"); if (G_parser(argc, argv)) exit(EXIT_FAILURE); name = option.output->answer; if (name != NULL && strcmp(name, "-") != 0) { if (NULL == freopen(name, "w", stdout)) { G_fatal_error(_("Unable to open file <%s> for writing"), name); } } sscanf(option.nsteps->answer, "%d", &nsteps); if (nsteps <= 0) { G_warning(_("'%s' must be greater than zero; using %s=255"), option.nsteps->key, option.nsteps->key); nsteps = 255; } cat_ranges = flag.C->answer; averaged = flag.A->answer; raw_output = flag.r->answer; as_int = flag.i->answer; nrows = Rast_window_rows(); ncols = Rast_window_cols(); fd = NULL; nfiles = 0; dp = -1; with_percents = flag.p->answer; with_counts = flag.c->answer; with_areas = flag.a->answer; with_labels = flag.l->answer; no_nulls = flag.n->answer; no_nulls_all = flag.N->answer; no_data_str = option.nv->answer; raw_data = flag.one->answer; with_coordinates = flag.g->answer; with_xy = flag.x->answer; if (with_coordinates || with_xy) raw_data = 1; /* get field separator */ strcpy(fs, " "); if (option.fs->answer) { if (strcmp(option.fs->answer, "space") == 0) *fs = ' '; else if (strcmp(option.fs->answer, "tab") == 0) *fs = '\t'; else if (strcmp(option.fs->answer, "\\t") == 0) *fs = '\t'; else *fs = *option.fs->answer; } /* open all raster maps */ if (option.cell->answers[0] == NULL) G_fatal_error(_("Raster map not found")); names = option.cell->answers; ptr = option.cell->answers; for (; *ptr != NULL; ptr++) { name = *ptr; fd = (int *)G_realloc(fd, (nfiles + 1) * sizeof(int)); is_fp = (int *)G_realloc(is_fp, (nfiles + 1) * sizeof(int)); DMAX = (DCELL *) G_realloc(DMAX, (nfiles + 1) * sizeof(DCELL)); DMIN = (DCELL *) G_realloc(DMIN, (nfiles + 1) * sizeof(DCELL)); fd[nfiles] = Rast_open_old(name, ""); if (!as_int) is_fp[nfiles] = Rast_map_is_fp(name, ""); else { is_fp[nfiles] = 0; if (cat_ranges || nsteps != 255) G_warning(_("Raster map <%s> is reading as integer map! " "Flag '-%c' and/or '%s' option will be ignored."), name, flag.C->key, option.nsteps->key); } if (with_labels || (cat_ranges && is_fp[nfiles])) { labels = (struct Categories *) G_realloc(labels, (nfiles + 1) * sizeof(struct Categories)); if (Rast_read_cats(name, "", &labels[nfiles]) < 0) Rast_init_cats("", &labels[nfiles]); } if (is_fp[nfiles]) /* floating point map */ { Rast_quant_init(&q); if (cat_ranges) { if (!Rast_quant_nof_rules(&labels[nfiles].q)) { G_warning(_("Cats for raster map <%s> are either missing or have no explicit labels. " "Using %s=%d."), name, option.nsteps->key, nsteps); cat_ranges = 0; } else if (nsteps != 255) G_warning(_("Flag '-%c' was given, using cats fp ranges of raster map <%s>, " "ignoring '%s' option"), flag.C->key, name, option.nsteps->key); } if (!cat_ranges) { /* DO NOT use else here, cat_ranges can change */ if (Rast_read_fp_range(name, "", &fp_range) < 0) G_fatal_error(_("Unable to read fp range of raster map <%s>"), name); Rast_get_fp_range_min_max(&fp_range, &DMIN[nfiles], &DMAX[nfiles]); G_debug(3, "file %2d: dmin=%f dmax=%f", nfiles, DMIN[nfiles], DMAX[nfiles]); Rast_quant_add_rule(&q, DMIN[nfiles], DMAX[nfiles], 1, nsteps+1); /* set the quant rules for reading the map */ Rast_set_quant_rules(fd[nfiles], &q); Rast_quant_get_limits(&q, &dmin, &dmax, &min, &max); G_debug(2, "overall: dmin=%f dmax=%f, qmin=%d qmax=%d", dmin, dmax, min, max); Rast_quant_free(&q); } else { /* cats ranges */ /* set the quant rules for reading the map */ Rast_set_quant_rules(fd[nfiles], &labels[nfiles].q); Rast_quant_get_limits(&labels[nfiles].q, &dmin, &dmax, &min, &max); } } else { if (Rast_read_range(name, "", &range) < 0) G_fatal_error(_("Unable to read range for map <%s>"), name); Rast_get_range_min_max(&range, &min, &max); } if (!null_set) { null_set = 1; NULL_CELL = max + 1; } else if (NULL_CELL < max + 1) NULL_CELL = max + 1; nfiles++; } if (dp < 0) strcpy(fmt, "%lf"); else sprintf(fmt, "%%.%dlf", dp); if (raw_data) raw_stats(fd, with_coordinates, with_xy, with_labels); else cell_stats(fd, with_percents, with_counts, with_areas, with_labels, fmt); exit(EXIT_SUCCESS); }
int main(int argc, char *argv[]) { unsigned int r, c, rows, cols; /* totals */ int map1_fd, map2_fd; double sumX, sumY, sumsqX, sumsqY, sumXY; double meanX, meanY, varX, varY, sdX, sdY; double A, B, R, F; long count = 0; DCELL *map1_buf, *map2_buf, map1_val, map2_val; char *name; struct Option *input_map1, *input_map2, *output_opt; struct Flag *shell_style; struct Cell_head region; struct GModule *module; G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("raster")); G_add_keyword(_("statistics")); module->description = _("Calculates linear regression from two raster maps: y = a + b*x."); /* Define the different options */ input_map1 = G_define_standard_option(G_OPT_R_MAP); input_map1->key = "map1"; input_map1->description = (_("Map for x coefficient")); input_map2 = G_define_standard_option(G_OPT_R_MAP); input_map2->key = "map2"; input_map2->description = (_("Map for y coefficient")); output_opt = G_define_standard_option(G_OPT_F_OUTPUT); output_opt->key = "output"; output_opt->required = NO; output_opt->description = (_("ASCII file for storing regression coefficients (output to screen if file not specified).")); shell_style = G_define_flag(); shell_style->key = 'g'; shell_style->description = _("Print in shell script style"); if (G_parser(argc, argv)) exit(EXIT_FAILURE); name = output_opt->answer; if (name != NULL && strcmp(name, "-") != 0) { if (NULL == freopen(name, "w", stdout)) { G_fatal_error(_("Unable to open file <%s> for writing"), name); } } G_get_window(®ion); rows = region.rows; cols = region.cols; /* open maps */ map1_fd = Rast_open_old(input_map1->answer, ""); map2_fd = Rast_open_old(input_map2->answer, ""); map1_buf = Rast_allocate_d_buf(); map2_buf = Rast_allocate_d_buf(); sumX = sumY = sumsqX = sumsqY = sumXY = 0.0; meanX = meanY = varX = varY = sdX = sdY = 0.0; for (r = 0; r < rows; r++) { G_percent(r, rows, 2); Rast_get_d_row(map1_fd, map1_buf, r); Rast_get_d_row(map2_fd, map2_buf, r); for (c = 0; c < cols; c++) { map1_val = map1_buf[c]; map2_val = map2_buf[c]; if (Rast_is_d_null_value(&map1_val) || Rast_is_d_null_value(&map2_val)) continue; sumX += map1_val; sumY += map2_val; sumsqX += map1_val * map1_val; sumsqY += map2_val * map2_val; sumXY += map1_val * map2_val; count++; } } Rast_close(map1_fd); Rast_close(map2_fd); G_free(map1_buf); G_free(map2_buf); B = (sumXY - sumX * sumY / count) / (sumsqX - sumX * sumX / count); R = (sumXY - sumX * sumY / count) / sqrt((sumsqX - sumX * sumX / count) * (sumsqY - sumY * sumY / count)); meanX = sumX / count; sumsqX = sumsqX / count; varX = sumsqX - (meanX * meanX); sdX = sqrt(varX); meanY = sumY / count; sumsqY = sumsqY / count; varY = sumsqY - (meanY * meanY); sdY = sqrt(varY); A = meanY - B * meanX; F = R * R / (1 - R * R / count - 2); if (shell_style->answer) { fprintf(stdout, "a=%f\n", A); fprintf(stdout, "b=%f\n", B); fprintf(stdout, "R=%f\n", R); fprintf(stdout, "N=%ld\n", count); fprintf(stdout, "F=%f\n", F); fprintf(stdout, "meanX=%f\n", meanX); fprintf(stdout, "sdX=%f\n", sdX); fprintf(stdout, "meanY=%f\n", meanY); fprintf(stdout, "sdY=%f\n", sdY); } else { fprintf(stdout, "y = a + b*x\n"); fprintf(stdout, " a (Offset): %f\n", A); fprintf(stdout, " b (Gain): %f\n", B); fprintf(stdout, " R (sumXY - sumX*sumY/N): %f\n", R); fprintf(stdout, " N (Number of elements): %ld\n", count); fprintf(stdout, " F (F-test significance): %f\n", F); fprintf(stdout, " meanX (Mean of map1): %f\n", meanX); fprintf(stdout, " sdX (Standard deviation of map1): %f\n", sdX); fprintf(stdout, " meanY (Mean of map2): %f\n", meanY); fprintf(stdout, " sdY (Standard deviation of map2): %f\n", sdY); } exit(EXIT_SUCCESS); }
/*----------------------------------------------------------------------------------------------------------*/ int main(int argc, char *argv[]) { /* Declarations */ int dim_vect, nparameters, BW, npoints; int nsply, nsplx, nsplx_adj, nsply_adj; int nsubregion_col, nsubregion_row; int subregion = 0, nsubregions = 0; const char *dvr, *db, *mapset; char table_name[GNAME_MAX]; char xname[GNAME_MAX], xmapset[GMAPSET_MAX]; double lambda, mean, stepN, stepE, HighThresh, LowThresh; double N_extension, E_extension, edgeE, edgeN; int i, nterrain, count_terrain; int last_row, last_column, flag_auxiliar = FALSE; int *lineVect; double *TN, *Q, *parVect; /* Interpolating and least-square vectors */ double **N, **obsVect, **obsVect_all; /* Interpolation and least-square matrix */ struct Map_info In, Out, Terrain; struct Option *in_opt, *out_opt, *out_terrain_opt, *stepE_opt, *stepN_opt, *lambda_f_opt, *Thresh_A_opt, *Thresh_B_opt; struct Flag *spline_step_flag; struct GModule *module; struct Cell_head elaboration_reg, original_reg; struct Reg_dimens dims; struct bound_box general_box, overlap_box; struct Point *observ; struct lidar_cat *lcat; dbDriver *driver; /*----------------------------------------------------------------------------------------------------------*/ /* Options' declaration */ module = G_define_module(); G_add_keyword(_("vector")); G_add_keyword(_("LIDAR")); module->description = _("Corrects the v.lidar.growing output. It is the last of the three algorithms for LIDAR filtering."); 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->description = _("Input observation vector map name (v.lidar.growing output)"); out_opt = G_define_standard_option(G_OPT_V_OUTPUT); out_opt->description = _("Output classified vector map name"); out_terrain_opt = G_define_option(); out_terrain_opt->key = "terrain"; out_terrain_opt->type = TYPE_STRING; out_terrain_opt->key_desc = "name"; out_terrain_opt->required = YES; out_terrain_opt->gisprompt = "new,vector,vector"; out_terrain_opt->description = _("Only 'terrain' points output vector map"); stepE_opt = G_define_option(); stepE_opt->key = "ew_step"; stepE_opt->type = TYPE_DOUBLE; stepE_opt->required = NO; stepE_opt->answer = "25"; 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 = "25"; stepN_opt->description = _("Length of each spline step in the north-south direction"); stepN_opt->guisection = _("Settings"); lambda_f_opt = G_define_option(); lambda_f_opt->key = "lambda_c"; lambda_f_opt->type = TYPE_DOUBLE; lambda_f_opt->required = NO; lambda_f_opt->description = _("Regularization weight in reclassification evaluation"); lambda_f_opt->answer = "1"; Thresh_A_opt = G_define_option(); Thresh_A_opt->key = "tch"; Thresh_A_opt->type = TYPE_DOUBLE; Thresh_A_opt->required = NO; Thresh_A_opt->description = _("High threshold for object to terrain reclassification"); Thresh_A_opt->answer = "2"; Thresh_B_opt = G_define_option(); Thresh_B_opt->key = "tcl"; Thresh_B_opt->type = TYPE_DOUBLE; Thresh_B_opt->required = NO; Thresh_B_opt->description = _("Low threshold for terrain to object reclassification"); Thresh_B_opt->answer = "1"; /* Parsing */ G_gisinit(argv[0]); if (G_parser(argc, argv)) exit(EXIT_FAILURE); stepN = atof(stepN_opt->answer); stepE = atof(stepE_opt->answer); lambda = atof(lambda_f_opt->answer); HighThresh = atof(Thresh_A_opt->answer); LowThresh = atof(Thresh_B_opt->answer); if (!(db = G_getenv_nofatal2("DB_DATABASE", G_VAR_MAPSET))) G_fatal_error(_("Unable to read name of database")); if (!(dvr = G_getenv_nofatal2("DB_DRIVER", G_VAR_MAPSET))) G_fatal_error(_("Unable to read name of driver")); /* Setting auxiliary table's name */ 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.lidar.correction execution */ if (db_table_exists(dvr, db, table_name)) { /* Start driver and open db */ driver = db_start_driver_open_database(dvr, db); if (driver == NULL) G_fatal_error(_("No database connection for driver <%s> is defined. Run db.connect."), dvr); 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); } /* Checking vector names */ Vect_check_input_output_name(in_opt->answer, out_opt->answer, G_FATAL_EXIT); /* 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>"), in_opt->answer); /* Input vector must be 3D */ if (!Vect_is_3d(&In)) G_fatal_error(_("Input vector map <%s> is not 3D!"), in_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) { G_message("Estimated point density: %.4g", dens); G_message("Estimated mean distance between points: %.4g", dist); } else G_warning(_("No points in current region!")); Vect_close(&In); exit(EXIT_SUCCESS); } /* Open output vector */ if (0 > Vect_open_new(&Out, out_opt->answer, WITH_Z)) { Vect_close(&In); G_fatal_error(_("Unable to create vector map <%s>"), out_opt->answer); } if (0 > Vect_open_new(&Terrain, out_terrain_opt->answer, WITH_Z)) { Vect_close(&In); Vect_close(&Out); G_fatal_error(_("Unable to create vector map <%s>"), out_opt->answer); } /* Copy vector Head File */ Vect_copy_head_data(&In, &Out); Vect_hist_copy(&In, &Out); Vect_hist_command(&Out); Vect_copy_head_data(&In, &Terrain); Vect_hist_copy(&In, &Terrain); Vect_hist_command(&Terrain); /* Start driver and open db */ driver = db_start_driver_open_database(dvr, db); if (driver == NULL) G_fatal_error(_("No database connection for driver <%s> is defined. Run db.connect."), dvr); db_set_error_handler_driver(driver); /* Create auxiliary table */ if ((flag_auxiliar = P_Create_Aux2_Table(driver, table_name)) == FALSE) { Vect_close(&In); Vect_close(&Out); Vect_close(&Terrain); exit(EXIT_FAILURE); } db_create_index2(driver, table_name, "ID"); /* sqlite likes that ??? */ db_close_database_shutdown_driver(driver); driver = db_start_driver_open_database(dvr, db); /* Setting regions and boxes */ G_get_set_window(&original_reg); G_get_set_window(&elaboration_reg); Vect_region_box(&elaboration_reg, &overlap_box); Vect_region_box(&elaboration_reg, &general_box); /*------------------------------------------------------------------ | Subdividing and working with tiles: | Each original region will be divided into several subregions. | Each one will be overlapped 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); 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(P_BILINEAR, &dims, stepE, stepN); P_set_dim(&dims, stepE, stepN, &nsplx_adj, &nsply_adj); G_verbose_message(n_("adjusted EW spline %d", "adjusted EW splines %d", nsplx_adj), nsplx_adj); G_verbose_message(n_("adjusted NS spline %d", "adjusted NS splines %d", nsply_adj), 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; elaboration_reg.south = original_reg.north; last_row = FALSE; while (last_row == FALSE) { /* For each 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; /* if (nsply > NSPLY_MAX) { nsply = NSPLY_MAX; } */ G_debug(1, _("nsply = %d"), nsply); elaboration_reg.east = original_reg.west; last_column = FALSE; while (last_column == FALSE) { /* For each column */ subregion++; if (nsubregions > 1) G_message(_("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; /* if (nsplx > NSPLX_MAX) { nsplx = NSPLX_MAX; } */ G_debug(1, _("nsplx = %d"), nsplx); dim_vect = nsplx * nsply; G_debug(1, _("read vector region map")); observ = P_Read_Vector_Correction(&In, &elaboration_reg, &npoints, &nterrain, dim_vect, &lcat); G_debug(5, _("npoints = %d, nterrain = %d"), npoints, nterrain); if (npoints > 0) { /* If there is any point falling into elaboration_reg. */ count_terrain = 0; nparameters = nsplx * nsply; /* Mean calculation */ G_debug(3, _("Mean calculation")); mean = P_Mean_Calc(&elaboration_reg, observ, npoints); /*Least Squares system */ BW = P_get_BandWidth(P_BILINEAR, nsply); /* Bilinear interpolation */ N = G_alloc_matrix(nparameters, BW); /* Normal matrix */ TN = G_alloc_vector(nparameters); /* vector */ parVect = G_alloc_vector(nparameters); /* Bilinear parameters vector */ obsVect = G_alloc_matrix(nterrain + 1, 3); /* Observation vector with terrain points */ obsVect_all = G_alloc_matrix(npoints + 1, 3); /* Observation vector with all points */ Q = G_alloc_vector(nterrain + 1); /* "a priori" var-cov matrix */ lineVect = G_alloc_ivector(npoints + 1); /* Setting obsVect vector & Q matrix */ G_debug(3, _("Only TERRAIN points")); for (i = 0; i < npoints; i++) { if (observ[i].cat == TERRAIN_SINGLE) { obsVect[count_terrain][0] = observ[i].coordX; obsVect[count_terrain][1] = observ[i].coordY; obsVect[count_terrain][2] = observ[i].coordZ - mean; Q[count_terrain] = 1; /* Q=I */ count_terrain++; } lineVect[i] = observ[i].lineID; obsVect_all[i][0] = observ[i].coordX; obsVect_all[i][1] = observ[i].coordY; obsVect_all[i][2] = observ[i].coordZ - mean; } G_free(observ); G_verbose_message(_("Bilinear interpolation")); normalDefBilin(N, TN, Q, obsVect, stepE, stepN, nsplx, nsply, elaboration_reg.west, elaboration_reg.south, nterrain, nparameters, BW); nCorrectGrad(N, lambda, nsplx, nsply, stepE, stepN); G_math_solver_cholesky_sband(N, parVect, TN, nparameters, BW); G_free_matrix(N); G_free_vector(TN); G_free_vector(Q); G_free_matrix(obsVect); G_verbose_message( _("Correction and creation of terrain vector")); P_Sparse_Correction(&In, &Out, &Terrain, &elaboration_reg, general_box, overlap_box, obsVect_all, lcat, parVect, lineVect, stepN, stepE, dims.overlap, HighThresh, LowThresh, nsplx, nsply, npoints, driver, mean, table_name); G_free_vector(parVect); G_free_matrix(obsVect_all); G_free_ivector(lineVect); } else { G_free(observ); G_warning(_("No data within this subregion. " "Consider changing the spline step.")); } G_free(lcat); } /*! END WHILE; last_column = TRUE */ } /*! END WHILE; last_row = TRUE */ /* Dropping auxiliary table */ if (npoints > 0) { G_debug(1, _("Dropping <%s>"), 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); Vect_close(&Out); Vect_close(&Terrain); G_done_msg(" "); exit(EXIT_SUCCESS); } /*! END MAIN */
int main(int argc, char *argv[]) { int i, j, precision, field, type, nlines; int do_attr = 0, attr_cols[8], attr_size = 0, db_open = 0, cnt = 0; double width, radius; struct Option *in_opt, *out_opt, *prec_opt, *type_opt, *attr_opt, *field_opt; struct GModule *module; struct Map_info In; struct bound_box box; /* vector */ struct line_pnts *Points; struct line_cats *Cats; /* attribs */ dbDriver *Driver = NULL; dbHandle handle; dbTable *Table; dbString dbstring; struct field_info *Fi; /* init */ G_gisinit(argv[0]); /* parse command-line */ module = G_define_module(); module->description = _("Exports a vector map to SVG file."); G_add_keyword(_("vector")); G_add_keyword(_("export")); in_opt = G_define_standard_option(G_OPT_V_INPUT); field_opt = G_define_standard_option(G_OPT_V_FIELD_ALL); out_opt = G_define_standard_option(G_OPT_F_OUTPUT); out_opt->description = _("Name for SVG output file"); type_opt = G_define_option(); type_opt->key = "type"; type_opt->type = TYPE_STRING; type_opt->required = YES; type_opt->multiple = NO; type_opt->answer = "poly"; type_opt->options = "poly,line,point"; type_opt->label = _("Output type"); type_opt->description = _("Defines which feature-type will be extracted"); prec_opt = G_define_option(); prec_opt->key = "precision"; prec_opt->type = TYPE_INTEGER; prec_opt->required = NO; prec_opt->answer = "6"; prec_opt->multiple = NO; prec_opt->description = _("Coordinate precision"); attr_opt = G_define_standard_option(G_OPT_DB_COLUMNS); attr_opt->key = "attribute"; attr_opt->required = NO; attr_opt->multiple = YES; attr_opt->description = _("Attribute(s) to include in output SVG"); if (G_parser(argc, argv)) exit(EXIT_FAILURE); Points = Vect_new_line_struct(); Cats = Vect_new_cats_struct(); if (type_opt->answer[0] == 'l') { type = TYPE_LINE; } else { if (type_opt->answer[2] == 'l') type = TYPE_POLY; else type = TYPE_POINT; } /* override coordinate precision if any */ precision = atof(prec_opt->answer); if (precision < 0) { G_fatal_error(_("Precision must not be negative")); } if (precision > 15) { G_fatal_error(_("Precision must not be higher than 15")); } /* open input vector */ Vect_set_open_level(2); if (Vect_open_old2(&In, in_opt->answer, "", field_opt->answer) < 0) G_fatal_error(_("Unable to open vector map <%s>"), in_opt->answer); /* parse field number */ field = Vect_get_field_number(&In, field_opt->answer); /* open db-driver to attribs */ db_init_string(&dbstring); /* check for requested field */ Fi = Vect_get_field(&In, field); if (Fi != NULL) { Driver = db_start_driver(Fi->driver); if (Driver == NULL) { G_fatal_error(_("Unable to start driver <%s>"), Fi->driver); } /* open db */ db_init_handle(&handle); db_set_handle(&handle, Fi->database, NULL); if (db_open_database(Driver, &handle) != DB_OK) { G_fatal_error(_("Unable to open database <%s> by driver <%s>"), Fi->database, Fi->driver); } db_set_string(&dbstring, Fi->table); if (db_describe_table(Driver, &dbstring, &Table) != DB_OK) { G_fatal_error(_("Unable to describe table <%s>"), Fi->table); } /* define column-indices for columns to extract */ dbColumn *Column; for (i = 0; i < db_get_table_number_of_columns(Table); i++) { Column = db_get_table_column(Table, i); if (attr_opt->answer != NULL) { for (j = 0; attr_opt->answers[j] != NULL; j++) { if (G_strcasecmp(attr_opt->answers[j], db_get_column_name(Column)) == 0) { attr_cols[attr_size] = i; attr_size += 1; break; } } } } do_attr = 1; db_open = 1; } /* parse bounding box and define default stroke-width, radius */ Vect_get_map_box(&In, &box); if ((box.E - box.W) >= (box.N - box.S)) { radius = (box.E - box.W) * RADIUS_SCALE; width = (box.E - box.W) * WIDTH_SCALE; } else { radius = (box.N - box.S) * RADIUS_SCALE; width = (box.N - box.S) * WIDTH_SCALE; } /* open output SVG-file and print SVG-header with viewBox and Namenspaces */ if ((fpsvg = fopen(out_opt->answer, "w")) == NULL) { G_fatal_error(_("Unable to create SVG file <%s>"), out_opt->answer); } fprintf(fpsvg, "<svg xmlns=\"%s\" xmlns:xlink=\"%s\" xmlns:gg=\"%s\" ", SVG_NS, XLINK_NS, GRASS_NS); fprintf(fpsvg, "viewBox=\"%.*f %.*f %.*f %.*f\">\n", precision, box.W, precision, box.N * -1, precision, box.E - box.W, precision, box.N - box.S); fprintf(fpsvg, "<title>v.out.svg %s %s</title>\n", in_opt->answer, out_opt->answer); nlines = Vect_get_num_lines(&In); /* extract areas if any or requested */ if (type == TYPE_POLY) { if (Vect_get_num_areas(&In) == 0) { G_warning(_("No areas found, skipping %s"), "type=poly"); } else { int nareas; nareas = Vect_get_num_areas(&In); /* extract area as paths */ fprintf(fpsvg, " <g id=\"%s\" fill=\"#CCC\" stroke=\"#000\" stroke-width=\"%.*f\" >\n", G_Areas, precision, width); for (i = 1; i <= nareas; i++) { G_percent(i, nareas, 5); /* skip areas without centroid */ if (Vect_get_area_centroid(&In, i) == 0) { G_warning(_("Skipping area %d without centroid"), i); continue; } /* extract attribs, parse area */ Vect_get_area_cats(&In, i, Cats); fprintf(fpsvg, " <path "); if (Cats->n_cats > 0) { mk_attribs(Cats->cat[0], Fi, Driver, Table, attr_cols, attr_size, do_attr); } fprintf(fpsvg, "d=\""); Vect_get_area_points(&In, i, Points); mk_path(Points, precision); /* append islands if any within current path */ for (j = 0; j < Vect_get_area_num_isles(&In, i); j++) { Vect_get_isle_points(&In, Vect_get_area_isle(&In, i, j), Points); mk_path(Points, precision); } fprintf(fpsvg, "\" />\n"); cnt += 1; } fprintf(fpsvg, " </g>\n"); G_message(_("%d areas extracted"), cnt); } } /* extract points if requested */ if (type == TYPE_POINT) { if (Vect_get_num_primitives(&In, GV_POINTS) == 0) { G_warning(_("No points found, skipping %s"), "type=point"); } else { /* extract points as circles */ fprintf(fpsvg, " <g id=\"%s\" fill=\"#FC0\" stroke=\"#000\" " "stroke-width=\"%.*f\" >\n", G_Points, precision, width); for (i = 1; i <= nlines; i++) { G_percent(i, nlines, 5); if (!(Vect_read_line(&In, Points, Cats, i) & GV_POINTS)) continue; if (field != -1 && !Vect_cat_get(Cats, field, NULL)) continue; for (j = 0; j < Points->n_points; j++) { fprintf(fpsvg, " <circle "); if (Cats->n_cats > 0) { mk_attribs(Cats->cat[j], Fi, Driver, Table, attr_cols, attr_size, do_attr); } fprintf(fpsvg, "cx=\"%.*f\" cy=\"%.*f\" r=\"%.*f\" />\n", precision, Points->x[j], precision, Points->y[j] * -1, precision, radius); cnt += 1; } } fprintf(fpsvg, " </g>\n"); G_message(_("%d points extracted"), cnt); } } /* extract lines if requested */ if (type == TYPE_LINE) { if (Vect_get_num_primitives(&In, GV_LINES) == 0) { G_warning(_("No lines found, skipping %s"), "type=line"); } else { /* extract lines as paths */ fprintf(fpsvg, " <g id=\"%s\" fill=\"none\" stroke=\"#000\" " "stroke-width=\"%.*f\" >\n", G_Lines, precision, width); for (i = 1; i <= nlines; i++) { G_percent(i, nlines, 5); if (!(Vect_read_line(&In, Points, Cats, i) & GV_LINES)) continue; if (field != -1 && !Vect_cat_get(Cats, field, NULL)) continue; fprintf(fpsvg, " <path "); if (Cats->n_cats > 0) { mk_attribs(Cats->cat[0], Fi, Driver, Table, attr_cols, attr_size, do_attr); } fprintf(fpsvg, "d=\""); mk_path(Points, precision); fprintf(fpsvg, "\" />\n"); cnt += 1; } fprintf(fpsvg, " </g>\n"); G_message(_("%d lines extracted"), cnt); } } /* finish code */ fprintf(fpsvg, "</svg>\n"); if (db_open == 1) { /* close database handle */ db_close_database(Driver); db_shutdown_driver(Driver); } /* close SVG-file */ fclose(fpsvg); exit(EXIT_SUCCESS); }
int main(int argc, char *argv[]) { struct Map_info In, Out, Buf; struct line_pnts *Points; struct line_cats *Cats, *BCats; char bufname[GNAME_MAX]; struct GModule *module; struct Option *in_opt, *out_opt, *type_opt, *dista_opt, *distb_opt, *angle_opt; struct Flag *straight_flag, *nocaps_flag; struct Option *tol_opt, *bufcol_opt, *scale_opt, *field_opt; int verbose; double da, db, dalpha, tolerance, unit_tolerance; int type; int i, ret, nareas, area, nlines, line; char *Areas, *Lines; int field; struct buf_contours *arr_bc; struct buf_contours_pts arr_bc_pts; int buffers_count = 0, line_id; struct spatial_index si; struct bound_box bbox; /* Attributes if sizecol is used */ int nrec, ctype; struct field_info *Fi; dbDriver *Driver; dbCatValArray cvarr; double size_val, scale; module = G_define_module(); G_add_keyword(_("vector")); G_add_keyword(_("geometry")); G_add_keyword(_("buffer")); module->description = _("Creates a buffer around vector features of given type."); in_opt = G_define_standard_option(G_OPT_V_INPUT); field_opt = G_define_standard_option(G_OPT_V_FIELD_ALL); field_opt->guisection = _("Selection"); type_opt = G_define_standard_option(G_OPT_V_TYPE); type_opt->options = "point,line,boundary,centroid,area"; type_opt->answer = "point,line,area"; type_opt->guisection = _("Selection"); out_opt = G_define_standard_option(G_OPT_V_OUTPUT); dista_opt = G_define_option(); dista_opt->key = "distance"; dista_opt->type = TYPE_DOUBLE; dista_opt->required = NO; dista_opt->description = _("Buffer distance along major axis in map units"); dista_opt->guisection = _("Distance"); distb_opt = G_define_option(); distb_opt->key = "minordistance"; distb_opt->type = TYPE_DOUBLE; distb_opt->required = NO; distb_opt->description = _("Buffer distance along minor axis in map units"); distb_opt->guisection = _("Distance"); angle_opt = G_define_option(); angle_opt->key = "angle"; angle_opt->type = TYPE_DOUBLE; angle_opt->required = NO; angle_opt->answer = "0"; angle_opt->description = _("Angle of major axis in degrees"); angle_opt->guisection = _("Distance"); bufcol_opt = G_define_standard_option(G_OPT_DB_COLUMN); bufcol_opt->key = "bufcolumn"; bufcol_opt->description = _("Name of column to use for buffer distances"); bufcol_opt->guisection = _("Distance"); scale_opt = G_define_option(); scale_opt->key = "scale"; scale_opt->type = TYPE_DOUBLE; scale_opt->required = NO; scale_opt->answer = "1.0"; scale_opt->description = _("Scaling factor for attribute column values"); scale_opt->guisection = _("Distance"); tol_opt = G_define_option(); tol_opt->key = "tolerance"; tol_opt->type = TYPE_DOUBLE; tol_opt->required = NO; tol_opt->answer = "0.01"; tol_opt->description = _("Maximum distance between theoretical arc and polygon segments as multiple of buffer"); tol_opt->guisection = _("Distance"); straight_flag = G_define_flag(); straight_flag->key = 's'; straight_flag->description = _("Make outside corners straight"); nocaps_flag = G_define_flag(); nocaps_flag->key = 'c'; nocaps_flag->description = _("Don't make caps at the ends of polylines"); G_gisinit(argv[0]); if (G_parser(argc, argv)) exit(EXIT_FAILURE); type = Vect_option_to_types(type_opt); if ((dista_opt->answer && bufcol_opt->answer) || (!(dista_opt->answer || bufcol_opt->answer))) G_fatal_error(_("Select a buffer distance/minordistance/angle " "or column, but not both.")); if (bufcol_opt->answer) G_warning(_("The bufcol option may contain bugs during the cleaning " "step. If you encounter problems, use the debug " "option or clean manually with v.clean tool=break; " "v.category step=0; v.extract -d type=area")); if (field_opt->answer) field = Vect_get_field_number(&In, field_opt->answer); else field = -1; if (bufcol_opt->answer && field == -1) G_fatal_error(_("The bufcol option requires a valid layer.")); tolerance = atof(tol_opt->answer); if (tolerance <= 0) G_fatal_error(_("The tolerance must be > 0.")); if (adjust_tolerance(&tolerance)) G_warning(_("The tolerance was reset to %g"), tolerance); scale = atof(scale_opt->answer); if (scale <= 0.0) G_fatal_error("Illegal scale value"); da = db = dalpha = 0; if (dista_opt->answer) { da = atof(dista_opt->answer); if (distb_opt->answer) db = atof(distb_opt->answer); else db = da; if (angle_opt->answer) dalpha = atof(angle_opt->answer); else dalpha = 0; unit_tolerance = tolerance * MIN(da, db); G_verbose_message(_("The tolerance in map units = %g"), unit_tolerance); } Vect_check_input_output_name(in_opt->answer, out_opt->answer, GV_FATAL_EXIT); Points = Vect_new_line_struct(); Cats = Vect_new_cats_struct(); BCats = Vect_new_cats_struct(); Vect_set_open_level(2); /* topology required */ if (1 > Vect_open_old2(&In, in_opt->answer, "", field_opt->answer)) G_fatal_error(_("Unable to open vector map <%s>"), in_opt->answer); if (0 > Vect_open_new(&Out, out_opt->answer, WITHOUT_Z)) { Vect_close(&In); G_fatal_error(_("Unable to create vector map <%s>"), out_opt->answer); } /* open tmp vector for buffers, needed for cleaning */ sprintf(bufname, "%s_tmp_%d", out_opt->answer, getpid()); if (0 > Vect_open_new(&Buf, bufname, 0)) { Vect_close(&In); Vect_close(&Out); Vect_delete(out_opt->answer); exit(EXIT_FAILURE); } Vect_build_partial(&Buf, GV_BUILD_BASE); /* check and load attribute column data */ if (bufcol_opt->answer) { db_CatValArray_init(&cvarr); Fi = Vect_get_field(&In, field); if (Fi == NULL) G_fatal_error(_("Database connection not defined for layer %d"), field); 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); /* Note do not check if the column exists in the table because it may be expression */ /* TODO: only select values we need instead of all in column */ nrec = db_select_CatValArray(Driver, Fi->table, Fi->key, bufcol_opt->answer, NULL, &cvarr); if (nrec < 0) G_fatal_error(_("Unable to select data from table <%s>"), Fi->table); G_debug(2, "%d records selected from table", nrec); ctype = cvarr.ctype; if (ctype != DB_C_TYPE_INT && ctype != DB_C_TYPE_DOUBLE) G_fatal_error(_("Column type not supported")); db_close_database_shutdown_driver(Driver); /* Output cats/values list */ for (i = 0; i < cvarr.n_values; i++) { if (ctype == DB_C_TYPE_INT) { G_debug(4, "cat = %d val = %d", cvarr.value[i].cat, cvarr.value[i].val.i); } else if (ctype == DB_C_TYPE_DOUBLE) { G_debug(4, "cat = %d val = %f", cvarr.value[i].cat, cvarr.value[i].val.d); } } } Vect_copy_head_data(&In, &Out); Vect_hist_copy(&In, &Out); Vect_hist_command(&Out); /* Create buffers' boundaries */ nlines = nareas = 0; if ((type & GV_POINTS) || (type & GV_LINES)) nlines += Vect_get_num_primitives(&In, type); if (type & GV_AREA) nareas = Vect_get_num_areas(&In); if (nlines + nareas == 0) { G_warning(_("No features available for buffering. " "Check type option and features available in the input vector.")); exit(EXIT_SUCCESS); } buffers_count = 1; arr_bc = G_malloc((nlines + nareas + 1) * sizeof(struct buf_contours)); Vect_spatial_index_init(&si, 0); /* Lines (and Points) */ if ((type & GV_POINTS) || (type & GV_LINES)) { int ltype; if (nlines > 0) G_message(_("Buffering lines...")); for (line = 1; line <= nlines; line++) { int cat; G_debug(2, "line = %d", line); G_percent(line, nlines, 2); if (!Vect_line_alive(&In, line)) continue; ltype = Vect_read_line(&In, Points, Cats, line); if (!(ltype & type)) continue; if (field > 0 && !Vect_cat_get(Cats, field, &cat)) continue; if (bufcol_opt->answer) { ret = db_CatValArray_get_value_di(&cvarr, cat, &size_val); if (ret != DB_OK) { G_warning(_("No record for category %d in table <%s>"), cat, Fi->table); continue; } if (size_val < 0.0) { G_warning(_("Attribute is of invalid size (%.3f) for category %d"), size_val, cat); continue; } if (size_val == 0.0) continue; da = size_val * scale; db = da; dalpha = 0; unit_tolerance = tolerance * MIN(da, db); G_debug(2, " dynamic buffer size = %.2f", da); G_debug(2, _("The tolerance in map units: %g"), unit_tolerance); } Vect_line_prune(Points); if (ltype & GV_POINTS || Points->n_points == 1) { Vect_point_buffer2(Points->x[0], Points->y[0], da, db, dalpha, !(straight_flag->answer), unit_tolerance, &(arr_bc_pts.oPoints)); Vect_write_line(&Out, GV_BOUNDARY, arr_bc_pts.oPoints, BCats); line_id = Vect_write_line(&Buf, GV_BOUNDARY, arr_bc_pts.oPoints, Cats); Vect_destroy_line_struct(arr_bc_pts.oPoints); /* add buffer to spatial index */ Vect_get_line_box(&Buf, line_id, &bbox); Vect_spatial_index_add_item(&si, buffers_count, &bbox); arr_bc[buffers_count].outer = line_id; arr_bc[buffers_count].inner_count = 0; arr_bc[buffers_count].inner = NULL; buffers_count++; } else { Vect_line_buffer2(Points, da, db, dalpha, !(straight_flag->answer), !(nocaps_flag->answer), unit_tolerance, &(arr_bc_pts.oPoints), &(arr_bc_pts.iPoints), &(arr_bc_pts.inner_count)); Vect_write_line(&Out, GV_BOUNDARY, arr_bc_pts.oPoints, BCats); line_id = Vect_write_line(&Buf, GV_BOUNDARY, arr_bc_pts.oPoints, Cats); Vect_destroy_line_struct(arr_bc_pts.oPoints); /* add buffer to spatial index */ Vect_get_line_box(&Buf, line_id, &bbox); Vect_spatial_index_add_item(&si, buffers_count, &bbox); arr_bc[buffers_count].outer = line_id; arr_bc[buffers_count].inner_count = arr_bc_pts.inner_count; if (arr_bc_pts.inner_count > 0) { arr_bc[buffers_count].inner = G_malloc(arr_bc_pts.inner_count * sizeof(int)); for (i = 0; i < arr_bc_pts.inner_count; i++) { Vect_write_line(&Out, GV_BOUNDARY, arr_bc_pts.iPoints[i], BCats); line_id = Vect_write_line(&Buf, GV_BOUNDARY, arr_bc_pts.iPoints[i], Cats); Vect_destroy_line_struct(arr_bc_pts.iPoints[i]); /* add buffer to spatial index */ Vect_get_line_box(&Buf, line_id, &bbox); Vect_spatial_index_add_item(&si, buffers_count, &bbox); arr_bc[buffers_count].inner[i] = line_id; } G_free(arr_bc_pts.iPoints); } buffers_count++; } } } /* Areas */ if (type & GV_AREA) { int centroid; if (nareas > 0) G_message(_("Buffering areas...")); for (area = 1; area <= nareas; area++) { int cat; G_percent(area, nareas, 2); if (!Vect_area_alive(&In, area)) continue; centroid = Vect_get_area_centroid(&In, area); if (centroid == 0) continue; Vect_read_line(&In, NULL, Cats, centroid); if (field > 0 && !Vect_cat_get(Cats, field, &cat)) continue; if (bufcol_opt->answer) { ret = db_CatValArray_get_value_di(&cvarr, cat, &size_val); if (ret != DB_OK) { G_warning(_("No record for category %d in table <%s>"), cat, Fi->table); continue; } if (size_val < 0.0) { G_warning(_("Attribute is of invalid size (%.3f) for category %d"), size_val, cat); continue; } if (size_val == 0.0) continue; da = size_val * scale; db = da; dalpha = 0; unit_tolerance = tolerance * MIN(da, db); G_debug(2, " dynamic buffer size = %.2f", da); G_debug(2, _("The tolerance in map units: %g"), unit_tolerance); } Vect_area_buffer2(&In, area, da, db, dalpha, !(straight_flag->answer), !(nocaps_flag->answer), unit_tolerance, &(arr_bc_pts.oPoints), &(arr_bc_pts.iPoints), &(arr_bc_pts.inner_count)); Vect_write_line(&Out, GV_BOUNDARY, arr_bc_pts.oPoints, BCats); line_id = Vect_write_line(&Buf, GV_BOUNDARY, arr_bc_pts.oPoints, Cats); Vect_destroy_line_struct(arr_bc_pts.oPoints); /* add buffer to spatial index */ Vect_get_line_box(&Buf, line_id, &bbox); Vect_spatial_index_add_item(&si, buffers_count, &bbox); arr_bc[buffers_count].outer = line_id; arr_bc[buffers_count].inner_count = arr_bc_pts.inner_count; if (arr_bc_pts.inner_count > 0) { arr_bc[buffers_count].inner = G_malloc(arr_bc_pts.inner_count * sizeof(int)); for (i = 0; i < arr_bc_pts.inner_count; i++) { Vect_write_line(&Out, GV_BOUNDARY, arr_bc_pts.iPoints[i], BCats); line_id = Vect_write_line(&Buf, GV_BOUNDARY, arr_bc_pts.iPoints[i], Cats); Vect_destroy_line_struct(arr_bc_pts.iPoints[i]); /* add buffer to spatial index */ Vect_get_line_box(&Buf, line_id, &bbox); Vect_spatial_index_add_item(&si, buffers_count, &bbox); arr_bc[buffers_count].inner[i] = line_id; } G_free(arr_bc_pts.iPoints); } buffers_count++; } } verbose = G_verbose(); G_message(_("Cleaning buffers...")); /* Break lines */ G_message(_("Building parts of topology...")); Vect_build_partial(&Out, GV_BUILD_BASE); G_message(_("Snapping boundaries...")); Vect_snap_lines(&Out, GV_BOUNDARY, 1e-7, NULL); G_message(_("Breaking polygons...")); Vect_break_polygons(&Out, GV_BOUNDARY, NULL); G_message(_("Removing duplicates...")); Vect_remove_duplicates(&Out, GV_BOUNDARY, NULL); do { G_message(_("Breaking boundaries...")); Vect_break_lines(&Out, GV_BOUNDARY, NULL); G_message(_("Removing duplicates...")); Vect_remove_duplicates(&Out, GV_BOUNDARY, NULL); G_message(_("Cleaning boundaries at nodes")); } while (Vect_clean_small_angles_at_nodes(&Out, GV_BOUNDARY, NULL) > 0); /* Dangles and bridges don't seem to be necessary if snapping is small enough. */ /* Still needed for larger buffer distances ? */ /* G_message(_("Removing dangles...")); Vect_remove_dangles(&Out, GV_BOUNDARY, -1, NULL); G_message (_("Removing bridges...")); Vect_remove_bridges(&Out, NULL); */ G_message(_("Attaching islands...")); Vect_build_partial(&Out, GV_BUILD_ATTACH_ISLES); /* Calculate new centroids for all areas */ nareas = Vect_get_num_areas(&Out); Areas = (char *)G_calloc(nareas + 1, sizeof(char)); G_message(_("Calculating centroids for areas...")); G_percent(0, nareas, 2); for (area = 1; area <= nareas; area++) { double x, y; G_percent(area, nareas, 2); G_debug(3, "area = %d", area); if (!Vect_area_alive(&Out, area)) continue; ret = Vect_get_point_in_area(&Out, area, &x, &y); if (ret < 0) { G_warning(_("Cannot calculate area centroid")); continue; } ret = point_in_buffer(arr_bc, &si, &Buf, x, y); if (ret) { G_debug(3, " -> in buffer"); Areas[area] = 1; } } /* Make a list of boundaries to be deleted (both sides inside) */ nlines = Vect_get_num_lines(&Out); G_debug(3, "nlines = %d", nlines); Lines = (char *)G_calloc(nlines + 1, sizeof(char)); G_message(_("Generating list of boundaries to be deleted...")); for (line = 1; line <= nlines; line++) { int j, side[2], areas[2]; G_percent(line, nlines, 2); G_debug(3, "line = %d", line); if (!Vect_line_alive(&Out, line)) continue; Vect_get_line_areas(&Out, line, &side[0], &side[1]); for (j = 0; j < 2; j++) { if (side[j] == 0) { /* area/isle not build */ areas[j] = 0; } else if (side[j] > 0) { /* area */ areas[j] = side[j]; } else { /* < 0 -> island */ areas[j] = Vect_get_isle_area(&Out, abs(side[j])); } } G_debug(3, " areas = %d , %d -> Areas = %d, %d", areas[0], areas[1], Areas[areas[0]], Areas[areas[1]]); if (Areas[areas[0]] && Areas[areas[1]]) Lines[line] = 1; } G_free(Areas); /* Delete boundaries */ G_message(_("Deleting boundaries...")); for (line = 1; line <= nlines; line++) { G_percent(line, nlines, 2); if (!Vect_line_alive(&Out, line)) continue; if (Lines[line]) { G_debug(3, " delete line %d", line); Vect_delete_line(&Out, line); } else { /* delete incorrect boundaries */ int side[2]; Vect_get_line_areas(&Out, line, &side[0], &side[1]); if (!side[0] && !side[1]) Vect_delete_line(&Out, line); } } G_free(Lines); /* Create new centroids */ Vect_reset_cats(Cats); Vect_cat_set(Cats, 1, 1); nareas = Vect_get_num_areas(&Out); G_message(_("Calculating centroids for areas...")); for (area = 1; area <= nareas; area++) { double x, y; G_percent(area, nareas, 2); G_debug(3, "area = %d", area); if (!Vect_area_alive(&Out, area)) continue; ret = Vect_get_point_in_area(&Out, area, &x, &y); if (ret < 0) { G_warning(_("Cannot calculate area centroid")); continue; } ret = point_in_buffer(arr_bc, &si, &Buf, x, y); if (ret) { Vect_reset_line(Points); Vect_append_point(Points, x, y, 0.); Vect_write_line(&Out, GV_CENTROID, Points, Cats); } } /* free arr_bc[] */ /* will only slow down the module for (i = 0; i < buffers_count; i++) { Vect_destroy_line_struct(arr_bc[i].oPoints); for (j = 0; j < arr_bc[i].inner_count; j++) Vect_destroy_line_struct(arr_bc[i].iPoints[j]); G_free(arr_bc[i].iPoints); } */ Vect_spatial_index_destroy(&si); Vect_close(&Buf); Vect_delete(bufname); G_set_verbose(verbose); Vect_close(&In); Vect_build_partial(&Out, GV_BUILD_NONE); Vect_build(&Out); Vect_close(&Out); exit(EXIT_SUCCESS); }
int main(int argc, char *argv[]) { int m1; struct FPRange range; DCELL cellmin, cellmax; FCELL *cellrow, fcellmin; struct GModule *module; struct { struct Option *input, *elev, *slope, *aspect, *pcurv, *tcurv, *mcurv, *smooth, *maskmap, *zmult, *fi, *segmax, *npmin, *res_ew, *res_ns, *overlap, *theta, *scalex; } parm; struct { struct Flag *deriv, *cprght; } flag; G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("raster")); G_add_keyword(_("resample")); module->description = _("Reinterpolates and optionally computes topographic analysis from " "input raster map to a new raster map (possibly with " "different resolution) using regularized spline with " "tension and smoothing."); parm.input = G_define_standard_option(G_OPT_R_INPUT); parm.res_ew = G_define_option(); parm.res_ew->key = "ew_res"; parm.res_ew->type = TYPE_DOUBLE; parm.res_ew->required = YES; parm.res_ew->description = _("Desired east-west resolution"); parm.res_ns = G_define_option(); parm.res_ns->key = "ns_res"; parm.res_ns->type = TYPE_DOUBLE; parm.res_ns->required = YES; parm.res_ns->description = _("Desired north-south resolution"); parm.elev = G_define_standard_option(G_OPT_R_ELEV); parm.elev->required = NO; parm.elev->gisprompt = "new,cell,raster"; parm.elev->description = _("Name for output elevation raster map"); parm.elev->guisection = _("Output"); parm.slope = G_define_standard_option(G_OPT_R_OUTPUT); parm.slope->key = "slope"; parm.slope->required = NO; parm.slope->description = _("Name for output slope map (or fx)"); parm.slope->guisection = _("Output"); parm.aspect = G_define_standard_option(G_OPT_R_OUTPUT); parm.aspect->key = "aspect"; parm.aspect->required = NO; parm.aspect->description = _("Name for output aspect map (or fy)"); parm.aspect->guisection = _("Output"); parm.pcurv = G_define_standard_option(G_OPT_R_OUTPUT); parm.pcurv->key = "pcurvature"; parm.pcurv->required = NO; parm.pcurv->description = _("Name for output profile curvature map (or fxx)"); parm.pcurv->guisection = _("Output"); parm.tcurv = G_define_standard_option(G_OPT_R_OUTPUT); parm.tcurv->key = "tcurvature"; parm.tcurv->required = NO; parm.tcurv->description = _("Name for output tangential curvature map (or fyy)"); parm.tcurv->guisection = _("Output"); parm.mcurv = G_define_standard_option(G_OPT_R_OUTPUT); parm.mcurv->key = "mcurvature"; parm.mcurv->required = NO; parm.mcurv->description = _("Name for output mean curvature map (or fxy)"); parm.mcurv->guisection = _("Output"); parm.smooth = G_define_standard_option(G_OPT_R_INPUT); parm.smooth->key = "smooth"; parm.smooth->required = NO; parm.smooth->description = _("Name of input raster map containing smoothing"); parm.smooth->guisection = _("Settings"); parm.maskmap = G_define_standard_option(G_OPT_R_INPUT); parm.maskmap->key = "maskmap"; parm.maskmap->required = NO; parm.maskmap->description = _("Name of input raster map to be used as mask"); parm.maskmap->guisection = _("Settings"); parm.overlap = G_define_option(); parm.overlap->key = "overlap"; parm.overlap->type = TYPE_INTEGER; parm.overlap->required = NO; parm.overlap->answer = OVERLAP; parm.overlap->description = _("Rows/columns overlap for segmentation"); parm.overlap->guisection = _("Settings"); parm.zmult = G_define_option(); parm.zmult->key = "zscale"; parm.zmult->type = TYPE_DOUBLE; parm.zmult->answer = ZMULT; parm.zmult->required = NO; parm.zmult->description = _("Multiplier for z-values"); parm.zmult->guisection = _("Settings"); parm.fi = G_define_option(); parm.fi->key = "tension"; parm.fi->type = TYPE_DOUBLE; parm.fi->answer = TENSION; parm.fi->required = NO; parm.fi->description = _("Spline tension value"); parm.fi->guisection = _("Settings"); parm.theta = G_define_option(); parm.theta->key = "theta"; parm.theta->type = TYPE_DOUBLE; parm.theta->required = NO; parm.theta->description = _("Anisotropy angle (in degrees counterclockwise from East)"); parm.theta->guisection = _("Anisotropy"); parm.scalex = G_define_option(); parm.scalex->key = "scalex"; parm.scalex->type = TYPE_DOUBLE; parm.scalex->required = NO; parm.scalex->description = _("Anisotropy scaling factor"); parm.scalex->guisection = _("Anisotropy"); flag.cprght = G_define_flag(); flag.cprght->key = 't'; flag.cprght->description = _("Use dnorm independent tension"); flag.deriv = G_define_flag(); flag.deriv->key = 'd'; flag.deriv->description = _("Output partial derivatives instead of topographic parameters"); flag.deriv->guisection = _("Output"); if (G_parser(argc, argv)) exit(EXIT_FAILURE); G_get_set_window(&winhd); inp_ew_res = winhd.ew_res; inp_ns_res = winhd.ns_res; inp_cols = winhd.cols; inp_rows = winhd.rows; inp_x_orig = winhd.west; inp_y_orig = winhd.south; input = parm.input->answer; smooth = parm.smooth->answer; maskmap = parm.maskmap->answer; elev = parm.elev->answer; slope = parm.slope->answer; aspect = parm.aspect->answer; pcurv = parm.pcurv->answer; tcurv = parm.tcurv->answer; mcurv = parm.mcurv->answer; cond2 = ((pcurv != NULL) || (tcurv != NULL) || (mcurv != NULL)); cond1 = ((slope != NULL) || (aspect != NULL) || cond2); deriv = flag.deriv->answer; dtens = flag.cprght->answer; ertre = 0.1; if (!G_scan_resolution(parm.res_ew->answer, &ew_res, winhd.proj)) G_fatal_error(_("Unable to read ew_res value")); if (!G_scan_resolution(parm.res_ns->answer, &ns_res, winhd.proj)) G_fatal_error(_("Unable to read ns_res value")); if (sscanf(parm.fi->answer, "%lf", &fi) != 1) G_fatal_error(_("Invalid value for tension")); if (sscanf(parm.zmult->answer, "%lf", &zmult) != 1) G_fatal_error(_("Invalid value for zmult")); if (sscanf(parm.overlap->answer, "%d", &overlap) != 1) G_fatal_error(_("Invalid value for overlap")); if (parm.theta->answer) { if (sscanf(parm.theta->answer, "%lf", &theta) != 1) G_fatal_error(_("Invalid value for theta")); } if (parm.scalex->answer) { if (sscanf(parm.scalex->answer, "%lf", &scalex) != 1) G_fatal_error(_("Invalid value for scalex")); if (!parm.theta->answer) G_fatal_error(_("When using anisotropy both theta and scalex must be specified")); } /* * G_set_embedded_null_value_mode(1); */ outhd.ew_res = ew_res; outhd.ns_res = ns_res; outhd.east = winhd.east; outhd.west = winhd.west; outhd.north = winhd.north; outhd.south = winhd.south; outhd.proj = winhd.proj; outhd.zone = winhd.zone; G_adjust_Cell_head(&outhd, 0, 0); ew_res = outhd.ew_res; ns_res = outhd.ns_res; nsizc = outhd.cols; nsizr = outhd.rows; disk = (off_t)nsizc * nsizr * sizeof(int); az = G_alloc_vector(nsizc + 1); if (cond1) { adx = G_alloc_vector(nsizc + 1); ady = G_alloc_vector(nsizc + 1); if (cond2) { adxx = G_alloc_vector(nsizc + 1); adyy = G_alloc_vector(nsizc + 1); adxy = G_alloc_vector(nsizc + 1); } } if (smooth != NULL) { Rast_get_cellhd(smooth, "", &smhd); if ((winhd.ew_res != smhd.ew_res) || (winhd.ns_res != smhd.ns_res)) G_fatal_error(_("Map <%s> is the wrong resolution"), smooth); if (Rast_read_fp_range(smooth, "", &range) >= 0) Rast_get_fp_range_min_max(&range, &cellmin, &cellmax); fcellmin = (float)cellmin; if (Rast_is_f_null_value(&fcellmin) || fcellmin < 0.0) G_fatal_error(_("Smoothing values can not be negative or NULL")); } Rast_get_cellhd(input, "", &inphd); if ((winhd.ew_res != inphd.ew_res) || (winhd.ns_res != inphd.ns_res)) G_fatal_error(_("Input map resolution differs from current region resolution!")); sdisk = 0; if (elev != NULL) sdisk += disk; if (slope != NULL) sdisk += disk; if (aspect != NULL) sdisk += disk; if (pcurv != NULL) sdisk += disk; if (tcurv != NULL) sdisk += disk; if (mcurv != NULL) sdisk += disk; G_message(_("Processing all selected output files will require")); if (sdisk > 1024) { if (sdisk > 1024 * 1024) { if (sdisk > 1024 * 1024 * 1024) { G_message(_("%.2f GB of disk space for temp files."), sdisk / (1024. * 1024. * 1024.)); } else G_message(_("%.2f MB of disk space for temp files."), sdisk / (1024. * 1024.)); } else G_message(_("%.2f KB of disk space for temp files."), sdisk / 1024.); } else G_message(n_("%d byte of disk space for temp files.", "%d bytes of disk space for temp files.", (int)sdisk), (int)sdisk); fstar2 = fi * fi / 4.; tfsta2 = fstar2 + fstar2; deltx = winhd.east - winhd.west; delty = winhd.north - winhd.south; xmin = winhd.west; xmax = winhd.east; ymin = winhd.south; ymax = winhd.north; if (smooth != NULL) smc = -9999; else smc = 0.01; if (Rast_read_fp_range(input, "", &range) >= 0) { Rast_get_fp_range_min_max(&range, &cellmin, &cellmax); } else { fdinp = Rast_open_old(input, ""); cellrow = Rast_allocate_f_buf(); for (m1 = 0; m1 < inp_rows; m1++) { Rast_get_f_row(fdinp, cellrow, m1); Rast_row_update_fp_range(cellrow, m1, &range, FCELL_TYPE); } Rast_get_fp_range_min_max(&range, &cellmin, &cellmax); Rast_close(fdinp); } fcellmin = (float)cellmin; if (Rast_is_f_null_value(&fcellmin)) G_fatal_error(_("Maximum value of a raster map is NULL.")); zmin = (double)cellmin *zmult; zmax = (double)cellmax *zmult; G_debug(1, "zmin=%f, zmax=%f", zmin, zmax); if (fd4 != NULL) fprintf(fd4, "deltx,delty %f %f \n", deltx, delty); create_temp_files(); IL_init_params_2d(¶ms, NULL, 1, 1, zmult, KMIN, KMAX, maskmap, outhd.rows, outhd.cols, az, adx, ady, adxx, adyy, adxy, fi, MAXPOINTS, SCIK1, SCIK2, SCIK3, smc, elev, slope, aspect, pcurv, tcurv, mcurv, dmin, inp_x_orig, inp_y_orig, deriv, theta, scalex, Tmp_fd_z, Tmp_fd_dx, Tmp_fd_dy, Tmp_fd_xx, Tmp_fd_yy, Tmp_fd_xy, NULL, NULL, 0, NULL); /* In the above line, the penultimate argument is supposed to be a * deviations file pointer. None is obvious, so I used NULL. */ /* The 3rd and 4th argument are int-s, elatt and smatt (from the function * definition. The value 1 seemed like a good placeholder... or not. */ IL_init_func_2d(¶ms, IL_grid_calc_2d, IL_matrix_create, IL_check_at_points_2d, IL_secpar_loop_2d, IL_crst, IL_crstg, IL_write_temp_2d); G_message(_("Temporarily changing the region to desired resolution ...")); Rast_set_window(&outhd); bitmask = IL_create_bitmask(¶ms); /* change region to initial region */ G_message(_("Changing back to the original region ...")); Rast_set_window(&winhd); fdinp = Rast_open_old(input, ""); if (smooth != NULL) fdsmooth = Rast_open_old(smooth, ""); ertot = 0.; cursegm = 0; G_message(_("Percent complete: ")); NPOINT = IL_resample_interp_segments_2d(¶ms, bitmask, zmin, zmax, &zminac, &zmaxac, &gmin, &gmax, &c1min, &c1max, &c2min, &c2max, &ertot, nsizc, &dnorm, overlap, inp_rows, inp_cols, fdsmooth, fdinp, ns_res, ew_res, inp_ns_res, inp_ew_res, dtens); G_message(_("dnorm in mainc after grid before out1= %f"), dnorm); if (NPOINT < 0) { clean(); G_fatal_error(_("split_and_interpolate() failed")); } if (fd4 != NULL) fprintf(fd4, "max. error found = %f \n", ertot); G_free_vector(az); if (cond1) { G_free_vector(adx); G_free_vector(ady); if (cond2) { G_free_vector(adxx); G_free_vector(adyy); G_free_vector(adxy); } } G_message(_("dnorm in mainc after grid before out2= %f"), dnorm); if (IL_resample_output_2d(¶ms, zmin, zmax, zminac, zmaxac, c1min, c1max, c2min, c2max, gmin, gmax, ertot, input, &dnorm, &outhd, &winhd, smooth, NPOINT) < 0) { clean(); G_fatal_error(_("Unable to write raster maps -- try increasing cell size")); } G_free(zero_array_cell); clean(); if (fd4) fclose(fd4); Rast_close(fdinp); if (smooth != NULL) Rast_close(fdsmooth); G_done_msg(" "); exit(EXIT_SUCCESS); }
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); }
int main(int argc, char **argv) { struct GModule *module; struct Option *bg_color_opt, *fg_color_opt, *coords, *n_arrow, *fsize, *width_opt, *rotation_opt, *lbl_opt, *text_color_opt; struct Flag *no_text, *rotate_text, *rads; double east, north; double rotation; double fontsize, line_width; int rot_with_text; /* Initialize the GIS calls */ G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("display")); G_add_keyword(_("cartography")); module->description = _("Displays a north arrow on the graphics monitor."); n_arrow = G_define_option(); n_arrow->key = "style"; n_arrow->description = _("North arrow style"); n_arrow->options = "1a,1b,2,3,4,5,6,7a,7b,8a,8b,9,fancy_compass,basic_compass,arrow1,arrow2,arrow3,star"; G_asprintf((char **)&(n_arrow->descriptions), "1a;%s;" "1b;%s;" "2;%s;" "3;%s;" "4;%s;" "5;%s;" "6;%s;" "7a;%s;" "7b;%s;" "8a;%s;" "8b;%s;" "9;%s;" "fancy_compass;%s;" "basic_compass;%s;" "arrow1;%s;" "arrow2;%s;" "arrow3;%s;" "star;%s;", _("Two color arrowhead"), _("Two color arrowhead with circle"), _("Narrow with blending N"), _("Long with small arrowhead"), _("Inverted narrow inside a circle"), _("Triangle and N inside a circle"), _("Arrowhead and N inside a circle"), _("Tall half convex arrowhead"), _("Tall half concave arrowhead"), _("Thin arrow in a circle"), _("Fat arrow in a circle"), _("One color arrowhead"), _("Fancy compass"), _("Basic compass"), _("Simple arrow"), _("Thin arrow"), _("Fat arrow"), _("4-point star")); n_arrow->answer = "1a"; n_arrow->guisection = _("Style"); n_arrow->gisprompt = "old,northarrow,northarrow"; coords = G_define_option(); coords->key = "at"; coords->key_desc = "x,y"; coords->type = TYPE_DOUBLE; coords->answer = "85.0,15.0"; coords->options = "0-100"; coords->label = _("Screen coordinates of the rectangle's top-left corner"); coords->description = _("(0,0) is lower-left of the display frame"); rotation_opt = G_define_option(); rotation_opt->key = "rotation"; rotation_opt->type = TYPE_DOUBLE; rotation_opt->required = NO; rotation_opt->answer = "0"; rotation_opt->description = _("Rotation angle in degrees (counter-clockwise)"); lbl_opt = G_define_option(); lbl_opt->key = "label"; lbl_opt->required = NO; lbl_opt->answer = "N"; lbl_opt->description = _("Displayed letter on the top of arrow"); lbl_opt->guisection = _("Text"); fg_color_opt = G_define_standard_option(G_OPT_CN); fg_color_opt->label = _("Line color"); fg_color_opt->guisection = _("Colors"); bg_color_opt = G_define_standard_option(G_OPT_CN); bg_color_opt->key = "fill_color"; bg_color_opt->label = _("Fill color"); bg_color_opt->guisection = _("Colors"); text_color_opt = G_define_standard_option(G_OPT_C); text_color_opt->key = "text_color"; text_color_opt->label = _("Text color"); text_color_opt->answer = NULL; text_color_opt->guisection = _("Colors"); width_opt = G_define_option(); width_opt->key = "width"; width_opt->type = TYPE_DOUBLE; width_opt->answer = "0"; width_opt->description = _("Line width"); fsize = G_define_option(); fsize->key = "fontsize"; fsize->type = TYPE_DOUBLE; fsize->required = NO; fsize->answer = "14"; fsize->options = "1-360"; fsize->description = _("Font size"); fsize->guisection = _("Text"); no_text = G_define_flag(); no_text->key = 't'; no_text->description = _("Draw the symbol without text"); no_text->guisection = _("Text"); rotate_text = G_define_flag(); rotate_text->key = 'w'; rotate_text->description = _("Do not rotate text with symbol"); rotate_text->guisection = _("Text"); rads = G_define_flag(); rads->key = 'r'; rads->description = _("Use radians instead of degrees for rotation"); /* TODO: - add a -n flag to rotate to match true north instead of grid north. Similar to 'g.region -n' but use the at=x,y coord for the convergence angle calc. (assuming that's the center of the icon) */ if (G_parser(argc, argv)) exit(EXIT_FAILURE); sscanf(coords->answers[0], "%lf", &east); sscanf(coords->answers[1], "%lf", &north); fontsize = atof(fsize->answer); if (no_text->answer) fontsize = -1; rot_with_text = 0; if (!rotate_text->answer) rot_with_text = 1; /* Convert to radians */ rotation = atof(rotation_opt->answer); if (!rads->answer) rotation *= M_PI / 180.0; rotation = fmod(rotation, 2.0 * M_PI); if (rotation < 0.0) rotation += 2.0 * M_PI; /* Parse and select foreground color */ fg_color = D_parse_color(fg_color_opt->answer, 1); /* Parse and select background color */ bg_color = D_parse_color(bg_color_opt->answer, 1); /* Parse and select text color */ if (text_color_opt->answer) text_color = D_parse_color(text_color_opt->answer, 0); else if (strcmp(fg_color_opt->answer, "none") != 0) text_color = D_parse_color(fg_color_opt->answer, 1); else if (strcmp(bg_color_opt->answer, "none") != 0) text_color = D_parse_color(bg_color_opt->answer, 1); else text_color = 0; line_width = atof(width_opt->answer); if (line_width < 0) line_width = 0; else if (line_width > 72) line_width = 72; D_open_driver(); draw_n_arrow(east, north, rotation, lbl_opt->answer, rot_with_text, fontsize, n_arrow->answer, line_width); D_save_command(G_recreate_command()); D_close_driver(); exit(EXIT_SUCCESS); }
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); }
int main(int argc, char *argv[]) { char *me; char *output, *input; char *fs; int dims, i, has_cat; struct GModule *module; FILE *in_fd, *out_fd; Site *site; Site_head shead; struct TimeStamp ts; struct { struct Option *input, *output, *dims, *fs, *date; } parm; G_gisinit(me = argv[0]); module = G_define_module(); G_add_keyword(_("sites")); module->description = "Convert an ASCII listing of site locations " "into a GRASS site list file."; parm.output = G_define_option(); parm.output->key = "output"; parm.output->type = TYPE_STRING; parm.output->required = YES; parm.output->description = "vector map to be created"; parm.output->gisprompt = "any,vector,vector"; parm.input = G_define_option(); parm.input->key = "input"; parm.input->type = TYPE_STRING; parm.input->required = NO; parm.input->description = "unix file containing sites"; parm.dims = G_define_option(); parm.dims->key = "d"; parm.dims->type = TYPE_INTEGER; parm.dims->required = NO; parm.dims->description = "number of dimensions (default=2)"; parm.fs = G_define_option(); parm.fs->key = "fs"; parm.fs->key_desc = "character|space|tab"; parm.fs->type = TYPE_STRING; parm.fs->required = NO; parm.fs->description = "input field separator"; parm.fs->answer = "space"; parm.date = G_define_option(); parm.date->key = "date"; parm.date->key_desc = "timestamp"; parm.date->required = NO; parm.date->type = TYPE_STRING; parm.date->description = "datetime or datetime1/datetime2"; if (G_parser(argc, argv)) exit(EXIT_FAILURE); if ((input = parm.input->answer)) { in_fd = fopen(input, "r"); if (NULL == in_fd) { fprintf(stderr, "%s - ", me); perror(input); exit(1); } } else in_fd = stdin; output = parm.output->answer; shead.name = G_store(parm.output->answer); shead.desc = G_store(G_recreate_command()); shead.form = shead.labels = shead.stime = (char *)NULL; /* add here time parameter */ if (parm.date->answer) { if (1 == G_scan_timestamp(&ts, parm.date->answer)) shead.time = &ts; else G_fatal_error("Invalid timestamp"); } else shead.time = (struct TimeStamp *)NULL; dims = 2; loop = 1; /* added 11/99 MNeteler */ if (parm.dims->answer != NULL) if ((i = sscanf(parm.dims->answer, "%d", &dims)) != 1) G_fatal_error("error scanning number of dimensions"); if (dims < 2) G_fatal_error("number of dimensions must be greater than 1"); if (strlen(parm.fs->answer) < 1) G_fatal_error("field separator cannot be empty"); else { fs = parm.fs->answer; if (strcmp(fs, "space") == 0) fs = NULL; else if (strcmp(fs, "tab") == 0) fs = NULL; } out_fd = G_fopen_sites_new(output); if (out_fd == NULL) G_fatal_error("can't create sites file [%s].", output); G_site_put_head(out_fd, &shead); while ((site = get_site(in_fd, dims, fs, &has_cat))) G_site_put(out_fd, site); G_sites_close(out_fd); exit(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); }
/* ************************************************************************* */ int main(int argc, char *argv[]) { RASTER3D_Region region; struct Cell_head window2d; struct GModule *module; void *map = NULL; /*The 3D Rastermap */ int changemask = 0; int elevfd = -1, outfd = -1; /*file descriptors */ int output_type, cols, rows; /* Initialize GRASS */ G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("raster3d")); G_add_keyword(_("profile")); G_add_keyword(_("raster")); G_add_keyword(_("voxel")); module->description = _("Creates cross section 2D raster map from 3D raster map based on 2D elevation map"); /* Get parameters from user */ set_params(); /* Have GRASS get inputs */ if (G_parser(argc, argv)) exit(EXIT_FAILURE); G_debug(3, "Open 3D raster map %s", param.input->answer); if (NULL == G_find_raster3d(param.input->answer, "")) Rast3d_fatal_error(_("3D raster map <%s> not found"), param.input->answer); /* Figure out the region from the map */ Rast3d_init_defaults(); Rast3d_get_window(®ion); /*Check if the g3d-region is equal to the 2d rows and cols */ rows = Rast_window_rows(); cols = Rast_window_cols(); /*If not equal, set the 2D windows correct */ if (rows != region.rows || cols != region.cols) { G_message (_("The 2D and 3D region settings are different. Using the 3D raster map settings to adjust the 2D region.")); G_get_set_window(&window2d); window2d.ns_res = region.ns_res; window2d.ew_res = region.ew_res; window2d.rows = region.rows; window2d.cols = region.cols; Rast_set_window(&window2d); } /*******************/ /*Open the 3d raster map */ /*******************/ map = Rast3d_open_cell_old(param.input->answer, G_find_raster3d(param.input->answer, ""), ®ion, RASTER3D_TILE_SAME_AS_FILE, RASTER3D_USE_CACHE_DEFAULT); if (map == NULL) Rast3d_fatal_error(_("Unable to open 3D raster map <%s>"), param.input->answer); /*Get the output type */ output_type = Rast3d_file_type_map(map); if (output_type == FCELL_TYPE || output_type == DCELL_TYPE) { /********************************/ /*Open the elevation raster map */ /********************************/ elevfd = Rast_open_old(param.elevation->answer, ""); globalElevMapType = Rast_get_map_type(elevfd); /**********************/ /*Open the Outputmap */ /**********************/ if (G_find_raster2(param.output->answer, "")) G_message(_("Output map already exists. Will be overwritten!")); if (output_type == FCELL_TYPE) outfd = Rast_open_new(param.output->answer, FCELL_TYPE); else if (output_type == DCELL_TYPE) outfd = Rast_open_new(param.output->answer, DCELL_TYPE); /*if requested set the Mask on */ if (param.mask->answer) { if (Rast3d_mask_file_exists()) { changemask = 0; if (Rast3d_mask_is_off(map)) { Rast3d_mask_on(map); changemask = 1; } } } /************************/ /*Create the Rastermaps */ /************************/ rast3d_cross_section(map, region, elevfd, outfd); /*We set the Mask off, if it was off before */ if (param.mask->answer) { if (Rast3d_mask_file_exists()) if (Rast3d_mask_is_on(map) && changemask) Rast3d_mask_off(map); } Rast_close(outfd); Rast_close(elevfd); } else { fatal_error(map, -1, -1, _("Wrong 3D raster datatype! Cannot create raster map")); } /* Close files and exit */ if (!Rast3d_close(map)) Rast3d_fatal_error(_("Unable to close 3D raster map <%s>"), param.input->answer); return (EXIT_SUCCESS); }
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); }
int main(int argc, char *argv[]) { struct GModule *module; struct { struct Option *rastin, *rastout, *method, *quantile; } parm; struct { struct Flag *nulls, *weight; } flag; struct History history; char title[64]; char buf_nsres[100], buf_ewres[100]; struct Colors colors; int row; G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("raster")); G_add_keyword(_("resample")); module->description = _("Resamples raster map layers to a coarser grid using aggregation."); parm.rastin = G_define_standard_option(G_OPT_R_INPUT); parm.rastout = G_define_standard_option(G_OPT_R_OUTPUT); parm.method = G_define_option(); parm.method->key = "method"; parm.method->type = TYPE_STRING; parm.method->required = NO; parm.method->description = _("Aggregation method"); parm.method->options = build_method_list(); parm.method->answer = "average"; parm.quantile = G_define_option(); parm.quantile->key = "quantile"; parm.quantile->type = TYPE_DOUBLE; parm.quantile->required = NO; parm.quantile->description = _("Quantile to calculate for method=quantile"); parm.quantile->options = "0.0-1.0"; parm.quantile->answer = "0.5"; flag.nulls = G_define_flag(); flag.nulls->key = 'n'; flag.nulls->description = _("Propagate NULLs"); flag.weight = G_define_flag(); flag.weight->key = 'w'; flag.weight->description = _("Weight according to area (slower)"); if (G_parser(argc, argv)) exit(EXIT_FAILURE); nulls = flag.nulls->answer; method = find_method(parm.method->answer); if (method < 0) G_fatal_error(_("Unknown method <%s>"), parm.method->answer); if (menu[method].method == c_quant) { quantile = atoi(parm.quantile->answer); closure = &quantile; } G_get_set_window(&dst_w); /* set window to old map */ Rast_get_cellhd(parm.rastin->answer, "", &src_w); /* enlarge source window */ { int r0 = (int)floor(Rast_northing_to_row(dst_w.north, &src_w)); int r1 = (int)ceil(Rast_northing_to_row(dst_w.south, &src_w)); int c0 = (int)floor(Rast_easting_to_col(dst_w.west, &src_w)); int c1 = (int)ceil(Rast_easting_to_col(dst_w.east, &src_w)); src_w.south -= src_w.ns_res * (r1 - src_w.rows); src_w.north += src_w.ns_res * (-r0); src_w.west -= src_w.ew_res * (-c0); src_w.east += src_w.ew_res * (c1 - src_w.cols); src_w.rows = r1 - r0; src_w.cols = c1 - c0; } Rast_set_input_window(&src_w); Rast_set_output_window(&dst_w); row_scale = 2 + ceil(dst_w.ns_res / src_w.ns_res); col_scale = 2 + ceil(dst_w.ew_res / src_w.ew_res); /* allocate buffers for input rows */ bufs = G_malloc(row_scale * sizeof(DCELL *)); for (row = 0; row < row_scale; row++) bufs[row] = Rast_allocate_d_input_buf(); /* open old map */ infile = Rast_open_old(parm.rastin->answer, ""); /* allocate output buffer */ outbuf = Rast_allocate_d_output_buf(); /* open new map */ outfile = Rast_open_new(parm.rastout->answer, DCELL_TYPE); if (flag.weight->answer && menu[method].method_w) resamp_weighted(); else resamp_unweighted(); G_percent(dst_w.rows, dst_w.rows, 2); Rast_close(infile); Rast_close(outfile); /* record map metadata/history info */ sprintf(title, "Aggregate resample by %s", parm.method->answer); Rast_put_cell_title(parm.rastout->answer, title); Rast_short_history(parm.rastout->answer, "raster", &history); Rast_set_history(&history, HIST_DATSRC_1, parm.rastin->answer); G_format_resolution(src_w.ns_res, buf_nsres, src_w.proj); G_format_resolution(src_w.ew_res, buf_ewres, src_w.proj); Rast_format_history(&history, HIST_DATSRC_2, "Source map NS res: %s EW res: %s", buf_nsres, buf_ewres); Rast_command_history(&history); Rast_write_history(parm.rastout->answer, &history); /* copy color table from source map */ if (strcmp(parm.method->answer, "sum") != 0) { if (Rast_read_colors(parm.rastin->answer, "", &colors) < 0) G_fatal_error(_("Unable to read color table for %s"), parm.rastin->answer); Rast_mark_colors_as_fp(&colors); Rast_write_colors(parm.rastout->answer, G_mapset(), &colors); } return (EXIT_SUCCESS); }
/*--------------------------------------------------------------------*/ 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 */
int main(int argc, char *argv[]) { struct GModule *module; struct Option *out_opt, *in_opt; struct Flag *z_flag, *circle_flag, *l_flag, *int_flag; char buf[2000]; /* DWG */ char path[2000]; short initerror, entset, retval; AD_OBJHANDLE pspace, mspace; PAD_ENT_HDR adenhd; PAD_ENT aden; AD_VMADDR entlist; G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("vector")); G_add_keyword(_("import")); module->description = _("Converts DWG/DXF to GRASS vector map"); in_opt = G_define_standard_option(G_OPT_F_INPUT); in_opt->description = _("Name of DWG or DXF file"); out_opt = G_define_standard_option(G_OPT_V_OUTPUT); out_opt->required = YES; layers_opt = G_define_option(); layers_opt->key = "layers"; layers_opt->type = TYPE_STRING; layers_opt->required = NO; layers_opt->multiple = YES; layers_opt->description = _("List of layers to import"); invert_flag = G_define_flag(); invert_flag->key = 'i'; invert_flag->description = _("Invert selection by layers (don't import layers in list)"); z_flag = G_define_flag(); z_flag->key = 'z'; z_flag->description = _("Create 3D vector map"); circle_flag = G_define_flag(); circle_flag->key = 'c'; circle_flag->description = _("Write circles as points (centre)"); l_flag = G_define_flag(); l_flag->key = 'l'; l_flag->description = _("List available layers and exit"); int_flag = G_define_flag(); int_flag->key = 'n'; int_flag->description = _("Use numeric type for attribute \"layer\""); if (G_parser(argc, argv)) exit(EXIT_FAILURE); db_init_string(&sql); db_init_string(&str); adenhd = (PAD_ENT_HDR) G_malloc(sizeof(AD_ENT_HDR)); aden = (PAD_ENT) G_malloc(sizeof(AD_ENT)); Layer = (PAD_LAY) G_malloc(sizeof(AD_LAY)); Points = Vect_new_line_struct(); Cats = Vect_new_cats_struct(); Block = NULL; atrans = 20; /* nested, recursive levels */ Trans = (TRANS *) G_malloc(atrans * sizeof(TRANS)); /* Init OpenDWG */ sprintf(path, "%s/etc/adinit.dat", G_gisbase()); if (!adInitAd2(path, &initerror)) { sprintf(buf, _("Unable to initialize OpenDWG Toolkit, error: %d: %s."), initerror, adErrorStr(initerror)); if (initerror == AD_UNABLE_TO_OPEN_INIT_FILE) sprintf(buf, _("%s Cannot open %s"), buf, path); G_fatal_error(buf); } adSetupDwgRead(); adSetupDxfRead(); /* Open input file */ if ((dwghandle = adLoadFile(in_opt->answer, AD_PRELOAD_ALL, 1)) == NULL) { G_fatal_error(_("Unable to open input file <%s>. Error %d: %s"), in_opt->answer, adError(), adErrorStr(adError())); } if (l_flag->answer) { /* List layers */ PAD_TB adtb; AD_DWGHDR adhd; int i; char on, frozen, vpfrozen, locked; adtb = (PAD_TB) G_malloc(sizeof(AD_TB)); G_debug(2, "%d layers", (int)adNumLayers(dwghandle)); adReadHeaderBlock(dwghandle, &adhd); adStartLayerGet(dwghandle); fprintf(stdout, "%d layers:\n", (int)adNumLayers(dwghandle)); for (i = 0; i < (int)adNumLayers(dwghandle); i++) { adGetLayer(dwghandle, &(adtb->lay)); if (!adtb->lay.purgedflag) { fprintf(stdout, "%s COLOR %d, ", adtb->lay.name, adtb->lay.color); } adGetLayerState(dwghandle, adtb->lay.objhandle, &on, &frozen, &vpfrozen, &locked); if (on) fprintf(stdout, "ON, "); else fprintf(stdout, "OFF, "); if (frozen) fprintf(stdout, "FROZEN, "); else fprintf(stdout, "THAWED, "); if (vpfrozen) fprintf(stdout, "VPFROZEN, "); else fprintf(stdout, "VPTHAWED, "); if (locked) fprintf(stdout, "LOCKED\n"); else fprintf(stdout, "UNLOCKED\n"); } adCloseFile(dwghandle); adCloseAd2(); exit(EXIT_SUCCESS); } /* open output vector */ if (Vect_open_new(&Map, out_opt->answer, z_flag->answer) < 0) G_fatal_error(_("Unable to create vector map <%s>"), out_opt->answer); Vect_hist_command(&Map); /* Add DB link */ 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>"), Vect_subst_var(Fi->database, &Map), Fi->driver); } db_set_error_handler_driver(driver); db_begin_transaction(driver); /* Create table */ if (int_flag->answer) { /* List layers */ sprintf(buf, "create table %s ( cat integer, entity_name varchar(20), color int, weight int, " "layer real, block varchar(100), txt varchar(100) )", Fi->table); } else { sprintf(buf, "create table %s ( cat integer, entity_name varchar(20), color int, weight int, " "layer varchar(100), block varchar(100), txt varchar(100) )", Fi->table); } db_set_string(&sql, buf); 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(_("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 for table <%s>, key <%s>"), Fi->table, GV_KEY_COLUMN); 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); cat = 1; n_elements = n_skipped = 0; /* Write each entity. Some entities may be composed by other entities (like INSERT or BLOCK) */ /* Set transformation for first (index 0) level */ Trans[0].dx = Trans[0].dy = Trans[0].dz = 0; Trans[0].xscale = Trans[0].yscale = Trans[0].zscale = 1; Trans[0].rotang = 0; if (adGetBlockHandle(dwghandle, pspace, AD_PAPERSPACE_HANDLE)) { entlist = adEntityList(dwghandle, pspace); adStartEntityGet(entlist); for (entset = 0; entset < 2; entset++) { do { if (!(retval = adGetEntity(entlist, adenhd, aden))) continue; wrentity(adenhd, aden, 0, entlist, circle_flag->answer); } while (retval == 1); if (entset == 0) { if (adGetBlockHandle(dwghandle, mspace, AD_MODELSPACE_HANDLE)) { entlist = adEntityList(dwghandle, mspace); adStartEntityGet(entlist); } } } } db_commit_transaction(driver); db_close_database_shutdown_driver(driver); adCloseFile(dwghandle); adCloseAd2(); Vect_build(&Map, stderr); Vect_close(&Map); if (n_skipped > 0) G_message(_("%d elements skipped (layer name was not in list)"), n_skipped); G_done_msg(_("%d elements processed"), n_elements); exit(EXIT_SUCCESS); }
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); }
int main(int argc, char *argv[]) { /* buffer for input-output rasters */ void *inrast_TEMPKA, *inrast_PATM, *inrast_RNET, *inrast_G0; DCELL *outrast; /* pointers to input-output raster files */ int infd_TEMPKA, infd_PATM, infd_RNET, infd_G0; int outfd; /* names of input-output raster files */ char *RNET, *TEMPKA, *PATM, *G0; char *ETa; /* input-output cell values */ DCELL d_tempka, d_pt_patm, d_rnet, d_g0; DCELL d_pt_alpha, d_pt_delta, d_pt_ghamma, d_daily_et; /* region information and handler */ struct Cell_head cellhd; int nrows, ncols; int row, col; /* parser stuctures definition */ struct GModule *module; struct Option *input_RNET, *input_TEMPKA, *input_PATM, *input_G0, *input_PT; struct Option *output; struct Flag *zero; struct Colors color; struct History history; /* Initialize the GIS calls */ G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("imagery")); G_add_keyword(_("evapotranspiration")); module->description = _("Computes evapotranspiration calculation " "Priestley and Taylor formulation, 1972."); /* Define different options */ input_RNET = G_define_standard_option(G_OPT_R_INPUT); input_RNET->key = "net_radiation"; input_RNET->description = _("Name of input net radiation raster map [W/m2]"); input_G0 = G_define_standard_option(G_OPT_R_INPUT); input_G0->key = "soil_heatflux"; input_G0->description = _("Name of input soil heat flux raster map [W/m2]"); input_TEMPKA = G_define_standard_option(G_OPT_R_INPUT); input_TEMPKA->key = "air_temperature"; input_TEMPKA->description = _("Name of input air temperature raster map [K]"); input_PATM = G_define_standard_option(G_OPT_R_INPUT); input_PATM->key = "atmospheric_pressure"; input_PATM->description = _("Name of input atmospheric pressure raster map [millibars]"); input_PT = G_define_option(); input_PT->key = "priestley_taylor_coeff"; input_PT->type = TYPE_DOUBLE; input_PT->required = YES; input_PT->description = _("Priestley-Taylor coefficient"); input_PT->answer = "1.26"; output = G_define_standard_option(G_OPT_R_OUTPUT); output->description = _("Name of output evapotranspiration raster map [mm/d]"); /* Define the different flags */ zero = G_define_flag(); zero->key = 'z'; zero->description = _("Set negative ETa to zero"); if (G_parser(argc, argv)) exit(EXIT_FAILURE); /* get entered parameters */ RNET = input_RNET->answer; TEMPKA = input_TEMPKA->answer; PATM = input_PATM->answer; G0 = input_G0->answer; d_pt_alpha = atof(input_PT->answer); ETa = output->answer; /* open pointers to input raster files */ infd_RNET = Rast_open_old(RNET, ""); infd_TEMPKA = Rast_open_old(TEMPKA, ""); infd_PATM = Rast_open_old(PATM, ""); infd_G0 = Rast_open_old(G0, ""); /* read headers of raster files */ Rast_get_cellhd(RNET, "", &cellhd); Rast_get_cellhd(TEMPKA, "", &cellhd); Rast_get_cellhd(PATM, "", &cellhd); Rast_get_cellhd(G0, "", &cellhd); /* Allocate input buffer */ inrast_RNET = Rast_allocate_d_buf(); inrast_TEMPKA = Rast_allocate_d_buf(); inrast_PATM = Rast_allocate_d_buf(); inrast_G0 = Rast_allocate_d_buf(); /* get rows and columns number of the current region */ nrows = Rast_window_rows(); ncols = Rast_window_cols(); /* allocate output buffer */ outrast = Rast_allocate_d_buf(); /* open pointers to output raster files */ outfd = Rast_open_new(ETa, DCELL_TYPE); /* start the loop through cells */ for (row = 0; row < nrows; row++) { G_percent(row, nrows, 2); /* read input raster row into line buffer */ Rast_get_d_row(infd_RNET, inrast_RNET, row); Rast_get_d_row(infd_TEMPKA, inrast_TEMPKA, row); Rast_get_d_row(infd_PATM, inrast_PATM, row); Rast_get_d_row(infd_G0, inrast_G0, row); for (col = 0; col < ncols; col++) { /* read current cell from line buffer */ d_rnet = ((DCELL *) inrast_RNET)[col]; d_tempka = ((DCELL *) inrast_TEMPKA)[col]; d_pt_patm = ((DCELL *) inrast_PATM)[col]; d_g0 = ((DCELL *) inrast_G0)[col]; /*Delta_pt and Ghamma_pt */ d_pt_delta = pt_delta(d_tempka); d_pt_ghamma = pt_ghamma(d_tempka, d_pt_patm); /*Calculate ET */ d_daily_et = pt_daily_et(d_pt_alpha, d_pt_delta, d_pt_ghamma, d_rnet, d_g0, d_tempka); if (zero->answer && d_daily_et < 0) d_daily_et = 0.0; /* write calculated ETP to output line buffer */ outrast[col] = d_daily_et; } /* write output line buffer to output raster file */ Rast_put_d_row(outfd, outrast); } /* free buffers and close input maps */ G_free(inrast_RNET); G_free(inrast_TEMPKA); G_free(inrast_PATM); G_free(inrast_G0); Rast_close(infd_RNET); Rast_close(infd_TEMPKA); Rast_close(infd_PATM); Rast_close(infd_G0); /* generate color table between -20 and 20 */ Rast_make_rainbow_colors(&color, -20, 20); Rast_write_colors(ETa, G_mapset(), &color); Rast_short_history(ETa, "raster", &history); Rast_command_history(&history); Rast_write_history(ETa, &history); /* free buffers and close output map */ G_free(outrast); Rast_close(outfd); return (EXIT_SUCCESS); }