int get_range(const char *name, long *min, long *max) { struct Range range; int nrows, ncols, row, col; CELL *cell; int fd; CELL cmin, cmax; struct Cell_head cellhd; if (Rast_read_range(name, "", &range) < 0) { Rast_init_range(&range); /* read the file to get the range */ Rast_get_cellhd(name, "", &cellhd); Rast_set_window(&cellhd); cell = Rast_allocate_c_buf(); fd = Rast_open_old(name, ""); nrows = Rast_window_rows(); ncols = Rast_window_cols(); G_message(_("Reading %s ..."), name); for (row = 0; row < nrows; row++) { G_percent(row, nrows, 2); Rast_get_c_row_nomask(fd, cell, row); for (col = 0; col < ncols; col++) Rast_update_range(cell[col], &range); } G_percent(row, nrows, 2); Rast_close(fd); G_free(cell); } Rast_get_range_min_max(&range, &cmin, &cmax); *min = cmin; *max = cmax; return 0; }
int open_map(MAPS* rast) { int row, col; int fd; char* mapset; struct Cell_head cellhd; int bufsize; void* tmp_buf; mapset = (char*)G_find_raster2(rast->elevname, ""); if (mapset == NULL) G_fatal_error(_("Raster map <%s> not found"), rast->elevname); rast->fd = Rast_open_old(rast->elevname, mapset); Rast_get_cellhd(rast->elevname, mapset, &cellhd); rast->raster_type = Rast_map_type(rast->elevname, mapset); if (window.ew_res < cellhd.ew_res || window.ns_res < cellhd.ns_res) G_warning(_("Region resolution shoudn't be lesser than map %s resolution. Run g.region rast=%s to set proper resolution"), rast->elevname, rast->elevname); tmp_buf=Rast_allocate_buf(rast->raster_type); rast->elev = (FCELL**) G_malloc((row_buffer_size+1) * sizeof(FCELL*)); for (row = 0; row < row_buffer_size+1; ++row) { rast->elev[row] = Rast_allocate_buf(FCELL_TYPE); Rast_get_row(rast->fd, tmp_buf,row, rast->raster_type); for (col=0;col<ncols;++col) get_cell(col, rast->elev[row], tmp_buf, rast->raster_type); } /* end elev */ G_free(tmp_buf); return 0; }
int get_stats(const char *name, struct Cell_stats *statf) { int fd; CELL *cell; int row, nrows, ncols; fd = Rast_open_old(name, ""); nrows = Rast_window_rows(); ncols = Rast_window_cols(); cell = Rast_allocate_c_buf(); Rast_init_cell_stats(statf); G_message(_("Reading %s ..."), name); for (row = 0; row < nrows; row++) { G_percent(row, nrows, 2); Rast_get_c_row(fd, cell, row); Rast_update_cell_stats(cell, ncols, statf); } if (row < nrows) exit(1); Rast_close(fd); G_free(cell); G_percent(row, nrows, 2); return 0; }
int cseg_read_cell(CSEG * cseg, char *map_name, char *mapset) { GW_LARGE_INT row, nrows; int map_fd; CELL *buffer; cseg->name = NULL; cseg->mapset = NULL; map_fd = Rast_open_old(map_name, mapset); nrows = Rast_window_rows(); buffer = Rast_allocate_c_buf(); for (row = 0; row < nrows; row++) { Rast_get_c_row(map_fd, buffer, row); if (Segment_put_row(&(cseg->seg), buffer, row) < 0) { G_free(buffer); Rast_close(map_fd); G_warning("%s(): unable to segment put row for [%s] in [%s]", me, map_name, mapset); return (-1); } } Rast_close(map_fd); G_free(buffer); cseg->name = G_store(map_name); cseg->mapset = G_store(mapset); return 0; }
/* ************************************************************************* */ int open_input_map(const char *name, const char *mapset) { G_debug(3, "Open raster file %s in mapset %s", name, mapset); /* open raster map */ return Rast_open_old(name, mapset); }
int distdrop ( cell_map *elev, cell_map *dist, cell_map *dir, cell_map *up, cell_map *dw, seg_map *segment_info, move *movements, queue **redo_segments) { int all_done = 1; int **neighbours = new_int_map ( ( int ) sizeof ( movements ), ( int ) sizeof ( movements[0] ), NULL ); elev->fd = Rast_open_old ( elev->name, "" ); elev->type = Rast_get_map_type( elev->fd ); init_seg_map(elev, segment_info); copy_segment(elev, 0); //print_map_with_seg ( elev, segment_info ); while ( all_done ){ // if all_done != 0? continue: break all_done = queue_pixel ( redo_segments, elev, dist, dir, up, dw, segment_info, movements, neighbours); } return 0; }
void openfiles(char *r_name, char *g_name, char *b_name, char *h_name, char *i_name, char *s_name, int fd_input[3], int fd_output[3], CELL * rowbuf[3]) { fd_input[0] = Rast_open_old(r_name, ""); fd_input[1] = Rast_open_old(g_name, ""); fd_input[2] = Rast_open_old(b_name, ""); /* open output files */ fd_output[0] = Rast_open_c_new(h_name); fd_output[1] = Rast_open_c_new(i_name); fd_output[2] = Rast_open_c_new(s_name); /* allocate the cell row buffer */ rowbuf[0] = Rast_allocate_c_buf(); rowbuf[1] = Rast_allocate_c_buf(); rowbuf[2] = Rast_allocate_c_buf(); }
void openfiles(char *h_name, char *i_name, char *s_name, char *r_name, char *g_name, char *b_name, int fd_input[3], int fd_output[3], CELL * rowbuf[3]) { /* open output files */ fd_output[0] = Rast_open_c_new(r_name); fd_output[1] = Rast_open_c_new(g_name); fd_output[2] = Rast_open_c_new(b_name); /* allocate the cell row buffer */ rowbuf[0] = Rast_allocate_c_buf(); rowbuf[1] = Rast_allocate_c_buf(); rowbuf[2] = Rast_allocate_c_buf(); /* open input files (maps can be in different mapsets) */ fd_input[0] = Rast_open_old(h_name, ""); fd_input[1] = Rast_open_old(i_name, ""); fd_input[2] = Rast_open_old(s_name, ""); }
/*! \brief Load raster map as integer map Calling function must have already allocated space in buff for struct BM of wind->rows & wind->cols. This routine simply loads the map into the bitmap by repetitve calls to get_map_row. Any value other than 0 in the map will set the bitmap. (may want to change later to allow specific value to set) Changed to use null. \param wind current window \param map_name raster map name \param[out] buff data buffer \returns 1 on success \return -1 on failure */ int Gs_loadmap_as_bitmap(struct Cell_head *wind, const char *map_name, struct BM *buff) { FILEDESC cellfile; const char *map_set; int *tmp_buf; int row, col; G_debug(3, "Gs_loadmap_as_bitmap"); map_set = G_find_raster2(map_name, ""); if (!map_set) { G_warning(_("Raster map <%s> not found"), map_name); return -1; } cellfile = Rast_open_old(map_name, map_set); tmp_buf = (int *)G_malloc(wind->cols * sizeof(int)); /* G_fatal_error */ if (!tmp_buf) { return -1; } G_message(_("Loading raster map <%s>..."), G_fully_qualified_name(map_name, map_set)); for (row = 0; row < wind->rows; row++) { Rast_get_c_row(cellfile, tmp_buf, row); for (col = 0; col < wind->cols; col++) { if (Rast_is_c_null_value(&tmp_buf[col])) { /* no data */ BM_set(buff, col, row, 1); } else { BM_set(buff, col, row, 0); } } } Rast_close(cellfile); G_free(tmp_buf); return (1); }
/*! \brief Load raster map as floating point map Calling function must have already allocated space in buff for wind->rows * wind->cols floats. This routine simply loads the map into a 2d array by repetitve calls to get_f_raster_row. \param wind current window \param map_name raster map name \param[out] buff data buffer \param[out] nullmap null map buffer \param[out] has_null indicates if raster map contains null-data \return 1 on success \return 0 on failure */ int Gs_loadmap_as_float(struct Cell_head *wind, const char *map_name, float *buff, struct BM *nullmap, int *has_null) { FILEDESC cellfile; const char *map_set; int offset, row, col; G_debug(3, "Gs_loadmap_as_float(): name=%s", map_name); map_set = G_find_raster2(map_name, ""); if (!map_set) { G_warning(_("Raster map <%s> not found"), map_name); return 0; } *has_null = 0; cellfile = Rast_open_old(map_name, map_set); G_message(_("Loading raster map <%s>..."), G_fully_qualified_name(map_name, map_set)); for (row = 0; row < wind->rows; row++) { offset = row * wind->cols; Rast_get_f_row(cellfile, &(buff[offset]), row); G_percent(row, wind->rows, 2); for (col = 0; col < wind->cols; col++) { if (Rast_is_f_null_value(buff + offset + col)) { *has_null = 1; BM_set(nullmap, col, row, 1); } /* set nm */ } } G_percent(1, 1, 1); G_debug(4, " has_null=%d", *has_null); Rast_close(cellfile); return (1); }
/*! \brief Open and allocate space for the group band files. \param refer pointer to band files structure \param[out] band_buffer buffer to read one row of each band \param[out] band_fd band files descriptors */ void open_band_files(struct Ref *refer, CELL *** band_buffer, int **band_fd) { int n, nbands; char *name, *mapset; G_debug(3, "open_band_files()"); /* allocate row buffers and open raster maps */ nbands = refer->nfiles; *band_buffer = (CELL **) G_malloc(nbands * sizeof(CELL *)); *band_fd = (int *)G_malloc(nbands * sizeof(int)); for (n = 0; n < nbands; n++) { (*band_buffer)[n] = Rast_allocate_c_buf(); name = refer->file[n].name; mapset = refer->file[n].mapset; (*band_fd)[n] = Rast_open_old(name, mapset); } }
void rast_segment_open(SEGMENT * segment, const char *name, RASTER_MAP_TYPE * map_type) { /* TODO: check if not passing the mapset is OK */ int rowio = Rast_open_old(name, ""); *map_type = Rast_get_map_type(rowio); int segment_rows = 64; /* we use long segments because this is how the values a binned */ int segment_cols = Rast_input_window_cols(); int segments_in_memory = 4; if (Segment_open(segment, G_tempfile(), Rast_input_window_rows(), Rast_input_window_cols(), segment_rows, segment_cols, Rast_cell_size(*map_type), segments_in_memory) != 1) G_fatal_error(_("Cannot create temporary file with segments of a raster map")); rast_segment_load(segment, rowio, *map_type); Rast_close(rowio); /* we won't need the raster again */ }
int get_cats(const char *name, const char *mapset) { int fd; int row, nrows, ncols; CELL *cell; struct Cell_head cellhd; /* set the window to the cell header */ Rast_get_cellhd(name, mapset, &cellhd); Rast_set_window(&cellhd); /* open the raster map */ fd = Rast_open_old(name, mapset); nrows = Rast_window_rows(); ncols = Rast_window_cols(); cell = Rast_allocate_c_buf(); Rast_init_cell_stats(&statf); /* read the raster map */ G_verbose_message(_("Reading <%s> in <%s>"), name, mapset); for (row = 0; row < nrows; row++) { if (G_verbose() > G_verbose_std()) G_percent(row, nrows, 2); Rast_get_c_row_nomask(fd, cell, row); Rast_update_cell_stats(cell, ncols, &statf); } /* done */ if (G_verbose() > G_verbose_std()) G_percent(row, nrows, 2); Rast_close(fd); G_free(cell); Rast_rewind_cell_stats(&statf); return 0; }
/* * do_histogram() - Creates histogram for CELL * * RETURN: EXIT_SUCCESS / EXIT_FAILURE */ int do_histogram(const char *name) { CELL *cell; struct Cell_head cellhd; struct Cell_stats statf; int nrows, ncols; int row; int fd; Rast_get_cellhd(name, "", &cellhd); Rast_set_window(&cellhd); fd = Rast_open_old(name, ""); nrows = Rast_window_rows(); ncols = Rast_window_cols(); cell = Rast_allocate_c_buf(); Rast_init_cell_stats(&statf); for (row = 0; row < nrows; row++) { Rast_get_c_row_nomask(fd, cell, row); Rast_update_cell_stats(cell, ncols, &statf); } if (row == nrows) Rast_write_histogram_cs(name, &statf); Rast_free_cell_stats(&statf); Rast_close(fd); G_free(cell); if (row < nrows) return -1; return 0; }
int camera_angle(char *name) { int row, col, nrows, ncols; double XC = group.XC; double YC = group.YC; double ZC = group.ZC; double c_angle, c_angle_min, c_alt, c_az, slope, aspect; double radians_to_degrees = 180.0 / M_PI; /* double degrees_to_radians = M_PI / 180.0; */ DCELL e1, e2, e3, e4, e5, e6, e7, e8, e9; double factor, V, H, dx, dy, dz, key; double north, south, east, west, ns_med; FCELL *fbuf0, *fbuf1, *fbuf2, *tmpbuf, *outbuf; int elevfd, outfd; struct Cell_head cellhd; struct Colors colr; FCELL clr_min, clr_max; struct History hist; char *type; G_message(_("Calculating camera angle to local surface...")); select_target_env(); /* align target window to elevation map, otherwise we get artefacts * like in r.slope.aspect -a */ Rast_get_cellhd(elev_name, elev_mapset, &cellhd); Rast_align_window(&target_window, &cellhd); Rast_set_window(&target_window); elevfd = Rast_open_old(elev_name, elev_mapset); if (elevfd < 0) { G_fatal_error(_("Could not open elevation raster")); return 1; } nrows = target_window.rows; ncols = target_window.cols; outfd = Rast_open_new(name, FCELL_TYPE); fbuf0 = Rast_allocate_buf(FCELL_TYPE); fbuf1 = Rast_allocate_buf(FCELL_TYPE); fbuf2 = Rast_allocate_buf(FCELL_TYPE); outbuf = Rast_allocate_buf(FCELL_TYPE); /* give warning if location units are different from meters and zfactor=1 */ factor = G_database_units_to_meters_factor(); if (factor != 1.0) G_warning(_("Converting units to meters, factor=%.6f"), factor); G_begin_distance_calculations(); north = Rast_row_to_northing(0.5, &target_window); ns_med = Rast_row_to_northing(1.5, &target_window); south = Rast_row_to_northing(2.5, &target_window); east = Rast_col_to_easting(2.5, &target_window); west = Rast_col_to_easting(0.5, &target_window); V = G_distance(east, north, east, south) * 4; H = G_distance(east, ns_med, west, ns_med) * 4; c_angle_min = 90; Rast_get_row(elevfd, fbuf1, 0, FCELL_TYPE); Rast_get_row(elevfd, fbuf2, 1, FCELL_TYPE); for (row = 0; row < nrows; row++) { G_percent(row, nrows, 2); Rast_set_null_value(outbuf, ncols, FCELL_TYPE); /* first and last row */ if (row == 0 || row == nrows - 1) { Rast_put_row(outfd, outbuf, FCELL_TYPE); continue; } tmpbuf = fbuf0; fbuf0 = fbuf1; fbuf1 = fbuf2; fbuf2 = tmpbuf; Rast_get_row(elevfd, fbuf2, row + 1, FCELL_TYPE); north = Rast_row_to_northing(row + 0.5, &target_window); for (col = 1; col < ncols - 1; col++) { e1 = fbuf0[col - 1]; if (Rast_is_d_null_value(&e1)) continue; e2 = fbuf0[col]; if (Rast_is_d_null_value(&e2)) continue; e3 = fbuf0[col + 1]; if (Rast_is_d_null_value(&e3)) continue; e4 = fbuf1[col - 1]; if (Rast_is_d_null_value(&e4)) continue; e5 = fbuf1[col]; if (Rast_is_d_null_value(&e5)) continue; e6 = fbuf1[col + 1]; if (Rast_is_d_null_value(&e6)) continue; e7 = fbuf2[col - 1]; if (Rast_is_d_null_value(&e7)) continue; e8 = fbuf2[col]; if (Rast_is_d_null_value(&e8)) continue; e9 = fbuf2[col + 1]; if (Rast_is_d_null_value(&e9)) continue; dx = ((e1 + e4 + e4 + e7) - (e3 + e6 + e6 + e9)) / H; dy = ((e7 + e8 + e8 + e9) - (e1 + e2 + e2 + e3)) / V; /* compute topographic parameters */ key = dx * dx + dy * dy; /* slope in radians */ slope = atan(sqrt(key)); /* aspect in radians */ if (key == 0.) aspect = 0.; else if (dx == 0) { if (dy > 0) aspect = M_PI / 2; else aspect = 1.5 * M_PI; } else { aspect = atan2(dy, dx); if (aspect <= 0.) aspect = 2 * M_PI + aspect; } /* camera altitude angle in radians */ east = Rast_col_to_easting(col + 0.5, &target_window); dx = east - XC; dy = north - YC; dz = ZC - e5; c_alt = atan(sqrt(dx * dx + dy * dy) / dz); /* camera azimuth angle in radians */ c_az = atan(dy / dx); if (east < XC && north != YC) c_az += M_PI; else if (north < YC && east > XC) c_az += 2 * M_PI; /* camera angle to real ground */ /* orthogonal to ground: 90 degrees */ /* parallel to ground: 0 degrees */ c_angle = asin(cos(c_alt) * cos(slope) - sin(c_alt) * sin(slope) * cos(c_az - aspect)); outbuf[col] = c_angle * radians_to_degrees; if (c_angle_min > outbuf[col]) c_angle_min = outbuf[col]; } Rast_put_row(outfd, outbuf, FCELL_TYPE); } G_percent(row, nrows, 2); Rast_close(elevfd); Rast_close(outfd); G_free(fbuf0); G_free(fbuf1); G_free(fbuf2); G_free(outbuf); type = "raster"; Rast_short_history(name, type, &hist); Rast_command_history(&hist); Rast_write_history(name, &hist); Rast_init_colors(&colr); if (c_angle_min < 0) { clr_min = (FCELL)((int)(c_angle_min / 10 - 1)) * 10; clr_max = 0; Rast_add_f_color_rule(&clr_min, 0, 0, 0, &clr_max, 0, 0, 0, &colr); } clr_min = 0; clr_max = 10; Rast_add_f_color_rule(&clr_min, 0, 0, 0, &clr_max, 255, 0, 0, &colr); clr_min = 10; clr_max = 40; Rast_add_f_color_rule(&clr_min, 255, 0, 0, &clr_max, 255, 255, 0, &colr); clr_min = 40; clr_max = 90; Rast_add_f_color_rule(&clr_min, 255, 255, 0, &clr_max, 0, 255, 0, &colr); Rast_write_colors(name, G_mapset(), &colr); select_current_env(); return 1; }
int main(int argc, char *argv[]) { int i, j, nlines, type, field, cat; int fd; /* struct Categories RCats; *//* TODO */ struct Cell_head window; RASTER_MAP_TYPE out_type; CELL *cell; DCELL *dcell; double drow, dcol; char buf[2000]; struct Option *vect_opt, *rast_opt, *field_opt, *col_opt, *where_opt; int Cache_size; struct order *cache; int cur_row; struct GModule *module; struct Map_info Map; struct line_pnts *Points; struct line_cats *Cats; int point; int point_cnt; /* number of points in cache */ int outside_cnt; /* points outside region */ int nocat_cnt; /* points inside region but without category */ int dupl_cnt; /* duplicate categories */ struct bound_box box; int *catexst, *cex; struct field_info *Fi; dbString stmt; dbDriver *driver; int select, norec_cnt, update_cnt, upderr_cnt, col_type; G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("vector")); G_add_keyword(_("raster")); G_add_keyword(_("position")); G_add_keyword(_("querying")); G_add_keyword(_("attribute table")); module->description = _("Uploads raster values at positions of vector points to the table."); vect_opt = G_define_standard_option(G_OPT_V_INPUT); vect_opt->key = "vector"; vect_opt->description = _("Name of input vector points map for which to edit attribute table"); rast_opt = G_define_standard_option(G_OPT_R_INPUT); rast_opt->key = "raster"; rast_opt->description = _("Name of existing raster map to be queried"); field_opt = G_define_standard_option(G_OPT_V_FIELD); col_opt = G_define_option(); col_opt->key = "column"; col_opt->type = TYPE_STRING; col_opt->required = YES; col_opt->description = _("Column name (will be updated by raster values)"); where_opt = G_define_standard_option(G_OPT_DB_WHERE); if (G_parser(argc, argv)) exit(EXIT_FAILURE); field = atoi(field_opt->answer); db_init_string(&stmt); Points = Vect_new_line_struct(); Cats = Vect_new_cats_struct(); G_get_window(&window); Vect_region_box(&window, &box); /* T and B set to +/- PORT_DOUBLE_MAX */ /* Open vector */ Vect_set_open_level(2); Vect_open_old(&Map, vect_opt->answer, ""); Fi = Vect_get_field(&Map, field); if (Fi == NULL) G_fatal_error(_("Database connection not defined for layer %d"), field); /* Open driver */ driver = db_start_driver_open_database(Fi->driver, Fi->database); if (driver == NULL) { G_fatal_error(_("Unable to open database <%s> by driver <%s>"), Fi->database, Fi->driver); } /* Open raster */ fd = Rast_open_old(rast_opt->answer, ""); out_type = Rast_get_map_type(fd); /* TODO: Later possibly category labels */ /* if ( Rast_read_cats (name, "", &RCats) < 0 ) G_fatal_error ( "Cannot read category file"); */ /* Check column type */ col_type = db_column_Ctype(driver, Fi->table, col_opt->answer); if (col_type == -1) G_fatal_error(_("Column <%s> not found"), col_opt->answer); if (col_type != DB_C_TYPE_INT && col_type != DB_C_TYPE_DOUBLE) G_fatal_error(_("Column type not supported")); if (out_type == CELL_TYPE && col_type == DB_C_TYPE_DOUBLE) G_warning(_("Raster type is integer and column type is float")); if (out_type != CELL_TYPE && col_type == DB_C_TYPE_INT) G_warning(_("Raster type is float and column type is integer, some data lost!!")); /* Read vector points to cache */ Cache_size = Vect_get_num_primitives(&Map, GV_POINT); /* Note: Some space may be wasted (outside region or no category) */ cache = (struct order *)G_calloc(Cache_size, sizeof(struct order)); point_cnt = outside_cnt = nocat_cnt = 0; nlines = Vect_get_num_lines(&Map); G_debug(1, "Reading %d vector features fom map", nlines); for (i = 1; i <= nlines; i++) { type = Vect_read_line(&Map, Points, Cats, i); G_debug(4, "line = %d type = %d", i, type); /* check type */ if (!(type & GV_POINT)) continue; /* Points only */ /* check region */ if (!Vect_point_in_box(Points->x[0], Points->y[0], 0.0, &box)) { outside_cnt++; continue; } Vect_cat_get(Cats, field, &cat); if (cat < 0) { /* no category of given field */ nocat_cnt++; continue; } G_debug(4, " cat = %d", cat); /* Add point to cache */ drow = Rast_northing_to_row(Points->y[0], &window); dcol = Rast_easting_to_col(Points->x[0], &window); /* a special case. * if north falls at southern edge, or east falls on eastern edge, * the point will appear outside the window. * So, for these edges, bring the point inside the window */ if (drow == window.rows) drow--; if (dcol == window.cols) dcol--; cache[point_cnt].row = (int)drow; cache[point_cnt].col = (int)dcol; cache[point_cnt].cat = cat; cache[point_cnt].count = 1; point_cnt++; } Vect_set_db_updated(&Map); Vect_hist_command(&Map); Vect_close(&Map); G_debug(1, "Read %d vector points", point_cnt); /* Cache may contain duplicate categories, sort by cat, find and remove duplicates * and recalc count and decrease point_cnt */ qsort(cache, point_cnt, sizeof(struct order), by_cat); G_debug(1, "Points are sorted, starting duplicate removal loop"); for (i = 0, j = 1; j < point_cnt; j++) if (cache[i].cat != cache[j].cat) cache[++i] = cache[j]; else cache[i].count++; point_cnt = i + 1; G_debug(1, "%d vector points left after removal of duplicates", point_cnt); /* Report number of points not used */ if (outside_cnt) G_warning(_("%d points outside current region were skipped"), outside_cnt); if (nocat_cnt) G_warning(_("%d points without category were skipped"), nocat_cnt); /* Sort cache by current region row */ qsort(cache, point_cnt, sizeof(struct order), by_row); /* Allocate space for raster row */ if (out_type == CELL_TYPE) cell = Rast_allocate_c_buf(); else dcell = Rast_allocate_d_buf(); /* Extract raster values from file and store in cache */ G_debug(1, "Extracting raster values"); cur_row = -1; for (point = 0; point < point_cnt; point++) { if (cache[point].count > 1) continue; /* duplicate cats */ if (cur_row != cache[point].row) { if (out_type == CELL_TYPE) Rast_get_c_row(fd, cell, cache[point].row); else Rast_get_d_row(fd, dcell, cache[point].row); } cur_row = cache[point].row; if (out_type == CELL_TYPE) { cache[point].value = cell[cache[point].col]; } else { cache[point].dvalue = dcell[cache[point].col]; } } /* point loop */ /* Update table from cache */ G_debug(1, "Updating db table"); /* select existing categories to array (array is sorted) */ select = db_select_int(driver, Fi->table, Fi->key, NULL, &catexst); db_begin_transaction(driver); norec_cnt = update_cnt = upderr_cnt = dupl_cnt = 0; for (point = 0; point < point_cnt; point++) { if (cache[point].count > 1) { G_warning(_("More points (%d) of category %d, value set to 'NULL'"), cache[point].count, cache[point].cat); dupl_cnt++; } /* category exist in DB ? */ cex = (int *)bsearch((void *)&(cache[point].cat), catexst, select, sizeof(int), srch_cat); if (cex == NULL) { /* cat does not exist in DB */ norec_cnt++; G_warning(_("No record for category %d in table <%s>"), cache[point].cat, Fi->table); continue; } sprintf(buf, "update %s set %s = ", Fi->table, col_opt->answer); db_set_string(&stmt, buf); if (out_type == CELL_TYPE) { if (cache[point].count > 1 || Rast_is_c_null_value(&cache[point].value)) { sprintf(buf, "NULL"); } else { sprintf(buf, "%d ", cache[point].value); } } else { /* FCELL or DCELL */ if (cache[point].count > 1 || Rast_is_d_null_value(&cache[point].dvalue)) { sprintf(buf, "NULL"); } else { sprintf(buf, "%.10f", cache[point].dvalue); } } db_append_string(&stmt, buf); sprintf(buf, " where %s = %d", Fi->key, cache[point].cat); db_append_string(&stmt, buf); /* user provides where condition: */ if (where_opt->answer) { sprintf(buf, " AND %s", where_opt->answer); db_append_string(&stmt, buf); } G_debug(3, db_get_string(&stmt)); /* Update table */ if (db_execute_immediate(driver, &stmt) == DB_OK) { update_cnt++; } else { upderr_cnt++; } } G_debug(1, "Committing DB transaction"); db_commit_transaction(driver); G_free(catexst); db_close_database_shutdown_driver(driver); db_free_string(&stmt); /* Report */ G_message(_("%d categories loaded from table"), select); G_message(_("%d categories loaded from vector"), point_cnt); G_message(_("%d categories from vector missing in table"), norec_cnt); G_message(_("%d duplicate categories in vector"), dupl_cnt); if (!where_opt->answer) G_message(_("%d records updated"), update_cnt); G_message(_("%d update errors"), upderr_cnt); exit(EXIT_SUCCESS); }
int main(int argc, char **argv) { struct Cell_head window; RASTER_MAP_TYPE raster_type, mag_raster_type = -1; int layer_fd; void *raster_row, *ptr; int nrows, ncols; int aspect_c = -1; float aspect_f = -1.0; double scale; int skip, no_arrow; char *mag_map = NULL; void *mag_raster_row = NULL, *mag_ptr = NULL; double length = -1; int mag_fd = -1; struct FPRange range; double mag_min, mag_max; struct GModule *module; struct Option *opt1, *opt2, *opt3, *opt4, *opt5, *opt6, *opt7, *opt8, *opt9; struct Flag *align; double t, b, l, r; G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("display")); G_add_keyword(_("raster")); module->description = _("Draws arrows representing cell aspect direction " "for a raster map containing aspect data."); opt1 = G_define_standard_option(G_OPT_R_MAP); opt1->description = _("Name of raster aspect map to be displayed"); opt2 = G_define_option(); opt2->key = "type"; opt2->type = TYPE_STRING; opt2->required = NO; opt2->answer = "grass"; opt2->options = "grass,compass,agnps,answers"; opt2->description = _("Type of existing raster aspect map"); opt3 = G_define_option(); opt3->key = "arrow_color"; opt3->type = TYPE_STRING; opt3->required = NO; opt3->answer = "green"; opt3->gisprompt = "old_color,color,color"; opt3->description = _("Color for drawing arrows"); opt3->guisection = _("Colors"); opt4 = G_define_option(); opt4->key = "grid_color"; opt4->type = TYPE_STRING; opt4->required = NO; opt4->answer = "gray"; opt4->gisprompt = "old_color,color,color_none"; opt4->description = _("Color for drawing grid or \"none\""); opt4->guisection = _("Colors"); opt5 = G_define_option(); opt5->key = "x_color"; opt5->type = TYPE_STRING; opt5->required = NO; opt5->answer = DEFAULT_FG_COLOR; opt5->gisprompt = "old_color,color,color_none"; opt5->description = _("Color for drawing X's (null values)"); opt5->guisection = _("Colors"); opt6 = G_define_option(); opt6->key = "unknown_color"; opt6->type = TYPE_STRING; opt6->required = NO; opt6->answer = "red"; opt6->gisprompt = "old_color,color,color_none"; opt6->description = _("Color for showing unknown information"); opt6->guisection = _("Colors"); opt9 = G_define_option(); opt9->key = "skip"; opt9->type = TYPE_INTEGER; opt9->required = NO; opt9->answer = "1"; opt9->description = _("Draw arrow every Nth grid cell"); opt7 = G_define_option(); opt7->key = "magnitude_map"; opt7->type = TYPE_STRING; opt7->required = NO; opt7->multiple = NO; opt7->gisprompt = "old,cell,raster"; opt7->description = _("Raster map containing values used for arrow length"); opt8 = G_define_option(); opt8->key = "scale"; opt8->type = TYPE_DOUBLE; opt8->required = NO; opt8->answer = "1.0"; opt8->description = _("Scale factor for arrows (magnitude map)"); align = G_define_flag(); align->key = 'a'; align->description = _("Align grids with raster cells"); /* Check command line */ if (G_parser(argc, argv)) exit(EXIT_FAILURE); layer_name = opt1->answer; arrow_color = D_translate_color(opt3->answer); x_color = D_translate_color(opt5->answer); unknown_color = D_translate_color(opt6->answer); if (strcmp("none", opt4->answer) == 0) grid_color = -1; else grid_color = D_translate_color(opt4->answer); if (strcmp("grass", opt2->answer) == 0) map_type = 1; else if (strcmp("agnps", opt2->answer) == 0) map_type = 2; else if (strcmp("answers", opt2->answer) == 0) map_type = 3; else if (strcmp("compass", opt2->answer) == 0) map_type = 4; scale = atof(opt8->answer); if (scale <= 0.0) G_fatal_error(_("Illegal value for scale factor")); skip = atoi(opt9->answer); if (skip <= 0) G_fatal_error(_("Illegal value for skip factor")); if (opt7->answer) { if (map_type != 1 && map_type != 4) G_fatal_error(_("Magnitude is only supported for GRASS and compass aspect maps.")); mag_map = opt7->answer; } else if (scale != 1.0) G_warning(_("Scale option requires magnitude_map")); /* Setup driver and check important information */ if (D_open_driver() != 0) G_fatal_error(_("No graphics device selected. " "Use d.mon to select graphics device.")); D_setup(0); /* Read in the map window associated with window */ G_get_window(&window); if (align->answer) { struct Cell_head wind; Rast_get_cellhd(layer_name, "", &wind); /* expand window extent by one wind resolution */ wind.west += wind.ew_res * ((int)((window.west - wind.west) / wind.ew_res) - (window.west < wind.west)); wind.east += wind.ew_res * ((int)((window.east - wind.east) / wind.ew_res) + (window.east > wind.east)); wind.south += wind.ns_res * ((int)((window.south - wind.south) / wind.ns_res) - (window.south < wind.south)); wind.north += wind.ns_res * ((int)((window.north - wind.north) / wind.ns_res) + (window.north > wind.north)); wind.rows = (wind.north - wind.south) / wind.ns_res; wind.cols = (wind.east - wind.west) / wind.ew_res; Rast_set_window(&wind); nrows = wind.rows; ncols = wind.cols; t = (wind.north - window.north) * nrows / (wind.north - wind.south); b = t + (window.north - window.south) * nrows / (wind.north - wind.south); l = (window.west - wind.west) * ncols / (wind.east - wind.west); r = l + (window.east - window.west) * ncols / (wind.east - wind.west); } else { nrows = window.rows; ncols = window.cols; t = 0; b = nrows; l = 0; r = ncols; } D_set_src(t, b, l, r); D_update_conversions(); /* figure out arrow scaling if using a magnitude map */ if (opt7->answer) { Rast_init_fp_range(&range); /* really needed? */ if (Rast_read_fp_range(mag_map, "", &range) != 1) G_fatal_error(_("Problem reading range file")); Rast_get_fp_range_min_max(&range, &mag_min, &mag_max); scale *= 1.5 / fabs(mag_max); G_debug(3, "scaling=%.2f rast_max=%.2f", scale, mag_max); } if (grid_color > 0) { /* ie not "none" */ /* Set color */ D_use_color(grid_color); /* Draw vertical grids */ for (col = 0; col < ncols; col++) D_line_abs(col, 0, col, nrows); /* Draw horizontal grids */ for (row = 0; row < nrows; row++) D_line_abs(0, row, ncols, row); } /* open the raster map */ layer_fd = Rast_open_old(layer_name, ""); raster_type = Rast_get_map_type(layer_fd); /* allocate the cell array */ raster_row = Rast_allocate_buf(raster_type); if (opt7->answer) { /* open the magnitude raster map */ mag_fd = Rast_open_old(mag_map, ""); mag_raster_type = Rast_get_map_type(mag_fd); /* allocate the cell array */ mag_raster_row = Rast_allocate_buf(mag_raster_type); } /* loop through cells, find value, determine direction (n,s,e,w,ne,se,sw,nw), and call appropriate function to draw an arrow on the cell */ for (row = 0; row < nrows; row++) { Rast_get_row(layer_fd, raster_row, row, raster_type); ptr = raster_row; if (opt7->answer) { Rast_get_row(mag_fd, mag_raster_row, row, mag_raster_type); mag_ptr = mag_raster_row; } for (col = 0; col < ncols; col++) { if (row % skip != 0) no_arrow = TRUE; else no_arrow = FALSE; if (col % skip != 0) no_arrow = TRUE; /* find aspect direction based on cell value */ if (raster_type == CELL_TYPE) aspect_f = *((CELL *) ptr); else if (raster_type == FCELL_TYPE) aspect_f = *((FCELL *) ptr); else if (raster_type == DCELL_TYPE) aspect_f = *((DCELL *) ptr); if (opt7->answer) { if (mag_raster_type == CELL_TYPE) length = *((CELL *) mag_ptr); else if (mag_raster_type == FCELL_TYPE) length = *((FCELL *) mag_ptr); else if (mag_raster_type == DCELL_TYPE) length = *((DCELL *) mag_ptr); length *= scale; if (Rast_is_null_value(mag_ptr, mag_raster_type)) { G_debug(5, "Invalid arrow length [NULL]. Skipping."); no_arrow = TRUE; } else if (length <= 0.0) { /* use fabs() or theta+=180? */ G_debug(5, "Illegal arrow length [%.3f]. Skipping.", length); no_arrow = TRUE; } } if (no_arrow) { ptr = G_incr_void_ptr(ptr, Rast_cell_size(raster_type)); if (opt7->answer) mag_ptr = G_incr_void_ptr(mag_ptr, Rast_cell_size(mag_raster_type)); no_arrow = FALSE; continue; } /* treat AGNPS and ANSWERS data like old zero-as-null CELL */ /* TODO: update models */ if (map_type == 2 || map_type == 3) { if (Rast_is_null_value(ptr, raster_type)) aspect_c = 0; else aspect_c = (int)(aspect_f + 0.5); } /** Now draw the arrows **/ /* case switch for standard GRASS aspect map measured in degrees counter-clockwise from east */ if (map_type == 1) { D_use_color(arrow_color); if (Rast_is_null_value(ptr, raster_type)) { D_use_color(x_color); draw_x(); D_use_color(arrow_color); } else if (aspect_f >= 0.0 && aspect_f <= 360.0) { if (opt7->answer) arrow_mag(aspect_f, length); else arrow_360(aspect_f); } else { D_use_color(unknown_color); unknown_(); D_use_color(arrow_color); } } /* case switch for AGNPS type aspect map */ else if (map_type == 2) { D_use_color(arrow_color); switch (aspect_c) { case 0: D_use_color(x_color); draw_x(); D_use_color(arrow_color); break; case 1: arrow_n(); break; case 2: arrow_ne(); break; case 3: arrow_e(); break; case 4: arrow_se(); break; case 5: arrow_s(); break; case 6: arrow_sw(); break; case 7: arrow_w(); break; case 8: arrow_nw(); break; default: D_use_color(unknown_color); unknown_(); D_use_color(arrow_color); break; } } /* case switch for ANSWERS type aspect map */ else if (map_type == 3) { D_use_color(arrow_color); if (aspect_c >= 15 && aspect_c <= 360) /* start at zero? */ arrow_360((double)aspect_c); else if (aspect_c == 400) { D_use_color(unknown_color); unknown_(); D_use_color(arrow_color); } else { D_use_color(x_color); draw_x(); D_use_color(arrow_color); } } /* case switch for compass type aspect map measured in degrees clockwise from north */ else if (map_type == 4) { D_use_color(arrow_color); if (Rast_is_null_value(ptr, raster_type)) { D_use_color(x_color); draw_x(); D_use_color(arrow_color); } else if (aspect_f >= 0.0 && aspect_f <= 360.0) { if (opt7->answer) arrow_mag(90 - aspect_f, length); else arrow_360(90 - aspect_f); } else { D_use_color(unknown_color); unknown_(); D_use_color(arrow_color); } } ptr = G_incr_void_ptr(ptr, Rast_cell_size(raster_type)); if (opt7->answer) mag_ptr = G_incr_void_ptr(mag_ptr, Rast_cell_size(mag_raster_type)); } } Rast_close(layer_fd); if (opt7->answer) Rast_close(mag_fd); D_save_command(G_recreate_command()); D_close_driver(); exit(EXIT_SUCCESS); }
int main(int argc, char *argv[]) { struct GModule *module; int infile; const char *mapset; size_t cell_size; int ytile, xtile, y, overlap; int *outfiles; void *inbuf; G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("raster")); G_add_keyword(_("tiling")); module->description = _("Splits a raster map into tiles."); parm.rastin = G_define_standard_option(G_OPT_R_INPUT); parm.rastout = G_define_option(); parm.rastout->key = "output"; parm.rastout->type = TYPE_STRING; parm.rastout->required = YES; parm.rastout->multiple = NO; parm.rastout->description = _("Output base name"); parm.width = G_define_option(); parm.width->key = "width"; parm.width->type = TYPE_INTEGER; parm.width->required = YES; parm.width->multiple = NO; parm.width->description = _("Width of tiles (columns)"); parm.height = G_define_option(); parm.height->key = "height"; parm.height->type = TYPE_INTEGER; parm.height->required = YES; parm.height->multiple = NO; parm.height->description = _("Height of tiles (rows)"); parm.overlap = G_define_option(); parm.overlap->key = "overlap"; parm.overlap->type = TYPE_INTEGER; parm.overlap->required = NO; parm.overlap->multiple = NO; parm.overlap->description = _("Overlap of tiles"); if (G_parser(argc, argv)) exit(EXIT_FAILURE); G_get_set_window(&src_w); overlap = parm.overlap->answer ? atoi(parm.overlap->answer) : 0; mapset = G_find_raster2(parm.rastin->answer, ""); if (mapset == NULL) G_fatal_error(_("Raster map <%s> not found"), parm.rastin->answer); /* set window to old map */ Rast_get_cellhd(parm.rastin->answer, "", &src_w); dst_w = src_w; dst_w.cols = atoi(parm.width->answer); dst_w.rows = atoi(parm.height->answer); G_adjust_Cell_head(&dst_w, 1, 1); xtiles = (src_w.cols + dst_w.cols - 1) / dst_w.cols; ytiles = (src_w.rows + dst_w.rows - 1) / dst_w.rows; G_debug(1, "X: %d * %d, Y: %d * %d", xtiles, dst_w.cols, ytiles, dst_w.rows); src_w.cols = xtiles * dst_w.cols + 2 * overlap; src_w.rows = ytiles * dst_w.rows + 2 * overlap; src_w.west = src_w.west - overlap * src_w.ew_res; src_w.east = src_w.west + (src_w.cols + 2 * overlap) * src_w.ew_res; src_w.north = src_w.north + overlap * src_w.ns_res; src_w.south = src_w.north - (src_w.rows + 2 * overlap) * src_w.ns_res; Rast_set_input_window(&src_w); /* set the output region */ ovl_w = dst_w; ovl_w.cols = ovl_w.cols + 2 * overlap; ovl_w.rows = ovl_w.rows + 2 * overlap; G_adjust_Cell_head(&ovl_w, 1, 1); Rast_set_output_window(&ovl_w); infile = Rast_open_old(parm.rastin->answer, ""); map_type = Rast_get_map_type(infile); cell_size = Rast_cell_size(map_type); inbuf = Rast_allocate_input_buf(map_type); outfiles = G_malloc(xtiles * sizeof(int)); G_debug(1, "X: %d * %d, Y: %d * %d", xtiles, dst_w.cols, ytiles, dst_w.rows); G_message(_("Generating %d x %d = %d tiles..."), xtiles, ytiles, xtiles * ytiles); for (ytile = 0; ytile < ytiles; ytile++) { G_debug(1, "reading y tile: %d", ytile); G_percent(ytile, ytiles, 2); for (xtile = 0; xtile < xtiles; xtile++) { char name[GNAME_MAX]; sprintf(name, "%s-%03d-%03d", parm.rastout->answer, ytile, xtile); outfiles[xtile] = Rast_open_new(name, map_type); } for (y = 0; y < ovl_w.rows; y++) { int row = ytile * dst_w.rows + y; G_debug(1, "reading row: %d", row); Rast_get_row(infile, inbuf, row, map_type); for (xtile = 0; xtile < xtiles; xtile++) { int cells = xtile * dst_w.cols; void *ptr = G_incr_void_ptr(inbuf, cells * cell_size); Rast_put_row(outfiles[xtile], ptr, map_type); } } for (xtile = 0; xtile < xtiles; xtile++) { Rast_close(outfiles[xtile]); write_support_files(xtile, ytile, overlap); } } Rast_close(infile); return EXIT_SUCCESS; }
/* SAMPLING UNIT SETUP DRIVER */ void sample(int t0, int b0, int l0, int r0, char *name, char *name1, char *name2, double *msc) { int btn, d, fmask; double tmp; /* IN name = name of raster map to be set up name1 = name of overlay vector map name2 = name of overlay site map msc[0]= cols of region/width of screen msc[1]= rows of region/height of screen t0 = top row of sampling frame b0 = bottom row of sampling frame l0 = left col of sampling frame r0 = right col of sampling frame */ /* determine whether the user will use the keyboard or mouse to setup the sampling units */ keyboard: fprintf(stderr, "\n\n HOW WILL YOU SPECIFY SAMPLING UNITS?\n"); fprintf(stderr, "\n Use keyboard to enter sampling unit dimensions 1"); fprintf(stderr, "\n Use mouse to draw sampling units 2\n"); fprintf(stderr, "\n Which Number? "); numtrap(1, &tmp); d = (int)(tmp); if (d < 1 || d > 2) { fprintf(stderr, " You did not enter a 1 or 2, try again\n"); goto keyboard; } if (d == 1 || d == 2) { /* return a value > 0 to fmask if there is a MASK present */ fprintf(stderr, "\n If a MASK is not present (see r.mask) a beep may sound\n"); fprintf(stderr, " and a WARNING may be printed that can be ignored.\n"); fprintf(stderr, " If a MASK is present there will be no warning.\n"); fmask = Rast_open_old("MASK", G_mapset()); fprintf(stderr, "\n"); /* call the routine to setup sampling units manually */ if (d == 1) man_unit(t0, b0, l0, r0, name, name1, name2, msc, fmask); /* call the routine to setup sampling units graphically */ else if (d == 2) graph_unit(t0, b0, l0, r0, name, name1, name2, msc, fmask); Rast_close(fmask); } /* if neither, then exit */ else exit(0); return; }
/* DEFINE SAMPLING UNITS MANUALLY */ static void man_unit(int t, int b, int l, int r, char *n1, char *n2, char *n3, double *mx, int fmask) { int i, j, dx, dy, w_w, w_l, u_w, u_l, method, l0, t0, randflag = 0, unit_num, num = 0, scales, h_d = 1, v_d = 1, itmp, thick, sites, *row_buf, fr, k, count = 0, maxsize = 0, nx = 0, ny = 0, numx = 0, numy = 0, al = 0, ar = 0, at = 0, ab = 0, au_w = 0, au_l = 0; double *ux, *uy; FILE *fp; double dtmp, ratio, size, intv = 0.0, start[2], cnt = 0, radius = 0.0; char *sites_mapset; struct Cell_head wind; /* VARIABLES: COORDINATES IN THIS ROUTINE ARE IN CELLS t = top row of sampling frame b = bottom row of sampling frame l = left col of sampling frame r = right col of sampling frame n1 = n2 = n3 = start[0]= row of UL corner of starting pt for strata start[1]= col of UL corner of starting pt for strata mx[0] = cols of region/width of screen mx[1] = rows of region/height of screen */ start[0] = 0.0; start[1] = 0.0; l = (int)((double)(l * mx[0]) + 0.5); r = (int)((double)(r * mx[0]) + 0.5); t = (int)((double)(t * mx[1]) + 0.5); b = (int)((double)(b * mx[1]) + 0.5); w_w = r - l; w_l = b - t; /* draw the sampling frame */ R_open_driver(); R_standard_color(D_translate_color("grey")); draw_box((int)(l / mx[0] + 0.5), (int)(t / mx[1] + 0.5), (int)(r / mx[0] + 0.5), (int)(b / mx[1] + 0.5), 1); R_close_driver(); /* open the units file for output */ fp = fopen0("r.le.para/units", "w"); G_sleep_on_error(0); /* get the number of scales */ do { fprintf(stderr, "\n How many different SCALES do you want (1-15)? "); numtrap(1, &dtmp); if (dtmp > 15 || dtmp < 1) { fprintf(stderr, "\n Too many (>15) or too few scales; try again"); } } while (dtmp < 1 || dtmp > 15); fprintf(fp, "%10d # of scales\n", (scales = (int)dtmp)); /* for each scale */ for (i = 0; i < scales; i++) { for (;;) { G_system("clear"); radius = 0.0; fprintf(stderr, "\n\n TYPE IN PARAMETERS FOR SCALE %d:\n", i + 1); /* get the distribution method */ fprintf(stderr, "\n Choose method of sampling unit DISTRIBUTION \n"); fprintf(stderr, " Random nonoverlapping 1\n"); fprintf(stderr, " Systematic contiguous 2\n"); fprintf(stderr, " Systematic noncontiguous 3\n"); fprintf(stderr, " Stratified random 4\n"); fprintf(stderr, " Centered over sites 5\n"); fprintf(stderr, " Exit to setup option menu 6\n\n"); do { fprintf(stderr, " Which Number? "); numtrap(1, &dtmp); if ((method = fabs(dtmp)) > 6 || method < 1) { fprintf(stderr, "\n Choice must between 1-5; try again"); } } while (method > 6 || method < 1); if (method == 6) return; /* for stratified random distribution, determine the number of strata */ if (method == 4) { getstrata: fprintf(stderr, "\n Number of strata along the x-axis? (1-60) "); numtrap(1, &dtmp); h_d = fabs(dtmp); fprintf(stderr, "\n Number of strata along the y-axis? (1-60) "); numtrap(1, &dtmp); v_d = fabs(dtmp); if (h_d < 1 || v_d < 1 || h_d > 60 || v_d > 60) { fprintf(stderr, "\n Number must be between 1-60; try again."); goto getstrata; } } /* for methods with strata */ if (method == 2 || method == 3 || method == 4) { strata: fprintf(stderr, "\n Sampling frame row & col for upper left corner of"); fprintf(stderr, " the strata?\n Rows are numbered down and columns"); fprintf(stderr, " are numbered to the right\n Enter 1 1 to start in"); fprintf(stderr, " upper left corner of sampling frame: "); numtrap(2, start); start[0] = start[0] - 1.0; start[1] = start[1] - 1.0; if (start[0] > w_l || start[0] < 0 || start[1] > w_w || start[1] < 0) { fprintf(stderr, "\n The starting row and col you entered are outside"); fprintf(stderr, " the sampling frame\n Try again\n"); goto strata; } } if (method == 4) { /* call draw_grid with the left, top, width, length, the number of horizontal and vertical strata, and the starting row and col for the strata */ draw_grid((int)(l / mx[0] + 0.5), (int)(t / mx[1] + 0.5), (int)(w_w / mx[0] + 0.5), (int)(w_l / mx[1] + 0.5), h_d, v_d, (int)(start[0] / mx[1] + 0.5), (int)(start[1] / mx[0] + 0.5), mx[0], mx[1]); if (!G_yes(" Are these strata OK? ", 1)) { if (G_yes("\n\n Refresh the screen? ", 1)) { paint_map(n1, n2, n3); R_open_driver(); R_standard_color(D_translate_color("grey")); draw_box((int)(l / mx[0] + 0.5), (int)(t / mx[1] + 0.5), (int)(r / mx[0] + 0.5), (int)(b / mx[1] + 0.5), 1); R_close_driver(); } goto getstrata; } } /* if sampling using circles */ fprintf(stderr, "\n Do you want to sample using rectangles"); if (!G_yes ("\n (including squares) (y) or circles (n)? ", 1)) { getradius: fprintf(stderr, "\n What radius do you want for the circles? Radius"); fprintf(stderr, "\n is in pixels; add 0.5 pixels, for the center"); fprintf(stderr, "\n pixel, to the number of pixels outside the"); fprintf(stderr, "\n center pixel. Type a real number with one"); fprintf(stderr, "\n decimal place ending in .5 (e.g., 4.5): "); numtrap(1, &radius); if (radius > 100.0) { fprintf(stderr, "\n Are you sure that you want such a large"); if (!G_yes("\n radius (> 100 pixels)? ", 1)) goto getradius; } ratio = 1.0; u_w = (int)(2 * radius); u_l = (int)(2 * radius); if (fmask > 0) { count = 0; row_buf = Rast_allocate_buf(CELL_TYPE); fr = Rast_open_old(n1, G_mapset()); for (j = t; j < b; j++) { Rast_zero_buf(row_buf, CELL_TYPE); Rast_get_row(fr, row_buf, j, CELL_TYPE); for (k = l; k < r; k++) { if (*(row_buf + k)) count++; } } G_free(row_buf); Rast_close(fr); cnt = (double)(count); if (cnt) cnt = sqrt(cnt); else cnt = 0; } else { count = (w_l - (int)(start[0])) * (w_w - (int)(start[1])); } } /* if sampling using rectangles/squares */ else { /* get the width/length ratio */ getratio: fprintf(stderr, "\n Sampling unit SHAPE (aspect ratio, #cols/#rows) " "expressed as real number" "\n (e.g., 10 cols/5 rows = 2.0) for sampling units " "of scale %d? ", i + 1); numtrap(1, &ratio); if (ratio < 0) ratio = -ratio; else if (ratio > 25.0) if (!G_yes ("\n Are you sure you want such a large ratio? ", 1)) goto getratio; /* determine the recommended maximum size for sampling units */ getsize: dtmp = (ratio > 1) ? 1 / ratio : ratio; dtmp /= (h_d > v_d) ? h_d * h_d : v_d * v_d; tryagain: if (method == 1) { if (fmask > 0) { count = 0; row_buf = Rast_allocate_buf(CELL_TYPE); fr = Rast_open_old(n1, G_mapset()); for (j = t; j < b; j++) { Rast_zero_buf(row_buf, CELL_TYPE); Rast_get_row(fr, row_buf, j, CELL_TYPE); for (k = l; k < r; k++) { if (*(row_buf + k)) count++; } } G_free(row_buf); Rast_close(fr); cnt = (double)(count); if (cnt) cnt = sqrt(cnt); else cnt = 0; maxsize = ((cnt * dtmp / 2) * (cnt * dtmp / 2) > 1.0 / dtmp) ? (cnt * dtmp / 2) * (cnt * dtmp / 2) : 1.0 / dtmp; fprintf(stderr, "\n Recommended maximum SIZE is %d in %d cell total", maxsize, count); fprintf(stderr, " area\n"); } else { fprintf(stderr, "\n Recommended maximum SIZE is"); fprintf(stderr, " %d in %d pixel total area\n", (int)((w_l - (int)(start[0])) * (w_w - (int)(start [1])) * dtmp / 2), (w_l - (int)(start[0])) * (w_w - (int)(start[1]))); count = (w_l - (int)(start[0])) * (w_w - (int)(start[1])); maxsize = (int)((w_l - (int)(start[0])) * (w_w - (int)(start[1])) * dtmp / 2); } } else if (method == 2 || method == 3 || method == 5) { fprintf(stderr, "\n Recommended maximum SIZE is %d in %d pixel total", (int)((w_l - (int)(start[0])) * (w_w - (int)(start[1])) * dtmp / 2), (w_l - (int)(start[0])) * (w_w - (int)(start[1]))); fprintf(stderr, " area\n"); } else if (method == 4) { fprintf(stderr, "\n Recommended maximum SIZE is"); fprintf(stderr, " %d in %d pixel individual", (int)(w_w * w_l * dtmp / 2), ((w_w - (int)(start[1])) / h_d) * ((w_l - (int)(start [0])) / v_d)); fprintf(stderr, " stratum area\n"); } /* get the unit size, display the calculated size, and ask if it is OK */ fprintf(stderr, " What size (in pixels) for each sampling unit of scale %d? ", i + 1); numtrap(1, &size); thick = 1; if (size < 15 || ratio < 0.2 || ratio > 5) thick = 0; u_w = sqrt(size * ratio); u_l = sqrt(size / ratio); fprintf(stderr, "\n The nearest size is %d cells wide X %d cells high = %d", u_w, u_l, u_w * u_l); fprintf(stderr, " cells\n"); if (!u_w || !u_l) { fprintf(stderr, "\n 0 cells wide or high is not acceptable; try again"); goto tryagain; } if (!G_yes(" Is this SIZE OK? ", 1)) goto getsize; } /* for syst. noncontig. distribution, get the interval between units */ if (method == 3) { fprintf(stderr, "\n The interval, in pixels, between the units of scale"); fprintf(stderr, " %d? ", i + 1); numtrap(1, &intv); } /* if the unit dimension + the interval is too large, print a warning and try getting another size */ if (u_w + intv > w_w / h_d || u_l + intv > w_l / v_d) { fprintf(stderr, "\n Unit size too large for sampling frame; try again\n"); if (radius) goto getradius; else goto getsize; } /* for stratified random distribution, the number of units is the same as the number of strata */ if (method == 4) num = h_d * v_d; /* for the other distributions, calculate the maximum number of units, then get the number of units */ else if (method == 1 || method == 2 || method == 3) { if (method == 1) { if (! (unit_num = calc_num(w_w, w_l, ratio, u_w, u_l, method, intv, (int)(start[1]), (int)(start[0]), u_w * u_l, count))) { fprintf(stderr, "\n Something wrong with sampling unit size, try again\n"); if (radius) goto getradius; else goto getsize; } fprintf(stderr, "\n Maximum NUMBER of units in scale %d is %d\n", i + 1, unit_num); fprintf(stderr, " Usually 1/2 of this number can be successfully"); fprintf(stderr, " distributed\n More than 1/2 can sometimes be"); fprintf(stderr, " distributed\n"); } else if (method == 2 || method == 3) { numx = floor((double)(w_w - start[1]) / (u_w + intv)); numy = floor((double)(w_l - start[0]) / (u_l + intv)); if (((w_w - (int)(start[1])) % (numx * (u_w + (int)(intv)))) >= u_w) numx++; if (((w_l - (int)(start[0])) % (numy * (u_l + (int)(intv)))) >= u_l) numy++; unit_num = numx * numy; fprintf(stderr, "\n Maximum NUMBER of units in scale %d is %d as %d", i + 1, unit_num, numy); fprintf(stderr, " rows with %d units per row", numx); } do { fprintf(stderr, "\n What NUMBER of sampling units do you want to try"); fprintf(stderr, " to use? "); numtrap(1, &dtmp); if ((num = dtmp) > unit_num || num < 1) { fprintf(stderr, "\n %d is greater than the maximum number of", num); fprintf(stderr, " sampling units; try again\n"); } else if (method == 2 || method == 3) { fprintf(stderr, "\n How many sampling units do you want per row? "); numtrap(1, &dtmp); if ((nx = dtmp) > num) { fprintf(stderr, "\n Number in each row > number requested; try"); fprintf(stderr, " again\n"); } else { if (nx > numx) { fprintf(stderr, "\n Can't fit %d units in each row, try", nx); fprintf(stderr, " again\n"); } else { if (num % nx) ny = num / nx + 1; else ny = num / nx; if (ny > numy) { fprintf(stderr, "\n Can't fit the needed %d rows, try", ny); fprintf(stderr, " again\n"); } } } } } while (num > unit_num || num < 1 || nx > num || nx > numx || ny > numy); } /* dynamically allocate storage for arrays to store the upper left corner of sampling units */ if (method != 5) { ux = G_calloc(num + 1, sizeof(double)); uy = G_calloc(num + 1, sizeof(double)); } else { ux = G_calloc(250, sizeof(double)); uy = G_calloc(250, sizeof(double)); } /* calculate the upper left corner of sampling units and store them in arrays ux and uy */ if (!calc_unit_loc (radius, t, b, l, r, ratio, u_w, u_l, method, intv, num, h_d, v_d, ux, uy, &sites, (int)(start[1]), (int)(start[0]), fmask, nx, mx[0], mx[1])) goto last; signal(SIGINT, SIG_DFL); if (method == 5) num = sites; /* draw the sampling units on the screen */ if (method == 2 || method == 3 || method == 5) { R_open_driver(); R_standard_color(D_translate_color("red")); for (j = 0; j < num; j++) { if (radius) { draw_circle((int)((double)(ux[j]) / mx[0]), (int)((double)(uy[j]) / mx[1]), (int)((double)(ux[j] + u_w) / mx[0]), (int)((double)(uy[j] + u_l) / mx[1]), 3); } else { draw_box((int)((double)(ux[j]) / mx[0]), (int)((double)(uy[j]) / mx[1]), (int)((double)(ux[j] + u_w) / mx[0]), (int)((double)(uy[j] + u_l) / mx[1]), 1); } } R_close_driver(); } if (G_yes("\n Is this set of sampling units OK? ", 1)) break; last: signal(SIGINT, SIG_DFL); if (G_yes("\n Refresh the screen? ", 1)) { paint_map(n1, n2, n3); R_open_driver(); R_standard_color(D_translate_color("grey")); draw_box((int)(l / mx[0]), (int)(t / mx[1]), (int)(r / mx[0]), (int)(b / mx[1]), 1); R_close_driver(); } } /* save the sampling unit parameters in r.le.para/units file */ fprintf(fp, "%10d # of units of scale %d.\n", num, (i + 1)); fprintf(fp, "%10d%10d u_w, u_l of units in scale %d\n", u_w, u_l, (i + 1)); fprintf(fp, "%10.1f radius of circles in scale %d\n", radius, (i + 1)); for (j = 0; j < num; j++) fprintf(fp, "%10d%10d left, top of unit[%d]\n", (int)ux[j], (int)uy[j], j + 1); if (i < scales - 1 && G_yes("\n\n Refresh the screen? ", 1)) { paint_map(n1, n2, n3); R_open_driver(); R_standard_color(D_translate_color("grey")); draw_box((int)(l / mx[0]), (int)(t / mx[1]), (int)(r / mx[0]), (int)(b / mx[1]), 1); R_close_driver(); } } /* free dynamically allocated memory */ G_free(ux); G_free(uy); fclose(fp); return; }
void filter_holes(Gfile * out) { int row, col, nrows, ncols; void *arast, *brast, *crast; int i, pixel[9], cold, warm, shadow, nulo, lim; Gfile tmp; nrows = Rast_window_rows(); ncols = Rast_window_cols(); if (nrows < 3 || ncols < 3) return; /* Open to read */ if ((out->fd = Rast_open_old(out->name, "")) < 0) G_fatal_error(_("Unable to open raster map <%s>"), out->name); arast = Rast_allocate_buf(CELL_TYPE); brast = Rast_allocate_buf(CELL_TYPE); crast = Rast_allocate_buf(CELL_TYPE); /* Open to write */ sprintf(tmp.name, "_%d.BBB", getpid()); tmp.rast = Rast_allocate_buf(CELL_TYPE); if ((tmp.fd = Rast_open_new(tmp.name, CELL_TYPE)) < 0) G_fatal_error(_("Unable to create raster map <%s>"), tmp.name); G_important_message(_("Filling small holes in clouds...")); /* Se puede acelerar creandolos nulos y luego arast = brast brast = crast y cargando crast solamente G_set_f_null_value(cell[2], ncols); */ for (row = 0; row < nrows; row++) { G_percent(row, nrows, 2); /* Read row values */ if (row != 0) { Rast_get_c_row(out->fd, arast, row - 1); } Rast_get_c_row(out->fd, brast, row); if (row != (nrows - 1)) { Rast_get_c_row(out->fd, crast, row + 1); } /* Analysis of all pixels */ for (col = 0; col < ncols; col++) { pixel[0] = pval(brast, col); if (pixel[0] == 0) { if (row == 0) { pixel[1] = -1; pixel[2] = -1; pixel[3] = -1; if (col == 0) { pixel[4] = -1; pixel[5] = pval(brast, col + 1); pixel[6] = -1; pixel[7] = pval(crast, col); pixel[8] = pval(crast, col + 1); } else if (col != (ncols - 1)) { pixel[4] = pval(brast, col - 1); pixel[5] = pval(brast, col + 1); pixel[6] = pval(crast, col - 1); pixel[7] = pval(crast, col); pixel[8] = pval(crast, col + 1); } else { pixel[4] = pval(brast, col - 1); pixel[5] = -1; pixel[6] = pval(crast, col - 1); pixel[7] = pval(crast, col); pixel[8] = -1; } } else if (row != (nrows - 1)) { if (col == 0) { pixel[1] = -1; pixel[2] = pval(arast, col); pixel[3] = pval(arast, col + 1); pixel[4] = -1; pixel[5] = pval(brast, col + 1); pixel[6] = -1; pixel[7] = pval(crast, col); pixel[8] = pval(crast, col + 1); } else if (col != (ncols - 1)) { pixel[1] = pval(arast, col - 1); pixel[2] = pval(arast, col); pixel[3] = pval(arast, col + 1); pixel[4] = pval(brast, col - 1); pixel[5] = pval(brast, col + 1); pixel[6] = pval(crast, col - 1); pixel[7] = pval(crast, col); pixel[8] = pval(crast, col + 1); } else { pixel[1] = pval(arast, col - 1); pixel[2] = pval(arast, col); pixel[3] = -1; pixel[4] = pval(brast, col - 1); pixel[5] = -1; pixel[6] = pval(crast, col - 1); pixel[7] = pval(crast, col); pixel[8] = -1; } } else { pixel[6] = -1; pixel[7] = -1; pixel[8] = -1; if (col == 0) { pixel[1] = -1; pixel[2] = pval(arast, col); pixel[3] = pval(arast, col + 1); pixel[4] = -1; pixel[5] = pval(brast, col + 1); } else if (col != (ncols - 1)) { pixel[1] = pval(arast, col - 1); pixel[2] = pval(arast, col); pixel[3] = pval(arast, col + 1); pixel[4] = pval(brast, col - 1); pixel[5] = pval(brast, col + 1); } else { pixel[1] = pval(arast, col - 1); pixel[2] = pval(arast, col); pixel[3] = -1; pixel[4] = pval(brast, col - 1); pixel[5] = -1; } } cold = warm = shadow = nulo = 0; for (i = 1; i < 9; i++) { switch (pixel[i]) { case IS_COLD_CLOUD: cold++; break; case IS_WARM_CLOUD: warm++; break; case IS_SHADOW: shadow++; break; default: nulo++; break; } } lim = (int)(cold + warm + shadow + nulo) / 2; /* Entra pixel[0] = 0 */ if (nulo < lim) { if (shadow >= (cold + warm)) pixel[0] = IS_SHADOW; else pixel[0] = (warm > cold) ? IS_WARM_CLOUD : IS_COLD_CLOUD; } } if (pixel[0] != 0) { ((CELL *) tmp.rast)[col] = pixel[0]; } else { Rast_set_c_null_value((CELL *) tmp.rast + col, 1); } } Rast_put_row(tmp.fd, tmp.rast, CELL_TYPE); } G_percent(1, 1, 1); G_free(arast); G_free(brast); G_free(crast); Rast_close(out->fd); G_free(tmp.rast); Rast_close(tmp.fd); G_remove("cats", out->name); G_remove("cell", out->name); G_remove("cellhd", out->name); G_remove("cell_misc", out->name); G_remove("hist", out->name); G_rename("cats", tmp.name, out->name); G_rename("cell", tmp.name, out->name); G_rename("cellhd", tmp.name, out->name); G_rename("cell_misc", tmp.name, out->name); G_rename("hist", tmp.name, out->name); return; }
int main(int argc, char *argv[]) { struct GModule *module; struct { struct Option *quant, *perc, *slots, *basemap, *covermap, *output; } opt; struct { struct Flag *r, *p; } flag; const char *basemap, *covermap; char **outputs; int reclass, print; int cover_fd, base_fd; struct Range range; struct FPRange fprange; int i; G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("raster")); G_add_keyword(_("statistics")); module->description = _("Compute category quantiles using two passes."); opt.basemap = G_define_standard_option(G_OPT_R_BASE); opt.covermap = G_define_standard_option(G_OPT_R_COVER); opt.quant = G_define_option(); opt.quant->key = "quantiles"; opt.quant->type = TYPE_INTEGER; opt.quant->required = NO; opt.quant->description = _("Number of quantiles"); opt.perc = G_define_option(); opt.perc->key = "percentiles"; opt.perc->type = TYPE_DOUBLE; opt.perc->multiple = YES; opt.perc->description = _("List of percentiles"); opt.perc->answer = "50"; opt.slots = G_define_option(); opt.slots->key = "bins"; opt.slots->type = TYPE_INTEGER; opt.slots->required = NO; opt.slots->description = _("Number of bins to use"); opt.slots->answer = "1000"; opt.output = G_define_standard_option(G_OPT_R_OUTPUT); opt.output->description = _("Resultant raster map(s)"); opt.output->required = NO; opt.output->multiple = YES; flag.r = G_define_flag(); flag.r->key = 'r'; flag.r->description = _("Create reclass map with statistics as category labels"); flag.p = G_define_flag(); flag.p->key = 'p'; flag.p->description = _("Do not create output maps; just print statistics"); if (G_parser(argc, argv)) exit(EXIT_FAILURE); basemap = opt.basemap->answer; covermap = opt.covermap->answer; outputs = opt.output->answers; reclass = flag.r->answer; print = flag.p->answer; if (!print && !opt.output->answers) G_fatal_error(_("Either -%c or %s= must be given"), flag.p->key, opt.output->key); if (print && opt.output->answers) G_fatal_error(_("-%c and %s= are mutually exclusive"), flag.p->key, opt.output->key); num_slots = atoi(opt.slots->answer); if (opt.quant->answer) { num_quants = atoi(opt.quant->answer) - 1; quants = G_calloc(num_quants, sizeof(DCELL)); for (i = 0; i < num_quants; i++) quants[i] = 1.0 * (i + 1) / (num_quants + 1); } else { for (i = 0; opt.perc->answers[i]; i++) ; num_quants = i; quants = G_calloc(num_quants, sizeof(DCELL)); for (i = 0; i < num_quants; i++) quants[i] = atof(opt.perc->answers[i]) / 100; qsort(quants, num_quants, sizeof(DCELL), compare_dcell); } if (opt.output->answer) { for (i = 0; opt.output->answers[i]; i++) ; if (i != num_quants) G_fatal_error(_("Number of quantiles (%d) does not match number of output maps (%d)"), num_quants, i); } base_fd = Rast_open_old(basemap, ""); cover_fd = Rast_open_old(covermap, ""); if (Rast_map_is_fp(basemap, "") != 0) G_fatal_error(_("The base map must be an integer (CELL) map")); if (Rast_read_range(basemap, "", &range) < 0) G_fatal_error(_("Unable to read range of base map <%s>"), basemap); Rast_get_range_min_max(&range, &min, &max); num_cats = max - min + 1; if (num_cats > MAX_CATS) G_fatal_error(_("Base map <%s> has too many categories (max: %d)"), basemap, MAX_CATS); Rast_read_fp_range(covermap, "", &fprange); Rast_get_fp_range_min_max(&fprange, &f_min, &f_max); slot_size = (f_max - f_min) / num_slots; basecats = G_calloc(num_cats, sizeof(struct basecat)); for (i = 0; i < num_cats; i++) basecats[i].slots = G_calloc(num_slots, sizeof(unsigned int)); rows = Rast_window_rows(); cols = Rast_window_cols(); get_slot_counts(base_fd, cover_fd); initialize_bins(); fill_bins(base_fd, cover_fd); sort_bins(); compute_quantiles(); if (print) print_quantiles(); else if (reclass) do_reclass(basemap, outputs); else do_output(base_fd, outputs, covermap); Rast_close(cover_fd); Rast_close(base_fd); return (EXIT_SUCCESS); }
int main(int argc, char *argv[]) { int i, row, col; /* counters */ unsigned long filesize; int endianness; /* 0=little, 1=big */ int data_format; /* 0=double 1=float 2=32bit signed int 5=8bit unsigned int (ie text) */ int data_type; /* 0=numbers 1=text */ int format_block; /* combo of endianness, 0, data_format, and type */ int realflag = 0; /* 0=only real values used */ /* should type be specifically uint32 ??? */ char array_name[32]; /* variable names must start with a letter (case sensitive) followed by letters, numbers, or underscores. 31 chars max. */ int name_len; int mrows, ncols; /* text/data/map array dimensions */ int val_i; /* for misc use */ float val_f; /* for misc use */ double val_d; /* for misc use */ char *infile, *outfile, *maptitle, *basename; struct Cell_head region; void *raster, *ptr; RASTER_MAP_TYPE map_type; struct Option *inputfile, *outputfile; struct GModule *module; int fd; FILE *fp1; G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("raster")); G_add_keyword(_("export")); module->description = _("Exports a GRASS raster to a binary MAT-File."); /* Define the different options */ inputfile = G_define_standard_option(G_OPT_R_INPUT); outputfile = G_define_option(); outputfile->key = "output"; outputfile->type = TYPE_STRING; outputfile->required = YES; outputfile->gisprompt = "new_file,file,output"; outputfile->description = _("Name for the output binary MAT-File"); if (G_parser(argc, argv)) exit(EXIT_FAILURE); infile = inputfile->answer; basename = G_store(outputfile->answer); G_basename(basename, "mat"); outfile = G_malloc(strlen(basename) + 5); sprintf(outfile, "%s.mat", basename); fd = Rast_open_old(infile, ""); map_type = Rast_get_map_type(fd); /* open bin file for writing */ fp1 = fopen(outfile, "wb"); if (NULL == fp1) G_fatal_error(_("Unable to open output file <%s>"), outfile); /* Check Endian State of Host Computer */ if (G_is_little_endian()) endianness = 0; /* ie little endian */ else endianness = 1; /* ie big endian */ G_debug(1, "Machine is %s endian.\n", endianness ? "big" : "little"); G_get_window(®ion); /********** Write map **********/ /** write text element (map name) **/ strncpy(array_name, "map_name", 31); mrows = 1; ncols = strlen(infile); data_format = 5; /* 0=double 1=float 2=32bit signed int 5=8bit unsigned int(text) */ data_type = 1; /* 0=numbers 1=text */ G_verbose_message(_("Exporting <%s>"), infile); /* 4 byte data format */ format_block = endianness * 1000 + data_format * 10 + data_type; fwrite(&format_block, sizeof(int), 1, fp1); /* fprintf(stderr, "name data format is [%04ld]\n", format_block); */ /* 4 byte number of rows & columns */ fwrite(&mrows, sizeof(int), 1, fp1); fwrite(&ncols, sizeof(int), 1, fp1); /* 4 byte real/imag flag 0=real vals only */ fwrite(&realflag, sizeof(int), 1, fp1); /* length of array_name+1 */ name_len = strlen(array_name) + 1; fwrite(&name_len, sizeof(int), 1, fp1); /* array name */ fprintf(fp1, "%s%c", array_name, '\0'); /* array data */ fprintf(fp1, "%s", infile); /********** Write title (if there is one) **********/ maptitle = Rast_get_cell_title(infile, ""); if (strlen(maptitle) >= 1) { /** write text element (map title) **/ strncpy(array_name, "map_title", 31); mrows = 1; ncols = strlen(maptitle); data_format = 5; /* 0=double 1=float 2=32bit signed int 5=8bit unsigned int(text) */ data_type = 1; /* 0=numbers 1=text */ /* 4 byte data format */ format_block = endianness * 1000 + data_format * 10 + data_type; fwrite(&format_block, sizeof(int), 1, fp1); /* 4 byte number of rows & columns */ fwrite(&mrows, sizeof(int), 1, fp1); fwrite(&ncols, sizeof(int), 1, fp1); /* 4 byte real/imag flag 0=real vals only */ fwrite(&realflag, sizeof(int), 1, fp1); /* length of array_name+1 */ name_len = strlen(array_name) + 1; fwrite(&name_len, sizeof(int), 1, fp1); /* array name */ fprintf(fp1, "%s%c", array_name, '\0'); /* array data */ fprintf(fp1, "%s", maptitle); } /***** Write bounds *****/ G_verbose_message(""); G_verbose_message(_("Using the Current Region settings:")); G_verbose_message(_("northern edge=%f"), region.north); G_verbose_message(_("southern edge=%f"), region.south); G_verbose_message(_("eastern edge=%f"), region.east); G_verbose_message(_("western edge=%f"), region.west); G_verbose_message(_("nsres=%f"), region.ns_res); G_verbose_message(_("ewres=%f"), region.ew_res); G_verbose_message(_("rows=%d"), region.rows); G_verbose_message(_("cols=%d"), region.cols); G_verbose_message(""); for (i = 0; i < 4; i++) { switch (i) { case 0: strncpy(array_name, "map_northern_edge", 31); val_d = region.north; break; case 1: strncpy(array_name, "map_southern_edge", 31); val_d = region.south; break; case 2: strncpy(array_name, "map_eastern_edge", 31); val_d = region.east; break; case 3: strncpy(array_name, "map_western_edge", 31); val_d = region.west; break; default: fclose(fp1); G_fatal_error("please contact development team"); break; } /** write data element **/ data_format = 0; /* 0=double 1=float 2=32bit signed int 5=8bit unsigned int(text) */ data_type = 0; /* 0=numbers 1=text */ mrows = 1; ncols = 1; /* 4 byte data format */ format_block = endianness * 1000 + data_format * 10 + data_type; fwrite(&format_block, sizeof(int), 1, fp1); /* fprintf(stderr, "bounds data format is [%04ld]\n", format_block); */ /* 4 byte number of rows , 4 byte number of colums */ fwrite(&mrows, sizeof(int), 1, fp1); fwrite(&ncols, sizeof(int), 1, fp1); /* 4 byte real/imag flag 0=only real */ fwrite(&realflag, sizeof(int), 1, fp1); /* length of array_name+1 */ name_len = strlen(array_name) + 1; fwrite(&name_len, sizeof(int), 1, fp1); /* array name */ fprintf(fp1, "%s%c", array_name, '\0'); /* write array data, by increasing column */ fwrite(&val_d, sizeof(double), 1, fp1); /** end of data element **/ } /***** Write map data *****/ strncpy(array_name, "map_data", 31); switch (map_type) { /* data_format: 0=double 1=float 2=32bit signed int 5=8bit unsigned int (ie text) */ case CELL_TYPE: data_format = 2; G_verbose_message(_("Exporting raster as integer values")); break; case FCELL_TYPE: data_format = 1; G_verbose_message(_("Exporting raster as floating point values")); break; case DCELL_TYPE: data_format = 0; G_verbose_message(_("Exporting raster as double FP values")); break; default: fclose(fp1); G_fatal_error("Please contact development team"); break; } data_type = 0; /* 0=numbers 1=text */ mrows = region.rows; ncols = region.cols; /* 4 byte data format */ format_block = (endianness * 1000) + (data_format * 10) + data_type; fwrite(&format_block, sizeof(int), 1, fp1); G_debug(3, "map data format is [%04d]\n", format_block); /* 4 byte number of rows & columns */ fwrite(&mrows, sizeof(int), 1, fp1); fwrite(&ncols, sizeof(int), 1, fp1); /* 4 byte real/imag flag 0=only real */ fwrite(&realflag, sizeof(int), 1, fp1); /* length of array_name+1 */ name_len = strlen(array_name) + 1; fwrite(&name_len, sizeof(int), 1, fp1); /* array name */ fprintf(fp1, "%s%c", array_name, '\0'); /* data array, by increasing column */ raster = G_calloc((Rast_window_rows() + 1) * (Rast_window_cols() + 1), Rast_cell_size(map_type)); G_debug(1, "mem alloc is %d bytes\n", /* I think _cols()+1 is unneeded? */ Rast_cell_size(map_type) * (Rast_window_rows() + 1) * (Rast_window_cols() + 1)); G_verbose_message(_("Reading in map ... ")); /* load entire map into memory */ for (row = 0, ptr = raster; row < mrows; row++, ptr = G_incr_void_ptr(ptr, (Rast_window_cols() + 1) * Rast_cell_size(map_type))) { Rast_get_row(fd, ptr, row, map_type); G_percent(row, mrows, 2); } G_percent(row, mrows, 2); /* finish it off */ G_verbose_message(_("Writing out map...")); /* then write it to disk */ /* NoGood: fwrite(raster, Rast_cell_size(map_type), mrows*ncols, fp1); */ for (col = 0; col < ncols; col++) { for (row = 0; row < mrows; row++) { ptr = raster; ptr = G_incr_void_ptr(ptr, (col + row * (ncols + 1)) * Rast_cell_size(map_type)); if (!Rast_is_null_value(ptr, map_type)) { if (map_type == CELL_TYPE) { val_i = *((CELL *) ptr); fwrite(&val_i, sizeof(int), 1, fp1); } else if (map_type == FCELL_TYPE) { val_f = *((FCELL *) ptr); fwrite(&val_f, sizeof(float), 1, fp1); } else if (map_type == DCELL_TYPE) { val_d = *((DCELL *) ptr); fwrite(&val_d, sizeof(double), 1, fp1); } } else { /* ie if NULL cell -> write IEEE NaN value */ if (map_type == CELL_TYPE) { val_i = *((CELL *) ptr); /* int has no NaN value, so use whatever GRASS uses */ fwrite(&val_i, sizeof(int), 1, fp1); } else if (map_type == FCELL_TYPE) { if (endianness) /* ie big */ fprintf(fp1, "%c%c%c%c", 0xff, 0xf8, 0, 0); else /* ie little */ fprintf(fp1, "%c%c%c%c", 0, 0, 0xf8, 0xff); } else if (map_type == DCELL_TYPE) { if (endianness) fprintf(fp1, "%c%c%c%c%c%c%c%c", 0xff, 0xf8, 0, 0, 0, 0, 0, 0); else fprintf(fp1, "%c%c%c%c%c%c%c%c", 0, 0, 0, 0, 0, 0, 0xf8, 0xff); } } } G_percent(col, ncols, 2); } G_percent(col, ncols, 2); /* finish it off */ /*** end of data element ***/ /* done! */ filesize = G_ftell(fp1); fclose(fp1); G_verbose_message(_("%ld bytes written to '%s'"), filesize, outfile); G_done_msg(""); G_free(basename); G_free(outfile); exit(EXIT_SUCCESS); }
int read_input_map(char *input, char *mapset, int ZEROFLAG) { int fd; int row; int hit; register int col; register CELL *cell; register MAPTYPE *ptr; map = (MAPTYPE *) G_malloc((size_t) window.rows * window.cols * sizeof(MAPTYPE)); fd = Rast_open_old(input, mapset); cell = Rast_allocate_c_buf(); ptr = map; minrow = -1; maxrow = -1; mincol = window.cols; maxcol = 0; G_message(_("Reading input raster map <%s>..."), G_fully_qualified_name(input, mapset)); count_rows_with_data = 0; for (row = 0; row < window.rows; row++) { hit = 0; G_percent(row, window.rows, 2); Rast_get_c_row(fd, cell, row); for (col = 0; col < window.cols; col++) { if (ZEROFLAG) { if ((*ptr++ = (*cell++ != 0))) { if (minrow < 0) minrow = row; maxrow = row; if (col < mincol) mincol = col; if (col > maxcol) maxcol = col; if (!hit) { count_rows_with_data++; hit = 1; } } } else { /* use NULL */ if ((*ptr++ = !Rast_is_c_null_value(cell++))) { if (minrow < 0) minrow = row; maxrow = row; if (col < mincol) mincol = col; if (col > maxcol) maxcol = col; if (!hit) { count_rows_with_data++; hit = 1; } } } } cell -= window.cols; } G_percent(row, window.rows, 2); Rast_close(fd); G_free(cell); return 0; }
int main(int argc, char **argv) { char *mapname, /* ptr to name of output layer */ *setname, /* ptr to name of input mapset */ *ipolname; /* name of interpolation method */ int fdi, /* input map file descriptor */ fdo, /* output map file descriptor */ method, /* position of method in table */ permissions, /* mapset permissions */ cell_type, /* output celltype */ cell_size, /* size of a cell in bytes */ row, col, /* counters */ irows, icols, /* original rows, cols */ orows, ocols, have_colors, /* Input map has a colour table */ overwrite, /* Overwrite */ curr_proj; /* output projection (see gis.h) */ void *obuffer, /* buffer that holds one output row */ *obufptr; /* column ptr in output buffer */ struct cache *ibuffer; /* buffer that holds the input map */ func interpolate; /* interpolation routine */ double xcoord1, xcoord2, /* temporary x coordinates */ ycoord1, ycoord2, /* temporary y coordinates */ col_idx, /* column index in input matrix */ row_idx, /* row index in input matrix */ onorth, osouth, /* save original border coords */ oeast, owest, inorth, isouth, ieast, iwest; char north_str[30], south_str[30], east_str[30], west_str[30]; struct Colors colr; /* Input map colour table */ struct History history; struct pj_info iproj, /* input map proj parameters */ oproj; /* output map proj parameters */ struct Key_Value *in_proj_info, /* projection information of */ *in_unit_info, /* input and output mapsets */ *out_proj_info, *out_unit_info; struct GModule *module; struct Flag *list, /* list files in source location */ *nocrop, /* don't crop output map */ *print_bounds, /* print output bounds and exit */ *gprint_bounds; /* same but print shell style */ struct Option *imapset, /* name of input mapset */ *inmap, /* name of input layer */ *inlocation, /* name of input location */ *outmap, /* name of output layer */ *indbase, /* name of input database */ *interpol, /* interpolation method: nearest neighbor, bilinear, cubic */ *memory, /* amount of memory for cache */ *res; /* resolution of target map */ struct Cell_head incellhd, /* cell header of input map */ outcellhd; /* and output map */ G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("raster")); G_add_keyword(_("projection")); G_add_keyword(_("transformation")); module->description = _("Re-projects a raster map from given location to the current location."); inmap = G_define_standard_option(G_OPT_R_INPUT); inmap->description = _("Name of input raster map to re-project"); inmap->required = NO; inmap->guisection = _("Source"); inlocation = G_define_option(); inlocation->key = "location"; inlocation->type = TYPE_STRING; inlocation->required = YES; inlocation->description = _("Location containing input raster map"); inlocation->gisprompt = "old,location,location"; inlocation->key_desc = "name"; imapset = G_define_standard_option(G_OPT_M_MAPSET); imapset->label = _("Mapset containing input raster map"); imapset->description = _("default: name of current mapset"); imapset->guisection = _("Source"); indbase = G_define_option(); indbase->key = "dbase"; indbase->type = TYPE_STRING; indbase->required = NO; indbase->description = _("Path to GRASS database of input location"); indbase->gisprompt = "old,dbase,dbase"; indbase->key_desc = "path"; indbase->guisection = _("Source"); outmap = G_define_standard_option(G_OPT_R_OUTPUT); outmap->required = NO; outmap->description = _("Name for output raster map (default: same as 'input')"); outmap->guisection = _("Target"); ipolname = make_ipol_list(); interpol = G_define_option(); interpol->key = "method"; interpol->type = TYPE_STRING; interpol->required = NO; interpol->answer = "nearest"; interpol->options = ipolname; interpol->description = _("Interpolation method to use"); interpol->guisection = _("Target"); interpol->descriptions = make_ipol_desc(); memory = G_define_option(); memory->key = "memory"; memory->type = TYPE_INTEGER; memory->required = NO; memory->description = _("Cache size (MiB)"); res = G_define_option(); res->key = "resolution"; res->type = TYPE_DOUBLE; res->required = NO; res->description = _("Resolution of output raster map"); res->guisection = _("Target"); list = G_define_flag(); list->key = 'l'; list->description = _("List raster maps in input location and exit"); nocrop = G_define_flag(); nocrop->key = 'n'; nocrop->description = _("Do not perform region cropping optimization"); print_bounds = G_define_flag(); print_bounds->key = 'p'; print_bounds->description = _("Print input map's bounds in the current projection and exit"); print_bounds->guisection = _("Target"); gprint_bounds = G_define_flag(); gprint_bounds->key = 'g'; gprint_bounds->description = _("Print input map's bounds in the current projection and exit (shell style)"); gprint_bounds->guisection = _("Target"); /* The parser checks if the map already exists in current mapset, we switch out the check and do it in the module after the parser */ overwrite = G_check_overwrite(argc, argv); if (G_parser(argc, argv)) exit(EXIT_FAILURE); /* get the method */ for (method = 0; (ipolname = menu[method].name); method++) if (strcmp(ipolname, interpol->answer) == 0) break; if (!ipolname) G_fatal_error(_("<%s=%s> unknown %s"), interpol->key, interpol->answer, interpol->key); interpolate = menu[method].method; mapname = outmap->answer ? outmap->answer : inmap->answer; if (mapname && !list->answer && !overwrite && G_find_raster(mapname, G_mapset())) G_fatal_error(_("option <%s>: <%s> exists."), "output", mapname); setname = imapset->answer ? imapset->answer : G_store(G_mapset()); if (strcmp(inlocation->answer, G_location()) == 0 && (!indbase->answer || strcmp(indbase->answer, G_gisdbase()) == 0)) #if 0 G_fatal_error(_("Input and output locations can not be the same")); #else G_warning(_("Input and output locations are the same")); #endif G_get_window(&outcellhd); if(gprint_bounds->answer && !print_bounds->answer) print_bounds->answer = gprint_bounds->answer; curr_proj = G_projection(); /* Get projection info for output mapset */ if ((out_proj_info = G_get_projinfo()) == NULL) G_fatal_error(_("Unable to get projection info of output raster map")); if ((out_unit_info = G_get_projunits()) == NULL) G_fatal_error(_("Unable to get projection units of output raster map")); if (pj_get_kv(&oproj, out_proj_info, out_unit_info) < 0) G_fatal_error(_("Unable to get projection key values of output raster map")); /* Change the location */ G__create_alt_env(); G__setenv("GISDBASE", indbase->answer ? indbase->answer : G_gisdbase()); G__setenv("LOCATION_NAME", inlocation->answer); permissions = G__mapset_permissions(setname); if (permissions < 0) /* can't access mapset */ G_fatal_error(_("Mapset <%s> in input location <%s> - %s"), setname, inlocation->answer, permissions == 0 ? _("permission denied") : _("not found")); /* if requested, list the raster maps in source location - MN 5/2001 */ if (list->answer) { int i; char **list; G_verbose_message(_("Checking location <%s> mapset <%s>"), inlocation->answer, setname); list = G_list(G_ELEMENT_RASTER, G__getenv("GISDBASE"), G__getenv("LOCATION_NAME"), setname); for (i = 0; list[i]; i++) { fprintf(stdout, "%s\n", list[i]); } fflush(stdout); exit(EXIT_SUCCESS); /* leave r.proj after listing */ } if (!inmap->answer) G_fatal_error(_("Required parameter <%s> not set"), inmap->key); if (!G_find_raster(inmap->answer, setname)) G_fatal_error(_("Raster map <%s> in location <%s> in mapset <%s> not found"), inmap->answer, inlocation->answer, setname); /* Read input map colour table */ have_colors = Rast_read_colors(inmap->answer, setname, &colr); /* Get projection info for input mapset */ if ((in_proj_info = G_get_projinfo()) == NULL) G_fatal_error(_("Unable to get projection info of input map")); if ((in_unit_info = G_get_projunits()) == NULL) G_fatal_error(_("Unable to get projection units of input map")); if (pj_get_kv(&iproj, in_proj_info, in_unit_info) < 0) G_fatal_error(_("Unable to get projection key values of input map")); G_free_key_value(in_proj_info); G_free_key_value(in_unit_info); G_free_key_value(out_proj_info); G_free_key_value(out_unit_info); if (G_verbose() > G_verbose_std()) pj_print_proj_params(&iproj, &oproj); /* this call causes r.proj to read the entire map into memeory */ Rast_get_cellhd(inmap->answer, setname, &incellhd); Rast_set_input_window(&incellhd); if (G_projection() == PROJECTION_XY) G_fatal_error(_("Unable to work with unprojected data (xy location)")); /* Save default borders so we can show them later */ inorth = incellhd.north; isouth = incellhd.south; ieast = incellhd.east; iwest = incellhd.west; irows = incellhd.rows; icols = incellhd.cols; onorth = outcellhd.north; osouth = outcellhd.south; oeast = outcellhd.east; owest = outcellhd.west; orows = outcellhd.rows; ocols = outcellhd.cols; if (print_bounds->answer) { G_message(_("Input map <%s@%s> in location <%s>:"), inmap->answer, setname, inlocation->answer); if (pj_do_proj(&iwest, &isouth, &iproj, &oproj) < 0) G_fatal_error(_("Error in pj_do_proj (projection of input coordinate pair)")); if (pj_do_proj(&ieast, &inorth, &iproj, &oproj) < 0) G_fatal_error(_("Error in pj_do_proj (projection of input coordinate pair)")); G_format_northing(inorth, north_str, curr_proj); G_format_northing(isouth, south_str, curr_proj); G_format_easting(ieast, east_str, curr_proj); G_format_easting(iwest, west_str, curr_proj); if(gprint_bounds->answer) { fprintf(stdout, "n=%s s=%s w=%s e=%s rows=%d cols=%d\n", north_str, south_str, west_str, east_str, irows, icols); } else { fprintf(stdout, "Source cols: %d\n", icols); fprintf(stdout, "Source rows: %d\n", irows); fprintf(stdout, "Local north: %s\n", north_str); fprintf(stdout, "Local south: %s\n", south_str); fprintf(stdout, "Local west: %s\n", west_str); fprintf(stdout, "Local east: %s\n", east_str); } /* somehow approximate local ewres, nsres ?? (use 'g.region -m' on lat/lon side) */ exit(EXIT_SUCCESS); } /* Cut non-overlapping parts of input map */ if (!nocrop->answer) bordwalk(&outcellhd, &incellhd, &oproj, &iproj); /* Add 2 cells on each side for bilinear/cubic & future interpolation methods */ /* (should probably be a factor based on input and output resolution) */ incellhd.north += 2 * incellhd.ns_res; incellhd.east += 2 * incellhd.ew_res; incellhd.south -= 2 * incellhd.ns_res; incellhd.west -= 2 * incellhd.ew_res; if (incellhd.north > inorth) incellhd.north = inorth; if (incellhd.east > ieast) incellhd.east = ieast; if (incellhd.south < isouth) incellhd.south = isouth; if (incellhd.west < iwest) incellhd.west = iwest; Rast_set_input_window(&incellhd); /* And switch back to original location */ G__switch_env(); /* Adjust borders of output map */ if (!nocrop->answer) bordwalk(&incellhd, &outcellhd, &iproj, &oproj); #if 0 outcellhd.west = outcellhd.south = HUGE_VAL; outcellhd.east = outcellhd.north = -HUGE_VAL; for (row = 0; row < incellhd.rows; row++) { ycoord1 = Rast_row_to_northing((double)(row + 0.5), &incellhd); for (col = 0; col < incellhd.cols; col++) { xcoord1 = Rast_col_to_easting((double)(col + 0.5), &incellhd); pj_do_proj(&xcoord1, &ycoord1, &iproj, &oproj); if (xcoord1 > outcellhd.east) outcellhd.east = xcoord1; if (ycoord1 > outcellhd.north) outcellhd.north = ycoord1; if (xcoord1 < outcellhd.west) outcellhd.west = xcoord1; if (ycoord1 < outcellhd.south) outcellhd.south = ycoord1; } } #endif if (res->answer != NULL) /* set user defined resolution */ outcellhd.ns_res = outcellhd.ew_res = atof(res->answer); G_adjust_Cell_head(&outcellhd, 0, 0); Rast_set_output_window(&outcellhd); G_message(" "); G_message(_("Input:")); G_message(_("Cols: %d (%d)"), incellhd.cols, icols); G_message(_("Rows: %d (%d)"), incellhd.rows, irows); G_message(_("North: %f (%f)"), incellhd.north, inorth); G_message(_("South: %f (%f)"), incellhd.south, isouth); G_message(_("West: %f (%f)"), incellhd.west, iwest); G_message(_("East: %f (%f)"), incellhd.east, ieast); G_message(_("EW-res: %f"), incellhd.ew_res); G_message(_("NS-res: %f"), incellhd.ns_res); G_message(" "); G_message(_("Output:")); G_message(_("Cols: %d (%d)"), outcellhd.cols, ocols); G_message(_("Rows: %d (%d)"), outcellhd.rows, orows); G_message(_("North: %f (%f)"), outcellhd.north, onorth); G_message(_("South: %f (%f)"), outcellhd.south, osouth); G_message(_("West: %f (%f)"), outcellhd.west, owest); G_message(_("East: %f (%f)"), outcellhd.east, oeast); G_message(_("EW-res: %f"), outcellhd.ew_res); G_message(_("NS-res: %f"), outcellhd.ns_res); G_message(" "); /* open and read the relevant parts of the input map and close it */ G__switch_env(); Rast_set_input_window(&incellhd); fdi = Rast_open_old(inmap->answer, setname); cell_type = Rast_get_map_type(fdi); ibuffer = readcell(fdi, memory->answer); Rast_close(fdi); G__switch_env(); Rast_set_output_window(&outcellhd); if (strcmp(interpol->answer, "nearest") == 0) { fdo = Rast_open_new(mapname, cell_type); obuffer = (CELL *) Rast_allocate_output_buf(cell_type); } else { fdo = Rast_open_fp_new(mapname); cell_type = FCELL_TYPE; obuffer = (FCELL *) Rast_allocate_output_buf(cell_type); } cell_size = Rast_cell_size(cell_type); xcoord1 = xcoord2 = outcellhd.west + (outcellhd.ew_res / 2); /**/ ycoord1 = ycoord2 = outcellhd.north - (outcellhd.ns_res / 2); /**/ G_important_message(_("Projecting...")); G_percent(0, outcellhd.rows, 2); for (row = 0; row < outcellhd.rows; row++) { obufptr = obuffer; for (col = 0; col < outcellhd.cols; col++) { /* project coordinates in output matrix to */ /* coordinates in input matrix */ if (pj_do_proj(&xcoord1, &ycoord1, &oproj, &iproj) < 0) Rast_set_null_value(obufptr, 1, cell_type); else { /* convert to row/column indices of input matrix */ col_idx = (xcoord1 - incellhd.west) / incellhd.ew_res; row_idx = (incellhd.north - ycoord1) / incellhd.ns_res; /* and resample data point */ interpolate(ibuffer, obufptr, cell_type, &col_idx, &row_idx, &incellhd); } obufptr = G_incr_void_ptr(obufptr, cell_size); xcoord2 += outcellhd.ew_res; xcoord1 = xcoord2; ycoord1 = ycoord2; } Rast_put_row(fdo, obuffer, cell_type); xcoord1 = xcoord2 = outcellhd.west + (outcellhd.ew_res / 2); ycoord2 -= outcellhd.ns_res; ycoord1 = ycoord2; G_percent(row, outcellhd.rows - 1, 2); } Rast_close(fdo); if (have_colors > 0) { Rast_write_colors(mapname, G_mapset(), &colr); Rast_free_colors(&colr); } Rast_short_history(mapname, "raster", &history); Rast_command_history(&history); Rast_write_history(mapname, &history); G_done_msg(NULL); exit(EXIT_SUCCESS); }
int rectify(char *name, char *mapset, struct cache *ebuffer, double aver_z, char *result, char *interp_method) { struct Cell_head cellhd; int ncols, nrows; int row, col; double row_idx, col_idx; int infd, outfd; RASTER_MAP_TYPE map_type; int cell_size; void *trast, *tptr; double n1, e1, z1; double nx, ex, nx1, ex1, zx1; struct cache *ibuffer; select_current_env(); Rast_get_cellhd(name, mapset, &cellhd); /* open the file to be rectified * set window to cellhd first to be able to read file exactly */ Rast_set_input_window(&cellhd); infd = Rast_open_old(name, mapset); map_type = Rast_get_map_type(infd); cell_size = Rast_cell_size(map_type); ibuffer = readcell(infd, seg_mb_img, 0); Rast_close(infd); /* (pmx) 17 april 2000 */ G_message(_("Rectify <%s@%s> (location <%s>)"), name, mapset, G_location()); select_target_env(); G_set_window(&target_window); G_message(_("into <%s@%s> (location <%s>) ..."), result, G_mapset(), G_location()); nrows = target_window.rows; ncols = target_window.cols; if (strcmp(interp_method, "nearest") != 0) { map_type = DCELL_TYPE; cell_size = Rast_cell_size(map_type); } /* open the result file into target window * this open must be first since we change the window later * raster maps open for writing are not affected by window changes * but those open for reading are */ outfd = Rast_open_new(result, map_type); trast = Rast_allocate_output_buf(map_type); for (row = 0; row < nrows; row++) { n1 = target_window.north - (row + 0.5) * target_window.ns_res; G_percent(row, nrows, 2); Rast_set_null_value(trast, ncols, map_type); tptr = trast; for (col = 0; col < ncols; col++) { DCELL *zp = CPTR(ebuffer, row, col); e1 = target_window.west + (col + 0.5) * target_window.ew_res; /* if target cell has no elevation, set to aver_z */ if (Rast_is_d_null_value(zp)) { G_warning(_("No elevation available at row = %d, col = %d"), row, col); z1 = aver_z; } else z1 = *zp; /* target coordinates e1, n1 to photo coordinates ex1, nx1 */ I_ortho_ref(e1, n1, z1, &ex1, &nx1, &zx1, &group.camera_ref, group.XC, group.YC, group.ZC, group.M); G_debug(5, "\t\tAfter ortho ref (photo cords): ex = %f \t nx = %f", ex1, nx1); /* photo coordinates ex1, nx1 to image coordinates ex, nx */ I_georef(ex1, nx1, &ex, &nx, group.E21, group.N21, 1); G_debug(5, "\t\tAfter geo ref: ex = %f \t nx = %f", ex, nx); /* convert to row/column indices of source raster */ row_idx = (cellhd.north - nx) / cellhd.ns_res; col_idx = (ex - cellhd.west) / cellhd.ew_res; /* resample data point */ interpolate(ibuffer, tptr, map_type, &row_idx, &col_idx, &cellhd); tptr = G_incr_void_ptr(tptr, cell_size); } Rast_put_row(outfd, trast, map_type); } G_percent(1, 1, 1); Rast_close(outfd); /* (pmx) 17 april 2000 */ G_free(trast); close(ibuffer->fd); release_cache(ibuffer); Rast_get_cellhd(result, G_mapset(), &cellhd); if (cellhd.proj == 0) { /* x,y imagery */ cellhd.proj = target_window.proj; cellhd.zone = target_window.zone; } if (target_window.proj != cellhd.proj) { cellhd.proj = target_window.proj; G_warning(_("Raster map <%s@%s>: projection don't match current settings"), name, mapset); } if (target_window.zone != cellhd.zone) { cellhd.zone = target_window.zone; G_warning(_("Raster map <%s@%s>: zone don't match current settings"), name, mapset); } select_current_env(); return 1; }
int main(int argc, char *argv[]) { char *name, *outfile; const char *unit; int unit_id; double factor; int fd, projection; FILE *fp, *coor_fp; double res; char *null_string; char ebuf[256], nbuf[256], label[512], formatbuff[256]; char b1[100], b2[100]; int n; int havefirst = FALSE; int coords = 0, i, k = -1; double e1, e2, n1, n2; RASTER_MAP_TYPE data_type; struct Cell_head window; struct { struct Option *opt1, *profile, *res, *output, *null_str, *coord_file, *units; struct Flag *g, *c, *m; } parm; struct GModule *module; G_gisinit(argv[0]); /* Set description */ module = G_define_module(); G_add_keyword(_("raster")); G_add_keyword(_("profile")); module->description = _("Outputs the raster map layer values lying on user-defined line(s)."); parm.opt1 = G_define_standard_option(G_OPT_R_INPUT); parm.output = G_define_standard_option(G_OPT_F_OUTPUT); parm.output->required = NO; parm.output->answer = "-"; parm.output->description = _("Name of file for output (use output=- for stdout)"); parm.profile = G_define_standard_option(G_OPT_M_COORDS); parm.profile->required = NO; parm.profile->multiple = YES; parm.profile->description = _("Profile coordinate pairs"); parm.coord_file = G_define_standard_option(G_OPT_F_INPUT); parm.coord_file->key = "file"; parm.coord_file->required = NO; parm.coord_file->label = _("Name of input file containing coordinate pairs"); parm.coord_file->description = _("Use instead of the 'coordinates' option. " "\"-\" reads from stdin."); parm.res = G_define_option(); parm.res->key = "resolution"; parm.res->type = TYPE_DOUBLE; parm.res->required = NO; parm.res->description = _("Resolution along profile (default = current region resolution)"); parm.null_str = G_define_option(); parm.null_str->key = "null"; parm.null_str->type = TYPE_STRING; parm.null_str->required = NO; parm.null_str->answer = "*"; parm.null_str->description = _("Character to represent no data cell"); parm.g = G_define_flag(); parm.g->key = 'g'; parm.g->description = _("Output easting and northing in first two columns of four column output"); parm.c = G_define_flag(); parm.c->key = 'c'; parm.c->description = _("Output RRR:GGG:BBB color values for each profile point"); parm.units = G_define_standard_option(G_OPT_M_UNITS); parm.units->options = "meters,kilometers,feet,miles"; parm.units->label = parm.units->description; parm.units->description = _("If units are not specified, current location units are used. " "Meters are used by default in geographic (latlon) locations."); if (G_parser(argc, argv)) exit(EXIT_FAILURE); clr = 0; if (parm.c->answer) clr = 1; /* color output */ null_string = parm.null_str->answer; if ((parm.profile->answer && parm.coord_file->answer) || (!parm.profile->answer && !parm.coord_file->answer)) G_fatal_error(_("Either use profile option or coordinate_file " " option, but not both")); G_get_window(&window); projection = G_projection(); /* get conversion factor and units name */ if (parm.units->answer) { unit_id = G_units(parm.units->answer); factor = 1. / G_meters_to_units_factor(unit_id); unit = G_get_units_name(unit_id, 1, 0); } /* keep meters in case of latlon */ else if (projection == PROJECTION_LL) { factor = 1; unit = "meters"; } else { /* get conversion factor to current units */ unit = G_database_unit_name(1); factor = G_database_units_to_meters_factor(); } if (parm.res->answer) { res = atof(parm.res->answer); /* Catch bad resolution ? */ if (res <= 0) G_fatal_error(_("Illegal resolution %g [%s]"), res / factor, unit); } else { /* Do average of EW and NS res */ res = (window.ew_res + window.ns_res) / 2; } G_message(_("Using resolution: %g [%s]"), res / factor, unit); G_begin_distance_calculations(); /* Open Input File for reading */ /* Get Input Name */ name = parm.opt1->answer; if (parm.g->answer) coords = 1; /* Open Raster File */ fd = Rast_open_old(name, ""); /* initialize color structure */ if (clr) Rast_read_colors(name, "", &colors); /* Open ASCII file for output or stdout */ outfile = parm.output->answer; if ((strcmp("-", outfile)) == 0) { fp = stdout; } else if (NULL == (fp = fopen(outfile, "w"))) G_fatal_error(_("Unable to open file <%s>"), outfile); /* Get Raster Type */ data_type = Rast_get_map_type(fd); /* Done with file */ /* Show message giving output format */ G_message(_("Output columns:")); if (coords == 1) sprintf(formatbuff, _("Easting, Northing, Along track dist. [%s], Elevation"), unit); else sprintf(formatbuff, _("Along track dist. [%s], Elevation"), unit); if (clr) strcat(formatbuff, _(" RGB color")); G_message(formatbuff); /* Get Profile Start Coords */ if (parm.coord_file->answer) { if (strcmp("-", parm.coord_file->answer) == 0) coor_fp = stdin; else coor_fp = fopen(parm.coord_file->answer, "r"); if (coor_fp == NULL) G_fatal_error(_("Could not open <%s>"), parm.coord_file->answer); for (n = 1; input(b1, ebuf, b2, nbuf, label, coor_fp); n++) { G_debug(4, "stdin line %d: ebuf=[%s] nbuf=[%s]", n, ebuf, nbuf); if (!G_scan_easting(ebuf, &e2, G_projection()) || !G_scan_northing(nbuf, &n2, G_projection())) G_fatal_error(_("Invalid coordinates %s %s"), ebuf, nbuf); if (havefirst) do_profile(e1, e2, n1, n2, coords, res, fd, data_type, fp, null_string, unit, factor); e1 = e2; n1 = n2; havefirst = TRUE; } if (coor_fp != stdin) fclose(coor_fp); } else { /* Coords given on the Command Line using the profile= option */ for (i = 0; parm.profile->answers[i]; i += 2) { /* Test for number coordinate pairs */ k = i; } if (k == 0) { /* Only one coordinate pair supplied */ G_scan_easting(parm.profile->answers[0], &e1, G_projection()); G_scan_northing(parm.profile->answers[1], &n1, G_projection()); e2 = e1; n2 = n1; /* Get profile info */ do_profile(e1, e2, n1, n2, coords, res, fd, data_type, fp, null_string, unit, factor); } else { for (i = 0; i <= k - 2; i += 2) { G_scan_easting(parm.profile->answers[i], &e1, G_projection()); G_scan_northing(parm.profile->answers[i + 1], &n1, G_projection()); G_scan_easting(parm.profile->answers[i + 2], &e2, G_projection()); G_scan_northing(parm.profile->answers[i + 3], &n2, G_projection()); /* Get profile info */ do_profile(e1, e2, n1, n2, coords, res, fd, data_type, fp, null_string, unit, factor); } } } Rast_close(fd); fclose(fp); if (clr) Rast_free_colors(&colors); exit(EXIT_SUCCESS); } /* Done with main */
int open_file(char *name) { int cell_file, buf_len; int i, row; CELL *buf; /* open raster map */ cell_file = Rast_open_old(name, ""); if (Rast_get_map_type(cell_file) != CELL_TYPE) { Rast_close(cell_file); G_fatal_error(_("Input raster must be of type CELL.")); } n_rows = Rast_window_rows(); n_cols = Rast_window_cols(); G_message(_("File %s -- %d rows X %d columns"), name, n_rows, n_cols); n_cols += (PAD << 1); /* copy raster map into our read/write file */ work_file_name = G_tempfile(); /* create the file and then open it for read and write */ close(creat(work_file_name, 0666)); if ((work_file = open(work_file_name, 2)) < 0) { unlink(work_file_name); G_fatal_error(_("%s: Unable to create temporary file <%s> -- errno = %d"), error_prefix, work_file_name, errno); } buf_len = n_cols * sizeof(CELL); buf = (CELL *) G_malloc(buf_len); Rast_set_c_null_value(buf, n_cols); for (i = 0; i < PAD; i++) { if (write(work_file, buf, buf_len) != buf_len) { unlink(work_file_name); G_fatal_error(_("%s: Error writing temporary file"), error_prefix); } } for (row = 0; row < n_rows; row++) { Rast_get_c_row(cell_file, buf + PAD, row); if (write(work_file, buf, buf_len) != buf_len) { unlink(work_file_name); G_fatal_error(_("%s: Error writing temporary file"), error_prefix); } } Rast_set_c_null_value(buf, n_cols); for (i = 0; i < PAD; i++) { if (write(work_file, buf, buf_len) != buf_len) { unlink(work_file_name); G_fatal_error(_("%s: Error writing temporary file"), error_prefix); } } n_rows += (PAD << 1); G_free(buf); Rast_close(cell_file); Rowio_setup(&row_io, work_file, MAX_ROW, n_cols * sizeof(CELL), read_row, write_row); return 0; }
static int load_files(void) { void *voidc; int rtype; register int i, rowoff, row, col, vxoff, vyoff, offset; int cnt, fd, size, tsiz, coff; int vnum; int y_rows, y_cols; char *pr, *pg, *pb; unsigned char *tr, *tg, *tb, *tset; char *mpfilename, *name; char *yfiles[MAXIMAGES]; struct Colors colors; int ret; size = nrows * ncols; pr = G_malloc(size); pg = G_malloc(size); pb = G_malloc(size); tsiz = Rast_window_cols(); tr = (unsigned char *)G_malloc(tsiz); tg = (unsigned char *)G_malloc(tsiz); tb = (unsigned char *)G_malloc(tsiz); tset = (unsigned char *)G_malloc(tsiz); for (cnt = 0; cnt < frames; cnt++) { if (cnt > MAXIMAGES) { cnt--; break; } for (i = 0; i < size; i++) pr[i] = pg[i] = pb[i] = 0; for (vnum = 0; vnum < numviews; vnum++) { if (icols == vcols) { vxoff = BORDER_W; vyoff = (irows == vrows) ? BORDER_W : BORDER_W + vnum * (BORDER_W + vrows); } else if (irows == vrows) { vxoff = (icols == vcols) ? BORDER_W : BORDER_W + vnum * (BORDER_W + vcols); vyoff = BORDER_W; } else { /* 4 views */ /* assumes we want: view1 view2 view3 view4 */ vxoff = vnum % 2 ? BORDER_W : vcols + 2 * BORDER_W; vyoff = vnum > 1 ? vrows + 2 * BORDER_W : BORDER_W; } name = vfiles[vnum][cnt]; G_message(_("Reading raster map <%s>..."), name); fd = Rast_open_old(name, ""); if (Rast_read_colors(name, "", &colors) < 0) G_fatal_error(_("Unable to read color table for <%s>"), name); rtype = Rast_get_map_type(fd); voidc = Rast_allocate_buf(rtype); for (row = 0; row < vrows; row++) { Rast_get_row(fd, voidc, (int)(row / vscale), rtype); rowoff = (vyoff + row) * ncols; Rast_lookup_colors(voidc, tr, tg, tb, tset, tsiz, &colors, rtype); for (col = 0; col < vcols; col++) { coff = (int)(col / vscale); offset = rowoff + col + vxoff; if (!tset[coff]) pr[offset] = pg[offset] = pb[offset] = (char)255; else { pr[offset] = (char)tr[coff]; pg[offset] = (char)tg[coff]; pb[offset] = (char)tb[coff]; } } } Rast_close(fd); } yfiles[cnt] = G_tempfile(); #ifdef USE_PPM write_ppm(pr, pg, pb, nrows, ncols, &y_rows, &y_cols, yfiles[cnt]); #else write_ycc(pr, pg, pb, nrows, ncols, &y_rows, &y_cols, yfiles[cnt]); #endif } mpfilename = G_tempfile(); write_params(mpfilename, yfiles, outfile, cnt, quality, y_rows, y_cols, 0); if (G_verbose() <= G_verbose_min()) ret = G_spawn(encoder, encoder, mpfilename, SF_REDIRECT_FILE, SF_STDOUT, SF_MODE_OUT, G_DEV_NULL, SF_REDIRECT_FILE, SF_STDERR, SF_MODE_OUT, G_DEV_NULL, NULL); else ret = G_spawn(encoder, encoder, mpfilename, NULL); if (ret != 0) G_warning(_("mpeg_encode ERROR")); clean_files(mpfilename, yfiles, cnt); G_free(voidc); G_free(tset); G_free(tr); G_free(tg); G_free(tb); G_free(pr); G_free(pg); G_free(pb); return (cnt); }
int main(int argc, char **argv) { static DCELL *count, *sum, *mean, *sumu, *sum2, *sum3, *sum4, *min, *max; DCELL *result; struct GModule *module; struct { struct Option *method, *basemap, *covermap, *output; } opt; struct { struct Flag *c, *r; } flag; char methods[2048]; const char *basemap, *covermap, *output; int usecats; int reclass; int base_fd, cover_fd; struct Categories cats; CELL *base_buf; DCELL *cover_buf; struct Range range; CELL mincat, ncats; int method; int rows, cols; int row, col, i; G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("raster")); G_add_keyword(_("statistics")); module->description = _("Calculates category or object oriented statistics (accumulator-based statistics)."); opt.basemap = G_define_standard_option(G_OPT_R_BASE); opt.covermap = G_define_standard_option(G_OPT_R_COVER); opt.method = G_define_option(); opt.method->key = "method"; opt.method->type = TYPE_STRING; opt.method->required = YES; opt.method->description = _("Method of object-based statistic"); for (i = 0; menu[i].name; i++) { if (i) strcat(methods, ","); else *(methods) = 0; strcat(methods, menu[i].name); } opt.method->options = G_store(methods); for (i = 0; menu[i].name; i++) { if (i) strcat(methods, ";"); else *(methods) = 0; strcat(methods, menu[i].name); strcat(methods, ";"); strcat(methods, menu[i].text); } opt.method->descriptions = G_store(methods); opt.output = G_define_standard_option(G_OPT_R_OUTPUT); opt.output->description = _("Resultant raster map"); opt.output->required = YES; flag.c = G_define_flag(); flag.c->key = 'c'; flag.c->description = _("Cover values extracted from the category labels of the cover map"); flag.r = G_define_flag(); flag.r->key = 'r'; flag.r->description = _("Create reclass map with statistics as category labels"); if (G_parser(argc, argv)) exit(EXIT_FAILURE); basemap = opt.basemap->answer; covermap = opt.covermap->answer; output = opt.output->answer; usecats = flag.c->answer; reclass = flag.r->answer; for (i = 0; menu[i].name; i++) if (strcmp(menu[i].name, opt.method->answer) == 0) break; if (!menu[i].name) { G_warning(_("<%s=%s> unknown %s"), opt.method->key, opt.method->answer, opt.method->key); G_usage(); exit(EXIT_FAILURE); } method = menu[i].val; base_fd = Rast_open_old(basemap, ""); cover_fd = Rast_open_old(covermap, ""); if (usecats && Rast_read_cats(covermap, "", &cats) < 0) G_fatal_error(_("Unable to read category file of cover map <%s>"), covermap); if (Rast_map_is_fp(basemap, "") != 0) G_fatal_error(_("The base map must be an integer (CELL) map")); if (Rast_read_range(basemap, "", &range) < 0) G_fatal_error(_("Unable to read range of base map <%s>"), basemap); mincat = range.min; ncats = range.max - range.min + 1; rows = Rast_window_rows(); cols = Rast_window_cols(); switch (method) { case COUNT: count = G_calloc(ncats, sizeof(DCELL)); break; case SUM: sum = G_calloc(ncats, sizeof(DCELL)); break; case MIN: min = G_malloc(ncats * sizeof(DCELL)); break; case MAX: max = G_malloc(ncats * sizeof(DCELL)); break; case RANGE: min = G_malloc(ncats * sizeof(DCELL)); max = G_malloc(ncats * sizeof(DCELL)); break; case AVERAGE: case ADEV: case VARIANCE2: case STDDEV2: case SKEWNESS2: case KURTOSIS2: count = G_calloc(ncats, sizeof(DCELL)); sum = G_calloc(ncats, sizeof(DCELL)); break; case VARIANCE1: case STDDEV1: count = G_calloc(ncats, sizeof(DCELL)); sum = G_calloc(ncats, sizeof(DCELL)); sum2 = G_calloc(ncats, sizeof(DCELL)); break; case SKEWNESS1: count = G_calloc(ncats, sizeof(DCELL)); sum = G_calloc(ncats, sizeof(DCELL)); sum2 = G_calloc(ncats, sizeof(DCELL)); sum3 = G_calloc(ncats, sizeof(DCELL)); break; case KURTOSIS1: count = G_calloc(ncats, sizeof(DCELL)); sum = G_calloc(ncats, sizeof(DCELL)); sum2 = G_calloc(ncats, sizeof(DCELL)); sum4 = G_calloc(ncats, sizeof(DCELL)); break; } if (min) for (i = 0; i < ncats; i++) min[i] = 1e300; if (max) for (i = 0; i < ncats; i++) max[i] = -1e300; base_buf = Rast_allocate_c_buf(); cover_buf = Rast_allocate_d_buf(); G_message(_("First pass")); for (row = 0; row < rows; row++) { Rast_get_c_row(base_fd, base_buf, row); Rast_get_d_row(cover_fd, cover_buf, row); for (col = 0; col < cols; col++) { int n; DCELL v; if (Rast_is_c_null_value(&base_buf[col])) continue; if (Rast_is_d_null_value(&cover_buf[col])) continue; n = base_buf[col] - mincat; if (n < 0 || n >= ncats) continue; v = cover_buf[col]; if (usecats) sscanf(Rast_get_c_cat((CELL *) &v, &cats), "%lf", &v); if (count) count[n]++; if (sum) sum[n] += v; if (sum2) sum2[n] += v * v; if (sum3) sum3[n] += v * v * v; if (sum4) sum4[n] += v * v * v * v; if (min && min[n] > v) min[n] = v; if (max && max[n] < v) max[n] = v; } G_percent(row, rows, 2); } G_percent(row, rows, 2); result = G_calloc(ncats, sizeof(DCELL)); switch (method) { case ADEV: case VARIANCE2: case STDDEV2: case SKEWNESS2: case KURTOSIS2: mean = G_calloc(ncats, sizeof(DCELL)); for (i = 0; i < ncats; i++) mean[i] = sum[i] / count[i]; G_free(sum); break; } switch (method) { case ADEV: sumu = G_calloc(ncats, sizeof(DCELL)); break; case VARIANCE2: case STDDEV2: sum2 = G_calloc(ncats, sizeof(DCELL)); break; case SKEWNESS2: sum2 = G_calloc(ncats, sizeof(DCELL)); sum3 = G_calloc(ncats, sizeof(DCELL)); break; case KURTOSIS2: sum2 = G_calloc(ncats, sizeof(DCELL)); sum4 = G_calloc(ncats, sizeof(DCELL)); break; } if (mean) { G_message(_("Second pass")); for (row = 0; row < rows; row++) { Rast_get_c_row(base_fd, base_buf, row); Rast_get_d_row(cover_fd, cover_buf, row); for (col = 0; col < cols; col++) { int n; DCELL v, d; if (Rast_is_c_null_value(&base_buf[col])) continue; if (Rast_is_d_null_value(&cover_buf[col])) continue; n = base_buf[col] - mincat; if (n < 0 || n >= ncats) continue; v = cover_buf[col]; if (usecats) sscanf(Rast_get_c_cat((CELL *) &v, &cats), "%lf", &v); d = v - mean[n]; if (sumu) sumu[n] += fabs(d); if (sum2) sum2[n] += d * d; if (sum3) sum3[n] += d * d * d; if (sum4) sum4[n] += d * d * d * d; } G_percent(row, rows, 2); } G_percent(row, rows, 2); G_free(mean); G_free(cover_buf); } switch (method) { case COUNT: for (i = 0; i < ncats; i++) result[i] = count[i]; break; case SUM: for (i = 0; i < ncats; i++) result[i] = sum[i]; break; case AVERAGE: for (i = 0; i < ncats; i++) result[i] = sum[i] / count[i]; break; case MIN: for (i = 0; i < ncats; i++) result[i] = min[i]; break; case MAX: for (i = 0; i < ncats; i++) result[i] = max[i]; break; case RANGE: for (i = 0; i < ncats; i++) result[i] = max[i] - min[i]; break; case VARIANCE1: for (i = 0; i < ncats; i++) { double n = count[i]; double var = (sum2[i] - sum[i] * sum[i] / n) / (n - 1); result[i] = var; } break; case STDDEV1: for (i = 0; i < ncats; i++) { double n = count[i]; double var = (sum2[i] - sum[i] * sum[i] / n) / (n - 1); result[i] = sqrt(var); } break; case SKEWNESS1: for (i = 0; i < ncats; i++) { double n = count[i]; double var = (sum2[i] - sum[i] * sum[i] / n) / (n - 1); double skew = (sum3[i] / n - 3 * sum[i] * sum2[i] / (n * n) + 2 * sum[i] * sum[i] * sum[i] / (n * n * n)) / (pow(var, 1.5)); result[i] = skew; } break; case KURTOSIS1: for (i = 0; i < ncats; i++) { double n = count[i]; double var = (sum2[i] - sum[i] * sum[i] / n) / (n - 1); double kurt = (sum4[i] / n - 4 * sum[i] * sum3[i] / (n * n) + 6 * sum[i] * sum[i] * sum2[i] / (n * n * n) - 3 * sum[i] * sum[i] * sum[i] * sum[i] / (n * n * n * n)) / (var * var) - 3; result[i] = kurt; } break; case ADEV: for (i = 0; i < ncats; i++) result[i] = sumu[i] / count[i]; break; case VARIANCE2: for (i = 0; i < ncats; i++) result[i] = sum2[i] / (count[i] - 1); break; case STDDEV2: for (i = 0; i < ncats; i++) result[i] = sqrt(sum2[i] / (count[i] - 1)); break; case SKEWNESS2: for (i = 0; i < ncats; i++) { double n = count[i]; double var = sum2[i] / (n - 1); double sdev = sqrt(var); result[i] = sum3[i] / (sdev * sdev * sdev) / n; } G_free(count); G_free(sum2); G_free(sum3); break; case KURTOSIS2: for (i = 0; i < ncats; i++) { double n = count[i]; double var = sum2[i] / (n - 1); result[i] = sum4[i] / (var * var) / n - 3; } G_free(count); G_free(sum2); G_free(sum4); break; } if (reclass) { const char *tempfile = G_tempfile(); char *input_arg = G_malloc(strlen(basemap) + 7); char *output_arg = G_malloc(strlen(output) + 8); char *rules_arg = G_malloc(strlen(tempfile) + 7); FILE *fp; G_message(_("Generating reclass map")); sprintf(input_arg, "input=%s", basemap); sprintf(output_arg, "output=%s", output); sprintf(rules_arg, "rules=%s", tempfile); fp = fopen(tempfile, "w"); if (!fp) G_fatal_error(_("Unable to open temporary file")); for (i = 0; i < ncats; i++) fprintf(fp, "%d = %d %f\n", mincat + i, mincat + i, result[i]); fclose(fp); G_spawn("r.reclass", "r.reclass", input_arg, output_arg, rules_arg, NULL); } else { int out_fd; DCELL *out_buf; struct Colors colors; G_message(_("Writing output map")); out_fd = Rast_open_fp_new(output); out_buf = Rast_allocate_d_buf(); for (row = 0; row < rows; row++) { Rast_get_c_row(base_fd, base_buf, row); for (col = 0; col < cols; col++) if (Rast_is_c_null_value(&base_buf[col])) Rast_set_d_null_value(&out_buf[col], 1); else out_buf[col] = result[base_buf[col] - mincat]; Rast_put_d_row(out_fd, out_buf); G_percent(row, rows, 2); } G_percent(row, rows, 2); Rast_close(out_fd); if (Rast_read_colors(covermap, "", &colors) > 0) Rast_write_colors(output, G_mapset(), &colors); } return 0; }