int G3d_maskFileExists() { char buf[200]; sprintf(buf, "%s/%s", G3D_DIRECTORY, G3D_MASK_MAP); return (G_find_file(buf, G3D_CELL_ELEMENT, G_mapset()) != NULL); }
/* checks if user-supplied parameters are valid */ int check_parms (char *map_answer, char *input_answer, char *output_answer, int all ) { if ( map_answer != NULL ) { if ((G_find_file ("fcell", map_answer, "") == NULL) && (G_find_file ("dcell", map_answer, "") == NULL) && (G_find_file ("cell", map_answer, "") == NULL)) { /* no coverage map found */ G_fatal_error ("No raster map exists with the given name."); } /* specifying all means to disregard the map! */ if ( all == 1 ) { G_warning ("Map was specified, but the -a flag disregards map values!\n Your results might not be what you expect."); } } /* check if sample sites exist */ if (G_find_file ("vector", input_answer, "") == NULL) { G_fatal_error ("No sample/sites list exists with the given name!"); } /* check if a legal file name was given for output map this just overwrites existing sites */ if (G_legal_filename (output_answer) == -1) { G_fatal_error ("Name chosen for result map is not a valid file name!"); } /* return raster mode to caller */ if ( map_answer != NULL ) { return (G_raster_map_type (map_answer,"")); } else return (-1); }
int g3_find_dsp_file(char *cell, char *file, char *mset) { char element[100], name[GNAME_MAX], mapset[GMAPSET_MAX], tofind[GNAME_MAX]; if (file == NULL || *file == 0) return 0; strcpy(tofind, file); if (G__name_is_fully_qualified(cell, name, mapset)) sprintf(element, "grid3/%s/dsp", name); else sprintf(element, "grid3/%s/dsp", cell); return G_find_file(element, tofind, mset) != NULL; }
/* * Read symbol specified by name. * Name: group/name | group/name@mapset * (later add syntax to prefer symbol from GISBASE) * S_read() searches first in mapsets (standard GRASS search) and * then in GISBASE/etc/symbol/ */ SYMBOL *S_read(const char *sname) { int i, j, k, l; FILE *fp; char group[500], name[500], buf[2001]; const char *ms; char *c; double x, y, x2, y2, rad, ang1, ang2; int r, g, b; double fr, fg, fb; int ret; char clock; SYMBOL *symb; int current; /* current part_type */ SYMBPART *part; /* current part */ SYMBCHAIN *chain; /* current chain */ SYMBEL *elem; /* current element */ G_debug(3, "S_read(): sname = %s", sname); /* Find file */ /* Get group and name */ strcpy(group, sname); c = strchr(group, '/'); if (c == NULL) { G_warning(_("Incorrect symbol name: '%s' (should be: group/name or group/name@mapset)"), sname); return NULL; } c[0] = '\0'; c++; strcpy(name, c); G_debug(3, " group: '%s' name: '%s'", group, name); /* Search in mapsets */ sprintf(buf, "symbol/%s", group); ms = G_find_file(buf, name, NULL); if (ms != NULL) { /* Found in mapsets */ fp = G_fopen_old(buf, name, ms); } else { /* Search in GISBASE */ sprintf(buf, "%s/etc/symbol/%s", G_gisbase(), sname); fp = fopen(buf, "r"); } if (fp == NULL) { G_warning(_("Cannot find/open symbol: '%s'"), sname); return NULL; } /* create new symbol */ symb = new_symbol(); current = OBJ_NONE; /* no part */ /* read file */ while (G_getl2(buf, 2000, fp) != 0) { G_chop(buf); G_debug(3, " BUF: [%s]", buf); /* skip empty and comment lines */ if ((buf[0] == '#') || (buf[0] == '\0')) continue; get_key_data(buf); if (strcmp(key, "VERSION") == 0) { if (strcmp(data, "1.0") != 0) { sprintf(buf, "Wrong symbol version: '%s'", data); return (err(fp, symb, buf)); } } else if (strcmp(key, "BOX") == 0) { if (sscanf(data, "%lf %lf %lf %lf", &x, &y, &x2, &y2) != 4) { sprintf(buf, "Incorrect box definition: '%s'", data); return (err(fp, symb, buf)); } symb->xscale = 1 / (x2 - x); symb->yscale = 1 / (y2 - y); if (x2 - x > y2 - y) { symb->scale = symb->xscale; } else { symb->scale = symb->yscale; } } else if (strcmp(key, "STRING") == 0) { G_debug(4, " STRING >"); current = OBJ_STRING; part = new_part(S_STRING); add_part(symb, part); chain = new_chain(); add_chain(part, chain); } else if (strcmp(key, "POLYGON") == 0) { G_debug(4, " POLYGON >"); current = OBJ_POLYGON; part = new_part(S_POLYGON); add_part(symb, part); } else if (strcmp(key, "RING") == 0) { G_debug(4, " RING >"); current = OBJ_RING; chain = new_chain(); add_chain(part, chain); } else if (strcmp(key, "LINE") == 0) { G_debug(4, " LINE >"); elem = new_line(); add_element(chain, elem); read_coor(fp, elem); } else if (strcmp(key, "ARC") == 0) { G_debug(4, " ARC"); ret = sscanf(data, "%lf %lf %lf %lf %lf %c", &x, &y, &rad, &ang1, &ang2, &clock); if (ret < 5) { sprintf(buf, "Incorrect arc definition: '%s'", buf); return (err(fp, symb, buf)); } if (ret == 6 && (clock == 'c' || clock == 'C')) i = 1; else i = 0; elem = new_arc(x, y, rad, ang1, ang2, i); add_element(chain, elem); } else if (strcmp(key, "END") == 0) { switch (current) { case OBJ_STRING: G_debug(4, " STRING END"); current = OBJ_NONE; break; case OBJ_POLYGON: G_debug(4, " POLYGON END"); current = OBJ_NONE; break; case OBJ_RING: G_debug(4, " RING END"); current = OBJ_POLYGON; break; } } else if (strcmp(key, "COLOR") == 0) { if (G_strcasecmp(data, "NONE") == 0) { part->color.color = S_COL_NONE; } else if (sscanf(data, "%d %d %d", &r, &g, &b) == 3) { if (r < 0 || r > 255 || g < 0 || g > 255 || b < 0 || b > 255) G_warning(_("Incorrect symbol color: '%s', using default."), buf); else { fr = r / 255.0; fg = g / 255.0; fb = b / 255.0; part->color.color = S_COL_DEFINED; part->color.r = r; part->color.g = g; part->color.b = b; part->color.fr = fr; part->color.fg = fg; part->color.fb = fb; G_debug(4, " color [%d %d %d] = [%.3f %.3f %.3f]", r, g, b, fr, fg, fb); } } else { G_warning(_("Incorrect symbol color: '%s', using default."), buf); } } else if (strcmp(key, "FCOLOR") == 0) { if (G_strcasecmp(data, "NONE") == 0) { part->fcolor.color = S_COL_NONE; } else if (sscanf(data, "%d %d %d", &r, &g, &b) == 3) { if (r < 0 || r > 255 || g < 0 || g > 255 || b < 0 || b > 255) G_warning(_("Incorrect symbol color: '%s', using default."), buf); else { fr = r / 255.0; fg = g / 255.0; fb = b / 255.0; part->fcolor.color = S_COL_DEFINED; part->fcolor.r = r; part->fcolor.g = g; part->fcolor.b = b; part->fcolor.fr = fr; part->fcolor.fg = fg; part->fcolor.fb = fb; G_debug(4, " color [%d %d %d] = [%.3f %.3f %.3f]", r, g, b, fr, fg, fb); } } else { G_warning(_("Incorrect symbol color: '%s', using default."), buf); } } else { sprintf(buf, "Unknown keyword in symbol: '%s'", buf); return (err(fp, symb, buf)); break; } } /* Debug output */ G_debug(3, "Number of parts: %d", symb->count); for (i = 0; i < symb->count; i++) { part = symb->part[i]; G_debug(4, " Part %d: type: %d number of chains: %d", i, part->type, part->count); G_debug(4, " color: %d: fcolor: %d", part->color.color, part->fcolor.color); for (j = 0; j < part->count; j++) { chain = part->chain[j]; G_debug(4, " Chain %d: number of elements: %d", j, chain->count); for (k = 0; k < chain->count; k++) { elem = chain->elem[k]; G_debug(4, " Element %d: type: %d", k, elem->type); if (elem->type == S_LINE) { G_debug(4, " Number of points %d", elem->coor.line.count); for (l = 0; l < elem->coor.line.count; l++) { G_debug(4, " x, y: %f %f", elem->coor.line.x[l], elem->coor.line.y[l]); } } else { G_debug(4, " arc r = %f", elem->coor.arc.r); } } } } fclose(fp); return symb; }
int main(int argc, char *argv[]) { int r, c; DCELL con1, con2; double d1, d2; DCELL *alt_row; const char *con_name, *alt_name; int file_fd; DCELL value; struct History history; struct GModule *module; struct Option *opt1, *opt2; G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("raster")); G_add_keyword(_("surface")); G_add_keyword(_("interpolation")); module->description = _("Generates surface raster map from rasterized contours."); opt1 = G_define_standard_option(G_OPT_R_INPUT); opt1->description = _("Name of input raster map containing contours"); opt2 = G_define_standard_option(G_OPT_R_OUTPUT); if (G_parser(argc, argv)) exit(EXIT_FAILURE); con_name = opt1->answer; alt_name = opt2->answer; nrows = Rast_window_rows(); ncols = Rast_window_cols(); i_val_l_f = nrows + ncols; con = read_cell(con_name); alt_row = (DCELL *) G_malloc(ncols * sizeof(DCELL)); seen = flag_create(nrows, ncols); mask = flag_create(nrows, ncols); if (NULL != G_find_file("cell", "MASK", G_mapset())) { file_fd = Rast_open_old("MASK", G_mapset()); for (r = 0; r < nrows; r++) { Rast_get_d_row_nomask(file_fd, alt_row, r); for (c = 0; c < ncols; c++) if (Rast_is_d_null_value(&(alt_row[c])) || alt_row[c] == 0) FLAG_SET(mask, r, c); } Rast_close(file_fd); } zero = (NODE *) G_malloc(INIT_AR * sizeof(NODE)); minc = minr = 0; maxc = ncols - 1; maxr = nrows - 1; array_size = INIT_AR; file_fd = Rast_open_new(alt_name, DCELL_TYPE); for (r = 0; r < nrows; r++) { G_percent(r, nrows, 1); Rast_set_d_null_value(alt_row, ncols); for (c = 0; c < ncols; c++) { if (FLAG_GET(mask, r, c)) continue; value = con[r][c]; if (!Rast_is_d_null_value(&value)) { alt_row[c] = value; continue; } find_con(r, c, &d1, &d2, &con1, &con2); if (!Rast_is_d_null_value(&con2)) alt_row[c] = d2 * con1 / (d1 + d2) + d1 * con2 / (d1 + d2); else alt_row[c] = con1; } Rast_put_row(file_fd, alt_row, DCELL_TYPE); } G_percent(1, 1, 1); free_cell(con); flag_destroy(seen); flag_destroy(mask); Rast_close(file_fd); Rast_short_history(alt_name, "raster", &history); Rast_command_history(&history); Rast_write_history(alt_name, &history); exit(EXIT_SUCCESS); }
int main( int argc, char *argv[] ) { Shypothesis **samples; /* Data to be combined */ unsigned int i; FILE *kb; char **groups; int norm = 1; /* turn on normalisation of evidence by default */ /* these are for time keeping in the logfile */ time_t systime; clock_t proctime; unsigned long timeused; unsigned int days, hours, mins, secs; xmlDocPtr dstXMLFile; Sfp_struct* file_pointers; G_gisinit ( argv[0] ); module = G_define_module (); module->description = "Combines evidences from a DST knowledge base"; parm.file = G_define_option (); parm.file->key = "file"; parm.file->type = TYPE_STRING; parm.file->required = YES; parm.file->description = "Name of the knowledge base that contains the evidence"; parm.groups = G_define_option (); parm.groups->key = "sources"; parm.groups->type = TYPE_STRING; parm.groups->required = NO; parm.groups->multiple = YES; parm.groups->description = "Evidences to be combined (default: all)"; parm.type = G_define_option (); parm.type->key = "type"; parm.type->type = TYPE_STRING; parm.type->required = NO; parm.type->options = "const,rast,vect"; parm.type->answer = "rast"; parm.type->description = "Type(s) of evidences to combine"; parm.output = G_define_option (); parm.output->key = "output"; parm.output->type = TYPE_STRING; parm.output->required = NO; parm.output->answer = G_location (); parm.output->description = "Prefix for result maps (dflt: location name)"; parm.vals = G_define_option (); parm.vals->key = "values"; parm.vals->type = TYPE_STRING; parm.vals->required = NO; parm.vals->multiple = YES; parm.vals->options = "bel,pl,doubt,common,bint,woc,maxbpa,minbpa,maxsrc,minsrc"; parm.vals->answer = "bel"; parm.vals->description = "Dempster-Shafer values to map"; parm.hyps = G_define_option (); parm.hyps->key = "hypotheses"; parm.hyps->type = TYPE_STRING; parm.hyps->required = NO; parm.hyps->multiple = NO; parm.hyps->description = "Hypotheses to map (default: all)"; parm.logfile = G_define_option (); parm.logfile->key = "logfile"; parm.logfile->type = TYPE_STRING; parm.logfile->required = NO; parm.logfile->description = "Name of logfile"; /* TODO: not implemented yet parm.warnings = G_define_option (); parm.warnings->key = "warnings"; parm.warnings->type = TYPE_STRING; parm.warnings->required = NO; parm.warnings->description = "Name of site list to store locations of warnings." ; */ flag.norm = G_define_flag (); flag.norm->key = 'n'; flag.norm->description = "Turn off normalisation"; flag.quiet = G_define_flag (); flag.quiet->key = 'q'; flag.quiet->description = "Quiet operation: no progress diplay"; /* append output to existing logfile ? */ flag.append = G_define_flag (); flag.append->key = 'a'; flag.append->description = "Append log output to existing file"; no_assigns = 0; /* INIT GLOBAL VARS */ WOC_MIN = 0; WOC_MAX = 0; /* do not pause after a warning message was displayed */ G_sleep_on_error (0); /* parse command line */ if (G_parser (argc, argv)) { exit (-1); } /* check if given parameters are valid */ if (G_legal_filename (parm.file->answer) == -1) { G_fatal_error ("Please provide the name of an existing DST knowledge base.\n"); } if (G_find_file ("DST",parm.file->answer,G_mapset()) == NULL) { G_fatal_error ("Knowledge base does not exist in user's MAPSET!\n"); } /* check logfile */ if (parm.logfile->answer != NULL) { if ( !G_legal_filename (parm.logfile->answer) ) { G_fatal_error ("Please specify a legal filename for the logfile.\n"); } /* attempt to write to logfile */ if (flag.append->answer) { if (fopen (parm.logfile->answer, "r") == NULL) { lp = fopen (parm.logfile->answer, "w+"); if (lp == NULL) { G_fatal_error ("Logfile error: %s\n", strerror (errno)); } } else { lp = fopen (parm.logfile->answer, "a"); if (lp == NULL) { G_fatal_error ("Logfile error: %s\n", strerror (errno)); } fprintf (lp,"\n\n * * * * * \n\n"); } } else { if ( (lp = fopen ( parm.logfile->answer, "w+" ) ) == NULL ) { G_fatal_error ("Logfile error: %s\n", strerror (errno)); } } /* we want unbuffered output for the logfile */ setvbuf (lp,NULL,_IONBF,0); } else { /* log output to stderr by default */ lp = stderr; } /* setup coordinate file storage, if desired */ /* try to create a sites file to store coordinates */ /* set 'warn' to point to the user-defined sites file */ /* warn = NULL; if ( parm.warnings != NULL ) { } */ /* check if we have read/write access to knowledge base */ kb = G_fopen_old ("DST",parm.file->answer,G_mapset()); if ( kb == NULL ) { G_fatal_error ("Cannot open knowledge base file for reading and writing!\n"); } fclose(kb); /* start logfile */ if ( parm.logfile->answer != NULL) { fprintf (lp,"This is %s, version %.2f\n",argv[0],PROGVERSION); systime = time (NULL); fprintf (lp,"Calculation started on %s\n",ctime(&systime)); } /* open DST file and get basic evidence group information */ dstXMLFile = stat_XML ( parm.file->answer, &NO_SINGLETONS, &N ); groups = get_groups_XML ( N, dstXMLFile ); if ( NO_SINGLETONS == 1 ) { G_fatal_error ("Knowledge base does not contain any user-supplied hypotheses.\n"); } if ( parm.groups->answer != NULL ) { /* user specified a subset of groups */ N = check_groups ( groups ); } if ( N < 2 ) { G_fatal_error ("At least two groups of evidences must be present in the knowledge base.\n"); } /* allocate memory for all samples a sample holds one double for bel, pl and bpn for each piece of evidence. The number of pieces of evidence is the number of possible subsets in Theta = 2^NO_SINGLETONS ! The number of samples is = number of groups in the XML knowledge base file (N) ! */ samples = (Shypothesis**) G_malloc ((N * sizeof(Shypothesis*))); for ( i=0; i < N; i ++ ) { samples[i] = (Shypothesis*) G_malloc (sizeof(Shypothesis)); } /* turn off normalisation if user wants it so */ if ( flag.norm->answer == 1 ) { norm = 0; } /* do some type-dependant checking */ /* and open file pointers for all the maps to read! */ file_pointers = NULL; if ( !strcmp (parm.type->answer,"rast") ) { if ( parm.groups->answer != NULL ) { /* check only user-specified groups */ file_pointers = test_rast_XML ( parm.groups->answers, dstXMLFile ); } else { /* check all groups */ file_pointers = test_rast_XML ( groups, dstXMLFile ); } } /* read in all samples in a type-dependant manner */ if ( parm.groups->answer != NULL ) { /* read only user-specified groups */ if ( !strcmp (parm.type->answer,"const") ) { if ( strcmp (parm.output->answer,G_location ()) != 0) { G_warning ("Ignoring parameter 'output='.\n"); } if ( strcmp (parm.vals->answer,"bel") !=0 ) { G_warning ("Ignoring parameter 'values='.\n"); } if ( parm.hyps->answer != NULL ) { G_warning ("Ignoring parameter 'hypotheses='.\n"); } do_calculations_const (samples,parm.groups->answers, norm, dstXMLFile); } if ( !strcmp (parm.type->answer,"rast") ) { do_calculations_rast (samples,parm.groups->answers, norm, parm.output->answer, parm.vals->answers, parm.hyps->answer, flag.quiet->answer, parm.logfile->answer, dstXMLFile, file_pointers ); } } else { /* read all groups */ if ( !strcmp (parm.type->answer,"const") ) { if ( strcmp (parm.output->answer,G_location ()) != 0) { G_warning ("Ignoring parameter 'output='.\n"); } if ( strcmp (parm.vals->answer,"bel") !=0 ) { G_warning ("Ignoring parameter 'values='.\n"); } if ( parm.hyps->answer != NULL ) { G_warning ("Ignoring parameter 'hypotheses='.\n"); } do_calculations_const (samples,groups, norm, dstXMLFile); } if ( !strcmp (parm.type->answer,"rast") ) { do_calculations_rast (samples,groups, norm, parm.output->answer, parm.vals->answers, parm.hyps->answer, flag.quiet->answer, parm.logfile->answer, dstXMLFile, file_pointers ); } } /* close logfile */ /* write processing time to logfile */ proctime = clock (); timeused = (unsigned long) proctime / CLOCKS_PER_SEC; days = timeused / 86400; hours = (timeused - (days * 86400)) / 3600; mins = (timeused - (days * 86400) - (hours * 3600)) / 60; secs = (timeused - (days * 86400) - (hours * 3600) - (mins * 60)); systime = time (NULL); if ( parm.logfile->answer != NULL ) { fprintf (lp,"\nCalculation finished on %s",ctime(&systime)); fprintf (lp,"Processing time: %id, %ih, %im, %is\n", days, hours, mins, secs ); fflush (lp); } for (i=0; i<N; i++) { G_free (groups[i]); } G_free (groups); return (EXIT_SUCCESS); }
int main(int argc, char *argv[]) { struct GModule *module; struct Map_info Map; FILE *ascii, *att; char *input, *output, *delim, **columns, *where, *field_name, *cats; int format, dp, field, ret, region, old_format, header, type; int ver, pnt; struct cat_list *clist; clist = NULL; G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("vector")); G_add_keyword(_("export")); G_add_keyword("ASCII"); module->label = _("Exports a vector map to a GRASS ASCII vector representation."); module->description = _("By default only features with category are exported. " "To export all features use 'layer=-1'."); parse_args(argc, argv, &input, &output, &format, &dp, &delim, &field_name, &columns, &where, ®ion, &old_format, &header, &cats, &type); if (format == GV_ASCII_FORMAT_STD && columns) { G_warning(_("Parameter '%s' ignored in standard mode"), "column"); } ver = 5; pnt = 0; if (old_format) ver = 4; if (ver == 4 && format == GV_ASCII_FORMAT_POINT) { G_fatal_error(_("Format '%s' is not supported for old version"), "point"); } if (ver == 4 && strcmp(output, "-") == 0) { G_fatal_error(_("Parameter '%s' must be given for old version"), "output"); } /* open with topology only if needed */ if (format == GV_ASCII_FORMAT_WKT || (format == GV_ASCII_FORMAT_STD && (where || clist))) { if (Vect_open_old2(&Map, input, "", field_name) < 2) /* topology required for areas */ G_warning(_("Unable to open vector map <%s> at topology level. " "Areas will not be processed."), input); } else { Vect_set_open_level(1); /* topology not needed */ if (Vect_open_old2(&Map, input, "", field_name) < 0) G_fatal_error(_("Unable to open vector map <%s>"), input); if (Vect_maptype(&Map) != GV_FORMAT_NATIVE) { /* require topological level for external formats centroids are read from topo */ Vect_close(&Map); Vect_set_open_level(2); if (Vect_open_old2(&Map, input, "", field_name) < 0) G_fatal_error(_("Unable to open vector map <%s>"), input); } } field = Vect_get_field_number(&Map, field_name); if (cats) { clist = Vect_new_cat_list(); clist->field = field; if (clist->field < 1) G_fatal_error(_("Layer <%s> not found"), field_name); ret = Vect_str_to_cat_list(cats, clist); if (ret > 0) G_fatal_error(_n("%d error in <%s> option", "%d errors in <%s> option", ret), ret, "cats"); } if (strcmp(output, "-") != 0) { if (ver == 4) { ascii = G_fopen_new("dig_ascii", output); } else if (strcmp(output, "-") == 0) { ascii = stdout; } else { ascii = fopen(output, "w"); } if (ascii == NULL) { G_fatal_error(_("Unable to open file <%s>"), output); } } else { ascii = stdout; } if (format == GV_ASCII_FORMAT_STD) { Vect_write_ascii_head(ascii, &Map); fprintf(ascii, "VERTI:\n"); } /* Open dig_att */ att = NULL; if (ver == 4 && !pnt) { if (G_find_file("dig_att", output, G_mapset()) != NULL) G_fatal_error(_("dig_att file already exist")); if ((att = G_fopen_new("dig_att", output)) == NULL) G_fatal_error(_("Unable to open dig_att file <%s>"), output); } if (where || columns || clist) G_message(_("Fetching data...")); ret = Vect_write_ascii(ascii, att, &Map, ver, format, dp, delim, region, type, field, clist, (const char *)where, (const char **)columns, header); if (ret < 1) { if (format == GV_ASCII_FORMAT_POINT) { G_warning(_("No points found, nothing to be exported")); } else { G_warning(_("No features found, nothing to be exported")); } } if (ascii != NULL) fclose(ascii); if (att != NULL) fclose(att); Vect_close(&Map); if (cats) Vect_destroy_cat_list(clist); exit(EXIT_SUCCESS); }
int G__open ( char *element, char *name, char *mapset, int mode) { char path[1024]; char xname[512], xmapset[512], *dummy; int G_fd; G__check_gisinit(); /* READ */ if (mode == 0) { if (G__name_is_fully_qualified (name, xname, xmapset)) { if (strcmp (xmapset, mapset) != 0) { fprintf(stderr, "G__open(r): mapset (%s) doesn't match xmapset (%s)\n", mapset,xmapset); return -1; } name = xname; } if ((dummy = G_find_file (element, name, mapset)) == NULL) return -1; G_free (dummy); G__file_name (path, element, name, mapset); G_fd = open (path, 0); #if defined R_GRASS_INTERFACE && defined __MINGW32_VERSION setmode(G_fd, O_BINARY); #endif /* __MINGW32_VERSION && R_GRASS_INTERFACE */ return G_fd; } /* WRITE */ if (mode == 1 || mode == 2) { if (G__name_is_fully_qualified (name, xname, xmapset)) { if (strcmp (xmapset, G_mapset()) != 0) { fprintf(stderr, "G__open(w): xmapset (%s) != G_mapset() (%s)\n", xmapset,G_mapset()); return -1; } name = xname; } if (G_legal_filename(name) == -1) return -1; G__file_name (path, element, name, G_mapset()); if(mode == 1 || access(path,0) != 0) { G__make_mapset_element (element); close (creat (path, 0666)); } G_fd = open (path, mode); #if defined R_GRASS_INTERFACE && defined __MINGW32_VERSION setmode(G_fd, O_BINARY); #endif /* __MINGW32_VERSION && R_GRASS_INTERFACE */ return G_fd; } return -1; }
int main(int argc, char *argv[]) { struct GModule *module; struct GParams params; struct Map_info Map; struct Map_info **BgMap; /* background vector maps */ int nbgmaps; /* number of registrated background maps */ enum mode action_mode; FILE *ascii; int i; int move_first, snap; int ret, layer; double move_x, move_y, move_z, thresh[3]; struct line_pnts *coord; struct ilist *List; struct cat_list *Clist; ascii = NULL; List = NULL; BgMap = NULL; nbgmaps = 0; coord = NULL; Clist = NULL; G_gisinit(argv[0]); module = G_define_module(); module->overwrite = TRUE; G_add_keyword(_("vector")); G_add_keyword(_("geometry")); G_add_keyword(_("editing")); G_add_keyword(_("line")); G_add_keyword(_("node")); G_add_keyword(_("point")); G_add_keyword(_("vertex")); module->description = _("Edits a vector map, allows adding, deleting " "and modifying selected vector features."); if (!parser(argc, argv, ¶ms, &action_mode)) exit(EXIT_FAILURE); /* get list of categories */ Clist = Vect_new_cat_list(); if (params.cat->answer && Vect_str_to_cat_list(params.cat->answer, Clist)) { G_fatal_error(_("Unable to get category list <%s>"), params.cat->answer); } /* open input file */ if (params.in->answer) { if (strcmp(params.in->answer, "-") != 0) { ascii = fopen(params.in->answer, "r"); if (ascii == NULL) G_fatal_error(_("Unable to open file <%s>"), params.in->answer); } else { ascii = stdin; } } if (!ascii && action_mode == MODE_ADD) G_fatal_error(_("Required parameter <%s> not set"), params.in->key); if (action_mode == MODE_CREATE) { int overwrite, map_type; overwrite = G_check_overwrite(argc, argv); if (G_find_vector2(params.map->answer, G_mapset()) && (!G_find_file("", "OGR", G_mapset()) && !G_find_file("", "PG", G_mapset()))) { if (!overwrite) G_fatal_error(_("Vector map <%s> already exists"), params.map->answer); } /* 3D vector maps? */ putenv("GRASS_VECTOR_EXTERNAL_IMMEDIATE=1"); ret = Vect_open_new(&Map, params.map->answer, WITHOUT_Z); if (ret == -1) { G_fatal_error(_("Unable to create vector map <%s>"), params.map->answer); } Vect_set_error_handler_io(NULL, &Map); /* native or external data source ? */ map_type = Vect_maptype(&Map); if (map_type != GV_FORMAT_NATIVE) { int type; type = Vect_option_to_types(params.type); if (type != GV_POINT && !(type & GV_LINES)) G_fatal_error("%s: point,line,boundary", _("Supported feature types for non-native formats:")); /* create OGR or PostGIS layer */ if (Vect_write_line(&Map, type, NULL, NULL) < 0) G_fatal_error(_("Unable to create vector map <%s>"), params.map->answer); } G_debug(1, "Map created"); if (ascii) { /* also add new vector features */ action_mode = MODE_ADD; } } else { /* open selected vector file */ if (action_mode == MODE_ADD) /* write */ ret = Vect_open_update2(&Map, params.map->answer, G_mapset(), params.fld->answer); else /* read-only -- select features */ ret = Vect_open_old2(&Map, params.map->answer, G_mapset(), params.fld->answer); if (ret < 2) G_fatal_error(_("Unable to open vector map <%s> on topological level. " "Try to rebuild vector topology by v.build."), params.map->answer); } G_debug(1, "Map opened"); /* open background maps */ if (params.bmaps->answer) { i = 0; while (params.bmaps->answers[i]) { const char *bmap = params.bmaps->answers[i]; const char *mapset = G_find_vector2(bmap, ""); if (!mapset) G_fatal_error(_("Vector map <%s> not found"), bmap); if (strcmp( G_fully_qualified_name(params.map->answer, G_mapset()), G_fully_qualified_name(bmap, mapset)) == 0) { G_fatal_error(_("Unable to open vector map <%s> as the background map. " "It is given as vector map to be edited."), bmap); } nbgmaps++; BgMap = (struct Map_info **)G_realloc( BgMap, nbgmaps * sizeof(struct Map_info *)); BgMap[nbgmaps - 1] = (struct Map_info *)G_malloc(sizeof(struct Map_info)); if (Vect_open_old(BgMap[nbgmaps - 1], bmap, "") == -1) G_fatal_error(_("Unable to open vector map <%s>"), bmap); G_verbose_message(_("Background vector map <%s> registered"), bmap); i++; } } layer = Vect_get_field_number(&Map, params.fld->answer); i = 0; while (params.maxdist->answers[i]) { switch (i) { case THRESH_COORDS: thresh[THRESH_COORDS] = max_distance(atof(params.maxdist->answers[THRESH_COORDS])); thresh[THRESH_SNAP] = thresh[THRESH_QUERY] = thresh[THRESH_COORDS]; break; case THRESH_SNAP: thresh[THRESH_SNAP] = max_distance(atof(params.maxdist->answers[THRESH_SNAP])); break; case THRESH_QUERY: thresh[THRESH_QUERY] = atof(params.maxdist->answers[THRESH_QUERY]); break; default: break; } i++; } move_first = params.move_first->answer ? 1 : 0; snap = NO_SNAP; if (strcmp(params.snap->answer, "node") == 0) snap = SNAP; else if (strcmp(params.snap->answer, "vertex") == 0) snap = SNAPVERTEX; if (snap != NO_SNAP && thresh[THRESH_SNAP] <= 0) { G_warning(_("Threshold for snapping must be > 0. No snapping applied.")); snap = NO_SNAP; } if (action_mode != MODE_CREATE && action_mode != MODE_ADD) { /* select lines */ List = Vect_new_list(); G_message(_("Selecting features...")); if (action_mode == MODE_COPY && BgMap && BgMap[0]) { List = select_lines(BgMap[0], action_mode, ¶ms, thresh, List); } else { List = select_lines(&Map, action_mode, ¶ms, thresh, List); } } if ((action_mode != MODE_CREATE && action_mode != MODE_ADD && action_mode != MODE_SELECT)) { if (List->n_values < 1) { G_warning(_("No features selected, nothing to edit")); action_mode = MODE_NONE; ret = 0; } else { /* reopen the map for updating */ if (action_mode == MODE_ZBULK && !Vect_is_3d(&Map)) { Vect_close(&Map); G_fatal_error(_("Vector map <%s> is not 3D. Tool '%s' requires 3D vector map. " "Please convert the vector map " "to 3D using e.g. %s."), params.map->answer, params.tool->answer, "v.extrude"); } Vect_close(&Map); if (Vect_open_update2(&Map, params.map->answer, G_mapset(), params.fld->answer) < 0) G_fatal_error(_("Unable to open vector map <%s>"), params.map->answer); } } /* coords option -> array */ if (params.coord->answers) { coord = Vect_new_line_struct(); int i = 0; double east, north; while (params.coord->answers[i]) { east = atof(params.coord->answers[i]); north = atof(params.coord->answers[i + 1]); Vect_append_point(coord, east, north, 0.0); i += 2; } } /* perform requested editation */ switch (action_mode) { case MODE_CREATE: break; case MODE_ADD: if (!params.header->answer) Vect_read_ascii_head(ascii, &Map); int num_lines; num_lines = Vect_get_num_lines(&Map); ret = Vect_read_ascii(ascii, &Map); if (ret > 0) { int iline; struct ilist *List_added; G_message(n_("%d feature added", "%d features added", ret), ret); List_added = Vect_new_list(); for (iline = num_lines + 1; iline <= Vect_get_num_lines(&Map); iline++) Vect_list_append(List_added, iline); G_verbose_message(_("Threshold value for snapping is %.2f"), thresh[THRESH_SNAP]); if (snap != NO_SNAP) { /* apply snapping */ /* snap to vertex ? */ Vedit_snap_lines(&Map, BgMap, nbgmaps, List_added, thresh[THRESH_SNAP], snap == SNAP ? FALSE : TRUE); } if (params.close->answer) { /* close boundaries */ int nclosed; nclosed = close_lines(&Map, GV_BOUNDARY, thresh[THRESH_SNAP]); G_message(n_("%d boundary closed", "%d boundaries closed", nclosed), nclosed); } Vect_destroy_list(List_added); } break; case MODE_DEL: ret = Vedit_delete_lines(&Map, List); G_message(n_("%d feature deleted", "%d features deleted", ret), ret); break; case MODE_MOVE: move_x = atof(params.move->answers[0]); move_y = atof(params.move->answers[1]); move_z = atof(params.move->answers[2]); G_verbose_message(_("Threshold value for snapping is %.2f"), thresh[THRESH_SNAP]); ret = Vedit_move_lines(&Map, BgMap, nbgmaps, List, move_x, move_y, move_z, snap, thresh[THRESH_SNAP]); G_message(n_("%d feature moved", "%d features moved", ret), ret); break; case MODE_VERTEX_MOVE: move_x = atof(params.move->answers[0]); move_y = atof(params.move->answers[1]); move_z = atof(params.move->answers[2]); G_verbose_message(_("Threshold value for snapping is %.2f"), thresh[THRESH_SNAP]); ret = Vedit_move_vertex(&Map, BgMap, nbgmaps, List, coord, thresh[THRESH_COORDS], thresh[THRESH_SNAP], move_x, move_y, move_z, move_first, snap); G_message(n_("%d vertex moved", "%d vertices moved", ret), ret); break; case MODE_VERTEX_ADD: ret = Vedit_add_vertex(&Map, List, coord, thresh[THRESH_COORDS]); G_message(n_("%d vertex added", "%d vertices added", ret), ret); break; case MODE_VERTEX_DELETE: ret = Vedit_remove_vertex(&Map, List, coord, thresh[THRESH_COORDS]); G_message(n_("%d vertex removed", "%d vertices removed", ret), ret); break; case MODE_BREAK: if (params.coord->answer) { ret = Vedit_split_lines(&Map, List, coord, thresh[THRESH_COORDS], NULL); } else { ret = Vect_break_lines_list(&Map, List, NULL, GV_LINES, NULL); } G_message(n_("%d line broken", "%d lines broken", ret), ret); break; case MODE_CONNECT: G_verbose_message(_("Threshold value for snapping is %.2f"), thresh[THRESH_SNAP]); ret = Vedit_connect_lines(&Map, List, thresh[THRESH_SNAP]); G_message(n_("%d line connected", "%d lines connected", ret), ret); break; case MODE_MERGE: ret = Vedit_merge_lines(&Map, List); G_message(n_("%d line merged", "%d lines merged", ret), ret); break; case MODE_SELECT: ret = print_selected(List); break; case MODE_CATADD: ret = Vedit_modify_cats(&Map, List, layer, 0, Clist); G_message(n_("%d feature modified", "%d features modified", ret), ret); break; case MODE_CATDEL: ret = Vedit_modify_cats(&Map, List, layer, 1, Clist); G_message(n_("%d feature modified", "%d features modified", ret), ret); break; case MODE_COPY: if (BgMap && BgMap[0]) { if (nbgmaps > 1) G_warning(_("Multiple background maps were given. " "Selected features will be copied only from " "vector map <%s>."), Vect_get_full_name(BgMap[0])); ret = Vedit_copy_lines(&Map, BgMap[0], List); } else { ret = Vedit_copy_lines(&Map, NULL, List); } G_message(n_("%d feature copied", "%d features copied", ret), ret); break; case MODE_SNAP: G_verbose_message(_("Threshold value for snapping is %.2f"), thresh[THRESH_SNAP]); ret = snap_lines(&Map, List, thresh[THRESH_SNAP]); break; case MODE_FLIP: ret = Vedit_flip_lines(&Map, List); G_message(n_("%d line flipped", "%d lines flipped", ret), ret); break; case MODE_NONE: break; case MODE_ZBULK: { double start, step; double x1, y1, x2, y2; start = atof(params.zbulk->answers[0]); step = atof(params.zbulk->answers[1]); x1 = atof(params.bbox->answers[0]); y1 = atof(params.bbox->answers[1]); x2 = atof(params.bbox->answers[2]); y2 = atof(params.bbox->answers[3]); ret = Vedit_bulk_labeling(&Map, List, x1, y1, x2, y2, start, step); G_message(n_("%d line labeled", "%d lines labeled", ret), ret); break; } case MODE_CHTYPE: ret = Vedit_chtype_lines(&Map, List); if (ret > 0) { G_message(n_("%d feature converted", "%d features converted", ret), ret); } else { G_message(_("No feature modified")); } break; case MODE_AREA_DEL: { ret = 0; for (i = 0; i < List->n_values; i++) { if (Vect_get_line_type(&Map, List->value[i]) != GV_CENTROID) { G_warning(_("Select feature %d is not centroid, ignoring..."), List->value[i]); continue; } ret += Vedit_delete_area_centroid(&Map, List->value[i]); } G_message(n_("%d area removed", "%d areas removed", ret), ret); break; } default: G_warning(_("Operation not implemented")); ret = -1; break; } Vect_hist_command(&Map); /* build topology only if requested or if tool!=select */ if (action_mode != MODE_SELECT && action_mode != MODE_NONE && params.topo->answer != 1) { Vect_build_partial(&Map, GV_BUILD_NONE); Vect_build(&Map); } if (List) Vect_destroy_list(List); Vect_close(&Map); G_debug(1, "Map closed"); /* close background maps */ for (i = 0; i < nbgmaps; i++) { Vect_close(BgMap[i]); G_free((void *)BgMap[i]); } G_free((void *)BgMap); if (coord) Vect_destroy_line_struct(coord); if (Clist) Vect_destroy_cat_list(Clist); G_done_msg(" "); if (ret > -1) { exit(EXIT_SUCCESS); } else { exit(EXIT_FAILURE); } }
int main(int argc, char *argv[]) { int col, row; /* to menage start (source) raster map */ struct Range start_range; CELL start_range_min, start_range_max; int start_is_time; /* 0 or 1 */ struct { struct Option *max, *dir, *base, *start, *spotdist, *velocity, *mois, *least, *comp_dens, *init_time, *time_lag, *backdrop, *out, *x_out, *y_out; } parm; struct { /* please, remove display before GRASS 7 released */ struct Flag *display, *spotting, *start_is_time; } flag; struct GModule *module; /* initialize access to database and create temporary files */ G_gisinit(argv[0]); /* Set description */ module = G_define_module(); G_add_keyword(_("raster")); G_add_keyword(_("fire")); G_add_keyword(_("spread")); G_add_keyword(_("hazard")); module->label = _("Simulates elliptically anisotropic spread."); module->description = _("Generates a raster map of the cumulative time of spread, " "given raster maps containing the rates of spread (ROS), " "the ROS directions and the spread origins. " "It optionally produces raster maps to contain backlink UTM " "coordinates for tracing spread paths. " "Usable for fire spread simulations."); parm.max = G_define_option(); parm.max->key = "max"; parm.max->type = TYPE_STRING; parm.max->required = YES; parm.max->gisprompt = "old,cell,raster"; parm.max->guisection = _("Input maps"); parm.max->label = _("Raster map containing maximal ROS (cm/min)"); parm.max->description = _("Name of an existing raster map layer in the user's current " "mapset search path containing the maximum ROS values (cm/minute)."); parm.dir = G_define_option(); parm.dir->key = "dir"; parm.dir->type = TYPE_STRING; parm.dir->required = YES; parm.dir->gisprompt = "old,cell,raster"; parm.dir->guisection = _("Input maps"); parm.dir->label = _("Raster map containing directions of maximal ROS (degree)"); parm.dir->description = _("Name of an existing raster map layer in the user's " "current mapset search path containing directions of the maximum ROSes, " "clockwise from north (degree)."); /* TODO: clockwise from north? see r.ros */ parm.base = G_define_option(); parm.base->key = "base"; parm.base->type = TYPE_STRING; parm.base->required = YES; parm.base->gisprompt = "old,cell,raster"; parm.base->guisection = _("Input maps"); parm.base->label = _("Raster map containing base ROS (cm/min)"); parm.base->description = _("Name of an existing raster map layer in the user's " "current mapset search path containing the ROS values in the directions " "perpendicular to maximum ROSes' (cm/minute). These ROSes are also the ones " "without the effect of directional factors."); parm.start = G_define_option(); parm.start->key = "start"; parm.start->type = TYPE_STRING; parm.start->required = YES; parm.start->gisprompt = "old,cell,raster"; parm.start->guisection = _("Input maps"); parm.start->description = _("Raster map containing starting sources"); parm.start->description = _("Name of an existing raster map layer in the " "user's current mapset search path containing starting locations of the " "spread phenomenon. Any positive integers in this map are recognized as " "starting sources (seeds)."); parm.spotdist = G_define_option(); parm.spotdist->key = "spot_dist"; parm.spotdist->type = TYPE_STRING; parm.spotdist->gisprompt = "old,cell,raster"; parm.spotdist->guisection = _("Input maps"); parm.spotdist->label = _("Raster map containing maximal spotting distance (m, required with -s)"); parm.spotdist->description = _("Name of an existing raster map layer in " "the user's current mapset search path containing the maximum potential " "spotting distances (meters)."); parm.velocity = G_define_option(); parm.velocity->key = "w_speed"; parm.velocity->type = TYPE_STRING; parm.velocity->gisprompt = "old,cell,raster"; parm.velocity->guisection = _("Input maps"); parm.velocity->label = _("Raster map containing midflame wind speed (ft/min, required with -s)"); parm.velocity->description = _("Name of an existing raster map layer in the " "user's current mapset search path containing wind velocities at half of " "the average flame height (feet/minute)."); parm.mois = G_define_option(); parm.mois->key = "f_mois"; parm.mois->type = TYPE_STRING; parm.mois->gisprompt = "old,cell,raster"; parm.mois->guisection = _("Input maps"); parm.mois->label = _("Raster map containing fine fuel moisture of the cell receiving a spotting firebrand (%, required with -s)"); parm.mois->description = _("Name of an existing raster map layer in the " "user's current mapset search path containing the 1-hour (<.25\") fuel " "moisture (percentage content multiplied by 100)."); parm.least = G_define_option(); parm.least->key = "least_size"; parm.least->type = TYPE_STRING; parm.least->key_desc = "odd int"; parm.least->options = "3,5,7,9,11,13,15"; parm.least->description = _("Basic sampling window size needed to meet certain accuracy (3)"); /* TODO: what is 3 here? default? */ parm.least->description = _("An odd integer ranging 3 - 15 indicating " "the basic sampling window size within which all cells will be considered " "to see whether they will be reached by the current spread cell. The default " "number is 3 which means a 3x3 window."); parm.comp_dens = G_define_option(); parm.comp_dens->key = "comp_dens"; parm.comp_dens->type = TYPE_STRING; parm.comp_dens->key_desc = "decimal"; parm.comp_dens->label = _("Sampling density for additional computing (range: 0.0 - 1.0 (0.5))"); /* TODO: again, what is 0.5?, TODO: range not set */ parm.comp_dens->description = _("A decimal number ranging 0.0 - 1.0 indicating " "additional sampling cells will be considered to see whether they will be " "reached by the current spread cell. The closer to 1.0 the decimal number " "is, the longer the program will run and the higher the simulation accuracy " "will be. The default number is 0.5."); parm.init_time = G_define_option(); parm.init_time->key = "init_time"; parm.init_time->type = TYPE_STRING; parm.init_time->key_desc = "int (>= 0)"; /* TODO: move to ->options */ parm.init_time->answer = "0"; parm.init_time->label = _("Initial time for current simulation (0) (min)"); parm.init_time->description = _("A non-negative number specifying the initial " "time for the current spread simulation (minutes). This is useful when multiple " "phase simulation is conducted. The default time is 0."); parm.time_lag = G_define_option(); parm.time_lag->key = "lag"; parm.time_lag->type = TYPE_STRING; parm.time_lag->key_desc = "int (>= 0)"; /* TODO: move to ->options */ parm.time_lag->description = _("Simulating time duration LAG (fill the region) (min)"); /* TODO: what does this mean? */ parm.time_lag->description = _("A non-negative integer specifying the simulating " "duration time lag (minutes). The default is infinite, but the program will " "terminate when the current geographic region/mask has been filled. It also " "controls the computational time, the shorter the time lag, the faster the " "program will run."); /* TODO: what's this? probably display, so remove */ parm.backdrop = G_define_option(); parm.backdrop->key = "backdrop"; parm.backdrop->type = TYPE_STRING; parm.backdrop->gisprompt = "old,cell,raster"; parm.backdrop->label = _("Name of raster map as a display backdrop"); parm.backdrop->description = _("Name of an existing raster map layer in the " "user's current mapset search path to be used as the background on which " "the \"live\" movement will be shown."); parm.out = G_define_option(); parm.out->key = "output"; parm.out->type = TYPE_STRING; parm.out->required = YES; parm.out->gisprompt = "new,cell,raster"; parm.out->guisection = _("Output maps"); parm.out->label = _("Raster map to contain output spread time (min)"); parm.out->description = _("Name of the new raster map layer to contain " "the results of the cumulative spread time needed for a phenomenon to reach " "each cell from the starting sources (minutes)."); parm.x_out = G_define_option(); parm.x_out->key = "x_output"; parm.x_out->type = TYPE_STRING; parm.x_out->gisprompt = "new,cell,raster"; parm.x_out->guisection = _("Output maps"); parm.x_out->label = _("Name of raster map to contain X back coordinates"); parm.x_out->description = _("Name of the new raster map layer to contain " "the results of backlink information in UTM easting coordinates for each " "cell."); parm.y_out = G_define_option(); parm.y_out->key = "y_output"; parm.y_out->type = TYPE_STRING; parm.y_out->gisprompt = "new,cell,raster"; parm.y_out->guisection = _("Output maps"); parm.y_out->label = _("Name of raster map to contain Y back coordinates"); parm.y_out->description = _("Name of the new raster map layer to contain " "the results of backlink information in UTM northing coordinates for each " "cell."); flag.display = G_define_flag(); flag.display->key = 'd'; #if 0 flag.display->label = _("DISPLAY 'live' spread process on screen"); flag.display->description = _("Display the 'live' simulation on screen. A graphics window " "must be opened and selected before using this option."); #else flag.display->description = _("Live display - disabled and depreciated"); #endif flag.spotting = G_define_flag(); flag.spotting->key = 's'; flag.spotting->description = _("Consider spotting effect (for wildfires)"); flag.start_is_time = G_define_flag(); flag.start_is_time->key = 'i'; flag.start_is_time->label = _("Use start raster map values in" " output spread time raster map"); flag.start_is_time->description = _("Designed to be used with output" " of previous run of r.spread when computing spread iteratively." " The values in start raster map are considered as time." " Allowed values in raster map are from zero" " to the value of init_time option." " If not enabled, init_time is used in the area of start raster map"); /* Parse command line */ if (G_parser(argc, argv)) exit(EXIT_FAILURE); /* FIXME - allow seed to be specified for repeatability */ G_srand48_auto(); display = flag.display->answer; #if 1 if (display) G_fatal_error(_("The display feature is disabled")); #endif spotting = flag.spotting->answer; max_layer = parm.max->answer; dir_layer = parm.dir->answer; base_layer = parm.base->answer; start_layer = parm.start->answer; backdrop_layer = parm.backdrop->answer; out_layer = parm.out->answer; if (parm.x_out->answer) { x_out = 1; x_out_layer = parm.x_out->answer; } if (parm.y_out->answer) { y_out = 1; y_out_layer = parm.y_out->answer; } if (spotting) { if (! (parm.spotdist->answer && parm.velocity->answer && parm.mois->answer)) { G_warning ("SPOTTING DISTANCE, fuel MOISTURE, or wind VELOCITY map not given w/ -s"); G_usage(); exit(EXIT_FAILURE); } else { spotdist_layer = parm.spotdist->answer; velocity_layer = parm.velocity->answer; mois_layer = parm.mois->answer; } } /*Check the given the least sampling size, assign the default if needed */ if (parm.least->answer) least = atoi(parm.least->answer); else least = 3; /*Check the given computing density, assign the default if needed */ if (parm.comp_dens->answer) { comp_dens = atof(parm.comp_dens->answer); if (comp_dens < 0.0 || comp_dens > 1.0) { G_warning("Illegal computing density <%s>", parm.comp_dens->answer); G_usage(); exit(EXIT_FAILURE); } } else { comp_dens = 0.5; } /*Check the given initial time and simulation time lag, assign the default if needed */ init_time = atoi(parm.init_time->answer); if (init_time < 0) { G_warning("Illegal initial time <%s>", parm.init_time->answer); G_usage(); exit(EXIT_FAILURE); } if (parm.time_lag->answer) { time_lag = atoi(parm.time_lag->answer); if (time_lag < 0) { G_warning("Illegal simulating time lag <%s>", parm.time_lag->answer); G_usage(); exit(EXIT_FAILURE); } } else { time_lag = 99999; } /* Get database window parameters */ G_get_window(&window); /* find number of rows and columns in window */ nrows = Rast_window_rows(); ncols = Rast_window_cols(); /*transfor measurement unit from meters to centimeters due to ROS unit *if the input ROSs are in m/min units, cancell the following*/ window.ns_res = 100 * window.ns_res; window.ew_res = 100 * window.ew_res; /* Initialize display screens */ #if 0 if (display) display_init(); #endif /* Check if input layers exists in data base */ if (G_find_raster2(max_layer, "") == NULL) G_fatal_error("Raster map <%s> not found", max_layer); if (G_find_raster2(dir_layer, "") == NULL) G_fatal_error(_("Raster map <%s> not found"), dir_layer); if (G_find_raster2(base_layer, "") == NULL) G_fatal_error(_("Raster map <%s> not found"), base_layer); if (G_find_raster2(start_layer, "") == NULL) G_fatal_error(_("Raster map <%s> not found"), start_layer); if (spotting) { if (G_find_raster2(spotdist_layer, "") == NULL) G_fatal_error(_("Raster map <%s> not found"), spotdist_layer); if (G_find_raster2(velocity_layer, "") == NULL) G_fatal_error(_("Raster map <%s> not found"), velocity_layer); if (G_find_raster2(mois_layer, "") == NULL) G_fatal_error(_("Raster map <%s> not found"), mois_layer); } /* Open input cell layers for reading */ max_fd = Rast_open_old(max_layer, G_find_raster2(max_layer, "")); dir_fd = Rast_open_old(dir_layer, G_find_raster2(dir_layer, "")); base_fd = Rast_open_old(base_layer, G_find_raster2(base_layer, "")); if (spotting) { spotdist_fd = Rast_open_old(spotdist_layer, G_find_raster2(spotdist_layer, "")); velocity_fd = Rast_open_old(velocity_layer, G_find_raster2(velocity_layer, "")); mois_fd = Rast_open_old(mois_layer, G_find_raster2(mois_layer, "")); } /* Allocate memories for a row */ cell = Rast_allocate_c_buf(); if (x_out) x_cell = Rast_allocate_c_buf(); if (y_out) y_cell = Rast_allocate_c_buf(); /* Allocate memories for a map */ map_max = (CELL *) G_calloc(nrows * ncols + 1, sizeof(CELL)); map_dir = (CELL *) G_calloc(nrows * ncols + 1, sizeof(CELL)); map_base = (CELL *) G_calloc(nrows * ncols + 1, sizeof(CELL)); map_visit = (CELL *) G_calloc(nrows * ncols + 1, sizeof(CELL)); map_out = (float *)G_calloc(nrows * ncols + 1, sizeof(float)); if (spotting) { map_spotdist = (CELL *) G_calloc(nrows * ncols + 1, sizeof(CELL)); map_velocity = (CELL *) G_calloc(nrows * ncols + 1, sizeof(CELL)); map_mois = (CELL *) G_calloc(nrows * ncols + 1, sizeof(CELL)); } if (x_out) map_x_out = (CELL *) G_calloc(nrows * ncols + 1, sizeof(CELL)); if (y_out) map_y_out = (CELL *) G_calloc(nrows * ncols + 1, sizeof(CELL)); /* Write the input layers in the map "arrays" */ G_message(_("Reading inputs...")); for (row = 0; row < nrows; row++) { G_percent(row, nrows, 2); Rast_get_c_row(max_fd, cell, row); for (col = 0; col < ncols; col++) DATA(map_max, row, col) = cell[col]; Rast_get_c_row(dir_fd, cell, row); for (col = 0; col < ncols; col++) DATA(map_dir, row, col) = cell[col]; Rast_get_c_row(base_fd, cell, row); for (col = 0; col < ncols; col++) DATA(map_base, row, col) = cell[col]; if (spotting) { Rast_get_c_row(spotdist_fd, cell, row); for (col = 0; col < ncols; col++) DATA(map_spotdist, row, col) = cell[col]; Rast_get_c_row(velocity_fd, cell, row); for (col = 0; col < ncols; col++) DATA(map_velocity, row, col) = cell[col]; Rast_get_c_row(mois_fd, cell, row); for (col = 0; col < ncols; col++) DATA(map_mois, row, col) = cell[col]; } } G_percent(row, nrows, 2); /* Scan the START layer searching for starting points. * Create an array of starting points (min_heap) ordered by costs. */ start_fd = Rast_open_old(start_layer, G_find_raster2(start_layer, "")); Rast_read_range(start_layer, G_find_file("cell", start_layer, ""), &start_range); Rast_get_range_min_max(&start_range, &start_range_min, &start_range_max); start_is_time = flag.start_is_time->answer; /* values higher than init_time are unexpected and may cause segfaults */ if (start_is_time && start_range_max > init_time) G_fatal_error(_("Maximum of start raster map is grater than init_time" " (%d > %d)"), start_range_max, init_time); /* values lower then zero does not make sense for time */ if (start_is_time && start_range_min < 0) G_fatal_error(_("Minimum of start raster map is less than zero" " (%d < 0)"), start_range_min, init_time); /* Initialize the heap */ heap = (struct costHa *)G_calloc(nrows * ncols + 1, sizeof(struct costHa)); heap_len = 0; G_message(_("Reading %s..."), start_layer); G_debug(1, "Collecting origins..."); collect_ori(start_fd, start_is_time); G_debug(1, "Done"); /* Major computation of spread time */ G_debug(1, "Spreading..."); spread(); G_debug(1, "Done"); /* Open cumulative cost layer (and x, y direction layers) for writing */ cum_fd = Rast_open_c_new(out_layer); if (x_out) x_fd = Rast_open_c_new(x_out_layer); if (y_out) y_fd = Rast_open_c_new(y_out_layer); /* prepare output -- adjust from cm to m */ window.ew_res = window.ew_res / 100; window.ns_res = window.ns_res / 100; /* copy maps in ram to output maps */ ram2out(); G_free(map_max); G_free(map_dir); G_free(map_base); G_free(map_out); G_free(map_visit); if (x_out) G_free(map_x_out); if (y_out) G_free(map_y_out); if (spotting) { G_free(map_spotdist); G_free(map_mois); G_free(map_velocity); } Rast_close(max_fd); Rast_close(dir_fd); Rast_close(base_fd); Rast_close(start_fd); Rast_close(cum_fd); if (x_out) Rast_close(x_fd); if (y_out) Rast_close(y_fd); if (spotting) { Rast_close(spotdist_fd); Rast_close(velocity_fd); Rast_close(mois_fd); } /* close graphics */ #if 0 if (display) display_close(); #endif exit(EXIT_SUCCESS); }
int IL_resample_output_2d(struct interp_params *params, double zmin, double zmax, /* min,max input z-values */ double zminac, double zmaxac, /* min,max interpolated values */ double c1min, double c1max, double c2min, double c2max, double gmin, double gmax, double ertot, /* total interplating func. error */ char *input, /* input file name */ double *dnorm, struct Cell_head *outhd, /* Region with desired resolution */ struct Cell_head *winhd, /* Current region */ char *smooth, int n_points) /* * Creates output files as well as history files and color tables for * them. */ { FCELL *cell1; /* cell buffer */ int cf1 = 0, cf2 = 0, cf3 = 0, cf4 = 0, cf5 = 0, cf6 = 0; /* cell file descriptors */ int nrows, ncols; /* current region rows and columns */ int i; /* loop counter */ char *mapset; float dat1, dat2; struct Colors colors, colors2; double value1, value2; struct History hist, hist1, hist2, hist3, hist4, hist5; struct _Color_Rule_ *rule; char *maps, *type; int cond1, cond2; cond2 = ((params->pcurv != NULL) || (params->tcurv != NULL) || (params->mcurv != NULL)); cond1 = ((params->slope != NULL) || (params->aspect != NULL) || cond2); /* change region to output cell file region */ fprintf(stderr, "Temporarily changing the region to desired resolution...\n"); if (G_set_window(outhd) < 0) { fprintf(stderr, "Cannot set region to output region!\n"); return -1; } mapset = G_mapset(); cell1 = G_allocate_f_raster_buf(); if (params->elev != NULL) { cf1 = G_open_fp_cell_new(params->elev); if (cf1 < 0) { fprintf(stderr, "unable to create raster map %s\n", params->elev); return -1; } } if (params->slope != NULL) { cf2 = G_open_fp_cell_new(params->slope); if (cf2 < 0) { fprintf(stderr, "unable to create raster map %s\n", params->slope); return -1; } } if (params->aspect != NULL) { cf3 = G_open_fp_cell_new(params->aspect); if (cf3 < 0) { fprintf(stderr, "unable to create raster map %s\n", params->aspect); return -1; } } if (params->pcurv != NULL) { cf4 = G_open_fp_cell_new(params->pcurv); if (cf4 < 0) { fprintf(stderr, "unable to create raster map %s\n", params->pcurv); return -1; } } if (params->tcurv != NULL) { cf5 = G_open_fp_cell_new(params->tcurv); if (cf5 < 0) { fprintf(stderr, "unable to create raster map %s\n", params->tcurv); return -1; } } if (params->mcurv != NULL) { cf6 = G_open_fp_cell_new(params->mcurv); if (cf6 < 0) { fprintf(stderr, "unable to create raster map %s\n", params->mcurv); return -1; } } nrows = outhd->rows; if (nrows != params->nsizr) { fprintf(stderr, "first change your rows number(%d) to %d!\n", nrows, params->nsizr); return -1; } ncols = outhd->cols; if (ncols != params->nsizc) { fprintf(stderr, "first change your rows number(%d) to %d!\n", ncols, params->nsizc); return -1; } if (params->elev != NULL) { fseek(params->Tmp_fd_z, 0L, 0); /* seek to the beginning */ for (i = 0; i < params->nsizr; i++) { /* seek to the right row */ if (fseek(params->Tmp_fd_z, (long) ((params->nsizr - 1 - i) * params->nsizc * sizeof(FCELL)), 0) == -1) { fprintf(stderr, "cannot fseek to the right spot\n"); return -1; } fread(cell1, sizeof(FCELL), params->nsizc, params->Tmp_fd_z); if (G_put_f_raster_row(cf1, cell1) < 0) { fprintf(stderr, "cannot write file\n"); return -1; } } } if (params->slope != NULL) { fseek(params->Tmp_fd_dx, 0L, 0); /* seek to the beginning */ for (i = 0; i < params->nsizr; i++) { /* seek to the right row */ if (fseek(params->Tmp_fd_dx, (long) ((params->nsizr - 1 - i) * params->nsizc * sizeof(FCELL)), 0) == -1) { fprintf(stderr, "cannot fseek to the right spot\n"); return -1; } fread(cell1, sizeof(FCELL), params->nsizc, params->Tmp_fd_dx); /* * for (ii==0;ii<params->nsizc;ii++) { fprintf(stderr,"ii=%d ",ii); * fprintf(stderr,"%f ",cell1[ii]); } * fprintf(stderr,"params->nsizc=%d \n",params->nsizc); */ if (G_put_f_raster_row(cf2, cell1) < 0) { fprintf(stderr, "cannot write file\n"); return -1; } } } if (params->aspect != NULL) { fseek(params->Tmp_fd_dy, 0L, 0); /* seek to the beginning */ for (i = 0; i < params->nsizr; i++) { /* seek to the right row */ if (fseek(params->Tmp_fd_dy, (long) ((params->nsizr - 1 - i) * params->nsizc * sizeof(FCELL)), 0) == -1) { fprintf(stderr, "cannot fseek to the right spot\n"); return -1; } fread(cell1, sizeof(FCELL), params->nsizc, params->Tmp_fd_dy); if (G_put_f_raster_row(cf3, cell1) < 0) { fprintf(stderr, "cannot write file\n"); return -1; } } } if (params->pcurv != NULL) { fseek(params->Tmp_fd_xx, 0L, 0); /* seek to the beginning */ for (i = 0; i < params->nsizr; i++) { /* seek to the right row */ if (fseek(params->Tmp_fd_xx, (long) ((params->nsizr - 1 - i) * params->nsizc * sizeof(FCELL)), 0) == -1) { fprintf(stderr, "cannot fseek to the right spot\n"); return -1; } fread(cell1, sizeof(FCELL), params->nsizc, params->Tmp_fd_xx); if (G_put_f_raster_row(cf4, cell1) < 0) { fprintf(stderr, "cannot write file\n"); return -1; } } } if (params->tcurv != NULL) { fseek(params->Tmp_fd_yy, 0L, 0); /* seek to the beginning */ for (i = 0; i < params->nsizr; i++) { /* seek to the right row */ if (fseek(params->Tmp_fd_yy, (long) ((params->nsizr - 1 - i) * params->nsizc * sizeof(FCELL)), 0) == -1) { fprintf(stderr, "cannot fseek to the right spot\n"); return -1; } fread(cell1, sizeof(FCELL), params->nsizc, params->Tmp_fd_yy); if (G_put_f_raster_row(cf5, cell1) < 0) { fprintf(stderr, "cannot write file\n"); return -1; } } } if (params->mcurv != NULL) { fseek(params->Tmp_fd_xy, 0L, 0); /* seek to the beginning */ for (i = 0; i < params->nsizr; i++) { /* seek to the right row */ if (fseek(params->Tmp_fd_xy, (long) ((params->nsizr - 1 - i) * params->nsizc * sizeof(FCELL)), 0) == -1) { fprintf(stderr, "cannot fseek to the right spot\n"); return -1; } fread(cell1, sizeof(FCELL), params->nsizc, params->Tmp_fd_xy); if (G_put_f_raster_row(cf6, cell1) < 0) { fprintf(stderr, "cannot write file\n"); return -1; } } } if (cf1) G_close_cell(cf1); if (cf2) G_close_cell(cf2); if (cf3) G_close_cell(cf3); if (cf4) G_close_cell(cf4); if (cf5) G_close_cell(cf5); if (cf6) G_close_cell(cf6); /* write colormaps and history for output cell files */ /* colortable for elevations */ maps = G_find_file("cell", input, ""); if (params->elev != NULL) { if (maps == NULL) { fprintf(stderr, "file [%s] not found\n", input); return -1; } G_init_colors(&colors2); /* * G_mark_colors_as_fp(&colors2); */ if (G_read_colors(input, maps, &colors) >= 0) { if (colors.modular.rules) { rule = colors.modular.rules; while (rule->next) rule = rule->next; for (; rule; rule = rule->prev) { value1 = rule->low.value * params->zmult; value2 = rule->high.value * params->zmult; G_add_modular_d_raster_color_rule(&value1, rule->low.red, rule->low.grn, rule->low.blu, &value2, rule->high.red, rule->high.grn, rule->high.blu, &colors2); } } if (colors.fixed.rules) { rule = colors.fixed.rules; while (rule->next) rule = rule->next; for (; rule; rule = rule->prev) { value1 = rule->low.value * params->zmult; value2 = rule->high.value * params->zmult; G_add_d_raster_color_rule(&value1, rule->low.red, rule->low.grn, rule->low.blu, &value2, rule->high.red, rule->high.grn, rule->high.blu, &colors2); } } maps = NULL; maps = G_find_file("cell", params->elev, ""); if (maps == NULL) { fprintf(stderr, "file [%s] not found\n", params->elev); return -1; } if (G_write_colors(params->elev, maps, &colors2) < 0) { fprintf(stderr, "Cannot write color table\n"); return -1; } G_quantize_fp_map_range(params->elev, mapset, zminac - 0.5, zmaxac + 0.5, (CELL) (zminac - 0.5), (CELL) (zmaxac + 0.5)); } else fprintf(stderr, "No color table for input file -- will not create color table\n"); } /* colortable for slopes */ if (cond1 & (!params->deriv)) { G_init_colors(&colors); G_add_color_rule(0, 255, 255, 255, 2, 255, 255, 0, &colors); G_add_color_rule(2, 255, 255, 0, 5, 0, 255, 0, &colors); G_add_color_rule(5, 0, 255, 0, 10, 0, 255, 255, &colors); G_add_color_rule(10, 0, 255, 255, 15, 0, 0, 255, &colors); G_add_color_rule(15, 0, 0, 255, 30, 255, 0, 255, &colors); G_add_color_rule(30, 255, 0, 255, 50, 255, 0, 0, &colors); G_add_color_rule(50, 255, 0, 0, 90, 0, 0, 0, &colors); if (params->slope != NULL) { maps = NULL; maps = G_find_file("cell", params->slope, ""); if (maps == NULL) { fprintf(stderr, "file [%s] not found\n", params->slope); return -1; } G_write_colors(params->slope, maps, &colors); G_quantize_fp_map_range(params->slope, mapset, 0., 90., 0, 90); type = "raster"; G_short_history(params->slope, type, &hist1); if (params->elev != NULL) sprintf(hist1.edhist[0], "The elevation map is %s", params->elev); sprintf(hist1.datsrc_1, "raster map %s", input); hist1.edlinecnt = 1; G_write_history(params->slope, &hist1); } /* colortable for aspect */ G_init_colors(&colors); G_add_color_rule(0, 255, 255, 255, 0, 255, 255, 255, &colors); G_add_color_rule(1, 255, 255, 0, 90, 0, 255, 0, &colors); G_add_color_rule(90, 0, 255, 0, 180, 0, 255, 255, &colors); G_add_color_rule(180, 0, 255, 255, 270, 255, 0, 0, &colors); G_add_color_rule(270, 255, 0, 0, 360, 255, 255, 0, &colors); if (params->aspect != NULL) { maps = NULL; maps = G_find_file("cell", params->aspect, ""); if (maps == NULL) { fprintf(stderr, "file [%s] not found\n", params->aspect); return -1; } G_write_colors(params->aspect, maps, &colors); G_quantize_fp_map_range(params->aspect, mapset, 0., 360., 0, 360); type = "raster"; G_short_history(params->aspect, type, &hist2); if (params->elev != NULL) sprintf(hist2.edhist[0], "The elevation map is %s", params->elev); sprintf(hist2.datsrc_1, "raster map %s", input); hist2.edlinecnt = 1; G_write_history(params->aspect, &hist2); } /* colortable for curvatures */ if (cond2) { G_init_colors(&colors); dat1 = (FCELL) amin1(c1min, c2min); dat2 = (FCELL) - 0.01; G_add_f_raster_color_rule(&dat1, 50, 0, 155, &dat2, 0, 0, 255, &colors); dat1 = dat2; dat2 = (FCELL) - 0.001; G_add_f_raster_color_rule(&dat1, 0, 0, 255, &dat2, 0, 127, 255, &colors); dat1 = dat2; dat2 = (FCELL) - 0.00001; G_add_f_raster_color_rule(&dat1, 0, 127, 255, &dat2, 0, 255, 255, &colors); dat1 = dat2; dat2 = (FCELL) 0.00; G_add_f_raster_color_rule(&dat1, 0, 255, 255, &dat2, 200, 255, 200, &colors); dat1 = dat2; dat2 = (FCELL) 0.00001; G_add_f_raster_color_rule(&dat1, 200, 255, 200, &dat2, 255, 255, 0, &colors); dat1 = dat2; dat2 = (FCELL) 0.001; G_add_f_raster_color_rule(&dat1, 255, 255, 0, &dat2, 255, 127, 0, &colors); dat1 = dat2; dat2 = (FCELL) 0.01; G_add_f_raster_color_rule(&dat1, 255, 127, 0, &dat2, 255, 0, 0, &colors); dat1 = dat2; dat2 = (FCELL) amax1(c1max, c2max); G_add_f_raster_color_rule(&dat1, 255, 0, 0, &dat2, 155, 0, 20, &colors); maps = NULL; if (params->pcurv != NULL) { maps = G_find_file("cell", params->pcurv, ""); if (maps == NULL) { fprintf(stderr, "file [%s] not found\n", params->pcurv); return -1; } G_write_colors(params->pcurv, maps, &colors); fprintf(stderr, "color map written\n"); G_quantize_fp_map_range(params->pcurv, mapset, dat1, dat2, (CELL) (dat1 * MULT), (CELL) (dat2 * MULT)); type = "raster"; G_short_history(params->pcurv, type, &hist3); if (params->elev != NULL) sprintf(hist3.edhist[0], "The elevation map is %s", params->elev); sprintf(hist3.datsrc_1, "raster map %s", input); hist3.edlinecnt = 1; G_write_history(params->pcurv, &hist3); } if (params->tcurv != NULL) { maps = NULL; maps = G_find_file("cell", params->tcurv, ""); if (maps == NULL) { fprintf(stderr, "file [%s] not found\n", params->tcurv); return -1; } G_write_colors(params->tcurv, maps, &colors); G_quantize_fp_map_range(params->tcurv, mapset, dat1, dat2, (CELL) (dat1 * MULT), (CELL) (dat2 * MULT)); type = "raster"; G_short_history(params->tcurv, type, &hist4); if (params->elev != NULL) sprintf(hist4.edhist[0], "The elevation map is %s", params->elev); sprintf(hist4.datsrc_1, "raster map %s", input); hist4.edlinecnt = 1; G_write_history(params->tcurv, &hist4); } if (params->mcurv != NULL) { maps = NULL; maps = G_find_file("cell", params->mcurv, ""); if (maps == NULL) { fprintf(stderr, "file [%s] not found\n", params->mcurv); return -1; } G_write_colors(params->mcurv, maps, &colors); G_quantize_fp_map_range(params->mcurv, mapset, dat1, dat2, (CELL) (dat1 * MULT), (CELL) (dat2 * MULT)); type = "raster"; G_short_history(params->mcurv, type, &hist5); if (params->elev != NULL) sprintf(hist5.edhist[0], "The elevation map is %s", params->elev); sprintf(hist5.datsrc_1, "raster map %s", input); hist5.edlinecnt = 1; G_write_history(params->mcurv, &hist5); } } } if (params->elev != NULL) { maps = G_find_file("cell", params->elev, ""); if (maps == NULL) { fprintf(stderr, "file [%s] not found \n", params->elev); return -1; } G_short_history(params->elev, "raster", &hist); if (smooth != NULL) sprintf(hist.edhist[0], "tension=%f, smoothing=%s", params->fi * 1000. / (*dnorm), smooth); else sprintf(hist.edhist[0], "tension=%f", params->fi * 1000. / (*dnorm)); sprintf(hist.edhist[1], "dnorm=%f, zmult=%f", *dnorm, params->zmult); sprintf(hist.edhist[2], "KMAX=%d, KMIN=%d, errtotal=%f", params->kmax, params->kmin, sqrt(ertot / n_points)); sprintf(hist.edhist[3], "zmin_data=%f, zmax_data=%f", zmin, zmax); sprintf(hist.edhist[4], "zmin_int=%f, zmax_int=%f", zminac, zmaxac); sprintf(hist.datsrc_1, "raster map %s", input); hist.edlinecnt = 5; G_write_history(params->elev, &hist); } /* change region to initial region */ fprintf(stderr, "Changing the region back to initial...\n"); if (G_set_window(winhd) < 0) { fprintf(stderr, "Cannot set region to back to initial region!\n"); return -1; } return 1; }