int get_ref_window(struct Cell_head *cellhd) { int i; int count; struct Cell_head win; /* from all the files in the group, get max extends and min resolutions */ count = 0; for (i = 0; i < group.group_ref.nfiles; i++) { if (!ref_list[i]) continue; if (count++ == 0) { Rast_get_cellhd(group.group_ref.file[i].name, group.group_ref.file[i].mapset, cellhd); } else { Rast_get_cellhd(group.group_ref.file[i].name, group.group_ref.file[i].mapset, &win); /* max extends */ if (cellhd->north < win.north) cellhd->north = win.north; if (cellhd->south > win.south) cellhd->south = win.south; if (cellhd->west > win.west) cellhd->west = win.west; if (cellhd->east < win.east) cellhd->east = win.east; /* min resolution */ if (cellhd->ns_res > win.ns_res) cellhd->ns_res = win.ns_res; if (cellhd->ew_res > win.ew_res) cellhd->ew_res = win.ew_res; } } /* if the north-south is not multiple of the resolution, * round the south downward */ cellhd->rows = (cellhd->north - cellhd->south) /cellhd->ns_res + 0.5; cellhd->south = cellhd->north - cellhd->rows * cellhd->ns_res; /* do the same for the west */ cellhd->cols = (cellhd->east - cellhd->west) / cellhd->ew_res + 0.5; cellhd->west = cellhd->east - cellhd->cols * cellhd->ew_res; return 1; }
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; }
/* Adjust the region to that of the input raster. Atmospheric corrections should be done on the whole satelite image, not just portions. */ static void adjust_region(const char *name) { struct Cell_head iimg_head; /* the input image header file */ Rast_get_cellhd(name, "", &iimg_head); Rast_set_window(&iimg_head); }
/* check compatibility of map header and region header */ void check_header(char* cellname) { const char *mapset; mapset = G_find_raster(cellname, ""); if (mapset == NULL) { G_fatal_error(_("Raster map <%s> not found"), cellname); } /* read cell header */ struct Cell_head cell_hd; Rast_get_cellhd (cellname, mapset, &cell_hd); /* check compatibility with module region */ if (!((region->ew_res == cell_hd.ew_res) && (region->ns_res == cell_hd.ns_res))) { G_fatal_error(_("cell file %s resolution differs from current region"), cellname); } else { if (opt->verbose) { G_message(_("cell %s header compatible with region header"), cellname); fflush(stderr); } } /* check type of input elevation raster and check if precision is lost */ RASTER_MAP_TYPE data_type; data_type = Rast_map_type(opt->elev_grid, mapset); #ifdef ELEV_SHORT G_verbose_message(_("Elevation stored as SHORT (%dB)"), sizeof(elevation_type)); if (data_type == FCELL_TYPE) { G_warning(_("raster %s is of type FCELL_TYPE " "--precision may be lost."), opt->elev_grid); } if (data_type == DCELL_TYPE) { G_warning(_("raster %s is of type DCELL_TYPE " "--precision may be lost."), opt->elev_grid); } #endif #ifdef ELEV_FLOAT G_verbose_message( _("Elevation stored as FLOAT (%dB)"), sizeof(elevation_type)); if (data_type == CELL_TYPE) { G_warning(_("raster %s is of type CELL_TYPE " "--you should use r.terraflow.short"), opt->elev_grid); } if (data_type == DCELL_TYPE) { G_warning(_("raster %s is of type DCELL_TYPE " "--precision may be lost."), opt->elev_grid); } #endif }
int shape_index(int fd, char **par, area_des ad, double *result) { double area; struct Cell_head hd; CELL complete_value; double EW_DIST1, EW_DIST2, NS_DIST1, NS_DIST2; int mask_fd = -1, null_count = 0; int i = 0, k = 0; int *mask_buf; Rast_set_c_null_value(&complete_value, 1); Rast_get_cellhd(ad->raster, "", &hd); /* open mask if needed */ if (ad->mask == 1) { if ((mask_fd = open(ad->mask_name, O_RDONLY, 0755)) < 0) return 0; mask_buf = malloc(ad->cl * sizeof(int)); for (i = 0; i < ad->rl; i++) { if (read(mask_fd, mask_buf, (ad->cl * sizeof(int))) < 0) return 0; for (k = 0; k < ad->cl; k++) { if (mask_buf[k] == 0) { null_count++; } } } } /*calculate distance */ G_begin_distance_calculations(); /* EW Dist at North edge */ EW_DIST1 = G_distance(hd.east, hd.north, hd.west, hd.north); /* EW Dist at South Edge */ EW_DIST2 = G_distance(hd.east, hd.south, hd.west, hd.south); /* NS Dist at East edge */ NS_DIST1 = G_distance(hd.east, hd.north, hd.east, hd.south); /* NS Dist at West edge */ NS_DIST2 = G_distance(hd.west, hd.north, hd.west, hd.south); area = (((EW_DIST1 + EW_DIST2) / 2) / hd.cols) * (((NS_DIST1 + NS_DIST2) / 2) / hd.rows) * (ad->rl * ad->cl - null_count); *result = area; return 1; }
static void write_support_files(int xtile, int ytile, int overlap) { char name[GNAME_MAX]; struct Cell_head cellhd; char title[64]; struct History history; struct Colors colors; struct Categories cats; sprintf(name, "%s-%03d-%03d", parm.rastout->answer, ytile, xtile); Rast_get_cellhd(name, G_mapset(), &cellhd); cellhd.north = src_w.north - ytile * dst_w.rows * src_w.ns_res; cellhd.south = cellhd.north - (dst_w.rows + 2 * overlap) * src_w.ns_res; cellhd.west = src_w.west + xtile * dst_w.cols * src_w.ew_res; cellhd.east = cellhd.west + (dst_w.cols + 2 * overlap) * src_w.ew_res; Rast_put_cellhd(name, &cellhd); /* copy cats from source map */ if (Rast_read_cats(parm.rastin->answer, "", &cats) < 0) G_fatal_error(_("Unable to read cats for %s"), parm.rastin->answer); Rast_write_cats(name, &cats); /* record map metadata/history info */ G_debug(1, "Tile %d,%d of %s: writing %s", xtile, ytile, parm.rastin->answer, name); sprintf(title, "Tile %d,%d of %s", xtile, ytile, parm.rastin->answer); Rast_put_cell_title(name, title); Rast_short_history(name, "raster", &history); Rast_set_history(&history, HIST_DATSRC_1, parm.rastin->answer); Rast_command_history(&history); Rast_write_history(name, &history); /* copy color table from source map */ if (Rast_read_colors(parm.rastin->answer, "", &colors) < 0) G_fatal_error(_("Unable to read color table for %s"), parm.rastin->answer); if (map_type != CELL_TYPE) Rast_mark_colors_as_fp(&colors); Rast_write_colors(name, G_mapset(), &colors); }
void update_input_region(char* raster, char* region, struct Cell_head &window, double &offset, bool ®ion3D) { if (region){ /* region= */ G_get_element_window(&window, "windows", region, ""); offset = window.bottom; if (window.top != window.bottom) region3D = true; } else if (raster) { struct FPRange range; double zmin, zmax; Rast_get_cellhd(raster, "", &window); Rast_read_fp_range(raster, "", &range); Rast_get_fp_range_min_max(&range, &zmin, &zmax); offset = zmin; } else { // current region G_get_set_window(&window); offset = 0; } }
int renyi(int fd, char **par, area_des ad, double *result) { int ris = RLI_OK; double indice = 0; struct Cell_head hd; Rast_get_cellhd(ad->raster, "", &hd); switch (ad->data_type) { case CELL_TYPE: { ris = calculate(ad, fd, par, &indice); break; } case DCELL_TYPE: { ris = calculateD(ad, fd, par, &indice); break; } case FCELL_TYPE: { ris = calculateF(ad, fd, par, &indice); break; } default: { G_fatal_error("data type unknown"); return RLI_ERRORE; } } if (ris != RLI_OK) return RLI_ERRORE; *result = indice; return RLI_OK; }
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 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; }
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 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[]) { struct GModule *module; struct Option *rastin, *rastout, *method; struct History history; char title[64]; char buf_nsres[100], buf_ewres[100]; struct Colors colors; int infile, outfile; DCELL *outbuf; int row, col; struct Cell_head dst_w, src_w; G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("raster")); G_add_keyword(_("resample")); module->description = _("Resamples raster map layers to a finer grid using interpolation."); rastin = G_define_standard_option(G_OPT_R_INPUT); rastout = G_define_standard_option(G_OPT_R_OUTPUT); method = G_define_option(); method->key = "method"; method->type = TYPE_STRING; method->required = NO; method->description = _("Interpolation method"); method->options = "nearest,bilinear,bicubic,lanczos"; method->answer = "bilinear"; if (G_parser(argc, argv)) exit(EXIT_FAILURE); if (G_strcasecmp(method->answer, "nearest") == 0) neighbors = 1; else if (G_strcasecmp(method->answer, "bilinear") == 0) neighbors = 2; else if (G_strcasecmp(method->answer, "bicubic") == 0) neighbors = 4; else if (G_strcasecmp(method->answer, "lanczos") == 0) neighbors = 5; else G_fatal_error(_("Invalid method: %s"), method->answer); G_get_set_window(&dst_w); /* set window to old map */ Rast_get_cellhd(rastin->answer, "", &src_w); /* enlarge source window */ { double north = Rast_row_to_northing(0.5, &dst_w); double south = Rast_row_to_northing(dst_w.rows - 0.5, &dst_w); int r0 = (int)floor(Rast_northing_to_row(north, &src_w) - 0.5) - 2; int r1 = (int)floor(Rast_northing_to_row(south, &src_w) - 0.5) + 3; double west = Rast_col_to_easting(0.5, &dst_w); double east = Rast_col_to_easting(dst_w.cols - 0.5, &dst_w); int c0 = (int)floor(Rast_easting_to_col(west, &src_w) - 0.5) - 2; int c1 = (int)floor(Rast_easting_to_col(east, &src_w) - 0.5) + 3; src_w.south -= src_w.ns_res * (r1 - src_w.rows); src_w.north += src_w.ns_res * (-r0); src_w.west -= src_w.ew_res * (-c0); src_w.east += src_w.ew_res * (c1 - src_w.cols); src_w.rows = r1 - r0; src_w.cols = c1 - c0; } Rast_set_input_window(&src_w); /* allocate buffers for input rows */ for (row = 0; row < neighbors; row++) bufs[row] = Rast_allocate_d_input_buf(); cur_row = -100; /* open old map */ infile = Rast_open_old(rastin->answer, ""); /* reset window to current region */ Rast_set_output_window(&dst_w); outbuf = Rast_allocate_d_output_buf(); /* open new map */ outfile = Rast_open_new(rastout->answer, DCELL_TYPE); switch (neighbors) { case 1: /* nearest */ for (row = 0; row < dst_w.rows; row++) { double north = Rast_row_to_northing(row + 0.5, &dst_w); double maprow_f = Rast_northing_to_row(north, &src_w) - 0.5; int maprow0 = (int)floor(maprow_f + 0.5); G_percent(row, dst_w.rows, 2); read_rows(infile, maprow0); for (col = 0; col < dst_w.cols; col++) { double east = Rast_col_to_easting(col + 0.5, &dst_w); double mapcol_f = Rast_easting_to_col(east, &src_w) - 0.5; int mapcol0 = (int)floor(mapcol_f + 0.5); double c = bufs[0][mapcol0]; if (Rast_is_d_null_value(&c)) { Rast_set_d_null_value(&outbuf[col], 1); } else { outbuf[col] = c; } } Rast_put_d_row(outfile, outbuf); } break; case 2: /* bilinear */ for (row = 0; row < dst_w.rows; row++) { double north = Rast_row_to_northing(row + 0.5, &dst_w); double maprow_f = Rast_northing_to_row(north, &src_w) - 0.5; int maprow0 = (int)floor(maprow_f); double v = maprow_f - maprow0; G_percent(row, dst_w.rows, 2); read_rows(infile, maprow0); for (col = 0; col < dst_w.cols; col++) { double east = Rast_col_to_easting(col + 0.5, &dst_w); double mapcol_f = Rast_easting_to_col(east, &src_w) - 0.5; int mapcol0 = (int)floor(mapcol_f); int mapcol1 = mapcol0 + 1; double u = mapcol_f - mapcol0; double c00 = bufs[0][mapcol0]; double c01 = bufs[0][mapcol1]; double c10 = bufs[1][mapcol0]; double c11 = bufs[1][mapcol1]; if (Rast_is_d_null_value(&c00) || Rast_is_d_null_value(&c01) || Rast_is_d_null_value(&c10) || Rast_is_d_null_value(&c11)) { Rast_set_d_null_value(&outbuf[col], 1); } else { outbuf[col] = Rast_interp_bilinear(u, v, c00, c01, c10, c11); } } Rast_put_d_row(outfile, outbuf); } break; case 4: /* bicubic */ for (row = 0; row < dst_w.rows; row++) { double north = Rast_row_to_northing(row + 0.5, &dst_w); double maprow_f = Rast_northing_to_row(north, &src_w) - 0.5; int maprow1 = (int)floor(maprow_f); int maprow0 = maprow1 - 1; double v = maprow_f - maprow1; G_percent(row, dst_w.rows, 2); read_rows(infile, maprow0); for (col = 0; col < dst_w.cols; col++) { double east = Rast_col_to_easting(col + 0.5, &dst_w); double mapcol_f = Rast_easting_to_col(east, &src_w) - 0.5; int mapcol1 = (int)floor(mapcol_f); int mapcol0 = mapcol1 - 1; int mapcol2 = mapcol1 + 1; int mapcol3 = mapcol1 + 2; double u = mapcol_f - mapcol1; double c00 = bufs[0][mapcol0]; double c01 = bufs[0][mapcol1]; double c02 = bufs[0][mapcol2]; double c03 = bufs[0][mapcol3]; double c10 = bufs[1][mapcol0]; double c11 = bufs[1][mapcol1]; double c12 = bufs[1][mapcol2]; double c13 = bufs[1][mapcol3]; double c20 = bufs[2][mapcol0]; double c21 = bufs[2][mapcol1]; double c22 = bufs[2][mapcol2]; double c23 = bufs[2][mapcol3]; double c30 = bufs[3][mapcol0]; double c31 = bufs[3][mapcol1]; double c32 = bufs[3][mapcol2]; double c33 = bufs[3][mapcol3]; if (Rast_is_d_null_value(&c00) || Rast_is_d_null_value(&c01) || Rast_is_d_null_value(&c02) || Rast_is_d_null_value(&c03) || Rast_is_d_null_value(&c10) || Rast_is_d_null_value(&c11) || Rast_is_d_null_value(&c12) || Rast_is_d_null_value(&c13) || Rast_is_d_null_value(&c20) || Rast_is_d_null_value(&c21) || Rast_is_d_null_value(&c22) || Rast_is_d_null_value(&c23) || Rast_is_d_null_value(&c30) || Rast_is_d_null_value(&c31) || Rast_is_d_null_value(&c32) || Rast_is_d_null_value(&c33)) { Rast_set_d_null_value(&outbuf[col], 1); } else { outbuf[col] = Rast_interp_bicubic(u, v, c00, c01, c02, c03, c10, c11, c12, c13, c20, c21, c22, c23, c30, c31, c32, c33); } } Rast_put_d_row(outfile, outbuf); } break; case 5: /* lanczos */ for (row = 0; row < dst_w.rows; row++) { double north = Rast_row_to_northing(row + 0.5, &dst_w); double maprow_f = Rast_northing_to_row(north, &src_w) - 0.5; int maprow1 = (int)floor(maprow_f + 0.5); int maprow0 = maprow1 - 2; double v = maprow_f - maprow1; G_percent(row, dst_w.rows, 2); read_rows(infile, maprow0); for (col = 0; col < dst_w.cols; col++) { double east = Rast_col_to_easting(col + 0.5, &dst_w); double mapcol_f = Rast_easting_to_col(east, &src_w) - 0.5; int mapcol2 = (int)floor(mapcol_f + 0.5); int mapcol0 = mapcol2 - 2; int mapcol4 = mapcol2 + 2; double u = mapcol_f - mapcol2; double c[25]; int ci = 0, i, j, do_lanczos = 1; for (i = 0; i < 5; i++) { for (j = mapcol0; j <= mapcol4; j++) { c[ci] = bufs[i][j]; if (Rast_is_d_null_value(&(c[ci]))) { Rast_set_d_null_value(&outbuf[col], 1); do_lanczos = 0; break; } ci++; } if (!do_lanczos) break; } if (do_lanczos) { outbuf[col] = Rast_interp_lanczos(u, v, c); } } Rast_put_d_row(outfile, outbuf); } break; } G_percent(dst_w.rows, dst_w.rows, 2); Rast_close(infile); Rast_close(outfile); /* record map metadata/history info */ sprintf(title, "Resample by %s interpolation", method->answer); Rast_put_cell_title(rastout->answer, title); Rast_short_history(rastout->answer, "raster", &history); Rast_set_history(&history, HIST_DATSRC_1, rastin->answer); G_format_resolution(src_w.ns_res, buf_nsres, src_w.proj); G_format_resolution(src_w.ew_res, buf_ewres, src_w.proj); Rast_format_history(&history, HIST_DATSRC_2, "Source map NS res: %s EW res: %s", buf_nsres, buf_ewres); Rast_command_history(&history); Rast_write_history(rastout->answer, &history); /* copy color table from source map */ if (Rast_read_colors(rastin->answer, "", &colors) < 0) G_fatal_error(_("Unable to read color table for %s"), rastin->answer); Rast_mark_colors_as_fp(&colors); Rast_write_colors(rastout->answer, G_mapset(), &colors); return (EXIT_SUCCESS); }
void* raster2array(const char* name, struct Cell_head* header, int* rows, int* cols, RASTER_MAP_TYPE out_type) { // Open the raster map and load the dem // for simplicity sake, the dem will be an array of // doubles, converted from any possible GRASS CELL type. //ORG char* mapset = G_find_cell2(name, ""); char* mapset = G_find_raster(name, ""); if (mapset == NULL) G_fatal_error("Raster map <%s> not found", name); // Find out the cell type of the DEM //ORG RASTER_MAP_TYPE type = G_raster_map_type(name, mapset); RASTER_MAP_TYPE type = Rast_map_type(name, mapset); // Get a file descriptor for the DEM raster map int infd; //ORG if ((infd = G_open_cell_old(name, mapset)) < 0) if ((infd = Rast_open_old(name, mapset)) < 0) G_fatal_error("Unable to open raster map <%s>", name); // Get header info for the DEM raster map struct Cell_head cellhd; //ORG if (G_get_cellhd(name, mapset, &cellhd) < 0) //ORG G_fatal_error("Unable to open raster map <%s>", name); Rast_get_cellhd(name, mapset, &cellhd); // Create a GRASS buffer for the DEM raster //ORG void* inrast = G_allocate_raster_buf(type); void* inrast = Rast_allocate_buf(type); // Get the max rows and max cols from the window information, since the // header gives the values for the full raster //ORG const int maxr = G_window_rows(); //ORG const int maxc = G_window_cols(); const int maxr = Rast_window_rows(); const int maxc = Rast_window_cols(); // Read in the raster line by line, copying it into the double array // rast for return. void* rast; switch (out_type) { case CELL_TYPE: rast = (int*) calloc(maxr * maxc, sizeof(int)); break; case FCELL_TYPE: rast = (float*) calloc(maxr * maxc, sizeof(float)); break; case DCELL_TYPE: rast = (double*) calloc(maxr * maxc, sizeof(double)); break; } if (rast == NULL) { G_fatal_error("Unable to allocate memory for raster map <%s>", name); } int row, col; for (row = 0; row < maxr; ++row) { //ORG if (G_get_raster_row(infd, inrast, row, type) < 0) //ORG G_fatal_error("Unable to read raster map <%s> row %d", name, row); Rast_get_row(infd, inrast, row, type); for (col = 0; col < maxc; ++col) { int index = col + row * maxc; if (out_type == CELL_TYPE) { switch (type) { case CELL_TYPE: ((int*) rast)[index] = ((int *) inrast)[col]; break; case FCELL_TYPE: ((int*) rast)[index] = (int) ((float *) inrast)[col]; break; case DCELL_TYPE: ((int*) rast)[index] = (int) ((double *) inrast)[col]; break; default: G_fatal_error("Unknown cell type"); break; } } if (out_type == FCELL_TYPE) { switch (type) { case CELL_TYPE: ((float*) rast)[index] = (float) ((int *) inrast)[col]; break; case FCELL_TYPE: ((float*) rast)[index] = ((float *) inrast)[col]; break; case DCELL_TYPE: ((float*) rast)[index] = (float) ((double *) inrast)[col]; break; default: G_fatal_error("Unknown cell type"); break; } } if (out_type == DCELL_TYPE) { switch (type) { case CELL_TYPE: ((double*) rast)[index] = (double) ((int *) inrast)[col]; break; case FCELL_TYPE: ((double*) rast)[index] = (double) ((float *) inrast)[col]; break; case DCELL_TYPE: ((double*) rast)[index] = ((double *) inrast)[col]; break; default: G_fatal_error("Unknown cell type"); break; } } } } // Return cellhd, maxr, and maxc by pointer if (header != NULL) *header = cellhd; if (rows != NULL) *rows = maxr; if (cols != NULL) *cols = maxc; return rast; }
int main(int argc, char *argv[]) { int m1; struct FPRange range; DCELL cellmin, cellmax; FCELL *cellrow, fcellmin; struct GModule *module; struct { struct Option *input, *elev, *slope, *aspect, *pcurv, *tcurv, *mcurv, *smooth, *maskmap, *zmult, *fi, *segmax, *npmin, *res_ew, *res_ns, *overlap, *theta, *scalex; } parm; struct { struct Flag *deriv, *cprght; } flag; G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("raster")); G_add_keyword(_("resample")); module->description = _("Reinterpolates and optionally computes topographic analysis from " "input raster map to a new raster map (possibly with " "different resolution) using regularized spline with " "tension and smoothing."); parm.input = G_define_standard_option(G_OPT_R_INPUT); parm.res_ew = G_define_option(); parm.res_ew->key = "ew_res"; parm.res_ew->type = TYPE_DOUBLE; parm.res_ew->required = YES; parm.res_ew->description = _("Desired east-west resolution"); parm.res_ns = G_define_option(); parm.res_ns->key = "ns_res"; parm.res_ns->type = TYPE_DOUBLE; parm.res_ns->required = YES; parm.res_ns->description = _("Desired north-south resolution"); parm.elev = G_define_option(); parm.elev->key = "elev"; parm.elev->type = TYPE_STRING; parm.elev->required = NO; parm.elev->gisprompt = "new,cell,raster"; parm.elev->description = _("Output z-file (elevation) map"); parm.elev->guisection = _("Output"); parm.slope = G_define_option(); parm.slope->key = "slope"; parm.slope->type = TYPE_STRING; parm.slope->required = NO; parm.slope->gisprompt = "new,cell,raster"; parm.slope->description = _("Output slope map (or fx)"); parm.slope->guisection = _("Output"); parm.aspect = G_define_option(); parm.aspect->key = "aspect"; parm.aspect->type = TYPE_STRING; parm.aspect->required = NO; parm.aspect->gisprompt = "new,cell,raster"; parm.aspect->description = _("Output aspect map (or fy)"); parm.aspect->guisection = _("Output"); parm.pcurv = G_define_option(); parm.pcurv->key = "pcurv"; parm.pcurv->type = TYPE_STRING; parm.pcurv->required = NO; parm.pcurv->gisprompt = "new,cell,raster"; parm.pcurv->description = _("Output profile curvature map (or fxx)"); parm.pcurv->guisection = _("Output"); parm.tcurv = G_define_option(); parm.tcurv->key = "tcurv"; parm.tcurv->type = TYPE_STRING; parm.tcurv->required = NO; parm.tcurv->gisprompt = "new,cell,raster"; parm.tcurv->description = _("Output tangential curvature map (or fyy)"); parm.tcurv->guisection = _("Output"); parm.mcurv = G_define_option(); parm.mcurv->key = "mcurv"; parm.mcurv->type = TYPE_STRING; parm.mcurv->required = NO; parm.mcurv->gisprompt = "new,cell,raster"; parm.mcurv->description = _("Output mean curvature map (or fxy)"); parm.mcurv->guisection = _("Output"); parm.smooth = G_define_option(); parm.smooth->key = "smooth"; parm.smooth->type = TYPE_STRING; parm.smooth->required = NO; parm.smooth->gisprompt = "old,cell,raster"; parm.smooth->description = _("Name of raster map containing smoothing"); parm.smooth->guisection = _("Settings"); parm.maskmap = G_define_option(); parm.maskmap->key = "maskmap"; parm.maskmap->type = TYPE_STRING; parm.maskmap->required = NO; parm.maskmap->gisprompt = "old,cell,raster"; parm.maskmap->description = _("Name of raster map to be used as mask"); parm.maskmap->guisection = _("Settings"); parm.overlap = G_define_option(); parm.overlap->key = "overlap"; parm.overlap->type = TYPE_INTEGER; parm.overlap->required = NO; parm.overlap->answer = OVERLAP; parm.overlap->description = _("Rows/columns overlap for segmentation"); parm.overlap->guisection = _("Settings"); parm.zmult = G_define_option(); parm.zmult->key = "zmult"; parm.zmult->type = TYPE_DOUBLE; parm.zmult->answer = ZMULT; parm.zmult->required = NO; parm.zmult->description = _("Multiplier for z-values"); parm.zmult->guisection = _("Settings"); parm.fi = G_define_option(); parm.fi->key = "tension"; parm.fi->type = TYPE_DOUBLE; parm.fi->answer = TENSION; parm.fi->required = NO; parm.fi->description = _("Spline tension value"); parm.fi->guisection = _("Settings"); parm.theta = G_define_option(); parm.theta->key = "theta"; parm.theta->type = TYPE_DOUBLE; parm.theta->required = NO; parm.theta->description = _("Anisotropy angle (in degrees)"); parm.theta->guisection = _("Anisotropy"); parm.scalex = G_define_option(); parm.scalex->key = "scalex"; parm.scalex->type = TYPE_DOUBLE; parm.scalex->required = NO; parm.scalex->description = _("Anisotropy scaling factor"); parm.scalex->guisection = _("Anisotropy"); flag.cprght = G_define_flag(); flag.cprght->key = 't'; flag.cprght->description = _("Use dnorm independent tension"); flag.deriv = G_define_flag(); flag.deriv->key = 'd'; flag.deriv->description = _("Output partial derivatives instead of topographic parameters"); flag.deriv->guisection = _("Output"); if (G_parser(argc, argv)) exit(EXIT_FAILURE); G_get_set_window(&winhd); inp_ew_res = winhd.ew_res; inp_ns_res = winhd.ns_res; inp_cols = winhd.cols; inp_rows = winhd.rows; inp_x_orig = winhd.west; inp_y_orig = winhd.south; input = parm.input->answer; smooth = parm.smooth->answer; maskmap = parm.maskmap->answer; elev = parm.elev->answer; slope = parm.slope->answer; aspect = parm.aspect->answer; pcurv = parm.pcurv->answer; tcurv = parm.tcurv->answer; mcurv = parm.mcurv->answer; cond2 = ((pcurv != NULL) || (tcurv != NULL) || (mcurv != NULL)); cond1 = ((slope != NULL) || (aspect != NULL) || cond2); deriv = flag.deriv->answer; dtens = flag.cprght->answer; ertre = 0.1; if (!G_scan_resolution(parm.res_ew->answer, &ew_res, winhd.proj)) G_fatal_error(_("Unable to read ew_res value")); if (!G_scan_resolution(parm.res_ns->answer, &ns_res, winhd.proj)) G_fatal_error(_("Unable to read ns_res value")); if (sscanf(parm.fi->answer, "%lf", &fi) != 1) G_fatal_error(_("Invalid value for tension")); if (sscanf(parm.zmult->answer, "%lf", &zmult) != 1) G_fatal_error(_("Invalid value for zmult")); if (sscanf(parm.overlap->answer, "%d", &overlap) != 1) G_fatal_error(_("Invalid value for overlap")); if (parm.theta->answer) { if (sscanf(parm.theta->answer, "%lf", &theta) != 1) G_fatal_error(_("Invalid value for theta")); } if (parm.scalex->answer) { if (sscanf(parm.scalex->answer, "%lf", &scalex) != 1) G_fatal_error(_("Invalid value for scalex")); if (!parm.theta->answer) G_fatal_error(_("When using anisotropy both theta and scalex must be specified")); } /* * G_set_embedded_null_value_mode(1); */ outhd.ew_res = ew_res; outhd.ns_res = ns_res; outhd.east = winhd.east; outhd.west = winhd.west; outhd.north = winhd.north; outhd.south = winhd.south; outhd.proj = winhd.proj; outhd.zone = winhd.zone; G_adjust_Cell_head(&outhd, 0, 0); ew_res = outhd.ew_res; ns_res = outhd.ns_res; nsizc = outhd.cols; nsizr = outhd.rows; disk = nsizc * nsizr * sizeof(int); az = G_alloc_vector(nsizc + 1); if (cond1) { adx = G_alloc_vector(nsizc + 1); ady = G_alloc_vector(nsizc + 1); if (cond2) { adxx = G_alloc_vector(nsizc + 1); adyy = G_alloc_vector(nsizc + 1); adxy = G_alloc_vector(nsizc + 1); } } if (smooth != NULL) { fdsmooth = Rast_open_old(smooth, ""); Rast_get_cellhd(smooth, "", &smhd); if ((winhd.ew_res != smhd.ew_res) || (winhd.ns_res != smhd.ns_res)) G_fatal_error(_("Map <%s> is the wrong resolution"), smooth); if (Rast_read_fp_range(smooth, "", &range) >= 0) Rast_get_fp_range_min_max(&range, &cellmin, &cellmax); fcellmin = (float)cellmin; if (Rast_is_f_null_value(&fcellmin) || fcellmin < 0.0) G_fatal_error(_("Smoothing values can not be negative or NULL")); } Rast_get_cellhd(input, "", &inphd); if ((winhd.ew_res != inphd.ew_res) || (winhd.ns_res != inphd.ns_res)) G_fatal_error(_("Input map resolution differs from current region resolution!")); fdinp = Rast_open_old(input, ""); sdisk = 0; if (elev != NULL) sdisk += disk; if (slope != NULL) sdisk += disk; if (aspect != NULL) sdisk += disk; if (pcurv != NULL) sdisk += disk; if (tcurv != NULL) sdisk += disk; if (mcurv != NULL) sdisk += disk; G_message(_("Processing all selected output files will require")); if (sdisk > 1024) { if (sdisk > 1024 * 1024) { if (sdisk > 1024 * 1024 * 1024) { G_message(_("%.2f GB of disk space for temp files."), sdisk / (1024. * 1024. * 1024.)); } else G_message(_("%.2f MB of disk space for temp files."), sdisk / (1024. * 1024.)); } else G_message(_("%.2f KB of disk space for temp files."), sdisk / 1024.); } else G_message(_("%d bytes of disk space for temp files."), sdisk); fstar2 = fi * fi / 4.; tfsta2 = fstar2 + fstar2; deltx = winhd.east - winhd.west; delty = winhd.north - winhd.south; xmin = winhd.west; xmax = winhd.east; ymin = winhd.south; ymax = winhd.north; if (smooth != NULL) smc = -9999; else smc = 0.01; if (Rast_read_fp_range(input, "", &range) >= 0) { Rast_get_fp_range_min_max(&range, &cellmin, &cellmax); } else { cellrow = Rast_allocate_f_buf(); for (m1 = 0; m1 < inp_rows; m1++) { Rast_get_f_row(fdinp, cellrow, m1); Rast_row_update_fp_range(cellrow, m1, &range, FCELL_TYPE); } Rast_get_fp_range_min_max(&range, &cellmin, &cellmax); } fcellmin = (float)cellmin; if (Rast_is_f_null_value(&fcellmin)) G_fatal_error(_("Maximum value of a raster map is NULL.")); zmin = (double)cellmin *zmult; zmax = (double)cellmax *zmult; G_debug(1, "zmin=%f, zmax=%f", zmin, zmax); if (fd4 != NULL) fprintf(fd4, "deltx,delty %f %f \n", deltx, delty); create_temp_files(); IL_init_params_2d(¶ms, NULL, 1, 1, zmult, KMIN, KMAX, maskmap, outhd.rows, outhd.cols, az, adx, ady, adxx, adyy, adxy, fi, MAXPOINTS, SCIK1, SCIK2, SCIK3, smc, elev, slope, aspect, pcurv, tcurv, mcurv, dmin, inp_x_orig, inp_y_orig, deriv, theta, scalex, Tmp_fd_z, Tmp_fd_dx, Tmp_fd_dy, Tmp_fd_xx, Tmp_fd_yy, Tmp_fd_xy, NULL, NULL, 0, NULL); /* In the above line, the penultimate argument is supposed to be a * deviations file pointer. None is obvious, so I used NULL. */ /* The 3rd and 4th argument are int-s, elatt and smatt (from the function * definition. The value 1 seemed like a good placeholder... or not. */ IL_init_func_2d(¶ms, IL_grid_calc_2d, IL_matrix_create, IL_check_at_points_2d, IL_secpar_loop_2d, IL_crst, IL_crstg, IL_write_temp_2d); G_message(_("Temporarily changing the region to desired resolution ...")); Rast_set_window(&outhd); bitmask = IL_create_bitmask(¶ms); /* change region to initial region */ G_message(_("Changing back to the original region ...")); Rast_set_window(&winhd); ertot = 0.; cursegm = 0; G_message(_("Percent complete: ")); NPOINT = IL_resample_interp_segments_2d(¶ms, bitmask, zmin, zmax, &zminac, &zmaxac, &gmin, &gmax, &c1min, &c1max, &c2min, &c2max, &ertot, nsizc, &dnorm, overlap, inp_rows, inp_cols, fdsmooth, fdinp, ns_res, ew_res, inp_ns_res, inp_ew_res, dtens); G_message(_("dnorm in mainc after grid before out1= %f"), dnorm); if (NPOINT < 0) { clean(); G_fatal_error(_("split_and_interpolate() failed")); } if (fd4 != NULL) fprintf(fd4, "max. error found = %f \n", ertot); G_free_vector(az); if (cond1) { G_free_vector(adx); G_free_vector(ady); if (cond2) { G_free_vector(adxx); G_free_vector(adyy); G_free_vector(adxy); } } G_message(_("dnorm in mainc after grid before out2= %f"), dnorm); if (IL_resample_output_2d(¶ms, zmin, zmax, zminac, zmaxac, c1min, c1max, c2min, c2max, gmin, gmax, ertot, input, &dnorm, &outhd, &winhd, smooth, NPOINT) < 0) { clean(); G_fatal_error(_("Unable to write raster maps -- try increasing cell size")); } G_free(zero_array_cell); clean(); if (fd4) fclose(fd4); Rast_close(fdinp); if (smooth != NULL) Rast_close(fdsmooth); G_done_msg(" "); exit(EXIT_SUCCESS); }
int main(int argc, char *argv[]) { /* Global variable & function declarations */ struct GModule *module; struct { struct Option *orig, *real, *imag; } opt; const char *Cellmap_real, *Cellmap_imag; const char *Cellmap_orig; int realfd, imagfd, outputfd, maskfd; /* the input and output file descriptors */ struct Cell_head realhead, imaghead; DCELL *cell_real, *cell_imag; CELL *maskbuf; int i, j; /* Loop control variables */ int rows, cols; /* number of rows & columns */ long totsize; /* Total number of data points */ double (*data)[2]; /* Data structure containing real & complex values of FFT */ G_gisinit(argv[0]); /* Set description */ module = G_define_module(); G_add_keyword(_("imagery")); G_add_keyword(_("transformation")); G_add_keyword(_("Fast Fourier Transform")); module->description = _("Inverse Fast Fourier Transform (IFFT) for image processing."); /* define options */ opt.real = G_define_standard_option(G_OPT_R_INPUT); opt.real->key = "real"; opt.real->description = _("Name of input raster map (image fft, real part)"); opt.imag = G_define_standard_option(G_OPT_R_INPUT); opt.imag->key = "imaginary"; opt.imag->description = _("Name of input raster map (image fft, imaginary part"); opt.orig = G_define_standard_option(G_OPT_R_OUTPUT); opt.orig->description = _("Name for output raster map"); /*call parser */ if (G_parser(argc, argv)) exit(EXIT_FAILURE); Cellmap_real = opt.real->answer; Cellmap_imag = opt.imag->answer; Cellmap_orig = opt.orig->answer; /* get and compare the original window data */ Rast_get_cellhd(Cellmap_real, "", &realhead); Rast_get_cellhd(Cellmap_imag, "", &imaghead); if (realhead.proj != imaghead.proj || realhead.zone != imaghead.zone || realhead.north != imaghead.north || realhead.south != imaghead.south || realhead.east != imaghead.east || realhead.west != imaghead.west || realhead.ew_res != imaghead.ew_res || realhead.ns_res != imaghead.ns_res) G_fatal_error(_("The real and imaginary original windows did not match")); Rast_set_window(&realhead); /* set the window to the whole cell map */ /* open input raster map */ realfd = Rast_open_old(Cellmap_real, ""); imagfd = Rast_open_old(Cellmap_imag, ""); /* get the rows and columns in the current window */ rows = Rast_window_rows(); cols = Rast_window_cols(); totsize = rows * cols; /* Allocate appropriate memory for the structure containing the real and complex components of the FFT. DATA[0] will contain the real, and DATA[1] the complex component. */ data = G_malloc(rows * cols * 2 * sizeof(double)); /* allocate the space for one row of cell map data */ cell_real = Rast_allocate_d_buf(); cell_imag = Rast_allocate_d_buf(); #define C(i, j) ((i) * cols + (j)) /* Read in cell map values */ G_message(_("Reading raster maps...")); for (i = 0; i < rows; i++) { Rast_get_d_row(realfd, cell_real, i); Rast_get_d_row(imagfd, cell_imag, i); for (j = 0; j < cols; j++) { data[C(i, j)][0] = cell_real[j]; data[C(i, j)][1] = cell_imag[j]; } G_percent(i+1, rows, 2); } /* close input cell maps */ Rast_close(realfd); Rast_close(imagfd); /* Read in cell map values */ G_message(_("Masking raster maps...")); maskfd = Rast_maskfd(); if (maskfd >= 0) { maskbuf = Rast_allocate_c_buf(); for (i = 0; i < rows; i++) { Rast_get_c_row(maskfd, maskbuf, i); for (j = 0; j < cols; j++) { if (maskbuf[j] == 0) { data[C(i, j)][0] = 0.0; data[C(i, j)][1] = 0.0; } } G_percent(i+1, rows, 2); } Rast_close(maskfd); G_free(maskbuf); } #define SWAP1(a, b) \ do { \ double temp = (a); \ (a) = (b); \ (b) = temp; \ } while (0) #define SWAP2(a, b) \ do { \ SWAP1(data[(a)][0], data[(b)][0]); \ SWAP1(data[(a)][1], data[(b)][1]); \ } while (0) /* rotate the data array for standard display */ G_message(_("Rotating data...")); for (i = 0; i < rows; i++) for (j = 0; j < cols / 2; j++) SWAP2(C(i, j), C(i, j + cols / 2)); for (i = 0; i < rows / 2; i++) for (j = 0; j < cols; j++) SWAP2(C(i, j), C(i + rows / 2, j)); /* perform inverse FFT */ G_message(_("Starting Inverse FFT...")); fft2(1, data, totsize, cols, rows); /* open the output cell map */ outputfd = Rast_open_fp_new(Cellmap_orig); /* Write out result to a new cell map */ G_message(_("Writing raster map <%s>..."), Cellmap_orig); for (i = 0; i < rows; i++) { for (j = 0; j < cols; j++) cell_real[j] = data[C(i, j)][0]; Rast_put_d_row(outputfd, cell_real); G_percent(i+1, rows, 2); } Rast_close(outputfd); G_free(cell_real); G_free(cell_imag); fft_colors(Cellmap_orig); /* Release memory resources */ G_free(data); G_done_msg(" "); exit(EXIT_SUCCESS); }
GDALDataset *GRASSDataset::Open( GDALOpenInfo * poOpenInfo ) { char *pszGisdb = NULL, *pszLoc = NULL; char *pszMapset = NULL, *pszElem = NULL, *pszName = NULL; char **papszCells = NULL; char **papszMapsets = NULL; /* -------------------------------------------------------------------- */ /* Does this even look like a grass file path? */ /* -------------------------------------------------------------------- */ if( strstr(poOpenInfo->pszFilename,"/cellhd/") == NULL && strstr(poOpenInfo->pszFilename,"/group/") == NULL ) return NULL; /* Always init, if no rasters are opened G_no_gisinit resets the projection and * rasters in different projection may be then opened */ // Don't use GISRC file and read/write GRASS variables (from location G_VAR_GISRC) to memory only. G_set_gisrc_mode ( G_GISRC_MODE_MEMORY ); // Init GRASS libraries (required) G_no_gisinit(); // Doesn't check write permissions for mapset compare to G_gisinit // Set error function G_set_error_routine ( (GrassErrorHandler) Grass2CPLErrorHook ); // GISBASE is path to the directory where GRASS is installed, if ( !getenv( "GISBASE" ) ) { static char* gisbaseEnv = NULL; const char *gisbase = GRASS_GISBASE; CPLError( CE_Warning, CPLE_AppDefined, "GRASS warning: GISBASE " "enviroment variable was not set, using:\n%s", gisbase ); char buf[2000]; snprintf ( buf, sizeof(buf), "GISBASE=%s", gisbase ); buf[sizeof(buf)-1] = '\0'; CPLFree(gisbaseEnv); gisbaseEnv = CPLStrdup ( buf ); putenv( gisbaseEnv ); } if ( !SplitPath( poOpenInfo->pszFilename, &pszGisdb, &pszLoc, &pszMapset, &pszElem, &pszName) ) { return NULL; } /* -------------------------------------------------------------------- */ /* Check element name */ /* -------------------------------------------------------------------- */ if ( strcmp(pszElem,"cellhd") != 0 && strcmp(pszElem,"group") != 0 ) { G_free(pszGisdb); G_free(pszLoc); G_free(pszMapset); G_free(pszElem); G_free(pszName); return NULL; } /* -------------------------------------------------------------------- */ /* Set GRASS variables */ /* -------------------------------------------------------------------- */ G__setenv( "GISDBASE", pszGisdb ); G__setenv( "LOCATION_NAME", pszLoc ); G__setenv( "MAPSET", pszMapset); // group is searched only in current mapset G_reset_mapsets(); G_add_mapset_to_search_path ( pszMapset ); /* -------------------------------------------------------------------- */ /* Check if this is a valid grass cell. */ /* -------------------------------------------------------------------- */ if ( strcmp(pszElem,"cellhd") == 0 ) { if ( G_find_file2("cell", pszName, pszMapset) == NULL ) { G_free(pszGisdb); G_free(pszLoc); G_free(pszMapset); G_free(pszElem); G_free(pszName); return NULL; } papszMapsets = CSLAddString( papszMapsets, pszMapset ); papszCells = CSLAddString( papszCells, pszName ); } /* -------------------------------------------------------------------- */ /* Check if this is a valid GRASS imagery group. */ /* -------------------------------------------------------------------- */ else { struct Ref ref; I_init_group_ref( &ref ); if ( I_get_group_ref( pszName, &ref ) == 0 ) { G_free(pszGisdb); G_free(pszLoc); G_free(pszMapset); G_free(pszElem); G_free(pszName); return NULL; } for( int iRef = 0; iRef < ref.nfiles; iRef++ ) { papszCells = CSLAddString( papszCells, ref.file[iRef].name ); papszMapsets = CSLAddString( papszMapsets, ref.file[iRef].mapset ); G_add_mapset_to_search_path ( ref.file[iRef].mapset ); } I_free_group_ref( &ref ); } G_free( pszMapset ); G_free( pszName ); /* -------------------------------------------------------------------- */ /* Create a corresponding GDALDataset. */ /* -------------------------------------------------------------------- */ GRASSDataset *poDS; poDS = new GRASSDataset(); /* notdef: should only allow read access to an existing cell, right? */ poDS->eAccess = poOpenInfo->eAccess; poDS->pszGisdbase = pszGisdb; poDS->pszLocation = pszLoc; poDS->pszElement = pszElem; /* -------------------------------------------------------------------- */ /* Capture some information from the file that is of interest. */ /* -------------------------------------------------------------------- */ #if GRASS_VERSION_MAJOR >= 7 Rast_get_cellhd( papszCells[0], papszMapsets[0], &(poDS->sCellInfo) ); #else if( G_get_cellhd( papszCells[0], papszMapsets[0], &(poDS->sCellInfo) ) != 0 ) { CPLError( CE_Warning, CPLE_AppDefined, "GRASS: Cannot open raster header"); delete poDS; return NULL; } #endif poDS->nRasterXSize = poDS->sCellInfo.cols; poDS->nRasterYSize = poDS->sCellInfo.rows; poDS->adfGeoTransform[0] = poDS->sCellInfo.west; poDS->adfGeoTransform[1] = poDS->sCellInfo.ew_res; poDS->adfGeoTransform[2] = 0.0; poDS->adfGeoTransform[3] = poDS->sCellInfo.north; poDS->adfGeoTransform[4] = 0.0; poDS->adfGeoTransform[5] = -1 * poDS->sCellInfo.ns_res; /* -------------------------------------------------------------------- */ /* Try to get a projection definition. */ /* -------------------------------------------------------------------- */ struct Key_Value *projinfo, *projunits; projinfo = G_get_projinfo(); projunits = G_get_projunits(); poDS->pszProjection = GPJ_grass_to_wkt ( projinfo, projunits, 0, 0); if (projinfo) G_free_key_value(projinfo); if (projunits) G_free_key_value(projunits); /* -------------------------------------------------------------------- */ /* Create band information objects. */ /* -------------------------------------------------------------------- */ for( int iBand = 0; papszCells[iBand] != NULL; iBand++ ) { GRASSRasterBand *rb = new GRASSRasterBand( poDS, iBand+1, papszMapsets[iBand], papszCells[iBand] ); if ( !rb->valid ) { CPLError( CE_Warning, CPLE_AppDefined, "GRASS: Cannot open raster band %d", iBand); delete rb; delete poDS; return NULL; } poDS->SetBand( iBand+1, rb ); } CSLDestroy(papszCells); CSLDestroy(papszMapsets); /* -------------------------------------------------------------------- */ /* Confirm the requested access is supported. */ /* -------------------------------------------------------------------- */ if( poOpenInfo->eAccess == GA_Update ) { delete poDS; CPLError( CE_Failure, CPLE_NotSupported, "The GRASS driver does not support update access to existing" " datasets.\n" ); return NULL; } return poDS; }
int main(int argc, char *argv[]) { struct GModule *module; struct { struct Option *rastin, *rastout, *method, *quantile; } parm; struct { struct Flag *nulls, *weight; } flag; struct History history; char title[64]; char buf_nsres[100], buf_ewres[100]; struct Colors colors; int row; G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("raster")); G_add_keyword(_("resample")); module->description = _("Resamples raster map layers to a coarser grid using aggregation."); parm.rastin = G_define_standard_option(G_OPT_R_INPUT); parm.rastout = G_define_standard_option(G_OPT_R_OUTPUT); parm.method = G_define_option(); parm.method->key = "method"; parm.method->type = TYPE_STRING; parm.method->required = NO; parm.method->description = _("Aggregation method"); parm.method->options = build_method_list(); parm.method->answer = "average"; parm.quantile = G_define_option(); parm.quantile->key = "quantile"; parm.quantile->type = TYPE_DOUBLE; parm.quantile->required = NO; parm.quantile->description = _("Quantile to calculate for method=quantile"); parm.quantile->options = "0.0-1.0"; parm.quantile->answer = "0.5"; flag.nulls = G_define_flag(); flag.nulls->key = 'n'; flag.nulls->description = _("Propagate NULLs"); flag.weight = G_define_flag(); flag.weight->key = 'w'; flag.weight->description = _("Weight according to area (slower)"); if (G_parser(argc, argv)) exit(EXIT_FAILURE); nulls = flag.nulls->answer; method = find_method(parm.method->answer); if (method < 0) G_fatal_error(_("Unknown method <%s>"), parm.method->answer); if (menu[method].method == c_quant) { quantile = atoi(parm.quantile->answer); closure = &quantile; } G_get_set_window(&dst_w); /* set window to old map */ Rast_get_cellhd(parm.rastin->answer, "", &src_w); /* enlarge source window */ { int r0 = (int)floor(Rast_northing_to_row(dst_w.north, &src_w)); int r1 = (int)ceil(Rast_northing_to_row(dst_w.south, &src_w)); int c0 = (int)floor(Rast_easting_to_col(dst_w.west, &src_w)); int c1 = (int)ceil(Rast_easting_to_col(dst_w.east, &src_w)); src_w.south -= src_w.ns_res * (r1 - src_w.rows); src_w.north += src_w.ns_res * (-r0); src_w.west -= src_w.ew_res * (-c0); src_w.east += src_w.ew_res * (c1 - src_w.cols); src_w.rows = r1 - r0; src_w.cols = c1 - c0; } Rast_set_input_window(&src_w); Rast_set_output_window(&dst_w); row_scale = 2 + ceil(dst_w.ns_res / src_w.ns_res); col_scale = 2 + ceil(dst_w.ew_res / src_w.ew_res); /* allocate buffers for input rows */ bufs = G_malloc(row_scale * sizeof(DCELL *)); for (row = 0; row < row_scale; row++) bufs[row] = Rast_allocate_d_input_buf(); /* open old map */ infile = Rast_open_old(parm.rastin->answer, ""); /* allocate output buffer */ outbuf = Rast_allocate_d_output_buf(); /* open new map */ outfile = Rast_open_new(parm.rastout->answer, DCELL_TYPE); if (flag.weight->answer && menu[method].method_w) resamp_weighted(); else resamp_unweighted(); G_percent(dst_w.rows, dst_w.rows, 2); Rast_close(infile); Rast_close(outfile); /* record map metadata/history info */ sprintf(title, "Aggregate resample by %s", parm.method->answer); Rast_put_cell_title(parm.rastout->answer, title); Rast_short_history(parm.rastout->answer, "raster", &history); Rast_set_history(&history, HIST_DATSRC_1, parm.rastin->answer); G_format_resolution(src_w.ns_res, buf_nsres, src_w.proj); G_format_resolution(src_w.ew_res, buf_ewres, src_w.proj); Rast_format_history(&history, HIST_DATSRC_2, "Source map NS res: %s EW res: %s", buf_nsres, buf_ewres); Rast_command_history(&history); Rast_write_history(parm.rastout->answer, &history); /* copy color table from source map */ if (strcmp(parm.method->answer, "sum") != 0) { if (Rast_read_colors(parm.rastin->answer, "", &colors) < 0) G_fatal_error(_("Unable to read color table for %s"), parm.rastin->answer); Rast_mark_colors_as_fp(&colors); Rast_write_colors(parm.rastout->answer, G_mapset(), &colors); } return (EXIT_SUCCESS); }
int main(int argc, char **argv) { struct Cell_head window; struct Categories cats; struct GModule *module; struct Option *opt1, *opt2, *opt3; struct Flag *fancy_mode, *simple_mode, *draw; char *tmpfile; FILE *fp; /* Initialize the GIS calls */ G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("display")); G_add_keyword(_("cartography")); module->description = _("Create a TITLE for a raster map in a form suitable " "for display with d.text."); opt1 = G_define_standard_option(G_OPT_R_MAP); opt2 = G_define_option(); opt2->key = "color"; opt2->type = TYPE_STRING; opt2->answer = DEFAULT_FG_COLOR; opt2->required = NO; opt2->gisprompt = "old_color,color,color"; opt2->description = _("Sets the text color"); opt3 = G_define_option(); opt3->key = "size"; opt3->type = TYPE_DOUBLE; opt3->answer = "4.0"; opt3->options = "0-100"; opt3->description = _("Sets the text size as percentage of the frame's height"); draw = G_define_flag(); draw->key = 'd'; draw->description = _("Draw title on current display"); fancy_mode = G_define_flag(); fancy_mode->key = 'f'; fancy_mode->description = _("Do a fancier title"); /* currently just title, but it doesn't have to be /that/ simple */ simple_mode = G_define_flag(); simple_mode->key = 's'; simple_mode->description = _("Do a simple title"); /* Check command line */ if (G_parser(argc, argv)) exit(EXIT_FAILURE); map_name = opt1->answer; color = opt2->answer; if (opt3->answer != NULL) sscanf(opt3->answer, "%f", &size); type = fancy_mode->answer ? FANCY : NORMAL; if (fancy_mode->answer && simple_mode->answer) G_fatal_error(_("Title can be fancy or simple, not both")); if (!strlen(map_name)) G_fatal_error(_("No map name given")); Rast_get_cellhd(map_name, "", &window); if (Rast_read_cats(map_name, "", &cats) == -1) G_fatal_error(_("Unable to read category file of raster map <%s>"), map_name); if (draw->answer) { tmpfile = G_convert_dirseps_to_host(G_tempfile()); if (!(fp = fopen(tmpfile, "w"))) G_fatal_error(_("Unable to open temporary file <%s>"), tmpfile); } else fp = stdout; if (type == NORMAL) normal(&window, &cats, simple_mode->answer, fp); else fancy(&window, &cats, fp); if (draw->answer) { char inarg[GPATH_MAX]; fclose(fp); sprintf(inarg, "input=%s", tmpfile); G_spawn("d.text", "d.text", inarg, NULL); unlink(tmpfile); /* note a tmp file will remain, created by d.text so it can survive d.redraw */ } exit(EXIT_SUCCESS); }
int main(int argc, char *argv[]) { char *p; int method; int in_fd; int selection_fd; int out_fd; DCELL *result; char *selection; RASTER_MAP_TYPE map_type; int row, col; int readrow; int nrows, ncols; int n; int copycolr; int half; stat_func *newvalue; stat_func_w *newvalue_w; ifunc cat_names; double quantile; const void *closure; struct Colors colr; struct Cell_head cellhd; struct Cell_head window; struct History history; struct GModule *module; struct { struct Option *input, *output, *selection; struct Option *method, *size; struct Option *title; struct Option *weight; struct Option *gauss; struct Option *quantile; } parm; struct { struct Flag *align, *circle; } flag; DCELL *values; /* list of neighborhood values */ DCELL(*values_w)[2]; /* list of neighborhood values and weights */ G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("raster")); G_add_keyword(_("algebra")); G_add_keyword(_("statistics")); module->description = _("Makes each cell category value a " "function of the category values assigned to the cells " "around it, and stores new cell values in an output raster " "map layer."); parm.input = G_define_standard_option(G_OPT_R_INPUT); parm.selection = G_define_standard_option(G_OPT_R_INPUT); parm.selection->key = "selection"; parm.selection->required = NO; parm.selection->description = _("Name of an input raster map to select the cells which should be processed"); parm.output = G_define_standard_option(G_OPT_R_OUTPUT); parm.method = G_define_option(); parm.method->key = "method"; parm.method->type = TYPE_STRING; parm.method->required = NO; parm.method->answer = "average"; p = G_malloc(1024); for (n = 0; menu[n].name; n++) { if (n) strcat(p, ","); else *p = 0; strcat(p, menu[n].name); } parm.method->options = p; parm.method->description = _("Neighborhood operation"); parm.method->guisection = _("Neighborhood"); parm.size = G_define_option(); parm.size->key = "size"; parm.size->type = TYPE_INTEGER; parm.size->required = NO; parm.size->description = _("Neighborhood size"); parm.size->answer = "3"; parm.size->guisection = _("Neighborhood"); parm.title = G_define_option(); parm.title->key = "title"; parm.title->key_desc = "phrase"; parm.title->type = TYPE_STRING; parm.title->required = NO; parm.title->description = _("Title of the output raster map"); parm.weight = G_define_standard_option(G_OPT_F_INPUT); parm.weight->key = "weight"; parm.weight->required = NO; parm.weight->description = _("Text file containing weights"); parm.gauss = G_define_option(); parm.gauss->key = "gauss"; parm.gauss->type = TYPE_DOUBLE; parm.gauss->required = NO; parm.gauss->description = _("Sigma (in cells) for Gaussian filter"); parm.quantile = G_define_option(); parm.quantile->key = "quantile"; parm.quantile->type = TYPE_DOUBLE; parm.quantile->required = NO; parm.quantile->description = _("Quantile to calculate for method=quantile"); parm.quantile->options = "0.0-1.0"; parm.quantile->answer = "0.5"; flag.align = G_define_flag(); flag.align->key = 'a'; flag.align->description = _("Do not align output with the input"); flag.circle = G_define_flag(); flag.circle->key = 'c'; flag.circle->description = _("Use circular neighborhood"); flag.circle->guisection = _("Neighborhood"); if (G_parser(argc, argv)) exit(EXIT_FAILURE); sscanf(parm.size->answer, "%d", &ncb.nsize); if (ncb.nsize <= 0) G_fatal_error(_("Neighborhood size must be positive")); if (ncb.nsize % 2 == 0) G_fatal_error(_("Neighborhood size must be odd")); ncb.dist = ncb.nsize / 2; if (parm.weight->answer && flag.circle->answer) G_fatal_error(_("weight= and -c are mutually exclusive")); if (parm.weight->answer && parm.gauss->answer) G_fatal_error(_("weight= and gauss= are mutually exclusive")); ncb.oldcell = parm.input->answer; ncb.newcell = parm.output->answer; if (!flag.align->answer) { Rast_get_cellhd(ncb.oldcell, "", &cellhd); G_get_window(&window); Rast_align_window(&window, &cellhd); Rast_set_window(&window); } nrows = Rast_window_rows(); ncols = Rast_window_cols(); /* open raster maps */ in_fd = Rast_open_old(ncb.oldcell, ""); map_type = Rast_get_map_type(in_fd); /* get the method */ for (method = 0; (p = menu[method].name); method++) if ((strcmp(p, parm.method->answer) == 0)) break; if (!p) { G_warning(_("<%s=%s> unknown %s"), parm.method->key, parm.method->answer, parm.method->key); G_usage(); exit(EXIT_FAILURE); } if (menu[method].method == c_quant) { quantile = atoi(parm.quantile->answer); closure = &quantile; } half = (map_type == CELL_TYPE) ? menu[method].half : 0; /* establish the newvalue routine */ newvalue = menu[method].method; newvalue_w = menu[method].method_w; /* copy color table? */ copycolr = menu[method].copycolr; if (copycolr) { G_suppress_warnings(1); copycolr = (Rast_read_colors(ncb.oldcell, "", &colr) > 0); G_suppress_warnings(0); } /* read the weights */ if (parm.weight->answer) { read_weights(parm.weight->answer); if (!newvalue_w) weights_mask(); } else if (parm.gauss->answer) { if (!newvalue_w) G_fatal_error(_("Method %s not compatible with Gaussian filter"), parm.method->answer); gaussian_weights(atof(parm.gauss->answer)); } else newvalue_w = NULL; /* allocate the cell buffers */ allocate_bufs(); result = Rast_allocate_d_buf(); /* get title, initialize the category and stat info */ if (parm.title->answer) strcpy(ncb.title, parm.title->answer); else sprintf(ncb.title, "%dx%d neighborhood: %s of %s", ncb.nsize, ncb.nsize, menu[method].name, ncb.oldcell); /* initialize the cell bufs with 'dist' rows of the old cellfile */ readrow = 0; for (row = 0; row < ncb.dist; row++) readcell(in_fd, readrow++, nrows, ncols); /* open the selection raster map */ if (parm.selection->answer) { G_message(_("Opening selection map <%s>"), parm.selection->answer); selection_fd = Rast_open_old(parm.selection->answer, ""); selection = Rast_allocate_null_buf(); } else { selection_fd = -1; selection = NULL; } /*open the new raster map */ out_fd = Rast_open_new(ncb.newcell, map_type); if (flag.circle->answer) circle_mask(); if (newvalue_w) values_w = (DCELL(*)[2]) G_malloc(ncb.nsize * ncb.nsize * 2 * sizeof(DCELL)); else values = (DCELL *) G_malloc(ncb.nsize * ncb.nsize * sizeof(DCELL)); for (row = 0; row < nrows; row++) { G_percent(row, nrows, 2); readcell(in_fd, readrow++, nrows, ncols); if (selection) Rast_get_null_value_row(selection_fd, selection, row); for (col = 0; col < ncols; col++) { DCELL *rp = &result[col]; if (selection && selection[col]) { *rp = ncb.buf[ncb.dist][col]; continue; } if (newvalue_w) n = gather_w(values_w, col); else n = gather(values, col); if (n < 0) Rast_set_d_null_value(rp, 1); else { if (newvalue_w) newvalue_w(rp, values_w, n, closure); else newvalue(rp, values, n, closure); if (half && !Rast_is_d_null_value(rp)) *rp += 0.5; } } Rast_put_d_row(out_fd, result); } G_percent(row, nrows, 2); Rast_close(out_fd); Rast_close(in_fd); if (selection) Rast_close(selection_fd); /* put out category info */ null_cats(); if ((cat_names = menu[method].cat_names)) cat_names(); Rast_write_cats(ncb.newcell, &ncb.cats); if (copycolr) Rast_write_colors(ncb.newcell, G_mapset(), &colr); Rast_short_history(ncb.newcell, "raster", &history); Rast_command_history(&history); Rast_write_history(ncb.newcell, &history); exit(EXIT_SUCCESS); }
int main(int argc, char *argv[]) { int i; int print_flag = 0; int flat_flag; int set_flag; double x; int ival; int row_flag = 0, col_flag = 0; struct Cell_head window, temp_window; const char *value; const char *name; const char *mapset; char **rast_ptr, **vect_ptr; struct GModule *module; struct { struct Flag *update, *print, *gprint, *flprint, *lprint, *eprint, *nangle, *center, *res_set, *dist_res, *dflt, *z, *savedefault, *bbox, *gmt_style, *wms_style; } flag; struct { struct Option *north, *south, *east, *west, *top, *bottom, *res, *nsres, *ewres, *res3, *tbres, *rows, *cols, *save, *region, *raster, *raster3d, *align, *zoom, *vect; } parm; G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("general")); G_add_keyword(_("settings")); module->description = _("Manages the boundary definitions for the " "geographic region."); /* flags */ flag.dflt = G_define_flag(); flag.dflt->key = 'd'; flag.dflt->description = _("Set from default region"); flag.dflt->guisection = _("Existing"); flag.savedefault = G_define_flag(); flag.savedefault->key = 's'; flag.savedefault->label = _("Save as default region"); flag.savedefault->description = _("Only possible from the PERMANENT mapset"); flag.savedefault->guisection = _("Existing"); flag.print = G_define_flag(); flag.print->key = 'p'; flag.print->description = _("Print the current region"); flag.print->guisection = _("Print"); flag.lprint = G_define_flag(); flag.lprint->key = 'l'; flag.lprint->description = _("Print the current region in lat/long " "using the current ellipsoid/datum"); flag.lprint->guisection = _("Print"); flag.eprint = G_define_flag(); flag.eprint->key = 'e'; flag.eprint->description = _("Print the current region extent"); flag.eprint->guisection = _("Print"); flag.center = G_define_flag(); flag.center->key = 'c'; flag.center->description = _("Print the current region map center coordinates"); flag.center->guisection = _("Print"); flag.gmt_style = G_define_flag(); flag.gmt_style->key = 't'; flag.gmt_style->description = _("Print the current region in GMT style"); flag.gmt_style->guisection = _("Print"); flag.wms_style = G_define_flag(); flag.wms_style->key = 'w'; flag.wms_style->description = _("Print the current region in WMS style"); flag.wms_style->guisection = _("Print"); flag.dist_res = G_define_flag(); flag.dist_res->key = 'm'; flag.dist_res->description = _("Print region resolution in meters (geodesic)"); flag.dist_res->guisection = _("Print"); flag.nangle = G_define_flag(); flag.nangle->key = 'n'; flag.nangle->label = _("Print the convergence angle (degrees CCW)"); flag.nangle->description = _("The difference between the projection's grid north and true north, " "measured at the center coordinates of the current region."); flag.nangle->guisection = _("Print"); flag.z = G_define_flag(); flag.z->key = '3'; flag.z->description = _("Print also 3D settings"); flag.z->guisection = _("Print"); flag.bbox = G_define_flag(); flag.bbox->key = 'b'; flag.bbox->description = _("Print the maximum bounding box in lat/long on WGS84"); flag.bbox->guisection = _("Print"); flag.gprint = G_define_flag(); flag.gprint->key = 'g'; flag.gprint->description = _("Print in shell script style"); flag.gprint->guisection = _("Print"); flag.flprint = G_define_flag(); flag.flprint->key = 'f'; flag.flprint->description = _("Print in shell script style, but in one line (flat)"); flag.flprint->guisection = _("Print"); flag.res_set = G_define_flag(); flag.res_set->key = 'a'; flag.res_set->description = _("Align region to resolution (default = align to bounds, " "works only for 2D resolution)"); flag.res_set->guisection = _("Bounds"); flag.update = G_define_flag(); flag.update->key = 'u'; flag.update->description = _("Do not update the current region"); flag.update->guisection = _("Effects"); /* parameters */ parm.region = G_define_standard_option(G_OPT_M_REGION); parm.region->description = _("Set current region from named region"); parm.region->guisection = _("Existing"); parm.raster = G_define_standard_option(G_OPT_R_MAP); parm.raster->key = "raster"; parm.raster->required = NO; parm.raster->multiple = YES; parm.raster->description = _("Set region to match raster map(s)"); parm.raster->guisection = _("Existing"); parm.raster3d = G_define_standard_option(G_OPT_R3_MAP); parm.raster3d->key = "raster_3d"; parm.raster3d->required = NO; parm.raster3d->multiple = NO; parm.raster3d->description = _("Set region to match 3D raster map(s) (both 2D and 3D " "values)"); parm.raster3d->guisection = _("Existing"); parm.vect = G_define_standard_option(G_OPT_V_MAP); parm.vect->key = "vector"; parm.vect->required = NO; parm.vect->multiple = YES; parm.vect->label = _("Set region to match vector map(s)"); parm.vect->description = NULL; parm.vect->guisection = _("Existing"); parm.north = G_define_option(); parm.north->key = "n"; parm.north->key_desc = "value"; parm.north->required = NO; parm.north->multiple = NO; parm.north->type = TYPE_STRING; parm.north->description = _("Value for the northern edge"); parm.north->guisection = _("Bounds"); parm.south = G_define_option(); parm.south->key = "s"; parm.south->key_desc = "value"; parm.south->required = NO; parm.south->multiple = NO; parm.south->type = TYPE_STRING; parm.south->description = _("Value for the southern edge"); parm.south->guisection = _("Bounds"); parm.east = G_define_option(); parm.east->key = "e"; parm.east->key_desc = "value"; parm.east->required = NO; parm.east->multiple = NO; parm.east->type = TYPE_STRING; parm.east->description = _("Value for the eastern edge"); parm.east->guisection = _("Bounds"); parm.west = G_define_option(); parm.west->key = "w"; parm.west->key_desc = "value"; parm.west->required = NO; parm.west->multiple = NO; parm.west->type = TYPE_STRING; parm.west->description = _("Value for the western edge"); parm.west->guisection = _("Bounds"); parm.top = G_define_option(); parm.top->key = "t"; parm.top->key_desc = "value"; parm.top->required = NO; parm.top->multiple = NO; parm.top->type = TYPE_STRING; parm.top->description = _("Value for the top edge"); parm.top->guisection = _("Bounds"); parm.bottom = G_define_option(); parm.bottom->key = "b"; parm.bottom->key_desc = "value"; parm.bottom->required = NO; parm.bottom->multiple = NO; parm.bottom->type = TYPE_STRING; parm.bottom->description = _("Value for the bottom edge"); parm.bottom->guisection = _("Bounds"); parm.rows = G_define_option(); parm.rows->key = "rows"; parm.rows->key_desc = "value"; parm.rows->required = NO; parm.rows->multiple = NO; parm.rows->type = TYPE_INTEGER; parm.rows->description = _("Number of rows in the new region"); parm.rows->guisection = _("Resolution"); parm.cols = G_define_option(); parm.cols->key = "cols"; parm.cols->key_desc = "value"; parm.cols->required = NO; parm.cols->multiple = NO; parm.cols->type = TYPE_INTEGER; parm.cols->description = _("Number of columns in the new region"); parm.cols->guisection = _("Resolution"); parm.res = G_define_option(); parm.res->key = "res"; parm.res->key_desc = "value"; parm.res->required = NO; parm.res->multiple = NO; parm.res->type = TYPE_STRING; parm.res->description = _("2D grid resolution (north-south and east-west)"); parm.res->guisection = _("Resolution"); parm.res3 = G_define_option(); parm.res3->key = "res3"; parm.res3->key_desc = "value"; parm.res3->required = NO; parm.res3->multiple = NO; parm.res3->type = TYPE_STRING; parm.res3->description = _("3D grid resolution (north-south, east-west and top-bottom)"); parm.res3->guisection = _("Resolution"); parm.nsres = G_define_option(); parm.nsres->key = "nsres"; parm.nsres->key_desc = "value"; parm.nsres->required = NO; parm.nsres->multiple = NO; parm.nsres->type = TYPE_STRING; parm.nsres->description = _("North-south 2D grid resolution"); parm.nsres->guisection = _("Resolution"); parm.ewres = G_define_option(); parm.ewres->key = "ewres"; parm.ewres->key_desc = "value"; parm.ewres->required = NO; parm.ewres->multiple = NO; parm.ewres->type = TYPE_STRING; parm.ewres->description = _("East-west 2D grid resolution"); parm.ewres->guisection = _("Resolution"); parm.tbres = G_define_option(); parm.tbres->key = "tbres"; parm.tbres->key_desc = "value"; parm.tbres->required = NO; parm.tbres->multiple = NO; parm.tbres->type = TYPE_STRING; parm.tbres->description = _("Top-bottom 3D grid resolution"); parm.tbres->guisection = _("Resolution"); parm.zoom = G_define_option(); parm.zoom->key = "zoom"; parm.zoom->key_desc = "name"; parm.zoom->required = NO; parm.zoom->multiple = NO; parm.zoom->type = TYPE_STRING; parm.zoom->description = _("Shrink region until it meets non-NULL data from this raster map"); parm.zoom->gisprompt = "old,cell,raster"; parm.zoom->guisection = _("Bounds"); parm.align = G_define_option(); parm.align->key = "align"; parm.align->key_desc = "name"; parm.align->required = NO; parm.align->multiple = NO; parm.align->type = TYPE_STRING; parm.align->description = _("Adjust region cells to cleanly align with this raster map"); parm.align->gisprompt = "old,cell,raster"; parm.align->guisection = _("Bounds"); parm.save = G_define_option(); parm.save->key = "save"; parm.save->key_desc = "name"; parm.save->required = NO; parm.save->multiple = NO; parm.save->type = TYPE_STRING; parm.save->description = _("Save current region settings in named region file"); parm.save->gisprompt = "new,windows,region"; parm.save->guisection = _("Effects"); G_option_required(flag.dflt, flag.savedefault, flag.print, flag.lprint, flag.eprint, flag.center, flag.gmt_style, flag.wms_style, flag.dist_res, flag.nangle, flag. z, flag.bbox, flag.gprint, flag.res_set, flag.update, parm.region, parm.raster, parm.raster3d, parm.vect, parm.north, parm.south, parm.east, parm.west, parm.top, parm.bottom, parm.rows, parm.cols, parm.res, parm.res3, parm.nsres, parm.ewres, parm.tbres, parm.zoom, parm.align, parm.save, NULL); if (G_parser(argc, argv)) exit(EXIT_FAILURE); G_get_default_window(&window); set_flag = !flag.update->answer; flat_flag = flag.flprint->answer; if (flag.print->answer) print_flag |= PRINT_REG; if (flag.gprint->answer) print_flag |= PRINT_SH; if (flag.lprint->answer) print_flag |= PRINT_LL; if (flag.eprint->answer) print_flag |= PRINT_EXTENT; if (flag.center->answer) print_flag |= PRINT_CENTER; if (flag.gmt_style->answer) print_flag |= PRINT_GMT; if (flag.wms_style->answer) print_flag |= PRINT_WMS; if (flag.nangle->answer) print_flag |= PRINT_NANGLE; if (flag.dist_res->answer) print_flag |= PRINT_METERS; if (flag.z->answer) print_flag |= PRINT_3D; if (flag.bbox->answer) print_flag |= PRINT_MBBOX; if (print_flag == PRINT_METERS) print_flag |= PRINT_SH; if (print_flag == PRINT_SH || print_flag & PRINT_3D || print_flag == PRINT_METERS + PRINT_SH) { print_flag |= PRINT_REG; } if (!flag.dflt->answer) G_get_window(&window); /* region= */ if ((name = parm.region->answer)) { mapset = G_find_file2("windows", name, ""); if (!mapset) G_fatal_error(_("Region <%s> not found"), name); G_get_element_window(&window, "windows", name, mapset); } /* raster= */ if (parm.raster->answer) { int first = 0; rast_ptr = parm.raster->answers; for (; *rast_ptr != NULL; rast_ptr++) { char rast_name[GNAME_MAX]; strcpy(rast_name, *rast_ptr); mapset = G_find_raster2(rast_name, ""); if (!mapset) G_fatal_error(_("Raster map <%s> not found"), rast_name); Rast_get_cellhd(rast_name, mapset, &temp_window); if (!first) { window = temp_window; first = 1; } else { window.north = (window.north > temp_window.north) ? window.north : temp_window.north; window.south = (window.south < temp_window.south) ? window.south : temp_window.south; window.east = (window.east > temp_window.east) ? window.east : temp_window.east; window.west = (window.west < temp_window.west) ? window.west : temp_window.west; } } G_adjust_Cell_head3(&window, 0, 0, 0); } /* raster3d= */ if ((name = parm.raster3d->answer)) { RASTER3D_Region win; if ((mapset = G_find_raster3d(name, "")) == NULL) G_fatal_error(_("3D raster map <%s> not found"), name); if (Rast3d_read_region_map(name, mapset, &win) < 0) G_fatal_error(_("Unable to read header of 3D raster map <%s@%s>"), name, mapset); Rast3d_region_to_cell_head(&win, &window); } /* vector= */ if (parm.vect->answer) { int first = 0; vect_ptr = parm.vect->answers; for (; *vect_ptr != NULL; vect_ptr++) { struct Map_info Map; struct bound_box box; char vect_name[GNAME_MAX]; struct Cell_head map_window; strcpy(vect_name, *vect_ptr); mapset = G_find_vector2(vect_name, ""); if (!mapset) G_fatal_error(_("Vector map <%s> not found"), vect_name); temp_window = window; Vect_set_open_level(2); if (2 > Vect_open_old_head(&Map, vect_name, mapset)) G_fatal_error(_("Unable to open vector map <%s> on topological level"), vect_name); Vect_get_map_box(&Map, &box); map_window = window; map_window.north = box.N; map_window.south = box.S; map_window.west = box.W; map_window.east = box.E; map_window.top = box.T; map_window.bottom = box.B; if (!first) { window = map_window; first = 1; } else { window.north = (window.north > map_window.north) ? window.north : map_window.north; window.south = (window.south < map_window.south) ? window.south : map_window.south; window.east = (window.east > map_window.east) ? window.east : map_window.east; window.west = (window.west < map_window.west) ? window.west : map_window.west; if (map_window.top > window.top) window.top = map_window.top; if (map_window.bottom < window.bottom) window.bottom = map_window.bottom; } if (window.north == window.south) { window.north = window.north + 0.5 * temp_window.ns_res; window.south = window.south - 0.5 * temp_window.ns_res; } if (window.east == window.west) { window.west = window.west - 0.5 * temp_window.ew_res; window.east = window.east + 0.5 * temp_window.ew_res; } if (window.top == window.bottom) { window.bottom = (window.bottom - 0.5 * temp_window.tb_res); window.top = (window.top + 0.5 * temp_window.tb_res); } if (flag.res_set->answer) Rast_align_window(&window, &temp_window); Vect_close(&Map); } } /* n= */ if ((value = parm.north->answer)) { if ((i = nsew(value, "n+", "n-", "s+"))) { if (!G_scan_resolution(value + 2, &x, window.proj)) die(parm.north); switch (i) { case 1: window.north += x; break; case 2: window.north -= x; break; case 3: window.north = window.south + x; break; } } else if (G_scan_northing(value, &x, window.proj)) window.north = x; else die(parm.north); } /* s= */ if ((value = parm.south->answer)) { if ((i = nsew(value, "s+", "s-", "n-"))) { if (!G_scan_resolution(value + 2, &x, window.proj)) die(parm.south); switch (i) { case 1: window.south += x; break; case 2: window.south -= x; break; case 3: window.south = window.north - x; break; } } else if (G_scan_northing(value, &x, window.proj)) window.south = x; else die(parm.south); } /* e= */ if ((value = parm.east->answer)) { if ((i = nsew(value, "e+", "e-", "w+"))) { if (!G_scan_resolution(value + 2, &x, window.proj)) die(parm.east); switch (i) { case 1: window.east += x; break; case 2: window.east -= x; break; case 3: window.east = window.west + x; break; } } else if (G_scan_easting(value, &x, window.proj)) window.east = x; else die(parm.east); } /* w= */ if ((value = parm.west->answer)) { if ((i = nsew(value, "w+", "w-", "e-"))) { if (!G_scan_resolution(value + 2, &x, window.proj)) die(parm.west); switch (i) { case 1: window.west += x; break; case 2: window.west -= x; break; case 3: window.west = window.east - x; break; } } else if (G_scan_easting(value, &x, window.proj)) window.west = x; else die(parm.west); } /* t= */ if ((value = parm.top->answer)) { if ((i = nsew(value, "t+", "t-", "b+"))) { if (sscanf(value + 2, "%lf", &x) != 1) die(parm.top); switch (i) { case 1: window.top += x; break; case 2: window.top -= x; break; case 3: window.top = window.bottom + x; break; } } else if (sscanf(value, "%lf", &x) == 1) window.top = x; else die(parm.top); } /* b= */ if ((value = parm.bottom->answer)) { if ((i = nsew(value, "b+", "b-", "t-"))) { if (sscanf(value + 2, "%lf", &x) != 1) die(parm.bottom); switch (i) { case 1: window.bottom += x; break; case 2: window.bottom -= x; break; case 3: window.bottom = window.top - x; break; } } else if (sscanf(value, "%lf", &x) == 1) window.bottom = x; else die(parm.bottom); } /* res= */ if ((value = parm.res->answer)) { if (!G_scan_resolution(value, &x, window.proj)) die(parm.res); window.ns_res = x; window.ew_res = x; if (flag.res_set->answer) { window.north = ceil(window.north / x) * x; window.south = floor(window.south / x) * x; window.east = ceil(window.east / x) * x; window.west = floor(window.west / x) * x; } } /* res3= */ if ((value = parm.res3->answer)) { if (!G_scan_resolution(value, &x, window.proj)) die(parm.res); window.ns_res3 = x; window.ew_res3 = x; window.tb_res = x; } /* nsres= */ if ((value = parm.nsres->answer)) { if (!G_scan_resolution(value, &x, window.proj)) die(parm.nsres); window.ns_res = x; if (flag.res_set->answer) { window.north = ceil(window.north / x) * x; window.south = floor(window.south / x) * x; } } /* ewres= */ if ((value = parm.ewres->answer)) { if (!G_scan_resolution(value, &x, window.proj)) die(parm.ewres); window.ew_res = x; if (flag.res_set->answer) { window.east = ceil(window.east / x) * x; window.west = floor(window.west / x) * x; } } /* tbres= */ if ((value = parm.tbres->answer)) { if (sscanf(value, "%lf", &x) != 1) die(parm.tbres); window.tb_res = x; if (flag.res_set->answer) { window.top = ceil(window.top / x) * x; window.bottom = floor(window.bottom / x) * x; } } /* rows= */ if ((value = parm.rows->answer)) { if (sscanf(value, "%i", &ival) != 1) die(parm.rows); window.rows = ival; row_flag = 1; } /* cols= */ if ((value = parm.cols->answer)) { if (sscanf(value, "%i", &ival) != 1) die(parm.cols); window.cols = ival; col_flag = 1; } /* zoom= */ if ((name = parm.zoom->answer)) { mapset = G_find_raster2(name, ""); if (!mapset) G_fatal_error(_("Raster map <%s> not found"), name); zoom(&window, name, mapset); } /* align= */ if ((name = parm.align->answer)) { mapset = G_find_raster2(name, ""); if (!mapset) G_fatal_error(_("Raster map <%s> not found"), name); Rast_get_cellhd(name, mapset, &temp_window); Rast_align_window(&window, &temp_window); } /* save= */ if ((name = parm.save->answer)) { temp_window = window; G_adjust_Cell_head3(&temp_window, 0, 0, 0); if (G_put_element_window(&temp_window, "windows", name) < 0) G_fatal_error(_("Unable to set region <%s>"), name); } G_adjust_Cell_head3(&window, row_flag, col_flag, 0); if (set_flag) { if (G_put_window(&window) < 0) G_fatal_error(_("Unable to update current region")); } if (flag.savedefault->answer) { if (strcmp(G_mapset(), "PERMANENT") == 0) { G_put_element_window(&window, "", "DEFAULT_WIND"); } else { G_fatal_error(_("Unable to change default region. " "The current mapset is not <PERMANENT>.")); } } /* / flag.savedefault->answer */ if (print_flag) print_window(&window, print_flag, flat_flag); exit(EXIT_SUCCESS); }
int main(int argc, char *argv[]) { /* buffer for input-output rasters */ void *inrast_TEMPKA, *inrast_PATM, *inrast_RNET, *inrast_G0; DCELL *outrast; /* pointers to input-output raster files */ int infd_TEMPKA, infd_PATM, infd_RNET, infd_G0; int outfd; /* names of input-output raster files */ char *RNET, *TEMPKA, *PATM, *G0; char *ETa; /* input-output cell values */ DCELL d_tempka, d_pt_patm, d_rnet, d_g0; DCELL d_pt_alpha, d_pt_delta, d_pt_ghamma, d_daily_et; /* region information and handler */ struct Cell_head cellhd; int nrows, ncols; int row, col; /* parser stuctures definition */ struct GModule *module; struct Option *input_RNET, *input_TEMPKA, *input_PATM, *input_G0, *input_PT; struct Option *output; struct Flag *zero; struct Colors color; struct History history; /* Initialize the GIS calls */ G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("imagery")); G_add_keyword(_("evapotranspiration")); module->description = _("Computes evapotranspiration calculation " "Priestley and Taylor formulation, 1972."); /* Define different options */ input_RNET = G_define_standard_option(G_OPT_R_INPUT); input_RNET->key = "net_radiation"; input_RNET->description = _("Name of input net radiation raster map [W/m2]"); input_G0 = G_define_standard_option(G_OPT_R_INPUT); input_G0->key = "soil_heatflux"; input_G0->description = _("Name of input soil heat flux raster map [W/m2]"); input_TEMPKA = G_define_standard_option(G_OPT_R_INPUT); input_TEMPKA->key = "air_temperature"; input_TEMPKA->description = _("Name of input air temperature raster map [K]"); input_PATM = G_define_standard_option(G_OPT_R_INPUT); input_PATM->key = "atmospheric_pressure"; input_PATM->description = _("Name of input atmospheric pressure raster map [millibars]"); input_PT = G_define_option(); input_PT->key = "priestley_taylor_coeff"; input_PT->type = TYPE_DOUBLE; input_PT->required = YES; input_PT->description = _("Priestley-Taylor coefficient"); input_PT->answer = "1.26"; output = G_define_standard_option(G_OPT_R_OUTPUT); output->description = _("Name of output evapotranspiration raster map [mm/d]"); /* Define the different flags */ zero = G_define_flag(); zero->key = 'z'; zero->description = _("Set negative ETa to zero"); if (G_parser(argc, argv)) exit(EXIT_FAILURE); /* get entered parameters */ RNET = input_RNET->answer; TEMPKA = input_TEMPKA->answer; PATM = input_PATM->answer; G0 = input_G0->answer; d_pt_alpha = atof(input_PT->answer); ETa = output->answer; /* open pointers to input raster files */ infd_RNET = Rast_open_old(RNET, ""); infd_TEMPKA = Rast_open_old(TEMPKA, ""); infd_PATM = Rast_open_old(PATM, ""); infd_G0 = Rast_open_old(G0, ""); /* read headers of raster files */ Rast_get_cellhd(RNET, "", &cellhd); Rast_get_cellhd(TEMPKA, "", &cellhd); Rast_get_cellhd(PATM, "", &cellhd); Rast_get_cellhd(G0, "", &cellhd); /* Allocate input buffer */ inrast_RNET = Rast_allocate_d_buf(); inrast_TEMPKA = Rast_allocate_d_buf(); inrast_PATM = Rast_allocate_d_buf(); inrast_G0 = Rast_allocate_d_buf(); /* get rows and columns number of the current region */ nrows = Rast_window_rows(); ncols = Rast_window_cols(); /* allocate output buffer */ outrast = Rast_allocate_d_buf(); /* open pointers to output raster files */ outfd = Rast_open_new(ETa, DCELL_TYPE); /* start the loop through cells */ for (row = 0; row < nrows; row++) { G_percent(row, nrows, 2); /* read input raster row into line buffer */ Rast_get_d_row(infd_RNET, inrast_RNET, row); Rast_get_d_row(infd_TEMPKA, inrast_TEMPKA, row); Rast_get_d_row(infd_PATM, inrast_PATM, row); Rast_get_d_row(infd_G0, inrast_G0, row); for (col = 0; col < ncols; col++) { /* read current cell from line buffer */ d_rnet = ((DCELL *) inrast_RNET)[col]; d_tempka = ((DCELL *) inrast_TEMPKA)[col]; d_pt_patm = ((DCELL *) inrast_PATM)[col]; d_g0 = ((DCELL *) inrast_G0)[col]; /*Delta_pt and Ghamma_pt */ d_pt_delta = pt_delta(d_tempka); d_pt_ghamma = pt_ghamma(d_tempka, d_pt_patm); /*Calculate ET */ d_daily_et = pt_daily_et(d_pt_alpha, d_pt_delta, d_pt_ghamma, d_rnet, d_g0, d_tempka); if (zero->answer && d_daily_et < 0) d_daily_et = 0.0; /* write calculated ETP to output line buffer */ outrast[col] = d_daily_et; } /* write output line buffer to output raster file */ Rast_put_d_row(outfd, outrast); } /* free buffers and close input maps */ G_free(inrast_RNET); G_free(inrast_TEMPKA); G_free(inrast_PATM); G_free(inrast_G0); Rast_close(infd_RNET); Rast_close(infd_TEMPKA); Rast_close(infd_PATM); Rast_close(infd_G0); /* generate color table between -20 and 20 */ Rast_make_rainbow_colors(&color, -20, 20); Rast_write_colors(ETa, G_mapset(), &color); Rast_short_history(ETa, "raster", &history); Rast_command_history(&history); Rast_write_history(ETa, &history); /* free buffers and close output map */ G_free(outrast); Rast_close(outfd); return (EXIT_SUCCESS); }
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 out_fd, base_raster; char *infile, *outmap; int percent; double zrange_min, zrange_max, d_tmp; double irange_min, irange_max; unsigned long estimated_lines; RASTER_MAP_TYPE rtype, base_raster_data_type; struct History history; char title[64]; SEGMENT base_segment; struct PointBinning point_binning; void *base_array; void *raster_row; struct Cell_head region; struct Cell_head input_region; int rows, last_rows, row0, cols; /* scan box size */ int row; /* counters */ int pass, npasses; unsigned long line, line_total; unsigned int counter; unsigned long n_invalid; char buff[BUFFSIZE]; double x, y, z; double intensity; int arr_row, arr_col; unsigned long count, count_total; int point_class; double zscale = 1.0; double iscale = 1.0; double res = 0.0; struct BinIndex bin_index_nodes; bin_index_nodes.num_nodes = 0; bin_index_nodes.max_nodes = 0; bin_index_nodes.nodes = 0; struct GModule *module; struct Option *input_opt, *output_opt, *percent_opt, *type_opt, *filter_opt, *class_opt; struct Option *method_opt, *base_raster_opt; struct Option *zrange_opt, *zscale_opt; struct Option *irange_opt, *iscale_opt; struct Option *trim_opt, *pth_opt, *res_opt; struct Option *file_list_opt; struct Flag *print_flag, *scan_flag, *shell_style, *over_flag, *extents_flag; struct Flag *intens_flag, *intens_import_flag; struct Flag *set_region_flag; struct Flag *base_rast_res_flag; struct Flag *only_valid_flag; /* LAS */ LASReaderH LAS_reader; LASHeaderH LAS_header; LASSRSH LAS_srs; LASPointH LAS_point; int return_filter; const char *projstr; struct Cell_head cellhd, loc_wind; unsigned int n_filtered; G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("raster")); G_add_keyword(_("import")); G_add_keyword(_("LIDAR")); G_add_keyword(_("statistics")); G_add_keyword(_("conversion")); G_add_keyword(_("aggregation")); G_add_keyword(_("binning")); module->description = _("Creates a raster map from LAS LiDAR points using univariate statistics."); input_opt = G_define_standard_option(G_OPT_F_BIN_INPUT); input_opt->required = NO; input_opt->label = _("LAS input file"); input_opt->description = _("LiDAR input files in LAS format (*.las or *.laz)"); input_opt->guisection = _("Input"); output_opt = G_define_standard_option(G_OPT_R_OUTPUT); output_opt->required = NO; output_opt->guisection = _("Output"); file_list_opt = G_define_standard_option(G_OPT_F_INPUT); file_list_opt->key = "file"; file_list_opt->label = _("File containing names of LAS input files"); file_list_opt->description = _("LiDAR input files in LAS format (*.las or *.laz)"); file_list_opt->required = NO; file_list_opt->guisection = _("Input"); method_opt = G_define_option(); method_opt->key = "method"; method_opt->type = TYPE_STRING; method_opt->required = NO; method_opt->description = _("Statistic to use for raster values"); method_opt->options = "n,min,max,range,sum,mean,stddev,variance,coeff_var,median,percentile,skewness,trimmean"; method_opt->answer = "mean"; method_opt->guisection = _("Statistic"); G_asprintf((char **)&(method_opt->descriptions), "n;%s;" "min;%s;" "max;%s;" "range;%s;" "sum;%s;" "mean;%s;" "stddev;%s;" "variance;%s;" "coeff_var;%s;" "median;%s;" "percentile;%s;" "skewness;%s;" "trimmean;%s", _("Number of points in cell"), _("Minimum value of point values in cell"), _("Maximum value of point values in cell"), _("Range of point values in cell"), _("Sum of point values in cell"), _("Mean (average) value of point values in cell"), _("Standard deviation of point values in cell"), _("Variance of point values in cell"), _("Coefficient of variance of point values in cell"), _("Median value of point values in cell"), _("pth (nth) percentile of point values in cell"), _("Skewness of point values in cell"), _("Trimmed mean of point values in cell")); type_opt = G_define_standard_option(G_OPT_R_TYPE); type_opt->required = NO; type_opt->answer = "FCELL"; base_raster_opt = G_define_standard_option(G_OPT_R_INPUT); base_raster_opt->key = "base_raster"; base_raster_opt->required = NO; base_raster_opt->label = _("Subtract raster values from the Z coordinates"); base_raster_opt->description = _("The scale for Z is applied beforehand, the range filter for" " Z afterwards"); base_raster_opt->guisection = _("Transform"); zrange_opt = G_define_option(); zrange_opt->key = "zrange"; zrange_opt->type = TYPE_DOUBLE; zrange_opt->required = NO; zrange_opt->key_desc = "min,max"; zrange_opt->description = _("Filter range for Z data (min,max)"); zrange_opt->guisection = _("Selection"); zscale_opt = G_define_option(); zscale_opt->key = "zscale"; zscale_opt->type = TYPE_DOUBLE; zscale_opt->required = NO; zscale_opt->answer = "1.0"; zscale_opt->description = _("Scale to apply to Z data"); zscale_opt->guisection = _("Transform"); irange_opt = G_define_option(); irange_opt->key = "intensity_range"; irange_opt->type = TYPE_DOUBLE; irange_opt->required = NO; irange_opt->key_desc = "min,max"; irange_opt->description = _("Filter range for intensity values (min,max)"); irange_opt->guisection = _("Selection"); iscale_opt = G_define_option(); iscale_opt->key = "intensity_scale"; iscale_opt->type = TYPE_DOUBLE; iscale_opt->required = NO; iscale_opt->answer = "1.0"; iscale_opt->description = _("Scale to apply to intensity values"); iscale_opt->guisection = _("Transform"); percent_opt = G_define_option(); percent_opt->key = "percent"; percent_opt->type = TYPE_INTEGER; percent_opt->required = NO; percent_opt->answer = "100"; percent_opt->options = "1-100"; percent_opt->description = _("Percent of map to keep in memory"); /* I would prefer to call the following "percentile", but that has too * much namespace overlap with the "percent" option above */ pth_opt = G_define_option(); pth_opt->key = "pth"; pth_opt->type = TYPE_INTEGER; pth_opt->required = NO; pth_opt->options = "1-100"; pth_opt->description = _("pth percentile of the values"); pth_opt->guisection = _("Statistic"); trim_opt = G_define_option(); trim_opt->key = "trim"; trim_opt->type = TYPE_DOUBLE; trim_opt->required = NO; trim_opt->options = "0-50"; trim_opt->label = _("Discard given percentage of the smallest and largest values"); trim_opt->description = _("Discard <trim> percent of the smallest and <trim> percent of the largest observations"); trim_opt->guisection = _("Statistic"); res_opt = G_define_option(); res_opt->key = "resolution"; res_opt->type = TYPE_DOUBLE; res_opt->required = NO; res_opt->description = _("Output raster resolution"); res_opt->guisection = _("Output"); filter_opt = G_define_option(); filter_opt->key = "return_filter"; filter_opt->type = TYPE_STRING; filter_opt->required = NO; filter_opt->label = _("Only import points of selected return type"); filter_opt->description = _("If not specified, all points are imported"); filter_opt->options = "first,last,mid"; filter_opt->guisection = _("Selection"); class_opt = G_define_option(); class_opt->key = "class_filter"; class_opt->type = TYPE_INTEGER; class_opt->multiple = YES; class_opt->required = NO; class_opt->label = _("Only import points of selected class(es)"); class_opt->description = _("Input is comma separated integers. " "If not specified, all points are imported."); class_opt->guisection = _("Selection"); print_flag = G_define_flag(); print_flag->key = 'p'; print_flag->description = _("Print LAS file info and exit"); extents_flag = G_define_flag(); extents_flag->key = 'e'; extents_flag->label = _("Use the extent of the input for the raster extent"); extents_flag->description = _("Set internally computational region extents based on the" " point cloud"); extents_flag->guisection = _("Output"); set_region_flag = G_define_flag(); set_region_flag->key = 'n'; set_region_flag->label = _("Set computation region to match the new raster map"); set_region_flag->description = _("Set computation region to match the 2D extent and resolution" " of the newly created new raster map"); set_region_flag->guisection = _("Output"); over_flag = G_define_flag(); over_flag->key = 'o'; over_flag->label = _("Override projection check (use current location's projection)"); over_flag->description = _("Assume that the dataset has same projection as the current location"); scan_flag = G_define_flag(); scan_flag->key = 's'; scan_flag->description = _("Scan data file for extent then exit"); shell_style = G_define_flag(); shell_style->key = 'g'; shell_style->description = _("In scan mode, print using shell script style"); intens_flag = G_define_flag(); intens_flag->key = 'i'; intens_flag->label = _("Use intensity values rather than Z values"); intens_flag->description = _("Uses intensity values everywhere as if they would be Z" " coordinates"); intens_import_flag = G_define_flag(); intens_import_flag->key = 'j'; intens_import_flag->description = _("Use Z values for filtering, but intensity values for statistics"); base_rast_res_flag = G_define_flag(); base_rast_res_flag->key = 'd'; base_rast_res_flag->label = _("Use base raster resolution instead of computational region"); base_rast_res_flag->description = _("For getting values from base raster, use its actual" " resolution instead of computational region resolution"); only_valid_flag = G_define_flag(); only_valid_flag->key = 'v'; only_valid_flag->label = _("Use only valid points"); only_valid_flag->description = _("Points invalid according to APSRS LAS specification will be" " filtered out"); only_valid_flag->guisection = _("Selection"); G_option_required(input_opt, file_list_opt, NULL); G_option_exclusive(input_opt, file_list_opt, NULL); G_option_required(output_opt, print_flag, scan_flag, shell_style, NULL); G_option_exclusive(intens_flag, intens_import_flag, NULL); G_option_requires(base_rast_res_flag, base_raster_opt, NULL); if (G_parser(argc, argv)) exit(EXIT_FAILURE); int only_valid = FALSE; n_invalid = 0; if (only_valid_flag->answer) only_valid = TRUE; /* we could use rules but this gives more info and allows continuing */ if (set_region_flag->answer && !(extents_flag->answer || res_opt->answer)) { G_warning(_("Flag %c makes sense only with %s option or -%c flag"), set_region_flag->key, res_opt->key, extents_flag->key); /* avoid the call later on */ set_region_flag->answer = '\0'; } struct StringList infiles; if (file_list_opt->answer) { if (access(file_list_opt->answer, F_OK) != 0) G_fatal_error(_("File <%s> does not exist"), file_list_opt->answer); string_list_from_file(&infiles, file_list_opt->answer); } else { string_list_from_one_item(&infiles, input_opt->answer); } /* parse input values */ outmap = output_opt->answer; if (shell_style->answer && !scan_flag->answer) { scan_flag->answer = 1; /* pointer not int, so set = shell_style->answer ? */ } /* check zrange and extent relation */ if (scan_flag->answer || extents_flag->answer) { if (zrange_opt->answer) G_warning(_("zrange will not be taken into account during scan")); } Rast_get_window(®ion); /* G_get_window seems to be unreliable if the location has been changed */ G_get_set_window(&loc_wind); /* TODO: v.in.lidar uses G_get_default_window() */ estimated_lines = 0; int i; for (i = 0; i < infiles.num_items; i++) { infile = infiles.items[i]; /* don't if file not found */ if (access(infile, F_OK) != 0) G_fatal_error(_("Input file <%s> does not exist"), infile); /* Open LAS file*/ LAS_reader = LASReader_Create(infile); if (LAS_reader == NULL) G_fatal_error(_("Unable to open file <%s> as a LiDAR point cloud"), infile); LAS_header = LASReader_GetHeader(LAS_reader); if (LAS_header == NULL) { G_fatal_error(_("Unable to read LAS header of <%s>"), infile); } LAS_srs = LASHeader_GetSRS(LAS_header); /* print info or check projection if we are actually importing */ if (print_flag->answer) { /* print filename when there is more than one file */ if (infiles.num_items > 1) fprintf(stdout, "File: %s\n", infile); /* Print LAS header */ print_lasinfo(LAS_header, LAS_srs); } else { /* report that we are checking more files */ if (i == 1) G_message(_("First file's projection checked," " checking projection of the other files...")); /* Fetch input map projection in GRASS form. */ projstr = LASSRS_GetWKT_CompoundOK(LAS_srs); /* we are printing the non-warning messages only for first file */ projection_check_wkt(cellhd, loc_wind, projstr, over_flag->answer, shell_style->answer || i); /* if there is a problem in some other file, first OK message * is printed but than a warning, this is not ideal but hopefully * not so confusing when importing multiple files */ } if (scan_flag->answer || extents_flag->answer) { /* we assign to the first one (i==0) but update for the rest */ scan_bounds(LAS_reader, shell_style->answer, extents_flag->answer, i, zscale, ®ion); } /* number of estimated point across all files */ /* TODO: this should be ull which won't work with percent report */ estimated_lines += LASHeader_GetPointRecordsCount(LAS_header); /* We are closing all again and we will be opening them later, * so we don't have to worry about limit for open files. */ LASSRS_Destroy(LAS_srs); LASHeader_Destroy(LAS_header); LASReader_Destroy(LAS_reader); } /* if we are not importing, end */ if (print_flag->answer || scan_flag->answer) exit(EXIT_SUCCESS); return_filter = LAS_ALL; if (filter_opt->answer) { if (strcmp(filter_opt->answer, "first") == 0) return_filter = LAS_FIRST; else if (strcmp(filter_opt->answer, "last") == 0) return_filter = LAS_LAST; else if (strcmp(filter_opt->answer, "mid") == 0) return_filter = LAS_MID; else G_fatal_error(_("Unknown filter option <%s>"), filter_opt->answer); } struct ReturnFilter return_filter_struct; return_filter_struct.filter = return_filter; struct ClassFilter class_filter; class_filter_create_from_strings(&class_filter, class_opt->answers); percent = atoi(percent_opt->answer); /* TODO: we already used zscale */ /* TODO: we don't report intensity range */ if (zscale_opt->answer) zscale = atof(zscale_opt->answer); if (iscale_opt->answer) iscale = atof(iscale_opt->answer); /* parse zrange */ if (zrange_opt->answer != NULL) { if (zrange_opt->answers[0] == NULL) G_fatal_error(_("Invalid zrange")); sscanf(zrange_opt->answers[0], "%lf", &zrange_min); sscanf(zrange_opt->answers[1], "%lf", &zrange_max); if (zrange_min > zrange_max) { d_tmp = zrange_max; zrange_max = zrange_min; zrange_min = d_tmp; } } /* parse irange */ if (irange_opt->answer != NULL) { if (irange_opt->answers[0] == NULL) G_fatal_error(_("Invalid %s"), irange_opt->key); sscanf(irange_opt->answers[0], "%lf", &irange_min); sscanf(irange_opt->answers[1], "%lf", &irange_max); if (irange_min > irange_max) { d_tmp = irange_max; irange_max = irange_min; irange_min = d_tmp; } } point_binning_set(&point_binning, method_opt->answer, pth_opt->answer, trim_opt->answer, FALSE); base_array = NULL; if (strcmp("CELL", type_opt->answer) == 0) rtype = CELL_TYPE; else if (strcmp("DCELL", type_opt->answer) == 0) rtype = DCELL_TYPE; else rtype = FCELL_TYPE; if (point_binning.method == METHOD_N) rtype = CELL_TYPE; if (res_opt->answer) { /* align to resolution */ res = atof(res_opt->answer); if (!G_scan_resolution(res_opt->answer, &res, region.proj)) G_fatal_error(_("Invalid input <%s=%s>"), res_opt->key, res_opt->answer); if (res <= 0) G_fatal_error(_("Option '%s' must be > 0.0"), res_opt->key); region.ns_res = region.ew_res = res; region.north = ceil(region.north / res) * res; region.south = floor(region.south / res) * res; region.east = ceil(region.east / res) * res; region.west = floor(region.west / res) * res; G_adjust_Cell_head(®ion, 0, 0); } else if (extents_flag->answer) { /* align to current region */ Rast_align_window(®ion, &loc_wind); } Rast_set_output_window(®ion); rows = last_rows = region.rows; npasses = 1; if (percent < 100) { rows = (int)(region.rows * (percent / 100.0)); npasses = region.rows / rows; last_rows = region.rows - npasses * rows; if (last_rows) npasses++; else last_rows = rows; } cols = region.cols; G_debug(2, "region.n=%f region.s=%f region.ns_res=%f", region.north, region.south, region.ns_res); G_debug(2, "region.rows=%d [box_rows=%d] region.cols=%d", region.rows, rows, region.cols); /* using row-based chunks (used for output) when input and output * region matches and using segment library when they don't */ int use_segment = 0; int use_base_raster_res = 0; /* TODO: see if the input region extent is smaller than the raster * if yes, the we need to load the whole base raster if the -e * flag was defined (alternatively clip the regions) */ if (base_rast_res_flag->answer) use_base_raster_res = 1; if (base_raster_opt->answer && (res_opt->answer || use_base_raster_res || extents_flag->answer)) use_segment = 1; if (base_raster_opt->answer && !use_segment) { /* TODO: do we need to test existence first? mapset? */ base_raster = Rast_open_old(base_raster_opt->answer, ""); base_raster_data_type = Rast_get_map_type(base_raster); base_array = G_calloc((size_t)rows * (cols + 1), Rast_cell_size(base_raster_data_type)); } if (base_raster_opt->answer && use_segment) { if (use_base_raster_res) { /* read raster actual extent and resolution */ Rast_get_cellhd(base_raster_opt->answer, "", &input_region); /* TODO: make it only as small as the output is or points are */ Rast_set_input_window(&input_region); /* we have split window */ } else { Rast_get_input_window(&input_region); } rast_segment_open(&base_segment, base_raster_opt->answer, &base_raster_data_type); } if (!scan_flag->answer) { if (!check_rows_cols_fit_to_size_t(rows, cols)) G_fatal_error(_("Unable to process the hole map at once. " "Please set the '%s' option to some value lower than 100."), percent_opt->key); point_binning_memory_test(&point_binning, rows, cols, rtype); } /* open output map */ out_fd = Rast_open_new(outmap, rtype); /* allocate memory for a single row of output data */ raster_row = Rast_allocate_output_buf(rtype); G_message(_("Reading data ...")); count_total = line_total = 0; /* main binning loop(s) */ for (pass = 1; pass <= npasses; pass++) { if (npasses > 1) G_message(_("Pass #%d (of %d) ..."), pass, npasses); /* figure out segmentation */ row0 = (pass - 1) * rows; if (pass == npasses) { rows = last_rows; } if (base_array) { G_debug(2, "filling base raster array"); for (row = 0; row < rows; row++) { Rast_get_row(base_raster, base_array + ((size_t) row * cols * Rast_cell_size(base_raster_data_type)), row, base_raster_data_type); } } G_debug(2, "pass=%d/%d rows=%d", pass, npasses, rows); point_binning_allocate(&point_binning, rows, cols, rtype); line = 0; count = 0; counter = 0; G_percent_reset(); /* loop of input files */ for (i = 0; i < infiles.num_items; i++) { infile = infiles.items[i]; /* we already know file is there, so just do basic checks */ LAS_reader = LASReader_Create(infile); if (LAS_reader == NULL) G_fatal_error(_("Unable to open file <%s>"), infile); while ((LAS_point = LASReader_GetNextPoint(LAS_reader)) != NULL) { line++; counter++; if (counter == 100000) { /* speed */ if (line < estimated_lines) G_percent(line, estimated_lines, 3); counter = 0; } /* We always count them and report because behavior * changed in between 7.0 and 7.2 from undefined (but skipping * invalid points) to filtering them out only when requested. */ if (!LASPoint_IsValid(LAS_point)) { n_invalid++; if (only_valid) continue; } x = LASPoint_GetX(LAS_point); y = LASPoint_GetY(LAS_point); if (intens_flag->answer) /* use intensity as z here to allow all filters (and * modifications) below to be applied for intensity */ z = LASPoint_GetIntensity(LAS_point); else z = LASPoint_GetZ(LAS_point); int return_n = LASPoint_GetReturnNumber(LAS_point); int n_returns = LASPoint_GetNumberOfReturns(LAS_point); if (return_filter_is_out(&return_filter_struct, return_n, n_returns)) { n_filtered++; continue; } point_class = (int) LASPoint_GetClassification(LAS_point); if (class_filter_is_out(&class_filter, point_class)) continue; if (y <= region.south || y > region.north) { continue; } if (x < region.west || x >= region.east) { continue; } /* find the bin in the current array box */ arr_row = (int)((region.north - y) / region.ns_res) - row0; if (arr_row < 0 || arr_row >= rows) continue; arr_col = (int)((x - region.west) / region.ew_res); z = z * zscale; if (base_array) { double base_z; if (row_array_get_value_row_col(base_array, arr_row, arr_col, cols, base_raster_data_type, &base_z)) z -= base_z; else continue; } else if (use_segment) { double base_z; if (rast_segment_get_value_xy(&base_segment, &input_region, base_raster_data_type, x, y, &base_z)) z -= base_z; else continue; } if (zrange_opt->answer) { if (z < zrange_min || z > zrange_max) { continue; } } if (intens_import_flag->answer || irange_opt->answer) { intensity = LASPoint_GetIntensity(LAS_point); intensity *= iscale; if (irange_opt->answer) { if (intensity < irange_min || intensity > irange_max) { continue; } } /* use intensity for statistics */ if (intens_import_flag->answer) z = intensity; } count++; /* G_debug(5, "x: %f, y: %f, z: %f", x, y, z); */ update_value(&point_binning, &bin_index_nodes, cols, arr_row, arr_col, rtype, x, y, z); } /* while !EOF of one input file */ /* close input LAS file */ LASReader_Destroy(LAS_reader); } /* end of loop for all input files files */ G_percent(1, 1, 1); /* flush */ G_debug(2, "pass %d finished, %lu coordinates in box", pass, count); count_total += count; line_total += line; /* calc stats and output */ G_message(_("Writing to map ...")); for (row = 0; row < rows; row++) { /* potentially vector writing can be independent on the binning */ write_values(&point_binning, &bin_index_nodes, raster_row, row, cols, rtype, NULL); /* write out line of raster data */ Rast_put_row(out_fd, raster_row, rtype); } /* free memory */ point_binning_free(&point_binning, &bin_index_nodes); } /* passes loop */ if (base_array) Rast_close(base_raster); if (use_segment) Segment_close(&base_segment); G_percent(1, 1, 1); /* flush */ G_free(raster_row); /* close raster file & write history */ Rast_close(out_fd); sprintf(title, "Raw X,Y,Z data binned into a raster grid by cell %s", method_opt->answer); Rast_put_cell_title(outmap, title); Rast_short_history(outmap, "raster", &history); Rast_command_history(&history); Rast_set_history(&history, HIST_DATSRC_1, infile); Rast_write_history(outmap, &history); /* set computation region to the new raster map */ /* TODO: should be in the done message */ if (set_region_flag->answer) G_put_window(®ion); if (n_invalid && only_valid) G_message(_("%lu input points were invalid and filtered out"), n_invalid); if (n_invalid && !only_valid) G_message(_("%lu input points were invalid, use -%c flag to filter" " them out"), n_invalid, only_valid_flag->key); if (infiles.num_items > 1) { sprintf(buff, _("Raster map <%s> created." " %lu points from %d files found in region."), outmap, count_total, infiles.num_items); } else { sprintf(buff, _("Raster map <%s> created." " %lu points found in region."), outmap, count_total); } G_done_msg("%s", buff); G_debug(1, "Processed %lu points.", line_total); string_list_free(&infiles); exit(EXIT_SUCCESS); }
int main(int argc, char *argv[]) { struct Cell_head cellhd; /*region+header info */ char *mapset; /*mapset name */ int nrows, ncols; int row, col; struct GModule *module; struct Option *input, *input1, *input2, *input3, *input4, *input5, *output; struct History history; /*metadata */ struct Colors colors; /*Color rules */ /************************************/ char *name, *name1, *name2; /*input raster name */ char *result; /*output raster name */ /*File Descriptors */ int nfiles, nfiles1, nfiles2; int infd[MAXFILES], infd1[MAXFILES], infd2[MAXFILES]; int outfd; /****************************************/ /* Pointers for file names */ char **names; char **ptr; char **names1; char **ptr1; char **names2; char **ptr2; /****************************************/ int DOYbeforeETa[MAXFILES], DOYafterETa[MAXFILES]; int bfr, aft; /****************************************/ int ok; int i = 0, j = 0; double etodoy; /*minimum ETo DOY */ double startperiod, endperiod; /*first and last days (DOYs) of the period studied */ void *inrast[MAXFILES], *inrast1[MAXFILES], *inrast2[MAXFILES]; DCELL *outrast; CELL val1, val2; RASTER_MAP_TYPE in_data_type[MAXFILES]; /* ETa */ RASTER_MAP_TYPE in_data_type1[MAXFILES]; /* DOY of ETa */ RASTER_MAP_TYPE in_data_type2[MAXFILES]; /* ETo */ RASTER_MAP_TYPE out_data_type = DCELL_TYPE; /************************************/ G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("imagery")); G_add_keyword(_("evapotranspiration")); module->description =_("Computes temporal integration of satellite " "ET actual (ETa) following the daily ET reference " "(ETo) from meteorological station(s)."); /* Define the different options */ input = G_define_standard_option(G_OPT_R_INPUTS); input->key = "eta"; input->description = _("Names of satellite ETa raster maps [mm/d or cm/d]"); input1 = G_define_standard_option(G_OPT_R_INPUTS); input1->key = "eta_doy"; input1->description = _("Names of satellite ETa Day of Year (DOY) raster maps [0-400] [-]"); input2 = G_define_standard_option(G_OPT_R_INPUTS); input2->key = "eto"; input2->description = _("Names of meteorological station ETo raster maps [0-400] [mm/d or cm/d]"); input3 = G_define_option(); input3->key = "eto_doy_min"; input3->type = TYPE_DOUBLE; input3->required = YES; input3->description = _("Value of DOY for ETo first day"); input4 = G_define_option(); input4->key = "start_period"; input4->type = TYPE_DOUBLE; input4->required = YES; input4->description = _("Value of DOY for the first day of the period studied"); input5 = G_define_option(); input5->key = "end_period"; input5->type = TYPE_DOUBLE; input5->required = YES; input5->description = _("Value of DOY for the last day of the period studied"); output = G_define_standard_option(G_OPT_R_OUTPUT); /* init nfiles */ nfiles = 1; nfiles1 = 1; nfiles2 = 1; /********************/ if (G_parser(argc, argv)) exit(EXIT_FAILURE); ok = 1; names = input->answers; ptr = input->answers; names1 = input1->answers; ptr1 = input1->answers; names2 = input2->answers; ptr2 = input2->answers; etodoy = atof(input3->answer); startperiod = atof(input4->answer); endperiod = atof(input5->answer); result = output->answer; /****************************************/ if (endperiod<startperiod) { G_fatal_error(_("The DOY for end_period can not be smaller than start_period")); ok = 0; } if (etodoy>startperiod) { G_fatal_error(_("The DOY for start_period can not be smaller than eto_doy_min")); ok = 0; } for (; *ptr != NULL; ptr++) { if (nfiles > MAXFILES) G_fatal_error(_("Too many ETa files. Only %d allowed."), MAXFILES); name = *ptr; /* Allocate input buffer */ infd[nfiles] = Rast_open_old(name, ""); Rast_get_cellhd(name, "", &cellhd); inrast[nfiles] = Rast_allocate_d_buf(); nfiles++; } nfiles--; if (nfiles <= 1) G_fatal_error(_("The min specified input map is two")); /****************************************/ for (; *ptr1 != NULL; ptr1++) { if (nfiles1 > MAXFILES) G_fatal_error(_("Too many ETa_doy files. Only %d allowed."), MAXFILES); name1 = *ptr1; /* Allocate input buffer */ infd1[nfiles1] = Rast_open_old(name1, ""); Rast_get_cellhd(name1, "", &cellhd); inrast1[nfiles1] = Rast_allocate_d_buf(); nfiles1++; } nfiles1--; if (nfiles1 <= 1) G_fatal_error(_("The min specified input map is two")); /****************************************/ if (nfiles != nfiles1) G_fatal_error(_("ETa and ETa_DOY file numbers are not equal!")); /****************************************/ for (; *ptr2 != NULL; ptr2++) { if (nfiles > MAXFILES) G_fatal_error(_("Too many ETo files. Only %d allowed."), MAXFILES); name2 = *ptr2; /* Allocate input buffer */ infd2[nfiles2] = Rast_open_old(name2, ""); Rast_get_cellhd(name2, "", &cellhd); inrast2[nfiles2] = Rast_allocate_d_buf(); nfiles2++; } nfiles2--; if (nfiles2 <= 1) G_fatal_error(_("The min specified input map is two")); /* Allocate output buffer, use input map data_type */ nrows = Rast_window_rows(); ncols = Rast_window_cols(); outrast = Rast_allocate_d_buf(); /* Create New raster files */ outfd = Rast_open_new(result, 1); /*******************/ /* Process pixels */ double doy[MAXFILES]; double sum[MAXFILES]; for (row = 0; row < nrows; row++) { DCELL d_out; DCELL d_ETrF[MAXFILES]; DCELL d[MAXFILES]; DCELL d1[MAXFILES]; DCELL d2[MAXFILES]; G_percent(row, nrows, 2); /* read input map */ for (i = 1; i <= nfiles; i++) Rast_get_d_row(infd[i], inrast[i], row); for (i = 1; i <= nfiles1; i++) Rast_get_d_row(infd1[i], inrast1[i], row); for (i = 1; i <= nfiles2; i++) Rast_get_d_row (infd2[i], inrast2[i], row); /*process the data */ for (col = 0; col < ncols; col++) { int d1_null=0; int d_null=0; for (i = 1; i <= nfiles; i++) { if (Rast_is_d_null_value(&((DCELL *) inrast[i])[col])) d_null=1; else d[i] = ((DCELL *) inrast[i])[col]; } for (i = 1; i <= nfiles1; i++) { if (Rast_is_d_null_value(&((DCELL *) inrast1[i])[col])) d1_null=1; else d1[i] = ((DCELL *) inrast1[i])[col]; } for (i = 1; i <= nfiles2; i++) d2[i] = ((DCELL *) inrast2[i])[col]; /* Find out the DOY of the eto image */ for (i = 1; i <= nfiles1; i++) { if ( d_null==1 || d1_null==1 ) Rast_set_d_null_value(&outrast[col],1); else { doy[i] = d1[i] - etodoy+1; if (Rast_is_d_null_value(&d2[(int)doy[i]]) || d2[(int)doy[i]]==0 ) Rast_set_d_null_value(&outrast[col],1); else d_ETrF[i] = d[i] / d2[(int)doy[i]]; } } for (i = 1; i <= nfiles1; i++) { /* do nothing */ if ( d_null==1 || d1_null==1) { /*G_message(" null value ");*/ } else { DOYbeforeETa[i]=0; DOYafterETa[i]=0; if (i == 1) DOYbeforeETa[i] = startperiod; else { int k=i-1; while (d1[k]>=startperiod ) { if (d1[k]<0) // case were d1[k] is null k=k-1; else { DOYbeforeETa[i] = 1+((d1[i] + d1[k])/2.0); break; } } } if (i == nfiles1) DOYafterETa[i] = endperiod; else { int k=i+1; while (d1[k]<=endperiod) { if (d1[k]<0) // case were d1[k] is null k=k+1; else { DOYafterETa[i] = (d1[i] + d1[k]) / 2.0; break; } } } } } sum[MAXFILES] = 0.0; for (i = 1; i <= nfiles1; i++) { if(d_null==1 || d1_null==1) { /* do nothing */ } else { if (DOYbeforeETa[i]==0 || DOYbeforeETa[i]==0 ) Rast_set_d_null_value(&outrast[col],1); else { bfr = (int)DOYbeforeETa[i]; aft = (int)DOYafterETa[i]; sum[i]=0.0; for (j = bfr; j < aft; j++) sum[i] += d2[(int)(j-etodoy+1)]; } } } d_out = 0.0; for (i = 1; i <= nfiles1; i++) { if(d_null==1 || d_null==1) Rast_set_d_null_value(&outrast[col],1); else { d_out += d_ETrF[i] * sum[i]; outrast[col] = d_out; } } } Rast_put_row(outfd, outrast, out_data_type); } for (i = 1; i <= nfiles; i++) { G_free(inrast[i]); Rast_close(infd[i]); } for (i = 1; i <= nfiles1; i++) { G_free(inrast1[i]); Rast_close(infd1[i]); } for (i = 1; i <= nfiles2; i++) { G_free(inrast2[i]); Rast_close(infd2[i]); } G_free(outrast); Rast_close(outfd); /* Color table from 0.0 to 10.0 */ Rast_init_colors(&colors); val1 = 0; val2 = 10; Rast_add_c_color_rule(&val1, 0, 0, 0, &val2, 255, 255, 255, &colors); /* Metadata */ Rast_short_history(result, "raster", &history); Rast_command_history(&history); Rast_write_history(result, &history); exit(EXIT_SUCCESS); }
int main(int argc, char *argv[]) { struct Cell_head cellhd; /* buffer for in out raster */ DCELL *inrast_T, *inrast_RH, *inrast_u2; DCELL *inrast_Rn, *inrast_DEM, *inrast_hc, *outrast; char *EPo; int nrows, ncols; int row, col; int infd_T, infd_RH, infd_u2, infd_Rn, infd_DEM, infd_hc; int outfd; char *T, *RH, *u2, *Rn, *DEM, *hc; DCELL d_T, d_RH, d_u2, d_Rn, d_Z, d_hc; DCELL d_EPo; int d_night; struct History history; struct GModule *module; struct Option *input_DEM, *input_T, *input_RH; struct Option *input_u2, *input_Rn, *input_hc, *output; struct Flag *day, *zero; G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("imagery")); G_add_keyword(_("evapotranspiration")); module->description = _("Computes potential evapotranspiration calculation with hourly Penman-Monteith."); /* Define different options */ input_DEM = G_define_standard_option(G_OPT_R_ELEV); input_DEM->description = _("Name of input elevation raster map [m a.s.l.]"); input_T = G_define_standard_option(G_OPT_R_INPUT); input_T->key = "temperature"; input_T->description = _("Name of input temperature raster map [C]"); input_RH = G_define_standard_option(G_OPT_R_INPUT); input_RH->key = "relativehumidity"; input_RH->description = _("Name of input relative humidity raster map [%]"); input_u2 = G_define_standard_option(G_OPT_R_INPUT); input_u2->key = "windspeed"; input_u2->description = _("Name of input wind speed raster map [m/s]"); input_Rn = G_define_standard_option(G_OPT_R_INPUT); input_Rn->key = "netradiation"; input_Rn->description = _("Name of input net solar radiation raster map [MJ/m2/h]"); input_hc = G_define_standard_option(G_OPT_R_INPUT); input_hc->key = "cropheight"; input_hc->description = _("Name of input crop height raster map [m]"); output = G_define_standard_option(G_OPT_R_OUTPUT); _("Name for output raster map [mm/h]"); zero = G_define_flag(); zero->key = 'z'; zero->description = _("Set negative evapotranspiration to zero"); day = G_define_flag(); day->key = 'n'; day->description = _("Use Night-time"); if (G_parser(argc, argv)) exit(EXIT_FAILURE); /* get entered parameters */ T = input_T->answer; RH = input_RH->answer; u2 = input_u2->answer; Rn = input_Rn->answer; EPo = output->answer; DEM = input_DEM->answer; hc = input_hc->answer; if (day->answer) { d_night = TRUE; } else { d_night = FALSE; } infd_T = Rast_open_old(T, ""); infd_RH = Rast_open_old(RH, ""); infd_u2 = Rast_open_old(u2, ""); infd_Rn = Rast_open_old(Rn, ""); infd_DEM = Rast_open_old(DEM, ""); infd_hc = Rast_open_old(hc, ""); Rast_get_cellhd(T, "", &cellhd); Rast_get_cellhd(RH, "", &cellhd); Rast_get_cellhd(u2, "", &cellhd); Rast_get_cellhd(Rn, "", &cellhd); Rast_get_cellhd(DEM, "", &cellhd); Rast_get_cellhd(hc, "", &cellhd); /* Allocate input buffer */ inrast_T = Rast_allocate_d_buf(); inrast_RH = Rast_allocate_d_buf(); inrast_u2 = Rast_allocate_d_buf(); inrast_Rn = Rast_allocate_d_buf(); inrast_DEM = Rast_allocate_d_buf(); inrast_hc = Rast_allocate_d_buf(); /* Allocate output buffer */ nrows = Rast_window_rows(); ncols = Rast_window_cols(); outrast = Rast_allocate_d_buf(); outfd = Rast_open_new(EPo, DCELL_TYPE); for (row = 0; row < nrows; row++) { /* read a line input maps into buffers */ Rast_get_d_row(infd_T, inrast_T, row); Rast_get_d_row(infd_RH, inrast_RH, row); Rast_get_d_row(infd_u2, inrast_u2, row); Rast_get_d_row(infd_Rn, inrast_Rn, row); Rast_get_d_row(infd_DEM, inrast_DEM, row); Rast_get_d_row(infd_hc, inrast_hc, row); /* read every cell in the line buffers */ for (col = 0; col < ncols; col++) { d_T = ((DCELL *) inrast_T)[col]; d_RH = ((DCELL *) inrast_RH)[col]; d_u2 = ((DCELL *) inrast_u2)[col]; d_Rn = ((DCELL *) inrast_Rn)[col]; d_Z = ((DCELL *) inrast_DEM)[col]; d_hc = ((DCELL *) inrast_hc)[col]; /* calculate evapotranspiration */ if (d_hc < 0) { /* calculate evaporation */ d_EPo = calc_openwaterETp(d_T, d_Z, d_u2, d_Rn, d_night, d_RH, d_hc); } else { /* calculate evapotranspiration */ d_EPo = calc_ETp(d_T, d_Z, d_u2, d_Rn, d_night, d_RH, d_hc); } if (zero->answer && d_EPo < 0) d_EPo = 0; ((DCELL *) outrast)[col] = d_EPo; } Rast_put_d_row(outfd, outrast); } G_free(inrast_T); G_free(inrast_RH); G_free(inrast_u2); G_free(inrast_Rn); G_free(inrast_DEM); G_free(inrast_hc); G_free(outrast); Rast_close(infd_T); Rast_close(infd_RH); Rast_close(infd_u2); Rast_close(infd_Rn); Rast_close(infd_DEM); Rast_close(infd_hc); Rast_close(outfd); /* add command line incantation to history file */ Rast_short_history(EPo, "raster", &history); Rast_command_history(&history); Rast_write_history(EPo, &history); exit(EXIT_SUCCESS); }
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 main(int argc, char *argv[]) { struct Cell_head cellhd; /* buffer for in, tmp and out raster */ void *inrast_Rn, *inrast_g0; void *inrast_z0m, *inrast_t0dem; DCELL *outrast; int nrows, ncols; int row, col; int row_wet, col_wet; int row_dry, col_dry; double m_row_wet, m_col_wet; double m_row_dry, m_col_dry; int infd_Rn, infd_g0; int infd_z0m, infd_t0dem; int outfd; char *Rn, *g0; char *z0m, *t0dem; char *h0; double ustar, ea; struct History history; struct GModule *module; struct Option *input_Rn, *input_g0; struct Option *input_z0m, *input_t0dem, *input_ustar; struct Option *input_ea, *output; struct Option *input_row_wet, *input_col_wet; struct Option *input_row_dry, *input_col_dry; struct Flag *flag2, *flag3; /********************************/ double xp, yp; double xmin, ymin; double xmax, ymax; double stepx, stepy; double latitude, longitude; int rowDry, colDry, rowWet, colWet; /********************************/ G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("imagery")); G_add_keyword(_("energy balance")); G_add_keyword(_("soil moisture")); G_add_keyword(_("evaporative fraction")); G_add_keyword(_("SEBAL")); module->description = _("Computes sensible heat flux iteration SEBAL 01."); /* Define different options */ input_Rn = G_define_standard_option(G_OPT_R_INPUT); input_Rn->key = "netradiation"; input_Rn->description = _("Name of instantaneous Net Radiation raster map [W/m2]"); input_g0 = G_define_standard_option(G_OPT_R_INPUT); input_g0->key = "soilheatflux"; input_g0->description = _("Name of instantaneous soil heat flux raster map [W/m2]"); input_z0m = G_define_standard_option(G_OPT_R_INPUT); input_z0m->key = "aerodynresistance"; input_z0m->description = _("Name of aerodynamic resistance to heat momentum raster map [s/m]"); input_t0dem = G_define_standard_option(G_OPT_R_INPUT); input_t0dem->key = "temperaturemeansealevel"; input_t0dem->description = _("Name of altitude corrected surface temperature raster map [K]"); input_ustar = G_define_option(); input_ustar->key = "frictionvelocitystar"; input_ustar->type = TYPE_DOUBLE; input_ustar->required = YES; input_ustar->gisprompt = "old,value"; input_ustar->answer = "0.32407"; input_ustar->description = _("Value of the height independent friction velocity (u*) [m/s]"); input_ustar->guisection = _("Parameters"); input_ea = G_define_option(); input_ea->key = "vapourpressureactual"; input_ea->type = TYPE_DOUBLE; input_ea->required = YES; input_ea->answer = "1.511"; input_ea->description = _("Value of the actual vapour pressure (e_act) [KPa]"); input_ea->guisection = _("Parameters"); input_row_wet = G_define_option(); input_row_wet->key = "row_wet_pixel"; input_row_wet->type = TYPE_DOUBLE; input_row_wet->required = NO; input_row_wet->description = _("Row value of the wet pixel"); input_row_wet->guisection = _("Parameters"); input_col_wet = G_define_option(); input_col_wet->key = "column_wet_pixel"; input_col_wet->type = TYPE_DOUBLE; input_col_wet->required = NO; input_col_wet->description = _("Column value of the wet pixel"); input_col_wet->guisection = _("Parameters"); input_row_dry = G_define_option(); input_row_dry->key = "row_dry_pixel"; input_row_dry->type = TYPE_DOUBLE; input_row_dry->required = NO; input_row_dry->description = _("Row value of the dry pixel"); input_row_dry->guisection = _("Parameters"); input_col_dry = G_define_option(); input_col_dry->key = "column_dry_pixel"; input_col_dry->type = TYPE_DOUBLE; input_col_dry->required = NO; input_col_dry->description = _("Column value of the dry pixel"); input_col_dry->guisection = _("Parameters"); output = G_define_standard_option(G_OPT_R_OUTPUT); output->description = _("Name for output sensible heat flux raster map [W/m2]"); /* Define the different flags */ flag2 = G_define_flag(); flag2->key = 'a'; flag2->description = _("Automatic wet/dry pixel (careful!)"); flag3 = G_define_flag(); flag3->key = 'c'; flag3->description = _("Dry/Wet pixels coordinates are in image projection, not row/col"); if (G_parser(argc, argv)) exit(EXIT_FAILURE); /* get entered parameters */ Rn = input_Rn->answer; g0 = input_g0->answer; z0m = input_z0m->answer; t0dem = input_t0dem->answer; h0 = output->answer; ustar = atof(input_ustar->answer); ea = atof(input_ea->answer); if(input_row_wet->answer&& input_col_wet->answer&& input_row_dry->answer&& input_col_dry->answer){ m_row_wet = atof(input_row_wet->answer); m_col_wet = atof(input_col_wet->answer); m_row_dry = atof(input_row_dry->answer); m_col_dry = atof(input_col_dry->answer); } if ((!input_row_wet->answer || !input_col_wet->answer || !input_row_dry->answer || !input_col_dry->answer) && !flag2->answer) { G_fatal_error(_("Either auto-mode either wet/dry pixels coordinates should be provided!")); } if (flag3->answer) { G_message(_("Manual wet/dry pixels in image coordinates")); G_message(_("Wet Pixel=> x:%f y:%f"), m_col_wet, m_row_wet); G_message(_("Dry Pixel=> x:%f y:%f"), m_col_dry, m_row_dry); } else { if(flag2->answer) G_message(_("Automatic mode selected")); else { G_message(_("Wet Pixel=> row:%.0f col:%.0f"), m_row_wet, m_col_wet); G_message(_("Dry Pixel=> row:%.0f col:%.0f"), m_row_dry, m_col_dry); } } /* check legal output name */ if (G_legal_filename(h0) < 0) G_fatal_error(_("<%s> is an illegal name"), h0); infd_Rn = Rast_open_old(Rn, ""); infd_g0 = Rast_open_old(g0, ""); infd_z0m = Rast_open_old(z0m, ""); infd_t0dem = Rast_open_old(t0dem, ""); Rast_get_cellhd(Rn, "", &cellhd); Rast_get_cellhd(g0, "", &cellhd); Rast_get_cellhd(z0m, "", &cellhd); Rast_get_cellhd(t0dem, "", &cellhd); /* Allocate input buffer */ inrast_Rn = Rast_allocate_d_buf(); inrast_g0 = Rast_allocate_d_buf(); inrast_z0m = Rast_allocate_d_buf(); inrast_t0dem = Rast_allocate_d_buf(); /***************************************************/ /* Setup pixel location variables */ /***************************************************/ stepx = cellhd.ew_res; stepy = cellhd.ns_res; xmin = cellhd.west; xmax = cellhd.east; ymin = cellhd.south; ymax = cellhd.north; nrows = Rast_window_rows(); ncols = Rast_window_cols(); /***************************************************/ /* Allocate output buffer */ /***************************************************/ outrast = Rast_allocate_d_buf(); outfd = Rast_open_new(h0, DCELL_TYPE); /***************************************************/ /* Allocate memory for temporary images */ double **d_Roh, **d_Rah; if ((d_Roh = G_alloc_matrix(nrows, ncols)) == NULL) G_message("Unable to allocate memory for temporary d_Roh image"); if ((d_Rah = G_alloc_matrix(nrows, ncols)) == NULL) G_message("Unable to allocate memory for temporary d_Rah image"); /***************************************************/ /* MANUAL T0DEM WET/DRY PIXELS */ DCELL d_Rn_dry,d_g0_dry; DCELL d_t0dem_dry,d_t0dem_wet; if (flag2->answer) { /* Process tempk min / max pixels */ /* Internal use only */ DCELL d_Rn_wet,d_g0_wet; DCELL d_Rn,d_g0,d_h0; DCELL t0dem_min,t0dem_max; /*********************/ for (row = 0; row < nrows; row++) { DCELL d_t0dem; G_percent(row, nrows, 2); Rast_get_d_row(infd_t0dem,inrast_t0dem,row); Rast_get_d_row(infd_Rn,inrast_Rn,row); Rast_get_d_row(infd_g0,inrast_g0,row); /*process the data */ for (col = 0; col < ncols; col++) { d_t0dem = ((DCELL *) inrast_t0dem)[col]; d_Rn = ((DCELL *) inrast_Rn)[col]; d_g0 = ((DCELL *) inrast_g0)[col]; if (Rast_is_d_null_value(&d_t0dem) || Rast_is_d_null_value(&d_Rn) || Rast_is_d_null_value(&d_g0)) { /* do nothing */ } else { if (d_t0dem <= 250.0) { /* do nothing */ } else { d_h0 = d_Rn - d_g0; if (d_t0dem < t0dem_min && d_Rn > 0.0 && d_g0 > 0.0 && d_h0 > 0.0 && d_h0 < 100.0) { t0dem_min = d_t0dem; d_t0dem_wet = d_t0dem; d_Rn_wet = d_Rn; d_g0_wet = d_g0; m_col_wet = col; m_row_wet = row; } if (d_t0dem > t0dem_max && d_Rn > 0.0 && d_g0 > 0.0 && d_h0 > 100.0 && d_h0 < 500.0) { t0dem_max = d_t0dem; d_t0dem_dry = d_t0dem; d_Rn_dry = d_Rn; d_g0_dry = d_g0; m_col_dry = col; m_row_dry = row; } } } } } G_message("row_wet=%d\tcol_wet=%d", row_wet, col_wet); G_message("row_dry=%d\tcol_dry=%d", row_dry, col_dry); G_message("g0_wet=%f", d_g0_wet); G_message("Rn_wet=%f", d_Rn_wet); G_message("LE_wet=%f", d_Rn_wet - d_g0_wet); G_message("t0dem_dry=%f", d_t0dem_dry); G_message("rnet_dry=%f", d_Rn_dry); G_message("g0_dry=%f", d_g0_dry); G_message("h0_dry=%f", d_Rn_dry - d_g0_dry); }/* END OF FLAG2 */ G_message("Passed here"); /* MANUAL T0DEM WET/DRY PIXELS */ /*DRY PIXEL */ if (flag3->answer) { /*Calculate coordinates of row/col from projected ones */ row = (int)((ymax - m_row_dry) / (double)stepy); col = (int)((m_col_dry - xmin) / (double)stepx); G_message("Dry Pixel | row:%i col:%i", row, col); } else { row = (int)m_row_dry; col = (int)m_col_dry; G_message("Dry Pixel | row:%i col:%i", row, col); } rowDry = row; colDry = col; Rast_get_d_row(infd_Rn, inrast_Rn, row); Rast_get_d_row(infd_g0, inrast_g0, row); Rast_get_d_row(infd_t0dem, inrast_t0dem, row); d_Rn_dry = ((DCELL *) inrast_Rn)[col]; d_g0_dry = ((DCELL *) inrast_g0)[col]; d_t0dem_dry = ((DCELL *) inrast_t0dem)[col]; /*WET PIXEL */ if (flag3->answer) { /*Calculate coordinates of row/col from projected ones */ row = (int)((ymax - m_row_wet) / (double)stepy); col = (int)((m_col_wet - xmin) / (double)stepx); G_message("Wet Pixel | row:%i col:%i", row, col); } else { row = m_row_wet; col = m_col_wet; G_message("Wet Pixel | row:%i col:%i", row, col); } rowWet = row; colWet = col; Rast_get_d_row(infd_t0dem, inrast_t0dem, row); d_t0dem_wet = ((DCELL *) inrast_t0dem)[col]; /* END OF MANUAL WET/DRY PIXELS */ double h_dry; h_dry = d_Rn_dry - d_g0_dry; G_message("h_dry = %f", h_dry); G_message("t0dem_dry = %f", d_t0dem_dry); G_message("t0dem_wet = %f", d_t0dem_wet); DCELL d_rah_dry; DCELL d_roh_dry; /* INITIALIZATION */ for (row = 0; row < nrows; row++) { DCELL d_t0dem,d_z0m; DCELL d_rah1,d_roh1; DCELL d_u5; G_percent(row, nrows, 2); /* read a line input maps into buffers */ Rast_get_d_row(infd_z0m, inrast_z0m, row); Rast_get_d_row(infd_t0dem, inrast_t0dem,row); /* read every cell in the line buffers */ for (col = 0; col < ncols; col++) { d_z0m = ((DCELL *) inrast_z0m)[col]; d_t0dem = ((DCELL *) inrast_t0dem)[col]; if (Rast_is_d_null_value(&d_t0dem) || Rast_is_d_null_value(&d_z0m)) { /* do nothing */ d_Roh[row][col] = -999.9; d_Rah[row][col] = -999.9; } else { d_u5 = (ustar / 0.41) * log(5 / d_z0m); d_rah1=(1/(d_u5*pow(0.41,2)))*log(5/d_z0m)*log(5/(d_z0m*0.1)); d_roh1=((998-ea)/(d_t0dem*2.87))+(ea/(d_t0dem*4.61)); if (d_roh1 > 5) d_roh1 = 1.0; else d_roh1=((1000-4.65)/(d_t0dem*2.87))+(4.65/(d_t0dem*4.61)); if (row == rowDry && col == colDry) { /*collect dry pix info */ d_rah_dry = d_rah1; d_roh_dry = d_roh1; G_message("d_rah_dry=%f d_roh_dry=%f",d_rah_dry,d_roh_dry); } d_Roh[row][col] = d_roh1; d_Rah[row][col] = d_rah1; } } } DCELL d_dT_dry; /*Calculate dT_dry */ d_dT_dry = (h_dry * d_rah_dry) / (1004 * d_roh_dry); double a, b; /*Calculate coefficients for next dT equation */ /*a = 1.0/ ((d_dT_dry-0.0) / (d_t0dem_dry-d_t0dem_wet)); */ /*b = ( a * d_t0dem_wet ) * (-1.0); */ double sumx = d_t0dem_wet + d_t0dem_dry; double sumy = d_dT_dry + 0.0; double sumx2 = pow(d_t0dem_wet, 2) + pow(d_t0dem_dry, 2); double sumxy = (d_t0dem_wet * 0.0) + (d_t0dem_dry * d_dT_dry); a = (sumxy - ((sumx * sumy) / 2.0)) / (sumx2 - (pow(sumx, 2) / 2.0)); b = (sumy - (a * sumx)) / 2.0; G_message("d_dT_dry=%f", d_dT_dry); G_message("dT1=%f * t0dem + (%f)", a, b); DCELL d_h_dry; /* ITERATION 1 */ for (row = 0; row < nrows; row++) { DCELL d_t0dem,d_z0m; DCELL d_h1,d_rah1,d_rah2,d_roh1; DCELL d_L,d_x,d_psih,d_psim; DCELL d_u5; G_percent(row, nrows, 2); /* read a line input maps into buffers */ Rast_get_d_row(infd_z0m, inrast_z0m, row); Rast_get_d_row(infd_t0dem, inrast_t0dem,row); /* read every cell in the line buffers */ for (col = 0; col < ncols; col++) { d_z0m = ((DCELL *) inrast_z0m)[col]; d_t0dem = ((DCELL *) inrast_t0dem)[col]; d_rah1 = d_Rah[row][col]; d_roh1 = d_Roh[row][col]; if (Rast_is_d_null_value(&d_t0dem) || Rast_is_d_null_value(&d_z0m)) { /* do nothing */ } else { if (d_rah1 < 1.0) d_h1 = 0.0; else d_h1 = (1004 * d_roh1) * (a * d_t0dem + b) / d_rah1; d_L =-1004*d_roh1*pow(ustar,3)*d_t0dem/(d_h1*9.81*0.41); d_x = pow((1-16*(5/d_L)),0.25); d_psim =2*log((1+d_x)/2)+log((1+pow(d_x,2))/2)-2*atan(d_x)+0.5*M_PI; d_psih =2*log((1+pow(d_x,2))/2); d_u5 =(ustar/0.41)*log(5/d_z0m); d_rah2 = (1/(d_u5*pow(0.41,2)))*log((5/d_z0m)-d_psim) *log((5/(d_z0m*0.1))-d_psih); if (row == rowDry && col == colDry) {/*collect dry pix info */ d_rah_dry = d_rah2; d_h_dry = d_h1; } d_Rah[row][col] = d_rah1; } } } /*Calculate dT_dry */ d_dT_dry = (d_h_dry * d_rah_dry) / (1004 * d_roh_dry); /*Calculate coefficients for next dT equation */ /* a = (d_dT_dry-0)/(d_t0dem_dry-d_t0dem_wet); */ /* b = (-1.0) * ( a * d_t0dem_wet ); */ /* G_message("d_dT_dry=%f",d_dT_dry); */ /* G_message("dT2=%f * t0dem + (%f)", a, b); */ sumx = d_t0dem_wet + d_t0dem_dry; sumy = d_dT_dry + 0.0; sumx2 = pow(d_t0dem_wet, 2) + pow(d_t0dem_dry, 2); sumxy = (d_t0dem_wet * 0.0) + (d_t0dem_dry * d_dT_dry); a = (sumxy - ((sumx * sumy) / 2.0)) / (sumx2 - (pow(sumx, 2) / 2.0)); b = (sumy - (a * sumx)) / 2.0; G_message("d_dT_dry=%f", d_dT_dry); G_message("dT1=%f * t0dem + (%f)", a, b); /* ITERATION 2 */ /***************************************************/ /***************************************************/ for (row = 0; row < nrows; row++) { DCELL d_t0dem; DCELL d_z0m; DCELL d_rah2; DCELL d_rah3; DCELL d_roh1; DCELL d_h2; DCELL d_L; DCELL d_x; DCELL d_psih; DCELL d_psim; DCELL d_u5; G_percent(row, nrows, 2); /* read a line input maps into buffers */ Rast_get_d_row(infd_z0m,inrast_z0m,row); Rast_get_d_row(infd_t0dem,inrast_t0dem,row); /* read every cell in the line buffers */ for (col = 0; col < ncols; col++) { d_z0m = ((DCELL *) inrast_z0m)[col]; d_t0dem = ((DCELL *) inrast_t0dem)[col]; d_rah2 = d_Rah[row][col]; d_roh1 = d_Roh[row][col]; if (Rast_is_d_null_value(&d_t0dem) || Rast_is_d_null_value(&d_z0m)) { /* do nothing */ } else { if (d_rah2 < 1.0) { d_h2 = 0.0; } else { d_h2 =(1004*d_roh1)*(a*d_t0dem+b)/d_rah2; } d_L =-1004*d_roh1*pow(ustar,3)*d_t0dem/(d_h2*9.81*0.41); d_x = pow((1 - 16 * (5 / d_L)), 0.25); d_psim =2*log((1+d_x)/2)+log((1+pow(d_x,2))/2)- 2*atan(d_x)+0.5*M_PI; d_psih =2*log((1+pow(d_x,2))/2); d_u5 =(ustar/0.41)*log(5/d_z0m); d_rah3=(1/(d_u5*pow(0.41,2)))*log((5/d_z0m)-d_psim)* log((5/(d_z0m*0.1))-d_psih); if (row == rowDry && col == colDry) {/*collect dry pix info */ d_rah_dry = d_rah2; d_h_dry = d_h2; } d_Rah[row][col] = d_rah2; } } } /*Calculate dT_dry */ d_dT_dry = (d_h_dry * d_rah_dry) / (1004 * d_roh_dry); /*Calculate coefficients for next dT equation */ /* a = (d_dT_dry-0)/(d_t0dem_dry-d_t0dem_wet); */ /* b = (-1.0) * ( a * d_t0dem_wet ); */ /* G_message("d_dT_dry=%f",d_dT_dry); */ /* G_message("dT3=%f * t0dem + (%f)", a, b); */ sumx = d_t0dem_wet + d_t0dem_dry; sumy = d_dT_dry + 0.0; sumx2 = pow(d_t0dem_wet, 2) + pow(d_t0dem_dry, 2); sumxy = (d_t0dem_wet * 0.0) + (d_t0dem_dry * d_dT_dry); a = (sumxy - ((sumx * sumy) / 2.0)) / (sumx2 - (pow(sumx, 2) / 2.0)); b = (sumy - (a * sumx)) / 2.0; G_message("d_dT_dry=%f", d_dT_dry); G_message("dT1=%f * t0dem + (%f)", a, b); /* ITERATION 3 */ /***************************************************/ /***************************************************/ for (row = 0; row < nrows; row++) { DCELL d_t0dem; DCELL d_z0m; DCELL d_rah3; DCELL d_roh1; DCELL d_h3; DCELL d_L; DCELL d_x; DCELL d_psih; DCELL d_psim; DCELL d; /* Output pixel */ G_percent(row, nrows, 2); /* read a line input maps into buffers */ Rast_get_d_row(infd_z0m, inrast_z0m, row); Rast_get_d_row(infd_t0dem,inrast_t0dem,row); /* read every cell in the line buffers */ for (col = 0; col < ncols; col++) { d_z0m = ((DCELL *) inrast_z0m)[col]; d_t0dem = ((DCELL *) inrast_t0dem)[col]; d_rah3 = d_Rah[row][col]; d_roh1 = d_Roh[row][col]; if (Rast_is_d_null_value(&d_t0dem) || Rast_is_d_null_value(&d_z0m)) { Rast_set_d_null_value(&outrast[col], 1); } else { if (d_rah3 < 1.0) { d_h3 = 0.0; } else { d_h3 = (1004 * d_roh1) * (a * d_t0dem + b) / d_rah3; } if (d_h3 < 0 && d_h3 > -50) { d_h3 = 0.0; } if (d_h3 < -50 || d_h3 > 1000) { Rast_set_d_null_value(&outrast[col], 1); } outrast[col] = d_h3; } } Rast_put_d_row(outfd, outrast); } G_free(inrast_z0m); Rast_close(infd_z0m); G_free(inrast_t0dem); Rast_close(infd_t0dem); G_free(outrast); Rast_close(outfd); /* add command line incantation to history file */ Rast_short_history(h0, "raster", &history); Rast_command_history(&history); Rast_write_history(h0, &history); exit(EXIT_SUCCESS); }