/*! \brief Sort categories \param pcats pointer to Categories structure \return -1 on error (nothing to sort) \return 0 on success */ int Rast_sort_cats(struct Categories *pcats) { int *indexes, i, ncats; char *descr; DCELL d1, d2; if (pcats->ncats <= 1) return -1; ncats = pcats->ncats; G_debug(3, "Rast_sort_cats(): Copying to save cats buffer"); Rast_copy_cats(&save_cats, pcats); Rast_free_cats(pcats); indexes = (int *)G_malloc(sizeof(int) * ncats); for (i = 0; i < ncats; i++) indexes[i] = i; qsort(indexes, ncats, sizeof(int), cmp); Rast_init_cats(save_cats.title, pcats); for (i = 0; i < ncats; i++) { descr = Rast_get_ith_d_cat(&save_cats, indexes[i], &d1, &d2); G_debug(4, " Write sorted cats, pcats = %p pcats->labels = %p", pcats, pcats->labels); Rast_set_d_cat(&d1, &d2, descr, pcats); } Rast_free_cats(&save_cats); return 0; }
/* * check_stats() - Check and update statistics * * RETURN: EXIT_SUCCESS / EXIT_FAILURE */ int check_stats(const char *name) { struct Categories cats; struct FPRange fprange; int cats_ok; G_message(_("Updating statistics for <%s>"), name); /* Get category status and max */ cats_ok = (Rast3d_read_cats(name, "", &cats) >= 0); Rast3d_read_range(name, "", &fprange); /* Further category checks */ if (!cats_ok) Rast_init_cats("", &cats); else if (cats.num != fprange.max) { cats.num = fprange.max; cats_ok = 0; } /* Update categories if needed */ if (!cats_ok) { G_message(_("Updating the number of categories for <%s>"), name); Rast3d_write_cats(name, &cats); } Rast_free_cats(&cats); return 0; }
int support(char **names, struct Cell_stats *statf, int nfiles, struct Categories *cats, int *cats_ok, struct Colors *colr, int *colr_ok, RASTER_MAP_TYPE out_type) { int i; struct Categories pcats; struct Colors pcolr; CELL n; long count; int red, grn, blu; int do_cats, do_colr; *cats_ok = 1; *colr_ok = 1; if (Rast_read_cats(names[0], "", cats) < 0) *cats_ok = 0; G_suppress_warnings(1); if (Rast_read_colors(names[0], "", colr) < 0) *colr_ok = 0; G_suppress_warnings(0); if (*cats_ok == 0 && *colr_ok == 0) return 0; for (i = 1; i < nfiles; i++) { do_cats = *cats_ok && (Rast_read_cats(names[i], "", &pcats) >= 0); G_suppress_warnings(1); do_colr = *colr_ok && (Rast_read_colors(names[i], "", &pcolr) >= 0); G_suppress_warnings(0); if (!do_cats && !do_colr) continue; if (out_type == CELL_TYPE) { Rast_rewind_cell_stats(statf + i); while (Rast_next_cell_stat(&n, &count, statf + i)) if (n && !Rast_find_cell_stat(n, &count, statf)) { if (do_cats) { Rast_update_cell_stats(&n, 1, statf); Rast_set_c_cat(&n, &n, Rast_get_c_cat((CELL *) &n, &pcats), cats); } if (do_colr) { Rast_get_c_color(&n, &red, &grn, &blu, &pcolr); Rast_set_c_color(n, red, grn, blu, colr); } } } /* else the color will be the color of the first map */ if (do_cats) Rast_free_cats(&pcats); if (do_colr) /* otherwise this memory is used in colr pointer */ Rast_free_colors(&pcolr); } return 1; }
int write_form_cat_colors (char* raster, CATCOLORS* ccolors) { struct Colors colors; struct Categories cats; int i; Rast_init_colors(&colors); for(i=1;i<CNT;++i) Rast_add_color_rule( &ccolors[i].cat, ccolors[i].r, ccolors[i].g, ccolors[i].b, &ccolors[i].cat, ccolors[i].r, ccolors[i].g, ccolors[i].b, &colors, CELL_TYPE); Rast_write_colors(raster, G_mapset(), &colors); Rast_free_colors(&colors); Rast_init_cats("Forms", &cats); for(i=1;i<CNT;++i) Rast_set_cat(&ccolors[i].cat, &ccolors[i].cat, ccolors[i].label, &cats, CELL_TYPE); Rast_write_cats(raster, &cats); Rast_free_cats(&cats); return 0; }
int main(int argc, char *argv[]) { const char *name; const char *mapset; long x, y; double dx; RASTER_MAP_TYPE map_type; int i; int from_stdin = FALSE; struct GModule *module; struct { struct Option *map, *fs, *cats, *vals, *raster, *file, *fmt_str, *fmt_coeff; } parm; G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("raster")); G_add_keyword(_("category")); module->description = _("Manages category values and labels associated " "with user-specified raster map layers."); parm.map = G_define_standard_option(G_OPT_R_MAP); parm.cats = G_define_standard_option(G_OPT_V_CATS); parm.cats->multiple = YES; parm.cats->guisection = _("Selection"); parm.vals = G_define_option(); parm.vals->key = "vals"; parm.vals->type = TYPE_DOUBLE; parm.vals->multiple = YES; parm.vals->required = NO; parm.vals->label = _("Comma separated value list"); parm.vals->description = _("Example: 1.4,3.8,13"); parm.vals->guisection = _("Selection"); parm.fs = G_define_standard_option(G_OPT_F_SEP); parm.fs->answer = "tab"; parm.raster = G_define_standard_option(G_OPT_R_INPUT); parm.raster->key = "raster"; parm.raster->required = NO; parm.raster->description = _("Raster map from which to copy category table"); parm.raster->guisection = _("Define"); parm.file = G_define_standard_option(G_OPT_F_INPUT); parm.file->key = "rules"; parm.file->required = NO; parm.file->description = _("File containing category label rules (or \"-\" to read from stdin)"); parm.file->guisection = _("Define"); parm.fmt_str = G_define_option(); parm.fmt_str->key = "format"; parm.fmt_str->type = TYPE_STRING; parm.fmt_str->required = NO; parm.fmt_str->label = _("Default label or format string for dynamic labeling"); parm.fmt_str->description = _("Used when no explicit label exists for the category"); parm.fmt_coeff = G_define_option(); parm.fmt_coeff->key = "coefficients"; parm.fmt_coeff->type = TYPE_DOUBLE; parm.fmt_coeff->required = NO; parm.fmt_coeff->key_desc = "mult1,offset1,mult2,offset2"; /* parm.fmt_coeff->answer = "0.0,0.0,0.0,0.0"; */ parm.fmt_coeff->label = _("Dynamic label coefficients"); parm.fmt_coeff->description = _("Two pairs of category multiplier and offsets, for $1 and $2"); if (G_parser(argc, argv)) exit(EXIT_FAILURE); name = parm.map->answer; fs = G_option_to_separator(parm.fs); mapset = G_find_raster2(name, ""); if (mapset == NULL) G_fatal_error(_("Raster map <%s> not found"), name); map_type = Rast_map_type(name, mapset); /* create category labels */ if (parm.raster->answer || parm.file->answer || parm.fmt_str->answer || parm.fmt_coeff->answer) { /* restrict editing to current mapset */ if (strcmp(mapset, G_mapset()) != 0) G_fatal_error(_("Raster map <%s> not found in current mapset"), name); /* use cats from another map */ if (parm.raster->answer) { int fd; const char *cmapset; cmapset = G_find_raster2(parm.raster->answer, ""); if (cmapset == NULL) G_fatal_error(_("Raster map <%s> not found"), parm.raster->answer); fd = Rast_open_old(name, mapset); Rast_init_cats("", &cats); if (0 > Rast_read_cats(parm.raster->answer, cmapset, &cats)) G_fatal_error(_("Unable to read category file of raster map <%s@%s>"), parm.raster->answer, cmapset); Rast_write_cats(name, &cats); G_message(_("Category table for <%s> set from <%s>"), name, parm.raster->answer); Rast_close(fd); } /* load cats from rules file */ if (parm.file->answer) { FILE *fp; char **tokens; int ntokens; char *e1; char *e2; if (strcmp("-", parm.file->answer) == 0) { from_stdin = TRUE; fp = stdin; } else { fp = fopen(parm.file->answer, "r"); if (!fp) G_fatal_error(_("Unable to open file <%s>"), parm.file->answer); } Rast_init_cats("", &cats); for (;;) { char buf[1024]; DCELL d1, d2; int parse_error = 0; if (!G_getl2(buf, sizeof(buf), fp)) break; tokens = G_tokenize(buf, fs); ntokens = G_number_of_tokens(tokens); if (ntokens == 3) { d1 = strtod(tokens[0], &e1); d2 = strtod(tokens[1], &e2); if (*e1 == 0 && *e2 == 0) Rast_set_d_cat(&d1, &d2, tokens[2], &cats); else parse_error = 1; } else if (ntokens == 2) { d1 = strtod(tokens[0], &e1); if (*e1 == 0) Rast_set_d_cat(&d1, &d1, tokens[1], &cats); else parse_error = 1; } else if (!strlen(buf)) continue; else parse_error = 1; if (parse_error) G_fatal_error(_("Incorrect format of input rules. " "Check separators. Invalid line is:\n%s"), buf); } G_free_tokens(tokens); Rast_write_cats(name, &cats); if (!from_stdin) fclose(fp); } /* set dynamic cat rules for cats without explicit labels */ if (parm.fmt_str->answer || parm.fmt_coeff->answer) { char *fmt_str; double m1, a1, m2, a2; /* read existing values */ Rast_init_cats("", &cats); if (0 > Rast_read_cats(name, G_mapset(), &cats)) G_warning(_("Unable to read category file of raster map <%s@%s>"), name, G_mapset()); if (parm.fmt_str->answer) { fmt_str = G_malloc(strlen(parm.fmt_str->answer) > strlen(cats.fmt) ? strlen(parm.fmt_str->answer) + 1 : strlen(cats.fmt) + 1); strcpy(fmt_str, parm.fmt_str->answer); } else { fmt_str = G_malloc(strlen(cats.fmt) + 1); strcpy(fmt_str, cats.fmt); } m1 = cats.m1; a1 = cats.a1; m2 = cats.m2; a2 = cats.a2; if (parm.fmt_coeff->answer) { m1 = atof(parm.fmt_coeff->answers[0]); a1 = atof(parm.fmt_coeff->answers[1]); m2 = atof(parm.fmt_coeff->answers[2]); a2 = atof(parm.fmt_coeff->answers[3]); } Rast_set_cats_fmt(fmt_str, m1, a1, m2, a2, &cats); Rast_write_cats(name, &cats); } Rast_free_cats(&cats); exit(EXIT_SUCCESS); } else { if (Rast_read_cats(name, mapset, &cats) < 0) G_fatal_error(_("Unable to read category file of raster map <%s> in <%s>"), name, mapset); } /* describe the category labels */ /* if no cats requested, use r.describe to get the cats */ if (parm.cats->answer == NULL) { if (map_type == CELL_TYPE) { get_cats(name, mapset); while (next_cat(&x)) print_label(x); exit(EXIT_SUCCESS); } } else { if (map_type != CELL_TYPE) G_warning(_("The map is floating point! Ignoring cats list, using vals list")); else { /* integer map */ for (i = 0; parm.cats->answers[i]; i++) if (!scan_cats(parm.cats->answers[i], &x, &y)) { G_usage(); exit(EXIT_FAILURE); } for (i = 0; parm.cats->answers[i]; i++) { scan_cats(parm.cats->answers[i], &x, &y); while (x <= y) print_label(x++); } exit(EXIT_SUCCESS); } } if (parm.vals->answer == NULL) G_fatal_error(_("vals argument is required for floating point map!")); for (i = 0; parm.vals->answers[i]; i++) if (!scan_vals(parm.vals->answers[i], &dx)) { G_usage(); exit(EXIT_FAILURE); } for (i = 0; parm.vals->answers[i]; i++) { scan_vals(parm.vals->answers[i], &dx); print_d_label(dx); } exit(EXIT_SUCCESS); }
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); }
/*! \brief Get categories/labels Formats label as in d.what.rast -> (catval) catlabel \param filename raster map name \param drow \param dcol \param catstr category string \return 1 on success \return 0 on failure */ int Gs_get_cat_label(const char *filename, int drow, int dcol, char *catstr) { struct Categories cats; const char *mapset; CELL *buf; DCELL *dbuf; RASTER_MAP_TYPE map_type; int fd = -1; if ((mapset = G_find_raster2(filename, "")) == NULL) { G_warning(_("Raster map <%s> not found"), filename); return 0; } if (-1 != Rast_read_cats(filename, mapset, &cats)) { fd = Rast_open_old(filename, mapset); map_type = Rast_get_map_type(fd); if (map_type == CELL_TYPE) { buf = Rast_allocate_c_buf(); Rast_get_c_row(fd, buf, drow); if (Rast_is_c_null_value(&buf[dcol])) { sprintf(catstr, "(NULL) %s", Rast_get_c_cat(&buf[dcol], &cats)); } else { sprintf(catstr, "(%d) %s", buf[dcol], Rast_get_c_cat(&buf[dcol], &cats)); } G_free(buf); } else { /* fp map */ dbuf = Rast_allocate_d_buf(); Rast_get_d_row(fd, dbuf, drow); if (Rast_is_d_null_value(&dbuf[dcol])) { sprintf(catstr, "(NULL) %s", Rast_get_d_cat(&dbuf[dcol], &cats)); } else { sprintf(catstr, "(%g) %s", dbuf[dcol], Rast_get_d_cat(&dbuf[dcol], &cats)); } G_free(dbuf); } } else { strcpy(catstr, "no category label"); return 0; } /* TODO: may want to keep these around for multiple queries */ Rast_free_cats(&cats); if (fd >= 0) Rast_close(fd); return (1); }
/* * check_stats() - Check and update statistics * * RETURN: 0 on success / 1 on failure */ int check_stats(const char *name) { RASTER_MAP_TYPE data_type; struct Histogram histogram; struct Categories cats; struct Range range; struct FPRange fprange; int i, histo_num; int cats_ok; int max; data_type = Rast_map_type(name, ""); G_message(_("Updating statistics for [%s]..."), name); if (!do_histogram(name)) return 1; if (Rast_read_histogram(name, "", &histogram) <= 0) return 1; /* Init histogram range */ if (data_type == CELL_TYPE) Rast_init_range(&range); else Rast_init_fp_range(&fprange); G_message(_("Updating histogram range...")); i = histo_num = Rast_get_histogram_num(&histogram); while (i >= 0) { G_percent(i, histo_num, 2); if (data_type == CELL_TYPE) Rast_update_range(Rast_get_histogram_cat(i--, &histogram), &range); else Rast_update_fp_range((DCELL) Rast_get_histogram_cat(i--, &histogram), &fprange); } /* Write histogram range */ if (data_type == CELL_TYPE) Rast_write_range(name, &range); else Rast_write_fp_range(name, &fprange); /* Get category status and max */ cats_ok = (Rast_read_cats(name, "", &cats) >= 0); max = (data_type == CELL_TYPE ? range.max : fprange.max); /* Further category checks */ if (!cats_ok) Rast_init_cats("", &cats); else if (cats.num != max) { cats.num = max; cats_ok = 0; } /* Update categories if needed */ if (!cats_ok) { G_message(_("Updating the number of categories for [%s]..."), name); Rast_write_cats(name, &cats); } Rast_free_histogram(&histogram); Rast_free_cats(&cats); return 0; }
int main(int argc, char *argv[]) { int fd[NFILES]; int outfd; int i; const char *name; const char *output; const char *mapset; int non_zero; struct Range range; CELL ncats, max_cats; int primary; struct Categories pcats; struct Colors pcolr; char buf[1024]; CELL result; struct GModule *module; struct { struct Option *input, *output; } parm; struct { struct Flag *z; } flag; G_gisinit(argv[0]); /* Define the different options */ module = G_define_module(); G_add_keyword(_("raster")); G_add_keyword(_("statistics")); module->description = _("Creates a cross product of the category values from " "multiple raster map layers."); parm.input = G_define_option(); parm.input->key = "input"; parm.input->type = TYPE_STRING; parm.input->required = YES; parm.input->multiple = YES; parm.input->gisprompt = "old,cell,raster"; sprintf(buf, _("Names of 2-%d input raster maps"), NFILES); parm.input->description = G_store(buf); parm.output = G_define_standard_option(G_OPT_R_OUTPUT); /* Define the different flags */ flag.z = G_define_flag(); flag.z->key = 'z'; flag.z->description = _("Non-zero data only"); if (G_parser(argc, argv)) exit(EXIT_FAILURE); nrows = Rast_window_rows(); ncols = Rast_window_cols(); nfiles = 0; non_zero = flag.z->answer; for (nfiles = 0; (name = parm.input->answers[nfiles]); nfiles++) { if (nfiles >= NFILES) G_fatal_error(_("More than %d files not allowed"), NFILES); mapset = G_find_raster2(name, ""); if (!mapset) G_fatal_error(_("Raster map <%s> not found"), name); names[nfiles] = name; fd[nfiles] = Rast_open_old(name, mapset); Rast_read_range(name, mapset, &range); ncats = range.max - range.min; if (nfiles == 0 || ncats > max_cats) { primary = nfiles; max_cats = ncats; } } if (nfiles <= 1) G_fatal_error(_("Must specify 2 or more input maps")); output = parm.output->answer; outfd = Rast_open_c_new(output); sprintf(buf, "Cross of %s", names[0]); for (i = 1; i < nfiles - 1; i++) { strcat(buf, ", "); strcat(buf, names[i]); } strcat(buf, " and "); strcat(buf, names[i]); Rast_init_cats(buf, &pcats); /* first step is cross product, but un-ordered */ result = cross(fd, non_zero, primary, outfd); /* print message STEP mesage */ G_message(_("%s: STEP 2 ..."), G_program_name()); /* now close all files */ for (i = 0; i < nfiles; i++) Rast_close(fd[i]); Rast_close(outfd); if (result <= 0) exit(0); /* build the renumbering/reclass and the new cats file */ qsort(reclass, result + 1, sizeof(RECLASS), cmp); table = (CELL *) G_calloc(result + 1, sizeof(CELL)); for (i = 0; i < nfiles; i++) { mapset = G_find_raster2(names[i], ""); Rast_read_cats(names[i], mapset, &labels[i]); } for (ncats = 0; ncats <= result; ncats++) { table[reclass[ncats].result] = ncats; set_cat(ncats, reclass[ncats].cat, &pcats); } for (i = 0; i < nfiles; i++) Rast_free_cats(&labels[i]); /* reopen the output cell for reading and for writing */ fd[0] = Rast_open_old(output, G_mapset()); outfd = Rast_open_c_new(output); renumber(fd[0], outfd); G_message(_("Creating support files for <%s>..."), output); Rast_close(fd[0]); Rast_close(outfd); Rast_write_cats(output, &pcats); Rast_free_cats(&pcats); if (result > 0) { Rast_make_random_colors(&pcolr, (CELL) 1, result); Rast_write_colors(output, G_mapset(), &pcolr); } G_message(_("%ld categories"), (long)result); exit(EXIT_SUCCESS); }
int exec_rectify(char *extension, char *interp_method, char *angle_map) { char *name; char *mapset; char *result; char *type = "raster"; int n; struct Colors colr; struct Categories cats; struct History hist; int colr_ok, cats_ok; long start_time, rectify_time; double aver_z; int elevfd; struct cache *ebuffer; G_debug(1, "Open elevation raster: "); /* open elevation raster */ select_target_env(); G_set_window(&target_window); G_debug(1, "target window: rs=%d cs=%d n=%f s=%f w=%f e=%f\n", target_window.rows, target_window.cols, target_window.north, target_window.south, target_window.west, target_window.east); elevfd = Rast_open_old(elev_name, elev_mapset); if (elevfd < 0) { G_fatal_error(_("Could not open elevation raster")); return 1; } ebuffer = readcell(elevfd, seg_mb_elev, 1); select_target_env(); Rast_close(elevfd); /* get an average elevation of the control points */ /* this is used only if target cells have no elevation */ get_aver_elev(&group.control_points, &aver_z); G_message("-----------------------------------------------"); /* rectify each file */ for (n = 0; n < group.group_ref.nfiles; n++) { if (!ref_list[n]) continue; name = group.group_ref.file[n].name; mapset = group.group_ref.file[n].mapset; result = G_malloc(strlen(group.group_ref.file[n].name) + strlen(extension) + 1); strcpy(result, group.group_ref.file[n].name); strcat(result, extension); G_debug(2, "ORTHO RECTIFYING:"); G_debug(2, "NAME %s", name); G_debug(2, "MAPSET %s", mapset); G_debug(2, "RESULT %s", result); G_debug(2, "select_current_env..."); select_current_env(); cats_ok = Rast_read_cats(name, mapset, &cats) >= 0; colr_ok = Rast_read_colors(name, mapset, &colr) > 0; /* Initialze History */ if (Rast_read_history(name, mapset, &hist) < 0) Rast_short_history(result, type, &hist); G_debug(2, "reading was fine..."); time(&start_time); G_debug(2, "Starting the rectification..."); if (rectify(name, mapset, ebuffer, aver_z, result, interp_method)) { G_debug(2, "Done. Writing results..."); select_target_env(); if (cats_ok) { Rast_write_cats(result, &cats); Rast_free_cats(&cats); } if (colr_ok) { Rast_write_colors(result, G_mapset(), &colr); Rast_free_colors(&colr); } /* Write out History */ Rast_command_history(&hist); Rast_write_history(result, &hist); select_current_env(); time(&rectify_time); report(rectify_time - start_time, 1); } else report((long)0, 0); G_free(result); } close(ebuffer->fd); release_cache(ebuffer); if (angle_map) { camera_angle(angle_map); } return 0; }
int main(int argc, char *argv[]) { const char *mapset; struct GModule *module; struct Option *raster, *title_opt, *history_opt; struct Option *datasrc1_opt, *datasrc2_opt, *datadesc_opt; struct Option *map_opt, *units_opt, *vunits_opt; struct Option *load_opt, *save_opt; struct Flag *stats_flag; const char *infile; char title[MAX_TITLE_LEN + 1]; struct History hist; /* Initialize GIS engine */ G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("raster3d")); G_add_keyword(_("metadata")); G_add_keyword(_("voxel")); module->description = _("Allows creation and/or modification of " "3D raster map layer support files."); raster = G_define_standard_option(G_OPT_R3_MAP); title_opt = G_define_option(); title_opt->key = "title"; title_opt->key_desc = "phrase"; title_opt->type = TYPE_STRING; title_opt->required = NO; title_opt->description = _("Text to use for map title"); history_opt = G_define_option(); history_opt->key = "history"; history_opt->key_desc = "phrase"; history_opt->type = TYPE_STRING; history_opt->required = NO; history_opt->description = _("Text to append to the next line of the map's metadata file"); units_opt = G_define_option(); units_opt->key = "unit"; units_opt->type = TYPE_STRING; units_opt->required = NO; units_opt->description = _("The map data unit"); vunits_opt = G_define_option(); vunits_opt->key = "vunit"; vunits_opt->type = TYPE_STRING; vunits_opt->required = NO; vunits_opt->description = _("The vertical unit of the map"); datasrc1_opt = G_define_option(); datasrc1_opt->key = "source1"; datasrc1_opt->key_desc = "phrase"; datasrc1_opt->type = TYPE_STRING; datasrc1_opt->required = NO; datasrc1_opt->description = _("Text to use for data source, line 1"); datasrc2_opt = G_define_option(); datasrc2_opt->key = "source2"; datasrc2_opt->key_desc = "phrase"; datasrc2_opt->type = TYPE_STRING; datasrc2_opt->required = NO; datasrc2_opt->description = _("Text to use for data source, line 2"); datadesc_opt = G_define_option(); datadesc_opt->key = "description"; datadesc_opt->key_desc = "phrase"; datadesc_opt->type = TYPE_STRING; datadesc_opt->required = NO; datadesc_opt->description = _("Text to use for data description or keyword(s)"); map_opt = G_define_option(); map_opt->key = "raster"; map_opt->type = TYPE_STRING; map_opt->required = NO; map_opt->gisprompt = "old,cell,raster"; map_opt->description = _("Raster map from which to copy category table"); load_opt = G_define_standard_option(G_OPT_F_INPUT); load_opt->key = "loadhistory"; load_opt->required = NO; load_opt->description = _("Text file from which to load history"); save_opt = G_define_standard_option(G_OPT_F_OUTPUT); save_opt->key = "savehistory"; save_opt->required = NO; save_opt->description = _("Text file in which to save history"); stats_flag = G_define_flag(); stats_flag->key = 's'; stats_flag->description = _("Update range"); /* Parse command-line options */ if (G_parser(argc, argv)) exit(EXIT_FAILURE); /* Make sure raster exists and set mapset */ infile = raster->answer; mapset = G_find_raster3d(infile, G_mapset()); /* current mapset only for editing */ if (!mapset || strcmp(mapset, G_mapset()) != 0) G_fatal_error(_("3D raster map <%s> not found"), infile); if (title_opt->answer) { strncpy(title, title_opt->answer, MAX_TITLE_LEN); title[MAX_TITLE_LEN - 1] = '\0'; /* strncpy doesn't null terminate over-sized input */ G_strip(title); G_debug(3, "map title= [%s] (%d chars)", title, (int)strlen(title)); Rast3d_read_history(raster->answer, "", &hist); Rast_set_history(&hist, HIST_TITLE, title); Rast3d_write_history(raster->answer, &hist); } if (save_opt->answer) { FILE *fp = fopen(save_opt->answer, "w"); int i; if (!fp) G_fatal_error(_("Unable to open output file <%s>"), save_opt->answer); Rast3d_read_history(raster->answer, "", &hist); for (i = 0; i < Rast_history_length(&hist); i++) fprintf(fp, "%s\n", Rast_history_line(&hist, i)); fclose(fp); } if (load_opt->answer) { FILE *fp = fopen(load_opt->answer, "r"); if (!fp) G_fatal_error(_("Unable to open input file <%s>"), load_opt->answer); Rast3d_read_history(raster->answer, "", &hist); Rast_clear_history(&hist); for (;;) { char buf[80]; if (!G_getl2(buf, sizeof(buf), fp)) break; Rast_append_history(&hist, buf); } fclose(fp); Rast3d_write_history(raster->answer, &hist); } if (history_opt->answer) { Rast3d_read_history(raster->answer, "", &hist); /* two less than defined as if only one less a newline gets appended in the hist file. bug? */ /* Should be RECORD_LEN, but r.info truncates at > 71 chars */ if (strlen(history_opt->answer) > 71) { int i; for (i = 0; i < strlen(history_opt->answer); i += 71) { char buf[72]; strncpy(buf, &history_opt->answer[i], sizeof(buf)-1); buf[sizeof(buf)-1] = '\0'; Rast_append_history(&hist, buf); } } else Rast_append_history(&hist, history_opt->answer); Rast3d_write_history(raster->answer, &hist); } if(units_opt->answer || vunits_opt->answer) { RASTER3D_Map *map; map = Rast3d_open_cell_old(raster->answer, G_mapset(), \ RASTER3D_DEFAULT_WINDOW, RASTER3D_TILE_SAME_AS_FILE, RASTER3D_USE_CACHE_DEFAULT); /* Modify the units */ if (units_opt->answer) Rast3d_set_unit(map, units_opt->answer); if (vunits_opt->answer) Rast3d_set_vertical_unit(map, vunits_opt->answer); Rast3d_rewrite_header(map); Rast3d_close(map); } if (datasrc1_opt->answer || datasrc2_opt->answer || datadesc_opt->answer) { Rast3d_read_history(raster->answer, "", &hist); if (datasrc1_opt->answer) Rast_set_history(&hist, HIST_DATSRC_1, datasrc1_opt->answer); if (datasrc2_opt->answer) Rast_set_history(&hist, HIST_DATSRC_2, datasrc2_opt->answer); if (datadesc_opt->answer) Rast_set_history(&hist, HIST_KEYWRD, datadesc_opt->answer); Rast3d_write_history(raster->answer, &hist); } if (map_opt->answer) { /* use cats from another map */ int fd; struct Categories cats; fd = Rast_open_old(infile, ""); Rast_init_cats("", &cats); if (Rast3d_read_cats(map_opt->answer, "", &cats) < 0) G_fatal_error(_("Unable to read category file of raster map <%s>"), map_opt->answer); Rast3d_write_cats(infile, &cats); G_message(_("cats table for [%s] set to %s"), infile, map_opt->answer); Rast_close(fd); Rast_free_cats(&cats); } /* Check the histogram and range */ if (stats_flag->answer) check_stats(raster->answer); return EXIT_SUCCESS; }
int main(int argc, char *argv[]) { char rname[GNAME_MAX]; /* Reclassed map name */ char rmapset[GMAPSET_MAX]; /* Reclassed mapset */ const char *mapset; /* Raster mapset */ struct Cell_head cellhd; struct GModule *module; struct Option *raster, *title_opt, *history_opt; struct Option *datasrc1_opt, *datasrc2_opt, *datadesc_opt; struct Option *map_opt, *units_opt, *vdatum_opt; struct Option *load_opt, *save_opt; struct Flag *stats_flag, *null_flag, *del_flag; int is_reclass; /* Is raster reclass? */ const char *infile; char title[MAX_TITLE_LEN + 1]; struct History hist; /* Initialize GIS engine */ G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("raster")); G_add_keyword(_("metadata")); module->description = _("Allows creation and/or modification of " "raster map layer support files."); raster = G_define_standard_option(G_OPT_R_MAP); title_opt = G_define_option(); title_opt->key = "title"; title_opt->key_desc = "phrase"; title_opt->type = TYPE_STRING; title_opt->required = NO; title_opt->description = _("Title for resultant raster map"); history_opt = G_define_option(); history_opt->key = "history"; history_opt->key_desc = "phrase"; history_opt->type = TYPE_STRING; history_opt->required = NO; history_opt->description = _("Text to append to the next line of the map's metadata file"); units_opt = G_define_option(); units_opt->key = "units"; units_opt->type = TYPE_STRING; units_opt->required = NO; units_opt->description = _("Text to use for map data units"); vdatum_opt = G_define_option(); vdatum_opt->key = "vdatum"; vdatum_opt->type = TYPE_STRING; vdatum_opt->required = NO; vdatum_opt->description = _("Text to use for map vertical datum"); datasrc1_opt = G_define_option(); datasrc1_opt->key = "source1"; datasrc1_opt->key_desc = "phrase"; datasrc1_opt->type = TYPE_STRING; datasrc1_opt->required = NO; datasrc1_opt->description = _("Text to use for data source, line 1"); datasrc2_opt = G_define_option(); datasrc2_opt->key = "source2"; datasrc2_opt->key_desc = "phrase"; datasrc2_opt->type = TYPE_STRING; datasrc2_opt->required = NO; datasrc2_opt->description = _("Text to use for data source, line 2"); datadesc_opt = G_define_option(); datadesc_opt->key = "description"; datadesc_opt->key_desc = "phrase"; datadesc_opt->type = TYPE_STRING; datadesc_opt->required = NO; datadesc_opt->description = _("Text to use for data description or keyword(s)"); map_opt = G_define_option(); map_opt->key = "raster"; map_opt->type = TYPE_STRING; map_opt->required = NO; map_opt->gisprompt = "old,cell,raster"; map_opt->description = _("Raster map from which to copy category table"); load_opt = G_define_standard_option(G_OPT_F_INPUT); load_opt->key = "loadhistory"; load_opt->required = NO; load_opt->description = _("Text file from which to load history"); save_opt = G_define_standard_option(G_OPT_F_OUTPUT); save_opt->key = "savehistory"; save_opt->required = NO; save_opt->description = _("Text file in which to save history"); stats_flag = G_define_flag(); stats_flag->key = 's'; stats_flag->description = _("Update statistics (histogram, range)"); null_flag = G_define_flag(); null_flag->key = 'n'; null_flag->description = _("Create/reset the null file"); del_flag = G_define_flag(); del_flag->key = 'd'; del_flag->description = _("Delete the null file"); /* Parse command-line options */ if (G_parser(argc, argv)) exit(EXIT_FAILURE); /* Make sure raster exists and set mapset */ infile = raster->answer; mapset = G_find_raster2(infile, G_mapset()); /* current mapset only for editing */ if (!mapset || strcmp(mapset, G_mapset()) != 0) G_fatal_error(_("Raster map <%s> not found in current mapset"), infile); Rast_get_cellhd(raster->answer, "", &cellhd); is_reclass = (Rast_is_reclass(raster->answer, "", rname, rmapset) > 0); if (title_opt->answer) { strncpy(title, title_opt->answer, MAX_TITLE_LEN); title[MAX_TITLE_LEN - 1] = '\0'; /* strncpy doesn't null terminate oversized input */ G_strip(title); G_debug(3, "map title= [%s] (%li chars)", title, strlen(title)); Rast_read_history(raster->answer, "", &hist); Rast_set_history(&hist, HIST_TITLE, title); Rast_write_history(raster->answer, &hist); } if (save_opt->answer) { FILE *fp = fopen(save_opt->answer, "w"); int i; if (!fp) G_fatal_error(_("Unable to open output file <%s>"), save_opt->answer); Rast_read_history(raster->answer, "", &hist); for (i = 0; i < Rast_history_length(&hist); i++) fprintf(fp, "%s\n", Rast_history_line(&hist, i)); fclose(fp); } if (load_opt->answer) { FILE *fp = fopen(load_opt->answer, "r"); if (!fp) G_fatal_error(_("Unable to open input file <%s>"), load_opt->answer); Rast_read_history(raster->answer, "", &hist); Rast_clear_history(&hist); for (;;) { char buf[80]; if (!G_getl2(buf, sizeof(buf), fp)) break; Rast_append_history(&hist, buf); } fclose(fp); Rast_write_history(raster->answer, &hist); } if (history_opt->answer) { Rast_read_history(raster->answer, "", &hist); /* two less than defined as if only one less a newline gets appended in the hist file. bug? */ /* Should be RECORD_LEN, but r.info truncates at > 71 chars */ if (strlen(history_opt->answer) > 71) { int i; for (i = 0; i < strlen(history_opt->answer); i += 71) { char buf[72]; strncpy(buf, &history_opt->answer[i], sizeof(buf)-1); buf[sizeof(buf)-1] = '\0'; Rast_append_history(&hist, buf); } } else Rast_append_history(&hist, history_opt->answer); Rast_write_history(raster->answer, &hist); } if (units_opt->answer) Rast_write_units(raster->answer, units_opt->answer); if (vdatum_opt->answer) Rast_write_vdatum(raster->answer, vdatum_opt->answer); if (datasrc1_opt->answer || datasrc2_opt->answer || datadesc_opt->answer) { Rast_read_history(raster->answer, "", &hist); if (datasrc1_opt->answer) Rast_set_history(&hist, HIST_DATSRC_1, datasrc1_opt->answer); if (datasrc2_opt->answer) Rast_set_history(&hist, HIST_DATSRC_2, datasrc2_opt->answer); if (datadesc_opt->answer) Rast_set_history(&hist, HIST_KEYWRD, datadesc_opt->answer); Rast_write_history(raster->answer, &hist); } if (map_opt->answer) { /* use cats from another map */ int fd; struct Categories cats; fd = Rast_open_old(infile, ""); Rast_init_cats("", &cats); if (Rast_read_cats(map_opt->answer, "", &cats) < 0) G_fatal_error(_("Unable to read category file of raster map <%s>"), map_opt->answer); Rast_write_cats(infile, &cats); G_message(_("cats table for [%s] set to %s"), infile, map_opt->answer); Rast_close(fd); Rast_free_cats(&cats); } if (title_opt->answer || history_opt->answer || units_opt->answer || vdatum_opt->answer || datasrc1_opt->answer || datasrc2_opt->answer || datadesc_opt->answer || map_opt->answer) exit(EXIT_SUCCESS); /* Check the histogram and range */ if (stats_flag->answer) check_stats(raster->answer); /* null file */ if (null_flag->answer) { unsigned char *null_bits; int row, col; int fd; if (is_reclass) G_fatal_error(_("[%s] is a reclass of another map. Exiting."), raster->answer); /* Create a file of no-nulls */ null_bits = Rast__allocate_null_bits(cellhd.cols); for (col = 0; col < Rast__null_bitstream_size(cellhd.cols); col++) null_bits[col] = 0; /* Open null file for writing */ Rast_set_window(&cellhd); fd = Rast__open_null_write(raster->answer); G_message(_("Writing new null file for [%s]... "), raster->answer); for (row = 0; row < cellhd.rows; row++) { G_percent(row, cellhd.rows, 1); Rast__write_null_bits(fd, null_bits); } G_percent(row, cellhd.rows, 1); /* Cleanup */ Rast__close_null(fd); G_free(null_bits); } if (del_flag->answer) { char path[GPATH_MAX]; if (is_reclass) G_fatal_error(_("[%s] is a reclass of another map. Exiting."), raster->answer); /* Write a file of no-nulls */ G_message(_("Removing null file for [%s]...\n"), raster->answer); G_file_name_misc(path, "cell_misc", "null", raster->answer, G_mapset()); unlink(path); G_file_name_misc(path, "cell_misc", "null2", raster->answer, G_mapset()); unlink(path); G_done_msg(_("Done.")); } return EXIT_SUCCESS; }
static int close_new(RASTER3D_Map * map) { char path[GPATH_MAX]; struct Categories cats; struct History hist; Rast3d_remove_color(map->fileName); /* create empty cats file */ Rast_init_cats(NULL, &cats); Rast3d_write_cats(map->fileName, &cats); Rast_free_cats(&cats); /*generate the history file, use the normal G_ functions */ Rast_short_history(map->fileName, "raster3d", &hist); Rast_command_history(&hist); /*Use the G3d function to write the history file, * otherwise the path is wrong */ if (Rast3d_write_history(map->fileName, &hist) < 0) { G_warning(_("Unable to write history for 3D raster map <%s>"), map->fileName); } Rast3d_range_write(map); close(map->data_fd); /* finally move tempfile to data file */ Rast3d_filename(path, RASTER3D_CELL_ELEMENT, map->fileName, map->mapset); #ifdef __MINGW32__ if (CopyFile(map->tempName, path, FALSE) == 0) { #else if (link(map->tempName, path) < 0) { #endif if (rename(map->tempName, path)) { G_warning(_("Unable to move temp raster map <%s> to 3D raster map <%s>"), map->tempName, path); return 0; } } else remove(map->tempName); return 1; } static int close_cell_new(RASTER3D_Map * map) { long ltmp; if (map->useCache) if (!Rast3d_flush_all_tiles(map)) { G_warning(_("Unable to flush all tiles")); return 0; } if (!Rast3d_flush_index(map)) { G_warning(_("Unable to flush index")); return 0; } /* write the header info which was filled with dummy values at the */ /* opening time */ if (lseek(map->data_fd, (long)(map->offset - sizeof(int) - sizeof(long)), SEEK_SET) == -1) { G_warning(_("Unable to position file")); return 0; } if (!Rast3d_write_ints(map->data_fd, map->useXdr, &(map->indexNbytesUsed), 1)) { G_warning(_("Unable to write header for 3D raster map <%s>"), map->fileName); return 0; } Rast3d_long_encode(&(map->indexOffset), (unsigned char *)<mp, 1); if (write(map->data_fd, <mp, sizeof(long)) != sizeof(long)) { G_warning(_("Unable to write header for 3D raster map <%s>"), map->fileName); return 0; } if (!close_new(map) != 0) { G_warning(_("Unable to create 3D raster map <%s>"), map->fileName); return 0; } return 1; }