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; }
/* 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); }
int configure_plot(void) { int i, j; int nrows; int ncols; nrows = region.rows - at_row; if (nrows <= 0) return DONE; if (nrows > max_rows) nrows = max_rows; ncols = region.cols; /* zero the raster */ switch (format) { case USE_CHAR: for (i = 0; i < nrows; i++) for (j = 0; j < ncols; j++) raster.c[i][j] = 0; break; case USE_UCHAR: for (i = 0; i < nrows; i++) for (j = 0; j < ncols; j++) raster.u[i][j] = 0; break; case USE_SHORT: for (i = 0; i < nrows; i++) for (j = 0; j < ncols; j++) raster.s[i][j] = 0; break; case USE_CELL: for (i = 0; i < nrows; i++) for (j = 0; j < ncols; j++) raster.cell[i][j] = 0; break; } /* change the region */ page.north = region.north - at_row * region.ns_res; page.south = page.north - nrows * region.ns_res; Rast_set_window(&page); /* configure the plot routines */ G_setup_plot(-0.5, page.rows - 0.5, -0.5, page.cols - 0.5, move, cont); return AGAIN; }
/*! \brief Graphics frame setup This is a high level D call. It does a full setup for the current graphics frame. Note: Connection to driver must already be made. Sets the source coordinate system to the current region, and adjusts the destination coordinate system to preserve the aspect ratio. Performs a full setup for the current graphics frame: - Makes sure there is a current graphics frame (will create a full-screen one, if not); - Sets the region coordinates so that the graphics frame and the active module region agree (may change active module region to do this); and - Performs graphic frame/region coordinate conversion initialization. If <b>clear</b> is true, the frame is cleared (same as running <i>d.erase</i>.) Otherwise, it is not cleared. \param clear 1 to clear frame (visually and coordinates) */ void D_setup(int clear) { struct Cell_head region; double dt, db, dl, dr; D_get_window(&dt, &db, &dl, &dr); G_get_set_window(®ion); Rast_set_window(®ion); D_do_conversions(®ion, dt, db, dl, dr); if (clear) D_erase(DEFAULT_BG_COLOR); }
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 zoom(struct Cell_head *window, const char *name, const char *mapset) { int fd; void *raster, *rast_ptr; RASTER_MAP_TYPE map_type; int row, col; int nrows, ncols; int top, bottom, left, right, mark; double north, south, east, west; G_adjust_Cell_head3(window, 0, 0, 0); Rast_set_window(window); nrows = window->rows; ncols = window->cols; fd = Rast_open_old(name, mapset); map_type = Rast_get_map_type(fd); raster = Rast_allocate_buf(map_type); /* find first non-null row */ top = nrows; bottom = -1; left = ncols; right = -1; for (row = 0; row < nrows; row++) { Rast_get_row(fd, rast_ptr = raster, row, map_type); for (col = 0; col < ncols; col++) { if (!Rast_is_null_value(rast_ptr, map_type)) break; rast_ptr = G_incr_void_ptr(rast_ptr, Rast_cell_size(map_type)); } if (col == ncols) continue; if (row < top) top = row; if (row > bottom) bottom = row; if (col < left) left = col; for (mark = col; col < ncols; col++) { if (!Rast_is_null_value(rast_ptr, map_type)) mark = col; rast_ptr = G_incr_void_ptr(rast_ptr, Rast_cell_size(map_type)); } if (mark > right) right = mark; } Rast_close(fd); G_free(raster); /* no data everywhere? */ if (bottom < 0) return 0; north = window->north - top * window->ns_res; south = window->north - (bottom + 1) * window->ns_res; west = window->west + left * window->ew_res; east = window->west + (right + 1) * window->ew_res; window->north = north; window->south = south; window->east = east; window->west = west; return 1; }
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[]) { RASTER3D_Region region, inputmap_bounds; struct Cell_head region2d; struct GModule *module; struct History history; void *map = NULL; /*The 3D Rastermap */ int i = 0, changemask = 0; int *fd = NULL, output_type, cols, rows; char *RasterFileName; int overwrite = 0; /* Initialize GRASS */ G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("raster3d")); G_add_keyword(_("conversion")); G_add_keyword(_("raster")); G_add_keyword(_("voxel")); module->description = _("Converts 3D raster maps to 2D raster maps"); /* Get parameters from user */ set_params(); /* Have GRASS get inputs */ if (G_parser(argc, argv)) exit(EXIT_FAILURE); G_debug(3, "Open 3D raster map <%s>", param.input->answer); if (NULL == G_find_raster3d(param.input->answer, "")) Rast3d_fatal_error(_("3D raster map <%s> not found"), param.input->answer); /*Set the defaults */ Rast3d_init_defaults(); /*Set the resolution of the output maps */ if (param.res->answer) { /*Open the map with current region */ map = Rast3d_open_cell_old(param.input->answer, G_find_raster3d(param.input->answer, ""), RASTER3D_DEFAULT_WINDOW, RASTER3D_TILE_SAME_AS_FILE, RASTER3D_USE_CACHE_DEFAULT); if (map == NULL) Rast3d_fatal_error(_("Unable to open 3D raster map <%s>"), param.input->answer); /*Get the region of the map */ Rast3d_get_region_struct_map(map, ®ion); /*set this region as current 3D window for map */ Rast3d_set_window_map(map, ®ion); /*Set the 2d region appropriate */ Rast3d_extract2d_region(®ion, ®ion2d); /*Make the new 2d region the default */ Rast_set_window(®ion2d); } else { /* Figure out the region from the map */ Rast3d_get_window(®ion); /*Open the 3d raster map */ map = Rast3d_open_cell_old(param.input->answer, G_find_raster3d(param.input->answer, ""), ®ion, RASTER3D_TILE_SAME_AS_FILE, RASTER3D_USE_CACHE_DEFAULT); if (map == NULL) Rast3d_fatal_error(_("Unable to open 3D raster map <%s>"), param.input->answer); } /*Check if the g3d-region is equal to the 2D rows and cols */ rows = Rast_window_rows(); cols = Rast_window_cols(); /*If not equal, set the 3D window correct */ if (rows != region.rows || cols != region.cols) { G_message(_("The 2D and 3D region settings are different. " "Using the 2D window settings to adjust the 2D part of the 3D region.")); G_get_set_window(®ion2d); region.ns_res = region2d.ns_res; region.ew_res = region2d.ew_res; region.rows = region2d.rows; region.cols = region2d.cols; Rast3d_adjust_region(®ion); Rast3d_set_window_map(map, ®ion); } /* save the input map region for later use (history meta-data) */ Rast3d_get_region_struct_map(map, &inputmap_bounds); /*Get the output type */ output_type = Rast3d_file_type_map(map); /*prepare the filehandler */ fd = (int *) G_malloc(region.depths * sizeof (int)); if (fd == NULL) fatal_error(map, NULL, 0, _("Out of memory")); G_message(_("Creating %i raster maps"), region.depths); /*Loop over all output maps! open */ for (i = 0; i < region.depths; i++) { /*Create the outputmaps */ G_asprintf(&RasterFileName, "%s_%05d", param.output->answer, i + 1); G_message(_("Raster map %i Filename: %s"), i + 1, RasterFileName); overwrite = G_check_overwrite(argc, argv); if (G_find_raster2(RasterFileName, "") && !overwrite) G_fatal_error(_("Raster map %d Filename: %s already exists. Use the flag --o to overwrite."), i + 1, RasterFileName); if (output_type == FCELL_TYPE) fd[i] = open_output_map(RasterFileName, FCELL_TYPE); else if (output_type == DCELL_TYPE) fd[i] = open_output_map(RasterFileName, DCELL_TYPE); } /*if requested set the Mask on */ if (param.mask->answer) { if (Rast3d_mask_file_exists()) { changemask = 0; if (Rast3d_mask_is_off(map)) { Rast3d_mask_on(map); changemask = 1; } } } /*Create the Rastermaps */ g3d_to_raster(map, region, fd); /*Loop over all output maps! close */ for (i = 0; i < region.depths; i++) { close_output_map(fd[i]); /* write history */ G_asprintf(&RasterFileName, "%s_%i", param.output->answer, i + 1); G_debug(4, "Raster map %d Filename: %s", i + 1, RasterFileName); Rast_short_history(RasterFileName, "raster", &history); Rast_set_history(&history, HIST_DATSRC_1, "3D Raster map:"); Rast_set_history(&history, HIST_DATSRC_2, param.input->answer); Rast_append_format_history(&history, "Level %d of %d", i + 1, region.depths); Rast_append_format_history(&history, "Level z-range: %f to %f", region.bottom + (i * region.tb_res), region.bottom + (i + 1 * region.tb_res)); Rast_append_format_history(&history, "Input map full z-range: %f to %f", inputmap_bounds.bottom, inputmap_bounds.top); Rast_append_format_history(&history, "Input map z-resolution: %f", inputmap_bounds.tb_res); if (!param.res->answer) { Rast_append_format_history(&history, "GIS region full z-range: %f to %f", region.bottom, region.top); Rast_append_format_history(&history, "GIS region z-resolution: %f", region.tb_res); } Rast_command_history(&history); Rast_write_history(RasterFileName, &history); } /*We set the Mask off, if it was off before */ if (param.mask->answer) { if (Rast3d_mask_file_exists()) if (Rast3d_mask_is_on(map) && changemask) Rast3d_mask_off(map); } /*Cleaning */ if (RasterFileName) G_free(RasterFileName); if (fd) G_free(fd); /* Close files and exit */ if (!Rast3d_close(map)) fatal_error(map, NULL, 0, _("Unable to close 3D raster map")); map = NULL; return (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); }
int main(int argc, char *argv[]) { int partfd; int nrows, ncols; const char *drain_name; const char *ridge_name; const char *part_name; CELL *drain, *ridge; struct Cell_head window; int row, col, npass, tpass; struct GModule *module; struct Option *num_opt, *drain_opt, *ridge_opt, *part_opt; G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("raster")); G_add_keyword(_("hydrology")); G_add_keyword(_("watershed")); module->description = _("Generates watershed subbasins raster map."); drain_opt = G_define_standard_option(G_OPT_R_INPUT); drain_opt->key = "cnetwork"; drain_opt->description = _("Name of input coded stream network raster map"); ridge_opt = G_define_standard_option(G_OPT_R_INPUT); ridge_opt->key = "tnetwork"; ridge_opt->description = _("Name of input thinned ridge network raster map"); part_opt = G_define_standard_option(G_OPT_R_OUTPUT); num_opt = G_define_option(); num_opt->key = "number"; num_opt->type = TYPE_INTEGER; num_opt->required = YES; num_opt->description = _("Number of passes through the dataset"); if (G_parser(argc, argv)) exit(EXIT_FAILURE); sscanf(num_opt->answer, "%d", &tpass); drain_name = drain_opt->answer; /* this isn't a nice thing to do. Rast_align_window() should be used first */ Rast_get_cellhd(drain_name, "", &window); Rast_set_window(&window); nrows = Rast_window_rows(); ncols = Rast_window_cols(); ridge_name = ridge_opt->answer; part_name = part_opt->answer; drain = read_map(drain_name, NOMASK, nrows, ncols); ridge = read_map(ridge_name, NOMASK, nrows, ncols); partfd = Rast_open_c_new(part_name); /* run through file and set streams to zero at locations where ridges exist */ for (row = 0; row < nrows; row++) { for (col = 0; col < ncols; col++) if (ridge[row * ncols + col] != 0) drain[row * ncols + col] = 0; } for (npass = 1; npass <= tpass; npass++) { for (row = 1; row < nrows - 1; row++) { for (col = 1; col < ncols - 1; col++) { if (drain[row * ncols + col] == 0 && ridge[row * ncols + col] == 0) { if (drain[(row - 1) * ncols + col] != 0 && ridge[(row - 1) * ncols + col] == 0) drain[row * ncols + col] = drain[(row - 1) * ncols + col]; if (drain[row * ncols + (col - 1)] != 0 && ridge[row * ncols + (col - 1)] == 0) drain[row * ncols + col] = drain[row * ncols + (col - 1)]; } } } G_message(_("Forward sweep complete")); for (row = nrows - 3; row > 1; --row) { for (col = ncols - 3; col > 1; --col) { if (drain[row * ncols + col] == 0 && ridge[row * ncols + col] == 0) { if (drain[(row + 1) * ncols + col] != 0 && ridge[(row + 1) * ncols + col] == 0) drain[row * ncols + col] = drain[(row + 1) * ncols + col]; if (drain[row * ncols + (col + 1)] != 0 && ridge[row * ncols + (col + 1)] == 0) drain[row * ncols + col] = drain[row * ncols + (col + 1)]; } } } G_message(_("Reverse sweep complete")); } /* write out partitioned watershed map */ for (row = 0; row < nrows; row++) Rast_put_row(partfd, drain + (row * ncols), CELL_TYPE); G_message(_("Creating support files for <%s>..."), part_name); Rast_close(partfd); exit(EXIT_SUCCESS); }
int main(int argc, char *argv[]) { char *input; char *output; char *title; char *temp; FILE *fd, *ft; int cf, direction, sz; struct Cell_head cellhd; struct History history; void *rast, *rast_ptr; int row, col; int nrows, ncols; double x; char y[128]; struct GModule *module; struct { struct Option *input, *output, *title, *mult, *nv, *type; } parm; struct { struct Flag *s; } flag; char *null_val_str; DCELL mult; RASTER_MAP_TYPE data_type; double atof(); G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("raster")); G_add_keyword(_("import")); G_add_keyword(_("conversion")); G_add_keyword("ASCII"); module->description = _("Converts a GRASS ASCII raster file to binary raster map."); parm.input = G_define_standard_option(G_OPT_F_INPUT); parm.input->label = _("Name of input file to be imported"); parm.input->description = _("'-' for standard input"); parm.output = G_define_standard_option(G_OPT_R_OUTPUT); parm.type = G_define_option(); parm.type->key = "type"; parm.type->type = TYPE_STRING; parm.type->required = NO; parm.type->options = "CELL,FCELL,DCELL"; parm.type->label = _("Storage type for resultant raster map"); parm.type->description = _("Default: CELL for integer values, DCELL for floating-point values"); 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 for resultant raster map"); parm.mult = G_define_option(); parm.mult->key = "multiplier"; parm.mult->type = TYPE_DOUBLE; parm.mult->description = _("Default: read from header"); parm.mult->required = NO; parm.mult->label = _("Multiplier for ASCII data"); parm.nv = G_define_standard_option(G_OPT_M_NULL_VALUE); parm.nv->description = _("Default: read from header"); parm.nv->label = _("String representing NULL value data cell"); parm.nv->guisection = _("NULL data"); flag.s = G_define_flag(); flag.s->key = 's'; flag.s->description = _("SURFER (Golden Software) ASCII file will be imported"); if (G_parser(argc, argv)) exit(EXIT_FAILURE); input = parm.input->answer; output = parm.output->answer; temp = G_tempfile(); ft = fopen(temp, "w+"); if (ft == NULL) G_fatal_error(_("Unable to open temporary file <%s>"), temp); if ((title = parm.title->answer)) G_strip(title); if (!parm.mult->answer) Rast_set_d_null_value(&mult, 1); else if ((sscanf(parm.mult->answer, "%lf", &mult)) != 1) G_fatal_error(_("Wrong entry for multiplier: %s"), parm.mult->answer); null_val_str = parm.nv->answer; data_type = -1; if (parm.type->answer) { switch(parm.type->answer[0]) { case 'C': data_type = CELL_TYPE; break; case 'F': data_type = FCELL_TYPE; break; case 'D': data_type = DCELL_TYPE; break; } } if (strcmp(input, "-") == 0) { Tmp_file = G_tempfile(); if (NULL == (Tmp_fd = fopen(Tmp_file, "w+"))) G_fatal_error(_("Unable to open temporary file <%s>"), Tmp_file); unlink(Tmp_file); if (0 > file_cpy(stdin, Tmp_fd)) G_fatal_error(_("Unable to read input from stdin")); fd = Tmp_fd; } else fd = fopen(input, "r"); if (fd == NULL) { G_fatal_error(_("Unable to read input from <%s>"), input); } direction = 1; sz = 0; if (flag.s->answer) { sz = getgrdhead(fd, &cellhd); /* for Surfer files, the data type is always FCELL_TYPE, the multiplier and the null_val_str are never used */ data_type = FCELL_TYPE; mult = 1.; null_val_str = ""; /* rows in surfer files are ordered from bottom to top, opposite of normal GRASS ordering */ direction = -1; } else sz = gethead(fd, &cellhd, &data_type, &mult, &null_val_str); if (!sz) G_fatal_error(_("Can't get cell header")); nrows = cellhd.rows; ncols = cellhd.cols; Rast_set_window(&cellhd); if (nrows != Rast_window_rows()) G_fatal_error(_("OOPS: rows changed from %d to %d"), nrows, Rast_window_rows()); if (ncols != Rast_window_cols()) G_fatal_error(_("OOPS: cols changed from %d to %d"), ncols, Rast_window_cols()); rast_ptr = Rast_allocate_buf(data_type); rast = rast_ptr; cf = Rast_open_new(output, data_type); for (row = 0; row < nrows; row++) { G_percent(row, nrows, 2); for (col = 0; col < ncols; col++) { if (fscanf(fd, "%s", y) != 1) { Rast_unopen(cf); G_fatal_error(_("Data conversion failed at row %d, col %d"), row + 1, col + 1); } if (strcmp(y, null_val_str)) { x = atof(y); if ((float)x == GS_BLANK) { Rast_set_null_value(rast_ptr, 1, data_type); } else { Rast_set_d_value(rast_ptr, (DCELL) (x * mult), data_type); } } else { Rast_set_null_value(rast_ptr, 1, data_type); } rast_ptr = G_incr_void_ptr(rast_ptr, Rast_cell_size(data_type)); } fwrite(rast, Rast_cell_size(data_type), ncols, ft); rast_ptr = rast; } G_percent(nrows, nrows, 2); G_debug(1, "Creating support files for %s", output); sz = 0; if (direction < 0) { sz = -ncols * Rast_cell_size(data_type); G_fseek(ft, sz, SEEK_END); sz *= 2; } else { G_fseek(ft, 0L, SEEK_SET); } for (row = 0; row < nrows; row += 1) { fread(rast, Rast_cell_size(data_type), ncols, ft); Rast_put_row(cf, rast, data_type); G_fseek(ft, sz, SEEK_CUR); } fclose(ft); unlink(temp); Rast_close(cf); if (title) Rast_put_cell_title(output, title); Rast_short_history(output, "raster", &history); Rast_command_history(&history); Rast_write_history(output, &history); G_done_msg(" "); exit(EXIT_SUCCESS); }
static void read_png(void) { unsigned char sig_buf[8]; png_bytep png_buffer; png_bytep *png_rows; int linesize; struct Cell_head cellhd; unsigned int y, c; png_color_8p sig_bit; int sbit, interlace; FILE *ifp; /* initialize input stream and PNG library */ ifp = fopen(input, "rb"); if (!ifp) G_fatal_error(_("Unable to open PNG file '%s'"), input); if (fread(sig_buf, sizeof(sig_buf), 1, ifp) != 1) G_fatal_error(_("Input file empty or too short")); if (png_sig_cmp(sig_buf, 0, sizeof(sig_buf)) != 0) G_fatal_error(_("Input file not a PNG file")); png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); if (!png_ptr) G_fatal_error(_("Unable to allocate PNG structure")); info_ptr = png_create_info_struct(png_ptr); if (!info_ptr) G_fatal_error(_("Unable to allocate PNG structure")); if (setjmp(png_jmpbuf(png_ptr))) G_fatal_error(_("PNG error")); png_init_io(png_ptr, ifp); png_set_sig_bytes(png_ptr, sizeof(sig_buf)); png_read_info(png_ptr, info_ptr); png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, &interlace_type, &compression_type, &filter_type); if (Header || G_verbose() == G_verbose_max()) print_header(); if (Header) { fclose(ifp); exit(0); } /* read image parameters and set up data conversions */ if (png_get_bit_depth(png_ptr, info_ptr) < 8) png_set_packing(png_ptr); sbit = png_get_sBIT(png_ptr, info_ptr, &sig_bit); if (sbit) png_set_shift(png_ptr, sig_bit); if (!png_get_gAMA(png_ptr, info_ptr, &f_gamma)) f_gamma = 0.0; if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) png_set_tRNS_to_alpha(png_ptr); if (Float && color_type == PNG_COLOR_TYPE_PALETTE) png_set_palette_to_rgb(png_ptr); png_read_update_info(png_ptr, info_ptr); interlace = (interlace_type != PNG_INTERLACE_NONE); ialpha = (int) (alpha * channels[C_A].maxval); t_gamma = (f_gamma != 0.0 && d_gamma != 0.0) ? f_gamma * d_gamma : 1.0; /* allocate input buffer */ linesize = png_get_rowbytes(png_ptr, info_ptr); png_buffer = G_malloc(interlace ? height * linesize : linesize); if (interlace) { png_rows = G_malloc(height * sizeof(png_bytep)); for (y = 0; y < height; y++) png_rows[y] = png_buffer + y * linesize; } /* initialize cell header */ Rast_get_window(&cellhd); cellhd.rows = height; cellhd.cols = width; cellhd.north = cellhd.rows; cellhd.south = 0.0; cellhd.east = cellhd.cols; cellhd.west = 0.0; cellhd.ns_res = 1; cellhd.ew_res = 1; Rast_set_window(&cellhd); /* initialize channel information */ switch (color_type) { case PNG_COLOR_TYPE_GRAY: init_channel(&channels[C_Y]); break; case PNG_COLOR_TYPE_GRAY_ALPHA: init_channel(&channels[C_Y]); init_channel(&channels[C_A]); break; case PNG_COLOR_TYPE_PALETTE: init_channel(&channels[C_P]); break; case PNG_COLOR_TYPE_RGB: init_channel(&channels[C_R]); init_channel(&channels[C_G]); init_channel(&channels[C_B]); break; case PNG_COLOR_TYPE_RGB_ALPHA: init_channel(&channels[C_R]); init_channel(&channels[C_G]); init_channel(&channels[C_B]); init_channel(&channels[C_A]); break; } if (sbit) { channels[C_R].maxval = (1 << sig_bit->red ) - 1; channels[C_G].maxval = (1 << sig_bit->green) - 1; channels[C_B].maxval = (1 << sig_bit->blue ) - 1; channels[C_Y].maxval = (1 << sig_bit->gray ) - 1; channels[C_A].maxval = (1 << sig_bit->alpha) - 1; } else { channels[C_R].maxval = (1 << bit_depth) - 1; channels[C_G].maxval = (1 << bit_depth) - 1; channels[C_B].maxval = (1 << bit_depth) - 1; channels[C_Y].maxval = (1 << bit_depth) - 1; channels[C_A].maxval = (1 << bit_depth) - 1; } /* read image and write raster layers */ if (interlace) png_read_image(png_ptr, png_rows); for (y = 0; y < height; y++) { png_bytep p; if (interlace) p = png_rows[y]; else { png_read_row(png_ptr, png_buffer, NULL); p = png_buffer; } if (Float) write_row_float(p); else write_row_int(p); } png_read_end(png_ptr, NULL); fclose(ifp); /* close output files */ for (c = 0; c < 6; c++) { channel *ch = &channels[c]; if (!ch->active) continue; Rast_close(ch->fd); if (Float) G_free(ch->fbuf); else G_free(ch->buf); } /* write title and color table */ G_verbose_message(_("Creating support files for <%s>..."), output); for (c = 0; c < 6; c++) { channel *ch = &channels[c]; if (!ch->active) continue; if (title && *title) Rast_put_cell_title(ch->name, title); if (Float) write_colors_float(c); else write_colors_int(c); } G_free(png_buffer); if (interlace) G_free(png_rows); png_destroy_read_struct(&png_ptr, &info_ptr, NULL); }
int main(int argc, char *argv[]) { char rname[GNAME_MAX]; /* Reclassed map name */ char rmapset[GMAPSET_MAX]; /* Reclassed mapset */ const char *mapset; /* Raster mapset */ struct Cell_head cellhd; struct GModule *module; struct Option *raster, *title_opt, *history_opt; struct Option *datasrc1_opt, *datasrc2_opt, *datadesc_opt; struct Option *map_opt, *units_opt, *vdatum_opt; struct Option *load_opt, *save_opt; struct Flag *stats_flag, *null_flag, *del_flag; int is_reclass; /* Is raster reclass? */ const char *infile; char title[MAX_TITLE_LEN + 1]; struct History hist; /* Initialize GIS engine */ G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("raster")); G_add_keyword(_("metadata")); module->description = _("Allows creation and/or modification of " "raster map layer support files."); raster = G_define_standard_option(G_OPT_R_MAP); title_opt = G_define_option(); title_opt->key = "title"; title_opt->key_desc = "phrase"; title_opt->type = TYPE_STRING; title_opt->required = NO; title_opt->description = _("Title for resultant raster map"); history_opt = G_define_option(); history_opt->key = "history"; history_opt->key_desc = "phrase"; history_opt->type = TYPE_STRING; history_opt->required = NO; history_opt->description = _("Text to append to the next line of the map's metadata file"); units_opt = G_define_option(); units_opt->key = "units"; units_opt->type = TYPE_STRING; units_opt->required = NO; units_opt->description = _("Text to use for map data units"); vdatum_opt = G_define_option(); vdatum_opt->key = "vdatum"; vdatum_opt->type = TYPE_STRING; vdatum_opt->required = NO; vdatum_opt->description = _("Text to use for map vertical datum"); datasrc1_opt = G_define_option(); datasrc1_opt->key = "source1"; datasrc1_opt->key_desc = "phrase"; datasrc1_opt->type = TYPE_STRING; datasrc1_opt->required = NO; datasrc1_opt->description = _("Text to use for data source, line 1"); datasrc2_opt = G_define_option(); datasrc2_opt->key = "source2"; datasrc2_opt->key_desc = "phrase"; datasrc2_opt->type = TYPE_STRING; datasrc2_opt->required = NO; datasrc2_opt->description = _("Text to use for data source, line 2"); datadesc_opt = G_define_option(); datadesc_opt->key = "description"; datadesc_opt->key_desc = "phrase"; datadesc_opt->type = TYPE_STRING; datadesc_opt->required = NO; datadesc_opt->description = _("Text to use for data description or keyword(s)"); map_opt = G_define_option(); map_opt->key = "raster"; map_opt->type = TYPE_STRING; map_opt->required = NO; map_opt->gisprompt = "old,cell,raster"; map_opt->description = _("Raster map from which to copy category table"); load_opt = G_define_standard_option(G_OPT_F_INPUT); load_opt->key = "loadhistory"; load_opt->required = NO; load_opt->description = _("Text file from which to load history"); save_opt = G_define_standard_option(G_OPT_F_OUTPUT); save_opt->key = "savehistory"; save_opt->required = NO; save_opt->description = _("Text file in which to save history"); stats_flag = G_define_flag(); stats_flag->key = 's'; stats_flag->description = _("Update statistics (histogram, range)"); null_flag = G_define_flag(); null_flag->key = 'n'; null_flag->description = _("Create/reset the null file"); del_flag = G_define_flag(); del_flag->key = 'd'; del_flag->description = _("Delete the null file"); /* Parse command-line options */ if (G_parser(argc, argv)) exit(EXIT_FAILURE); /* Make sure raster exists and set mapset */ infile = raster->answer; mapset = G_find_raster2(infile, G_mapset()); /* current mapset only for editing */ if (!mapset || strcmp(mapset, G_mapset()) != 0) G_fatal_error(_("Raster map <%s> not found in current mapset"), infile); Rast_get_cellhd(raster->answer, "", &cellhd); is_reclass = (Rast_is_reclass(raster->answer, "", rname, rmapset) > 0); if (title_opt->answer) { strncpy(title, title_opt->answer, MAX_TITLE_LEN); title[MAX_TITLE_LEN - 1] = '\0'; /* strncpy doesn't null terminate oversized input */ G_strip(title); G_debug(3, "map title= [%s] (%li chars)", title, strlen(title)); Rast_read_history(raster->answer, "", &hist); Rast_set_history(&hist, HIST_TITLE, title); Rast_write_history(raster->answer, &hist); } if (save_opt->answer) { FILE *fp = fopen(save_opt->answer, "w"); int i; if (!fp) G_fatal_error(_("Unable to open output file <%s>"), save_opt->answer); Rast_read_history(raster->answer, "", &hist); for (i = 0; i < Rast_history_length(&hist); i++) fprintf(fp, "%s\n", Rast_history_line(&hist, i)); fclose(fp); } if (load_opt->answer) { FILE *fp = fopen(load_opt->answer, "r"); if (!fp) G_fatal_error(_("Unable to open input file <%s>"), load_opt->answer); Rast_read_history(raster->answer, "", &hist); Rast_clear_history(&hist); for (;;) { char buf[80]; if (!G_getl2(buf, sizeof(buf), fp)) break; Rast_append_history(&hist, buf); } fclose(fp); Rast_write_history(raster->answer, &hist); } if (history_opt->answer) { Rast_read_history(raster->answer, "", &hist); /* two less than defined as if only one less a newline gets appended in the hist file. bug? */ /* Should be RECORD_LEN, but r.info truncates at > 71 chars */ if (strlen(history_opt->answer) > 71) { int i; for (i = 0; i < strlen(history_opt->answer); i += 71) { char buf[72]; strncpy(buf, &history_opt->answer[i], sizeof(buf)-1); buf[sizeof(buf)-1] = '\0'; Rast_append_history(&hist, buf); } } else Rast_append_history(&hist, history_opt->answer); Rast_write_history(raster->answer, &hist); } if (units_opt->answer) Rast_write_units(raster->answer, units_opt->answer); if (vdatum_opt->answer) Rast_write_vdatum(raster->answer, vdatum_opt->answer); if (datasrc1_opt->answer || datasrc2_opt->answer || datadesc_opt->answer) { Rast_read_history(raster->answer, "", &hist); if (datasrc1_opt->answer) Rast_set_history(&hist, HIST_DATSRC_1, datasrc1_opt->answer); if (datasrc2_opt->answer) Rast_set_history(&hist, HIST_DATSRC_2, datasrc2_opt->answer); if (datadesc_opt->answer) Rast_set_history(&hist, HIST_KEYWRD, datadesc_opt->answer); Rast_write_history(raster->answer, &hist); } if (map_opt->answer) { /* use cats from another map */ int fd; struct Categories cats; fd = Rast_open_old(infile, ""); Rast_init_cats("", &cats); if (Rast_read_cats(map_opt->answer, "", &cats) < 0) G_fatal_error(_("Unable to read category file of raster map <%s>"), map_opt->answer); Rast_write_cats(infile, &cats); G_message(_("cats table for [%s] set to %s"), infile, map_opt->answer); Rast_close(fd); Rast_free_cats(&cats); } if (title_opt->answer || history_opt->answer || units_opt->answer || vdatum_opt->answer || datasrc1_opt->answer || datasrc2_opt->answer || datadesc_opt->answer || map_opt->answer) exit(EXIT_SUCCESS); /* Check the histogram and range */ if (stats_flag->answer) check_stats(raster->answer); /* null file */ if (null_flag->answer) { unsigned char *null_bits; int row, col; int fd; if (is_reclass) G_fatal_error(_("[%s] is a reclass of another map. Exiting."), raster->answer); /* Create a file of no-nulls */ null_bits = Rast__allocate_null_bits(cellhd.cols); for (col = 0; col < Rast__null_bitstream_size(cellhd.cols); col++) null_bits[col] = 0; /* Open null file for writing */ Rast_set_window(&cellhd); fd = Rast__open_null_write(raster->answer); G_message(_("Writing new null file for [%s]... "), raster->answer); for (row = 0; row < cellhd.rows; row++) { G_percent(row, cellhd.rows, 1); Rast__write_null_bits(fd, null_bits); } G_percent(row, cellhd.rows, 1); /* Cleanup */ Rast__close_null(fd); G_free(null_bits); } if (del_flag->answer) { char path[GPATH_MAX]; if (is_reclass) G_fatal_error(_("[%s] is a reclass of another map. Exiting."), raster->answer); /* Write a file of no-nulls */ G_message(_("Removing null file for [%s]...\n"), raster->answer); G_file_name_misc(path, "cell_misc", "null", raster->answer, G_mapset()); unlink(path); G_file_name_misc(path, "cell_misc", "null2", raster->answer, G_mapset()); unlink(path); G_done_msg(_("Done.")); } return EXIT_SUCCESS; }
/*! * \brief Initiate a pde geometry data structure with a 2d region * * If the projection is not planimetric, a double array will be created based on the * number of rows of the provided region storing all computed areas for each row * * \param region sruct Cell_head * * \param geodata N_geom_data * - if a NULL pointer is given, a new structure will be allocatet and returned * * \return N_geom_data * * */ N_geom_data *N_init_geom_data_2d(struct Cell_head * region, N_geom_data * geodata) { N_geom_data *geom = geodata; struct Cell_head backup; double meters; short ll = 0; int i; /*create an openmp lock to assure that only one thread at a time will access this function */ #pragma omp critical { G_debug(2, "N_init_geom_data_2d: initializing the geometry structure"); /*make a backup from this region */ G_get_set_window(&backup); /*this function is not thread safe */ /*set the current region */ Rast_set_window(region); /*this function is not thread safe */ if (geom == NULL) geom = N_alloc_geom_data(); meters = G_database_units_to_meters_factor(); /*this function is not thread safe */ /*set the dim to 2d if it was not initiated with 3, that's a bit ugly :( */ if (geom->dim != 3) geom->dim = 2; geom->planimetric = 1; geom->rows = region->rows; geom->cols = region->cols; geom->dx = region->ew_res * meters; geom->dy = region->ns_res * meters; geom->Az = geom->dy * geom->dx; /*square meters in planimetric proj */ /*depths and dz are initialized with a 3d region */ /*Begin the area calculation */ ll = G_begin_cell_area_calculations(); /*this function is not thread safe */ /*if the projection is not planimetric, calc the area for each row */ if (ll == 2) { G_debug(2, "N_init_geom_data_2d: calculating the areas for non parametric projection"); geom->planimetric = 0; if (geom->area != NULL) G_free(geom->area); else geom->area = G_calloc(geom->rows, sizeof(double)); /*fill the area vector */ for (i = 0; i < geom->rows; i++) { geom->area[i] = G_area_of_cell_at_row(i); /*square meters */ } } /*restore the old region */ Rast_set_window(&backup); /*this function is not thread safe */ } return geom; }
/* ************************************************************************* */ int main(int argc, char *argv[]) { RASTER3D_Region region; struct Cell_head window2d; struct GModule *module; void *map = NULL; /*The 3D Rastermap */ int changemask = 0; int elevfd = -1, outfd = -1; /*file descriptors */ int output_type, cols, rows; /* Initialize GRASS */ G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("raster3d")); G_add_keyword(_("profile")); G_add_keyword(_("raster")); G_add_keyword(_("voxel")); module->description = _("Creates cross section 2D raster map from 3D raster map based on 2D elevation map"); /* Get parameters from user */ set_params(); /* Have GRASS get inputs */ if (G_parser(argc, argv)) exit(EXIT_FAILURE); G_debug(3, "Open 3D raster map %s", param.input->answer); if (NULL == G_find_raster3d(param.input->answer, "")) Rast3d_fatal_error(_("3D raster map <%s> not found"), param.input->answer); /* Figure out the region from the map */ Rast3d_init_defaults(); Rast3d_get_window(®ion); /*Check if the g3d-region is equal to the 2d rows and cols */ rows = Rast_window_rows(); cols = Rast_window_cols(); /*If not equal, set the 2D windows correct */ if (rows != region.rows || cols != region.cols) { G_message (_("The 2D and 3D region settings are different. Using the 3D raster map settings to adjust the 2D region.")); G_get_set_window(&window2d); window2d.ns_res = region.ns_res; window2d.ew_res = region.ew_res; window2d.rows = region.rows; window2d.cols = region.cols; Rast_set_window(&window2d); } /*******************/ /*Open the 3d raster map */ /*******************/ map = Rast3d_open_cell_old(param.input->answer, G_find_raster3d(param.input->answer, ""), ®ion, RASTER3D_TILE_SAME_AS_FILE, RASTER3D_USE_CACHE_DEFAULT); if (map == NULL) Rast3d_fatal_error(_("Unable to open 3D raster map <%s>"), param.input->answer); /*Get the output type */ output_type = Rast3d_file_type_map(map); if (output_type == FCELL_TYPE || output_type == DCELL_TYPE) { /********************************/ /*Open the elevation raster map */ /********************************/ elevfd = Rast_open_old(param.elevation->answer, ""); globalElevMapType = Rast_get_map_type(elevfd); /**********************/ /*Open the Outputmap */ /**********************/ if (G_find_raster2(param.output->answer, "")) G_message(_("Output map already exists. Will be overwritten!")); if (output_type == FCELL_TYPE) outfd = Rast_open_new(param.output->answer, FCELL_TYPE); else if (output_type == DCELL_TYPE) outfd = Rast_open_new(param.output->answer, DCELL_TYPE); /*if requested set the Mask on */ if (param.mask->answer) { if (Rast3d_mask_file_exists()) { changemask = 0; if (Rast3d_mask_is_off(map)) { Rast3d_mask_on(map); changemask = 1; } } } /************************/ /*Create the Rastermaps */ /************************/ rast3d_cross_section(map, region, elevfd, outfd); /*We set the Mask off, if it was off before */ if (param.mask->answer) { if (Rast3d_mask_file_exists()) if (Rast3d_mask_is_on(map) && changemask) Rast3d_mask_off(map); } Rast_close(outfd); Rast_close(elevfd); } else { fatal_error(map, -1, -1, _("Wrong 3D raster datatype! Cannot create raster map")); } /* Close files and exit */ if (!Rast3d_close(map)) Rast3d_fatal_error(_("Unable to close 3D raster map <%s>"), param.input->answer); return (EXIT_SUCCESS); }
/* ************************************************************************* */ int main(int argc, char *argv[]) { char *output = NULL; RASTER3D_Region region; struct Cell_head window2d; struct Cell_head default_region; FILE *fp = NULL; struct GModule *module; int dp, i, changemask = 0; int rows, cols; const char *mapset, *name; double scale = 1.0, llscale = 1.0; input_maps *in; /* Initialize GRASS */ G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("raster3d")); G_add_keyword(_("export")); G_add_keyword(_("voxel")); G_add_keyword("VTK"); module->description = _("Converts 3D raster maps into the VTK-ASCII format."); /* Get parameters from user */ set_params(); /* Have GRASS get inputs */ if (G_parser(argc, argv)) exit(EXIT_FAILURE); /*The precision of the output */ if (param.decimals->answer) { if (sscanf(param.decimals->answer, "%d", &dp) != 1) G_fatal_error(_("failed to interpret dp as an integer")); if (dp > 20 || dp < 0) G_fatal_error(_("dp has to be from 0 to 20")); } else { dp = 8; /*This value is taken from the lib settings in G_format_easting */ } /*Check the input */ check_input_maps(); /*Correct the coordinates, so the precision of VTK is not hurt :( */ if (param.coorcorr->answer) { /*Get the default region for coordiante correction */ G_get_default_window(&default_region); /*Use the center of the current region as extent */ y_extent = (default_region.north + default_region.south) / 2; x_extent = (default_region.west + default_region.east) / 2; } else { x_extent = 0; y_extent = 0; } /*open the output */ if (param.output->answer) { fp = fopen(param.output->answer, "w"); if (fp == NULL) { perror(param.output->answer); G_usage(); exit(EXIT_FAILURE); } } else fp = stdout; /* Figure out the region from the map */ Rast3d_init_defaults(); Rast3d_get_window(®ion); /*initiate the input mpas structure */ in = create_input_maps_struct(); /* read and compute the scale factor */ sscanf(param.elevscale->answer, "%lf", &scale); /*if LL projection, convert the elevation values to degrees */ if (param.scalell->answer && region.proj == PROJECTION_LL) { llscale = M_PI / (180) * 6378137; scale /= llscale; } /*Open the top and bottom file */ if (param.structgrid->answer) { /*Check if the g3d-region is equal to the 2d rows and cols */ rows = Rast_window_rows(); cols = Rast_window_cols(); /*If not equal, set the 2D windows correct */ if (rows != region.rows || cols != region.cols) { G_message(_("The 2D and 3D region settings are different. " "Using the 2D window settings to adjust the 2D part of the 3D region.")); G_get_set_window(&window2d); window2d.ns_res = region.ns_res; window2d.ew_res = region.ew_res; window2d.rows = region.rows; window2d.cols = region.cols; Rast_set_window(&window2d); } /*open top */ mapset = NULL; name = NULL; name = param.top->answer; mapset = G_find_raster2(name, ""); in->top = open_input_map(name, mapset); in->topMapType = Rast_get_map_type(in->top); /*open bottom */ mapset = NULL; name = NULL; name = param.bottom->answer; mapset = G_find_raster2(name, ""); in->bottom = open_input_map(name, mapset); in->bottomMapType = Rast_get_map_type(in->bottom); /* Write the vtk-header and the points */ if (param.point->answer) { write_vtk_structured_grid_header(fp, output, region); write_vtk_points(in, fp, region, dp, 1, scale); } else { write_vtk_unstructured_grid_header(fp, output, region); write_vtk_points(in, fp, region, dp, 0, scale); write_vtk_unstructured_grid_cells(fp, region); } Rast_close(in->top); in->top = -1; Rast_close(in->bottom); in->bottom = -1; } else { /* Write the structured point vtk-header */ write_vtk_structured_point_header(fp, output, region, dp, scale); } /*Write the normal VTK data (cell or point data) */ /*Loop over all 3d input maps! */ if (param.input->answers != NULL) { for (i = 0; param.input->answers[i] != NULL; i++) { G_debug(3, "Open 3D raster map <%s>", param.input->answers[i]); /*Open the map */ in->map = Rast3d_open_cell_old(param.input->answers[i], G_find_raster3d(param.input->answers[i], ""), ®ion, RASTER3D_TILE_SAME_AS_FILE, RASTER3D_USE_CACHE_DEFAULT); if (in->map == NULL) { G_warning(_("Unable to open 3D raster map <%s>"), param.input->answers[i]); fatal_error(" ", in); } /*if requested set the Mask on */ if (param.mask->answer) { if (Rast3d_mask_file_exists()) { changemask = 0; if (Rast3d_mask_is_off(in->map)) { Rast3d_mask_on(in->map); changemask = 1; } } } /* Write the point or cell data */ write_vtk_data(fp, in->map, region, param.input->answers[i], dp); /*We set the Mask off, if it was off before */ if (param.mask->answer) { if (Rast3d_mask_file_exists()) if (Rast3d_mask_is_on(in->map) && changemask) Rast3d_mask_off(in->map); } /* Close the 3d raster map */ if (!Rast3d_close(in->map)) { in->map = NULL; fatal_error(_("Unable to close 3D raster map, the VTK file may be incomplete"), in); } in->map = NULL; } } /*Write the RGB voxel data */ open_write_rgb_maps(in, region, fp, dp); open_write_vector_maps(in, region, fp, dp); /*Close the output file */ if (param.output->answer && fp != NULL) if (fclose(fp)) fatal_error(_("Unable to close VTK-ASCII file"), in); /*close all open maps and free memory */ release_input_maps_struct(in); return 0; }
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[]) { 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) { struct Cell_head window; RASTER_MAP_TYPE raster_type, mag_raster_type = -1; int layer_fd; void *raster_row, *ptr; int nrows, ncols; int aspect_c = -1; float aspect_f = -1.0; double scale; int skip, no_arrow; char *mag_map = NULL; void *mag_raster_row = NULL, *mag_ptr = NULL; double length = -1; int mag_fd = -1; struct FPRange range; double mag_min, mag_max; struct GModule *module; struct Option *opt1, *opt2, *opt3, *opt4, *opt5, *opt6, *opt7, *opt8, *opt9; struct Flag *align; double t, b, l, r; G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("display")); G_add_keyword(_("raster")); module->description = _("Draws arrows representing cell aspect direction " "for a raster map containing aspect data."); opt1 = G_define_standard_option(G_OPT_R_MAP); opt1->description = _("Name of raster aspect map to be displayed"); opt2 = G_define_option(); opt2->key = "type"; opt2->type = TYPE_STRING; opt2->required = NO; opt2->answer = "grass"; opt2->options = "grass,compass,agnps,answers"; opt2->description = _("Type of existing raster aspect map"); opt3 = G_define_option(); opt3->key = "arrow_color"; opt3->type = TYPE_STRING; opt3->required = NO; opt3->answer = "green"; opt3->gisprompt = "old_color,color,color"; opt3->description = _("Color for drawing arrows"); opt3->guisection = _("Colors"); opt4 = G_define_option(); opt4->key = "grid_color"; opt4->type = TYPE_STRING; opt4->required = NO; opt4->answer = "gray"; opt4->gisprompt = "old_color,color,color_none"; opt4->description = _("Color for drawing grid or \"none\""); opt4->guisection = _("Colors"); opt5 = G_define_option(); opt5->key = "x_color"; opt5->type = TYPE_STRING; opt5->required = NO; opt5->answer = DEFAULT_FG_COLOR; opt5->gisprompt = "old_color,color,color_none"; opt5->description = _("Color for drawing X's (null values)"); opt5->guisection = _("Colors"); opt6 = G_define_option(); opt6->key = "unknown_color"; opt6->type = TYPE_STRING; opt6->required = NO; opt6->answer = "red"; opt6->gisprompt = "old_color,color,color_none"; opt6->description = _("Color for showing unknown information"); opt6->guisection = _("Colors"); opt9 = G_define_option(); opt9->key = "skip"; opt9->type = TYPE_INTEGER; opt9->required = NO; opt9->answer = "1"; opt9->description = _("Draw arrow every Nth grid cell"); opt7 = G_define_option(); opt7->key = "magnitude_map"; opt7->type = TYPE_STRING; opt7->required = NO; opt7->multiple = NO; opt7->gisprompt = "old,cell,raster"; opt7->description = _("Raster map containing values used for arrow length"); opt8 = G_define_option(); opt8->key = "scale"; opt8->type = TYPE_DOUBLE; opt8->required = NO; opt8->answer = "1.0"; opt8->description = _("Scale factor for arrows (magnitude map)"); align = G_define_flag(); align->key = 'a'; align->description = _("Align grids with raster cells"); /* Check command line */ if (G_parser(argc, argv)) exit(EXIT_FAILURE); layer_name = opt1->answer; arrow_color = D_translate_color(opt3->answer); x_color = D_translate_color(opt5->answer); unknown_color = D_translate_color(opt6->answer); if (strcmp("none", opt4->answer) == 0) grid_color = -1; else grid_color = D_translate_color(opt4->answer); if (strcmp("grass", opt2->answer) == 0) map_type = 1; else if (strcmp("agnps", opt2->answer) == 0) map_type = 2; else if (strcmp("answers", opt2->answer) == 0) map_type = 3; else if (strcmp("compass", opt2->answer) == 0) map_type = 4; scale = atof(opt8->answer); if (scale <= 0.0) G_fatal_error(_("Illegal value for scale factor")); skip = atoi(opt9->answer); if (skip <= 0) G_fatal_error(_("Illegal value for skip factor")); if (opt7->answer) { if (map_type != 1 && map_type != 4) G_fatal_error(_("Magnitude is only supported for GRASS and compass aspect maps.")); mag_map = opt7->answer; } else if (scale != 1.0) G_warning(_("Scale option requires magnitude_map")); /* Setup driver and check important information */ if (D_open_driver() != 0) G_fatal_error(_("No graphics device selected. " "Use d.mon to select graphics device.")); D_setup(0); /* Read in the map window associated with window */ G_get_window(&window); if (align->answer) { struct Cell_head wind; Rast_get_cellhd(layer_name, "", &wind); /* expand window extent by one wind resolution */ wind.west += wind.ew_res * ((int)((window.west - wind.west) / wind.ew_res) - (window.west < wind.west)); wind.east += wind.ew_res * ((int)((window.east - wind.east) / wind.ew_res) + (window.east > wind.east)); wind.south += wind.ns_res * ((int)((window.south - wind.south) / wind.ns_res) - (window.south < wind.south)); wind.north += wind.ns_res * ((int)((window.north - wind.north) / wind.ns_res) + (window.north > wind.north)); wind.rows = (wind.north - wind.south) / wind.ns_res; wind.cols = (wind.east - wind.west) / wind.ew_res; Rast_set_window(&wind); nrows = wind.rows; ncols = wind.cols; t = (wind.north - window.north) * nrows / (wind.north - wind.south); b = t + (window.north - window.south) * nrows / (wind.north - wind.south); l = (window.west - wind.west) * ncols / (wind.east - wind.west); r = l + (window.east - window.west) * ncols / (wind.east - wind.west); } else { nrows = window.rows; ncols = window.cols; t = 0; b = nrows; l = 0; r = ncols; } D_set_src(t, b, l, r); D_update_conversions(); /* figure out arrow scaling if using a magnitude map */ if (opt7->answer) { Rast_init_fp_range(&range); /* really needed? */ if (Rast_read_fp_range(mag_map, "", &range) != 1) G_fatal_error(_("Problem reading range file")); Rast_get_fp_range_min_max(&range, &mag_min, &mag_max); scale *= 1.5 / fabs(mag_max); G_debug(3, "scaling=%.2f rast_max=%.2f", scale, mag_max); } if (grid_color > 0) { /* ie not "none" */ /* Set color */ D_use_color(grid_color); /* Draw vertical grids */ for (col = 0; col < ncols; col++) D_line_abs(col, 0, col, nrows); /* Draw horizontal grids */ for (row = 0; row < nrows; row++) D_line_abs(0, row, ncols, row); } /* open the raster map */ layer_fd = Rast_open_old(layer_name, ""); raster_type = Rast_get_map_type(layer_fd); /* allocate the cell array */ raster_row = Rast_allocate_buf(raster_type); if (opt7->answer) { /* open the magnitude raster map */ mag_fd = Rast_open_old(mag_map, ""); mag_raster_type = Rast_get_map_type(mag_fd); /* allocate the cell array */ mag_raster_row = Rast_allocate_buf(mag_raster_type); } /* loop through cells, find value, determine direction (n,s,e,w,ne,se,sw,nw), and call appropriate function to draw an arrow on the cell */ for (row = 0; row < nrows; row++) { Rast_get_row(layer_fd, raster_row, row, raster_type); ptr = raster_row; if (opt7->answer) { Rast_get_row(mag_fd, mag_raster_row, row, mag_raster_type); mag_ptr = mag_raster_row; } for (col = 0; col < ncols; col++) { if (row % skip != 0) no_arrow = TRUE; else no_arrow = FALSE; if (col % skip != 0) no_arrow = TRUE; /* find aspect direction based on cell value */ if (raster_type == CELL_TYPE) aspect_f = *((CELL *) ptr); else if (raster_type == FCELL_TYPE) aspect_f = *((FCELL *) ptr); else if (raster_type == DCELL_TYPE) aspect_f = *((DCELL *) ptr); if (opt7->answer) { if (mag_raster_type == CELL_TYPE) length = *((CELL *) mag_ptr); else if (mag_raster_type == FCELL_TYPE) length = *((FCELL *) mag_ptr); else if (mag_raster_type == DCELL_TYPE) length = *((DCELL *) mag_ptr); length *= scale; if (Rast_is_null_value(mag_ptr, mag_raster_type)) { G_debug(5, "Invalid arrow length [NULL]. Skipping."); no_arrow = TRUE; } else if (length <= 0.0) { /* use fabs() or theta+=180? */ G_debug(5, "Illegal arrow length [%.3f]. Skipping.", length); no_arrow = TRUE; } } if (no_arrow) { ptr = G_incr_void_ptr(ptr, Rast_cell_size(raster_type)); if (opt7->answer) mag_ptr = G_incr_void_ptr(mag_ptr, Rast_cell_size(mag_raster_type)); no_arrow = FALSE; continue; } /* treat AGNPS and ANSWERS data like old zero-as-null CELL */ /* TODO: update models */ if (map_type == 2 || map_type == 3) { if (Rast_is_null_value(ptr, raster_type)) aspect_c = 0; else aspect_c = (int)(aspect_f + 0.5); } /** Now draw the arrows **/ /* case switch for standard GRASS aspect map measured in degrees counter-clockwise from east */ if (map_type == 1) { D_use_color(arrow_color); if (Rast_is_null_value(ptr, raster_type)) { D_use_color(x_color); draw_x(); D_use_color(arrow_color); } else if (aspect_f >= 0.0 && aspect_f <= 360.0) { if (opt7->answer) arrow_mag(aspect_f, length); else arrow_360(aspect_f); } else { D_use_color(unknown_color); unknown_(); D_use_color(arrow_color); } } /* case switch for AGNPS type aspect map */ else if (map_type == 2) { D_use_color(arrow_color); switch (aspect_c) { case 0: D_use_color(x_color); draw_x(); D_use_color(arrow_color); break; case 1: arrow_n(); break; case 2: arrow_ne(); break; case 3: arrow_e(); break; case 4: arrow_se(); break; case 5: arrow_s(); break; case 6: arrow_sw(); break; case 7: arrow_w(); break; case 8: arrow_nw(); break; default: D_use_color(unknown_color); unknown_(); D_use_color(arrow_color); break; } } /* case switch for ANSWERS type aspect map */ else if (map_type == 3) { D_use_color(arrow_color); if (aspect_c >= 15 && aspect_c <= 360) /* start at zero? */ arrow_360((double)aspect_c); else if (aspect_c == 400) { D_use_color(unknown_color); unknown_(); D_use_color(arrow_color); } else { D_use_color(x_color); draw_x(); D_use_color(arrow_color); } } /* case switch for compass type aspect map measured in degrees clockwise from north */ else if (map_type == 4) { D_use_color(arrow_color); if (Rast_is_null_value(ptr, raster_type)) { D_use_color(x_color); draw_x(); D_use_color(arrow_color); } else if (aspect_f >= 0.0 && aspect_f <= 360.0) { if (opt7->answer) arrow_mag(90 - aspect_f, length); else arrow_360(90 - aspect_f); } else { D_use_color(unknown_color); unknown_(); D_use_color(arrow_color); } } ptr = G_incr_void_ptr(ptr, Rast_cell_size(raster_type)); if (opt7->answer) mag_ptr = G_incr_void_ptr(mag_ptr, Rast_cell_size(mag_raster_type)); } } Rast_close(layer_fd); if (opt7->answer) Rast_close(mag_fd); D_save_command(G_recreate_command()); D_close_driver(); exit(EXIT_SUCCESS); }
int main(int argc, char *argv[]) { struct Options opts; struct ScaleRange iscale; /* input file's data is scaled to this interval */ struct ScaleRange oscale; /* output file's scale */ int iimg_fd; /* input image's file descriptor */ int oimg_fd; /* output image's file descriptor */ int ialt_fd = -1; /* input elevation map's file descriptor */ int ivis_fd = -1; /* input visibility map's file descriptor */ struct History hist; struct Cell_head orig_window; /* Define module */ define_module(); /* Define the different input options */ opts = define_options(); /**** Start ****/ G_gisinit(argv[0]); if (G_parser(argc, argv) < 0) exit(EXIT_FAILURE); G_get_set_window(&orig_window); adjust_region(opts.iimg->answer); /* open input raster */ if ((iimg_fd = Rast_open_old(opts.iimg->answer, "")) < 0) G_fatal_error(_("Unable to open raster map <%s>"), opts.iimg->answer); if (opts.ialt->answer) { if ((ialt_fd = Rast_open_old(opts.ialt->answer, "")) < 0) G_fatal_error(_("Unable to open raster map <%s>"), opts.ialt->answer); } if (opts.ivis->answer) { if ((ivis_fd = Rast_open_old(opts.ivis->answer, "")) < 0) G_fatal_error(_("Unable to open raster map <%s>"), opts.ivis->answer); } /* open a floating point raster or not? */ if (opts.oint->answer) { if ((oimg_fd = Rast_open_new(opts.oimg->answer, CELL_TYPE)) < 0) G_fatal_error(_("Unable to create raster map <%s>"), opts.oimg->answer); } else { if ((oimg_fd = Rast_open_fp_new(opts.oimg->answer)) < 0) G_fatal_error(_("Unable to create raster map <%s>"), opts.oimg->answer); } /* read the scale parameters */ read_scale(opts.iscl, iscale); read_scale(opts.oscl, oscale); /* initialize this 6s computation and parse the input conditions file */ init_6S(opts.icnd->answer); InputMask imask = RADIANCE; /* the input mask tells us what transformations if any needs to be done to make our input values, reflectance values scaled between 0 and 1 */ if (opts.irad->answer) imask = REFLECTANCE; if (opts.etmbefore->answer) imask = (InputMask) (imask | ETM_BEFORE); if (opts.etmafter->answer) imask = (InputMask) (imask | ETM_AFTER); /* process the input raster and produce our atmospheric corrected output raster. */ G_message(_("Atmospheric correction...")); process_raster(iimg_fd, imask, iscale, ialt_fd, ivis_fd, oimg_fd, opts.oint->answer, oscale); /* Close the input and output file descriptors */ Rast_short_history(opts.oimg->answer, "raster", &hist); Rast_close(iimg_fd); if (opts.ialt->answer) Rast_close(ialt_fd); if (opts.ivis->answer) Rast_close(ivis_fd); Rast_close(oimg_fd); Rast_command_history(&hist); Rast_write_history(opts.oimg->answer, &hist); /* Copy the colors of the input raster to the output raster. Scaling is ignored and color ranges might not be correct. */ copy_colors(opts.iimg->answer, opts.oimg->answer); Rast_set_window(&orig_window); G_message(_("Atmospheric correction complete.")); exit(EXIT_SUCCESS); }
int main(int argc, char *argv[]) { const char *input, *source, *output; char *title; struct Cell_head cellhd; GDALDatasetH hDS; GDALRasterBandH hBand; struct GModule *module; struct { struct Option *input, *source, *output, *band, *title; } parm; struct { struct Flag *o, *f, *e, *r, *h, *v; } flag; int min_band, max_band, band; struct band_info info; int flip; struct Ref reference; G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("raster")); G_add_keyword(_("import")); G_add_keyword(_("input")); G_add_keyword(_("external")); module->description = _("Links GDAL supported raster data as a pseudo GRASS raster map."); parm.input = G_define_standard_option(G_OPT_F_INPUT); parm.input->description = _("Name of raster file to be linked"); parm.input->required = NO; parm.input->guisection = _("Input"); parm.source = G_define_option(); parm.source->key = "source"; parm.source->description = _("Name of non-file GDAL data source"); parm.source->required = NO; parm.source->type = TYPE_STRING; parm.source->key_desc = "name"; parm.source->guisection = _("Input"); parm.output = G_define_standard_option(G_OPT_R_OUTPUT); parm.band = G_define_option(); parm.band->key = "band"; parm.band->type = TYPE_INTEGER; parm.band->required = NO; parm.band->description = _("Band to select (default: all)"); parm.band->guisection = _("Input"); 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 for resultant raster map"); parm.title->guisection = _("Metadata"); flag.f = G_define_flag(); flag.f->key = 'f'; flag.f->description = _("List supported formats and exit"); flag.f->guisection = _("Print"); flag.f->suppress_required = YES; flag.o = G_define_flag(); flag.o->key = 'o'; flag.o->description = _("Override projection (use location's projection)"); flag.e = G_define_flag(); flag.e->key = 'e'; flag.e->description = _("Extend location extents based on new dataset"); flag.r = G_define_flag(); flag.r->key = 'r'; flag.r->description = _("Require exact range"); flag.h = G_define_flag(); flag.h->key = 'h'; flag.h->description = _("Flip horizontally"); flag.v = G_define_flag(); flag.v->key = 'v'; flag.v->description = _("Flip vertically"); if (G_parser(argc, argv)) exit(EXIT_FAILURE); GDALAllRegister(); if (flag.f->answer) { list_formats(); exit(EXIT_SUCCESS); } input = parm.input->answer; source = parm.source->answer; output = parm.output->answer; flip = 0; if (flag.h->answer) flip |= FLIP_H; if (flag.v->answer) flip |= FLIP_V; if (parm.title->answer) { title = G_store(parm.title->answer); G_strip(title); } else title = NULL; if (!input && !source) G_fatal_error(_("One of options <%s> or <%s> must be given"), parm.input->key, parm.source->key); if (input && source) G_fatal_error(_("Option <%s> and <%s> are mutually exclusive"), parm.input->key, parm.source->key); if (input && !G_is_absolute_path(input)) { char path[GPATH_MAX]; getcwd(path, sizeof(path)); strcat(path, "/"); strcat(path, input); input = G_store(path); } if (!input) input = source; hDS = GDALOpen(input, GA_ReadOnly); if (hDS == NULL) return 1; setup_window(&cellhd, hDS, &flip); check_projection(&cellhd, hDS, flag.o->answer); Rast_set_window(&cellhd); if (parm.band->answer) min_band = max_band = atoi(parm.band->answer); else min_band = 1, max_band = GDALGetRasterCount(hDS); G_verbose_message(_("Proceeding with import...")); if (max_band > min_band) { if (I_find_group(output) == 1) G_warning(_("Imagery group <%s> already exists and will be overwritten."), output); I_init_group_ref(&reference); } for (band = min_band; band <= max_band; band++) { char *output2, *title2 = NULL; G_message(_("Reading band %d of %d..."), band, GDALGetRasterCount( hDS )); hBand = GDALGetRasterBand(hDS, band); if (!hBand) G_fatal_error(_("Selected band (%d) does not exist"), band); if (max_band > min_band) { G_asprintf(&output2, "%s.%d", output, band); if (title) G_asprintf(&title2, "%s (band %d)", title, band); G_debug(1, "Adding raster map <%s> to group <%s>", output2, output); I_add_file_to_group_ref(output2, G_mapset(), &reference); } else { output2 = G_store(output); if (title) title2 = G_store(title); } query_band(hBand, output2, flag.r->answer, &cellhd, &info); create_map(input, band, output2, &cellhd, &info, title, flip); G_free(output2); G_free(title2); } if (flag.e->answer) update_default_window(&cellhd); /* Create the imagery group if multiple bands are imported */ if (max_band > min_band) { I_put_group_ref(output, &reference); I_put_group(output); G_message(_("Imagery group <%s> created"), output); } exit(EXIT_SUCCESS); }
int main(int argc, char *argv[]) { struct History history; struct GModule *module; char *desc; struct Cell_head cellhd, orig_cellhd; void *inrast, *outrast; int infd, outfd; void *ptr; int nrows, ncols, row, col; RASTER_MAP_TYPE in_data_type; struct Option *input_prefix, *output_prefix, *metfn, *sensor, *adate, *pdate, *elev, *bgain, *metho, *perc, *dark, *atmo, *lsatmet, *oscale; char *inputname, *met, *outputname, *sensorname; struct Flag *frad, *print_meta, *named; lsat_data lsat; char band_in[GNAME_MAX], band_out[GNAME_MAX]; int i, j, q, method, pixel, dn_dark[MAX_BANDS], dn_mode[MAX_BANDS], dn_sat; int overwrite; double qcal, rad, ref, percent, ref_mode, rayleigh, scale; unsigned long hist[QCALMAX], h_max; struct Colors colors; struct FPRange range; double min, max; /* initialize GIS environment */ G_gisinit(argv[0]); /* initialize module */ module = G_define_module(); module->description = _("Calculates top-of-atmosphere radiance or reflectance and temperature for Landsat MSS/TM/ETM+/OLI"); G_add_keyword(_("imagery")); G_add_keyword(_("radiometric conversion")); G_add_keyword(_("radiance")); G_add_keyword(_("reflectance")); G_add_keyword(_("brightness temperature")); G_add_keyword(_("Landsat")); G_add_keyword(_("atmospheric correction")); module->overwrite = TRUE; /* It defines the different parameters */ input_prefix = G_define_standard_option(G_OPT_R_BASENAME_INPUT); input_prefix->label = _("Base name of input raster bands"); input_prefix->description = _("Example: 'B.' for B.1, B.2, ..."); output_prefix = G_define_standard_option(G_OPT_R_BASENAME_OUTPUT); output_prefix->label = _("Prefix for output raster maps"); output_prefix->description = _("Example: 'B.toar.' generates B.toar.1, B.toar.2, ..."); metfn = G_define_standard_option(G_OPT_F_INPUT); metfn->key = "metfile"; metfn->required = NO; metfn->description = _("Name of Landsat metadata file (.met or MTL.txt)"); metfn->guisection = _("Metadata"); sensor = G_define_option(); sensor->key = "sensor"; sensor->type = TYPE_STRING; sensor->label = _("Spacecraft sensor"); sensor->description = _("Required only if 'metfile' not given (recommended for sanity)"); sensor->options = "mss1,mss2,mss3,mss4,mss5,tm4,tm5,tm7,oli8"; desc = NULL; G_asprintf(&desc, "mss1;%s;mss2;%s;mss3;%s;mss4;%s;mss5;%s;tm4;%s;tm5;%s;tm7;%s;oli8;%s", _("Landsat-1 MSS"), _("Landsat-2 MSS"), _("Landsat-3 MSS"), _("Landsat-4 MSS"), _("Landsat-5 MSS"), _("Landsat-4 TM"), _("Landsat-5 TM"), _("Landsat-7 ETM+"), _("Landsat_8 OLI/TIRS")); sensor->descriptions = desc; sensor->required = NO; /* perhaps YES for clarity */ sensor->guisection = _("Metadata"); metho = G_define_option(); metho->key = "method"; metho->type = TYPE_STRING; metho->required = NO; metho->options = "uncorrected,dos1,dos2,dos2b,dos3,dos4"; metho->label = _("Atmospheric correction method"); metho->description = _("Atmospheric correction method"); metho->answer = "uncorrected"; metho->guisection = _("Metadata"); adate = G_define_option(); adate->key = "date"; adate->type = TYPE_STRING; adate->required = NO; adate->key_desc = "yyyy-mm-dd"; adate->label = _("Image acquisition date (yyyy-mm-dd)"); adate->description = _("Required only if 'metfile' not given"); adate->guisection = _("Metadata"); elev = G_define_option(); elev->key = "sun_elevation"; elev->type = TYPE_DOUBLE; elev->required = NO; elev->label = _("Sun elevation in degrees"); elev->description = _("Required only if 'metfile' not given"); elev->guisection = _("Metadata"); pdate = G_define_option(); pdate->key = "product_date"; pdate->type = TYPE_STRING; pdate->required = NO; pdate->key_desc = "yyyy-mm-dd"; pdate->label = _("Image creation date (yyyy-mm-dd)"); pdate->description = _("Required only if 'metfile' not given"); pdate->guisection = _("Metadata"); bgain = G_define_option(); bgain->key = "gain"; bgain->type = TYPE_STRING; bgain->required = NO; bgain->label = _("Gain (H/L) of all Landsat ETM+ bands (1-5,61,62,7,8)"); bgain->description = _("Required only if 'metfile' not given"); bgain->guisection = _("Settings"); perc = G_define_option(); perc->key = "percent"; perc->type = TYPE_DOUBLE; perc->required = NO; perc->label = _("Percent of solar radiance in path radiance"); perc->description = _("Required only if 'method' is any DOS"); perc->answer = "0.01"; perc->guisection = _("Settings"); dark = G_define_option(); dark->key = "pixel"; dark->type = TYPE_INTEGER; dark->required = NO; dark->label = _("Minimum pixels to consider digital number as dark object"); dark->description = _("Required only if 'method' is any DOS"); dark->answer = "1000"; dark->guisection = _("Settings"); atmo = G_define_option(); atmo->key = "rayleigh"; atmo->type = TYPE_DOUBLE; atmo->required = NO; atmo->label = _("Rayleigh atmosphere (diffuse sky irradiance)"); /* scattering coefficient? */ atmo->description = _("Required only if 'method' is DOS3"); atmo->answer = "0.0"; atmo->guisection = _("Settings"); lsatmet = G_define_option(); lsatmet->key = "lsatmet"; lsatmet->type = TYPE_STRING; lsatmet->required = NO; lsatmet->multiple = YES; lsatmet->label = _("return value stored for a given metadata"); lsatmet->description = _("Required only if 'metfile' and -p given"); lsatmet->options = "number,creation,date,sun_elev,sensor,bands,sunaz,time"; desc = NULL; G_asprintf(&desc, "number;%s;creation;%s;date;%s;sun_elev;%s;sensor;%s;bands;%s;sunaz;%s;time;%s", _("Landsat Number"), _("Creation timestamp"), _("Date"), _("Sun Elevation"), _("Sensor"), _("Bands count"), _("Sun Azimuth Angle"), _("Time")); lsatmet->descriptions = desc; lsatmet->guisection = _("Settings"); oscale = G_define_option(); oscale->key = "scale"; oscale->type = TYPE_DOUBLE; oscale->answer = "1.0"; oscale->required = NO; oscale->description = _("Scale factor for output"); /* define the different flags */ frad = G_define_flag(); frad->key = 'r'; frad->description = _("Output at-sensor radiance instead of reflectance for all bands"); named = G_define_flag(); named->key = 'n'; named->description = _("Input raster maps use as extension the number of the band instead the code"); print_meta = G_define_flag(); print_meta->key = 'p'; print_meta->description = _("Print output metadata info"); /* options and afters parser */ if (G_parser(argc, argv)) exit(EXIT_FAILURE); /***************************************** * ---------- START -------------------- * Stores options and flags to variables *****************************************/ met = metfn->answer; inputname = input_prefix->answer; outputname = output_prefix->answer; sensorname = sensor->answer ? sensor->answer : ""; overwrite = G_check_overwrite(argc, argv); Rast_get_window(&orig_cellhd); G_zero(&lsat, sizeof(lsat)); if (adate->answer != NULL) { strncpy(lsat.date, adate->answer, 11); lsat.date[10] = '\0'; if (strlen(lsat.date) != 10) G_fatal_error(_("Illegal date format: [%s] (yyyy-mm-dd)"), lsat.date); } if (pdate->answer != NULL) { strncpy(lsat.creation, pdate->answer, 11); lsat.creation[10] = '\0'; if (strlen(lsat.creation) != 10) G_fatal_error(_("Illegal date format: [%s] (yyyy-mm-dd)"), lsat.creation); } lsat.sun_elev = elev->answer == NULL ? 0. : atof(elev->answer); percent = atof(perc->answer); pixel = atoi(dark->answer); rayleigh = atof(atmo->answer); scale = atof(oscale->answer); /* * Data from metadata file */ lsat.flag = NOMETADATAFILE; /* Unnecessary because G_zero filled, but for sanity */ if (met != NULL) { lsat.flag = METADATAFILE; lsat_metadata(met, &lsat); if (print_meta->answer) { char *lsatmeta; if (lsatmet->answer == NULL) { G_fatal_error(_("Please use a metadata keyword with -p")); } for (i = 0; lsatmet->answers[i] != NULL; i++) { lsatmeta = lsatmet->answers[i]; if (strcmp(lsatmeta, "number") == 0) { fprintf(stdout, "number=%d\n", lsat.number); } if (strcmp(lsatmeta, "creation") == 0) { fprintf(stdout, "creation=%s\n", lsat.creation); } if (strcmp(lsatmeta, "date") == 0) { fprintf(stdout, "date=%s\n", lsat.date); } if (strcmp(lsatmeta, "sun_elev") == 0) { fprintf(stdout, "sun_elev=%f\n", lsat.sun_elev); } if (strcmp(lsatmeta, "sunaz") == 0) { fprintf(stdout, "sunaz=%f\n", lsat.sun_az); } if (strcmp(lsatmeta, "sensor") == 0) { fprintf(stdout, "sensor=%s\n", lsat.sensor); } if (strcmp(lsatmeta, "bands") == 0) { fprintf(stdout, "bands=%d\n", lsat.bands); } if (strcmp(lsatmet->answer, "time") == 0) { fprintf(stdout, "%f\n", lsat.time); } } exit(EXIT_SUCCESS); } G_debug(1, "lsat.number = %d, lsat.sensor = [%s]", lsat.number, lsat.sensor); if (!lsat.sensor || lsat.number > 8 || lsat.number < 1) G_fatal_error(_("Failed to identify satellite")); G_debug(1, "Landsat-%d %s with data set in metadata file [%s]", lsat.number, lsat.sensor, met); if (elev->answer != NULL) { lsat.sun_elev = atof(elev->answer); G_warning("Overwriting solar elevation of metadata file"); } } /* * Data from command line */ else if (adate->answer == NULL || elev->answer == NULL) { G_fatal_error(_("Lacking '%s' and/or '%s' for this satellite"), adate->key, elev->key); } else { if (strcmp(sensorname, "tm7") == 0) { if (bgain->answer == NULL || strlen(bgain->answer) != 9) G_fatal_error(_("Landsat-7 requires band gain with 9 (H/L) characters")); set_ETM(&lsat, bgain->answer); } else if (strcmp(sensorname, "oli8") == 0) set_OLI(&lsat); else if (strcmp(sensorname, "tm5") == 0) set_TM5(&lsat); else if (strcmp(sensorname, "tm4") == 0) set_TM4(&lsat); else if (strcmp(sensorname, "mss5") == 0) set_MSS5(&lsat); else if (strcmp(sensorname, "mss4") == 0) set_MSS4(&lsat); else if (strcmp(sensorname, "mss3") == 0) set_MSS3(&lsat); else if (strcmp(sensorname, "mss2") == 0) set_MSS2(&lsat); else if (strcmp(sensorname, "mss1") == 0) set_MSS1(&lsat); else G_fatal_error(_("Unknown satellite type (defined by '%s')"), sensorname); } /***************************************** * ------------ PREPARATION -------------- *****************************************/ if (strcasecmp(metho->answer, "corrected") == 0) /* deleted 2013 */ method = CORRECTED; else if (strcasecmp(metho->answer, "dos1") == 0) method = DOS1; else if (strcasecmp(metho->answer, "dos2") == 0) method = DOS2; else if (strcasecmp(metho->answer, "dos2b") == 0) method = DOS2b; else if (strcasecmp(metho->answer, "dos3") == 0) method = DOS3; else if (strcasecmp(metho->answer, "dos4") == 0) method = DOS4; else method = UNCORRECTED; /* if (metho->answer[3] == '2') method = (metho->answer[4] == '\0') ? DOS2 : DOS2b; else if (metho->answer[3] == '1') method = DOS1; else if (metho->answer[3] == '3') method = DOS3; else if (metho->answer[3] == '4') method = DOS4; else method = UNCORRECTED; */ for (i = 0; i < lsat.bands; i++) { dn_mode[i] = 0; dn_dark[i] = (int)lsat.band[i].qcalmin; dn_sat = (int)(0.90 * lsat.band[i].qcalmax); /* Begin: calculate dark pixel */ if (method > DOS && !lsat.band[i].thermal) { for (q = 0; q <= lsat.band[i].qcalmax; q++) hist[q] = 0L; sprintf(band_in, "%s%d", inputname, lsat.band[i].code); Rast_get_cellhd(band_in, "", &cellhd); Rast_set_window(&cellhd); if ((infd = Rast_open_old(band_in, "")) < 0) G_fatal_error(_("Unable to open raster map <%s>"), band_in); in_data_type = Rast_get_map_type(infd); if (in_data_type < 0) G_fatal_error(_("Unable to read data type of raster map <%s>"), band_in); inrast = Rast_allocate_buf(in_data_type); nrows = Rast_window_rows(); ncols = Rast_window_cols(); G_message("Calculating dark pixel of <%s>... ", band_in); for (row = 0; row < nrows; row++) { Rast_get_row(infd, inrast, row, in_data_type); for (col = 0; col < ncols; col++) { switch (in_data_type) { case CELL_TYPE: ptr = (void *)((CELL *) inrast + col); q = (int)*((CELL *) ptr); break; case FCELL_TYPE: ptr = (void *)((FCELL *) inrast + col); q = (int)*((FCELL *) ptr); break; case DCELL_TYPE: ptr = (void *)((DCELL *) inrast + col); q = (int)*((DCELL *) ptr); break; default: ptr = NULL; q = -1.; } if (!Rast_is_null_value(ptr, in_data_type) && q >= lsat.band[i].qcalmin && q <= lsat.band[i].qcalmax) hist[q]++; } } /* DN of dark object */ for (j = lsat.band[i].qcalmin; j <= lsat.band[i].qcalmax; j++) { if (hist[j] >= (unsigned int)pixel) { dn_dark[i] = j; break; } } /* Mode of DN (exclude potentially saturated) */ h_max = 0L; for (j = lsat.band[i].qcalmin; j < dn_sat; j++) { /* G_debug(5, "%d-%ld", j, hist[j]); */ if (hist[j] > h_max) { h_max = hist[j]; dn_mode[i] = j; } } G_verbose_message ("... DN = %.2d [%lu] : mode %.2d [%lu], excluding DN > %d", dn_dark[i], hist[dn_dark[i]], dn_mode[i], hist[dn_mode[i]], dn_sat); G_free(inrast); Rast_close(infd); } /* End: calculate dark pixel */ /* Calculate transformation constants */ lsat_bandctes(&lsat, i, method, percent, dn_dark[i], rayleigh); } /* * unnecessary or necessary with more checking as acquisition date,... * if (strlen(lsat.creation) == 0) * G_fatal_error(_("Unknown production date (defined by '%s')"), pdate->key); */ if (G_verbose() > G_verbose_std()) { fprintf(stderr, "\n LANDSAT: %d SENSOR: %s\n", lsat.number, lsat.sensor); fprintf(stderr, " ACQUISITION DATE %s [production date %s]\n", lsat.date, lsat.creation); fprintf(stderr, " Earth-sun distance = %.8lf\n", lsat.dist_es); fprintf(stderr, " Solar elevation angle = %.8lf\n", lsat.sun_elev); fprintf(stderr, " Atmospheric correction: %s\n", (method == UNCORRECTED ? "UNCORRECTED" : metho->answer)); if (method > DOS) { fprintf(stderr, " Percent of solar irradiance in path radiance = %.4lf\n", percent); } for (i = 0; i < lsat.bands; i++) { fprintf(stderr, "-------------------\n"); fprintf(stderr, " BAND %d %s(code %d)\n", lsat.band[i].number, (lsat.band[i].thermal ? "thermal " : ""), lsat.band[i].code); fprintf(stderr, " calibrated digital number (DN): %.1lf to %.1lf\n", lsat.band[i].qcalmin, lsat.band[i].qcalmax); fprintf(stderr, " calibration constants (L): %.5lf to %.5lf\n", lsat.band[i].lmin, lsat.band[i].lmax); fprintf(stderr, " at-%s radiance = %.8lf * DN + %.5lf\n", (method > DOS ? "surface" : "sensor"), lsat.band[i].gain, lsat.band[i].bias); if (lsat.band[i].thermal) { fprintf(stderr, " at-sensor temperature = %.5lf / log[(%.5lf / radiance) + 1.0]\n", lsat.band[i].K2, lsat.band[i].K1); } else { fprintf(stderr, " mean solar exoatmospheric irradiance (ESUN): %.5lf\n", lsat.band[i].esun); fprintf(stderr, " at-%s reflectance = radiance / %.5lf\n", (method > DOS ? "surface" : "sensor"), lsat.band[i].K1); if (method > DOS) { fprintf(stderr, " the darkness DN with a least %d pixels is %d\n", pixel, dn_dark[i]); fprintf(stderr, " the DN mode is %d\n", dn_mode[i]); } } } fprintf(stderr, "-------------------\n"); fflush(stderr); } /***************************************** * ------------ CALCULUS ----------------- *****************************************/ G_message(_("Calculating...")); for (i = 0; i < lsat.bands; i++) { sprintf(band_in, "%s%d", inputname, (named->answer ? lsat.band[i].number : lsat.band[i].code)); sprintf(band_out, "%s%d", outputname, lsat.band[i].code); /* set same size as original band raster */ Rast_get_cellhd(band_in, "", &cellhd); Rast_set_window(&cellhd); if ((infd = Rast_open_old(band_in, "")) < 0) G_fatal_error(_("Unable to open raster map <%s>"), band_in); if (G_find_raster2(band_out, "")) { if (overwrite) { G_warning(_("Raster map <%s> already exists and will be overwritten"), band_out); } else { G_warning(_("Raster map <%s> exists. Skipping."), band_out); continue; } } in_data_type = Rast_get_map_type(infd); if (in_data_type < 0) G_fatal_error(_("Unable to read data type of raster map <%s>"), band_in); /* controlling, if we can write the raster */ if (G_legal_filename(band_out) < 0) G_fatal_error(_("<%s> is an illegal file name"), band_out); if ((outfd = Rast_open_new(band_out, DCELL_TYPE)) < 0) G_fatal_error(_("Unable to create raster map <%s>"), band_out); /* allocate input and output buffer */ inrast = Rast_allocate_buf(in_data_type); outrast = Rast_allocate_buf(DCELL_TYPE); nrows = Rast_window_rows(); ncols = Rast_window_cols(); G_important_message(_("Writing %s of <%s> to <%s>..."), (frad-> answer ? _("radiance") : (lsat.band[i]. thermal) ? _("temperature") : _("reflectance")), band_in, band_out); for (row = 0; row < nrows; row++) { G_percent(row, nrows, 2); Rast_get_row(infd, inrast, row, in_data_type); for (col = 0; col < ncols; col++) { switch (in_data_type) { case CELL_TYPE: ptr = (void *)((CELL *) inrast + col); qcal = (double)((CELL *) inrast)[col]; break; case FCELL_TYPE: ptr = (void *)((FCELL *) inrast + col); qcal = (double)((FCELL *) inrast)[col]; break; case DCELL_TYPE: ptr = (void *)((DCELL *) inrast + col); qcal = (double)((DCELL *) inrast)[col]; break; default: ptr = NULL; qcal = -1.; } if (Rast_is_null_value(ptr, in_data_type) || qcal < lsat.band[i].qcalmin) { Rast_set_d_null_value((DCELL *) outrast + col, 1); } else { rad = lsat_qcal2rad(qcal, &lsat.band[i]); if (frad->answer) { ref = rad; } else { if (lsat.band[i].thermal) { ref = lsat_rad2temp(rad, &lsat.band[i]); } else { ref = lsat_rad2ref(rad, &lsat.band[i]) * scale; if (ref < 0. && method > DOS) ref = 0.; } } ((DCELL *) outrast)[col] = ref; } } Rast_put_row(outfd, outrast, DCELL_TYPE); } G_percent(1, 1, 1); ref_mode = 0.; if (method > DOS && !lsat.band[i].thermal) { ref_mode = lsat_qcal2rad(dn_mode[i], &lsat.band[i]); ref_mode = lsat_rad2ref(ref_mode, &lsat.band[i]); } G_free(inrast); Rast_close(infd); G_free(outrast); Rast_close(outfd); /* * needed? * if (out_type != CELL_TYPE) * G_quantize_fp_map_range(band_out, G_mapset(), 0., 360., 0, * 360); */ /* set grey255 colortable */ Rast_init_colors(&colors); Rast_read_fp_range(band_out, G_mapset(), &range); Rast_get_fp_range_min_max(&range, &min, &max); Rast_make_grey_scale_fp_colors(&colors, min, max); Rast_write_colors(band_out, G_mapset(), &colors); /* Initialize the 'history' structure with basic info */ Rast_short_history(band_out, "raster", &history); Rast_append_format_history(&history, " %s of Landsat-%d %s (method %s)", (frad-> answer ? "Radiance" : (lsat.band[i]. thermal ? "Temperature" : "Reflectance")), lsat.number, lsat.sensor, metho->answer); Rast_append_history(&history, "-----------------------------------------------------------------"); Rast_append_format_history(&history, " Acquisition date (and time) ........... %s (%.4lf h)", lsat.date, lsat.time); Rast_append_format_history(&history, " Production date ....................... %s\n", lsat.creation); Rast_append_format_history(&history, " Earth-sun distance (d) ................ %.7lf", lsat.dist_es); Rast_append_format_history(&history, " Sun elevation (and azimuth) ........... %.5lf (%.5lf)", lsat.sun_elev, lsat.sun_az); Rast_append_format_history(&history, " Digital number (DN) range ............. %.0lf to %.0lf", lsat.band[i].qcalmin, lsat.band[i].qcalmax); Rast_append_format_history(&history, " Calibration constants (Lmin to Lmax) .. %+.5lf to %+.5lf", lsat.band[i].lmin, lsat.band[i].lmax); Rast_append_format_history(&history, " DN to Radiance (gain and bias) ........ %+.5lf and %+.5lf", lsat.band[i].gain, lsat.band[i].bias); if (lsat.band[i].thermal) { Rast_append_format_history(&history, " Temperature (K1 and K2) ............... %.3lf and %.3lf", lsat.band[i].K1, lsat.band[i].K2); } else { Rast_append_format_history(&history, " Mean solar irradiance (ESUN) .......... %.3lf", lsat.band[i].esun); Rast_append_format_history(&history, " Radiance to Reflectance (divide by) ... %+.5lf", lsat.band[i].K1); if (method > DOS) { Rast_append_format_history(&history, " "); Rast_append_format_history(&history, " Dark object (%4d pixels) DN = ........ %d", pixel, dn_dark[i]); Rast_append_format_history(&history, " Mode in reflectance histogram ......... %.5lf", ref_mode); } } Rast_append_history(&history, "------------------------------------------------------------------"); Rast_command_history(&history); Rast_write_history(band_out, &history); if (lsat.band[i].thermal) Rast_write_units(band_out, "Kelvin"); else if (frad->answer) Rast_write_units(band_out, "W/(m^2 sr um)"); else Rast_write_units(band_out, "unitless"); /* set raster timestamp from acq date? (see r.timestamp module) */ } Rast_set_window(&orig_cellhd); exit(EXIT_SUCCESS); }