int closefiles(char *h_name, char *i_name, char *s_name, int fd_output[3], CELL * rowbuf[3]) { int i; struct Colors colors; struct Range range; struct History history; CELL min, max; const char *mapset; for (i = 0; i < 3; i++) { Rast_close(fd_output[i]); G_free(rowbuf[i]); } mapset = G_mapset(); /* write colors */ /* set to 0,max_level instead of min,max ?? */ Rast_read_range(h_name, mapset, &range); Rast_get_range_min_max(&range, &min, &max); Rast_make_grey_scale_colors(&colors, min, max); Rast_write_colors(h_name, mapset, &colors); Rast_read_range(i_name, mapset, &range); Rast_get_range_min_max(&range, &min, &max); Rast_make_grey_scale_colors(&colors, min, max); Rast_write_colors(i_name, mapset, &colors); Rast_read_range(s_name, mapset, &range); Rast_get_range_min_max(&range, &min, &max); Rast_make_grey_scale_colors(&colors, min, max); Rast_write_colors(s_name, mapset, &colors); /* write metadata */ Rast_short_history(h_name, "raster", &history); Rast_command_history(&history); Rast_write_history(h_name, &history); Rast_put_cell_title(h_name, "Image hue"); Rast_short_history(i_name, "raster", &history); Rast_command_history(&history); Rast_write_history(i_name, &history); Rast_put_cell_title(i_name, "Image intensity"); Rast_short_history(s_name, "raster", &history); Rast_command_history(&history); Rast_write_history(s_name, &history); Rast_put_cell_title(s_name, "Image saturation"); return 0; }
/* * update_rast_history - Update a history file. Some of the digit file * information is placed in the history file. */ void update_rast_history(struct parms *parm) { struct History hist; /* write command line to history */ Rast_short_history(parm->outrast->answer, "raster", &hist); Rast_append_format_history(&hist, "%s version %.2f", G_program_name(), APP_VERSION); Rast_append_format_history(&hist, "stream width: %.2f", parm->swidth * 2); Rast_format_history(&hist, HIST_DATSRC_1, "raster elevation file: %s", parm->inrast->answer); Rast_format_history(&hist, HIST_DATSRC_2, "vector stream file: %s", parm->invect->answer); Rast_command_history(&hist); Rast_write_history(parm->outrast->answer, &hist); }
/* record map history info */ static void write_hist(char *map_name, char *title, char *source_name, int mode, int sfd) { struct History history; Rast_put_cell_title(map_name, title); Rast_short_history(map_name, "raster", &history); Rast_set_history(&history, HIST_DATSRC_1, source_name); Rast_append_format_history( &history, "Processing mode: %s", sfd ? "SFD (D8)" : "MFD"); Rast_append_format_history( &history, "Memory mode: %s", mode ? "Segmented" : "All in RAM"); Rast_command_history(&history); Rast_write_history(map_name, &history); }
static void write_support_files(int xtile, int ytile, int overlap) { char name[GNAME_MAX]; struct Cell_head cellhd; char title[64]; struct History history; struct Colors colors; struct Categories cats; sprintf(name, "%s-%03d-%03d", parm.rastout->answer, ytile, xtile); Rast_get_cellhd(name, G_mapset(), &cellhd); cellhd.north = src_w.north - ytile * dst_w.rows * src_w.ns_res; cellhd.south = cellhd.north - (dst_w.rows + 2 * overlap) * src_w.ns_res; cellhd.west = src_w.west + xtile * dst_w.cols * src_w.ew_res; cellhd.east = cellhd.west + (dst_w.cols + 2 * overlap) * src_w.ew_res; Rast_put_cellhd(name, &cellhd); /* copy cats from source map */ if (Rast_read_cats(parm.rastin->answer, "", &cats) < 0) G_fatal_error(_("Unable to read cats for %s"), parm.rastin->answer); Rast_write_cats(name, &cats); /* record map metadata/history info */ G_debug(1, "Tile %d,%d of %s: writing %s", xtile, ytile, parm.rastin->answer, name); sprintf(title, "Tile %d,%d of %s", xtile, ytile, parm.rastin->answer); Rast_put_cell_title(name, title); Rast_short_history(name, "raster", &history); Rast_set_history(&history, HIST_DATSRC_1, parm.rastin->answer); Rast_command_history(&history); Rast_write_history(name, &history); /* copy color table from source map */ if (Rast_read_colors(parm.rastin->answer, "", &colors) < 0) G_fatal_error(_("Unable to read color table for %s"), parm.rastin->answer); if (map_type != CELL_TYPE) Rast_mark_colors_as_fp(&colors); Rast_write_colors(name, G_mapset(), &colors); }
int main(int argc, char *argv[]) { struct GModule *module; struct Option *rastin, *rastout, *method; struct History history; char title[64]; char buf_nsres[100], buf_ewres[100]; struct Colors colors; int infile, outfile; DCELL *outbuf; int row, col; struct Cell_head dst_w, src_w; G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("raster")); G_add_keyword(_("resample")); module->description = _("Resamples raster map layers to a finer grid using interpolation."); rastin = G_define_standard_option(G_OPT_R_INPUT); rastout = G_define_standard_option(G_OPT_R_OUTPUT); method = G_define_option(); method->key = "method"; method->type = TYPE_STRING; method->required = NO; method->description = _("Interpolation method"); method->options = "nearest,bilinear,bicubic,lanczos"; method->answer = "bilinear"; if (G_parser(argc, argv)) exit(EXIT_FAILURE); if (G_strcasecmp(method->answer, "nearest") == 0) neighbors = 1; else if (G_strcasecmp(method->answer, "bilinear") == 0) neighbors = 2; else if (G_strcasecmp(method->answer, "bicubic") == 0) neighbors = 4; else if (G_strcasecmp(method->answer, "lanczos") == 0) neighbors = 5; else G_fatal_error(_("Invalid method: %s"), method->answer); G_get_set_window(&dst_w); /* set window to old map */ Rast_get_cellhd(rastin->answer, "", &src_w); /* enlarge source window */ { double north = Rast_row_to_northing(0.5, &dst_w); double south = Rast_row_to_northing(dst_w.rows - 0.5, &dst_w); int r0 = (int)floor(Rast_northing_to_row(north, &src_w) - 0.5) - 2; int r1 = (int)floor(Rast_northing_to_row(south, &src_w) - 0.5) + 3; double west = Rast_col_to_easting(0.5, &dst_w); double east = Rast_col_to_easting(dst_w.cols - 0.5, &dst_w); int c0 = (int)floor(Rast_easting_to_col(west, &src_w) - 0.5) - 2; int c1 = (int)floor(Rast_easting_to_col(east, &src_w) - 0.5) + 3; src_w.south -= src_w.ns_res * (r1 - src_w.rows); src_w.north += src_w.ns_res * (-r0); src_w.west -= src_w.ew_res * (-c0); src_w.east += src_w.ew_res * (c1 - src_w.cols); src_w.rows = r1 - r0; src_w.cols = c1 - c0; } Rast_set_input_window(&src_w); /* allocate buffers for input rows */ for (row = 0; row < neighbors; row++) bufs[row] = Rast_allocate_d_input_buf(); cur_row = -100; /* open old map */ infile = Rast_open_old(rastin->answer, ""); /* reset window to current region */ Rast_set_output_window(&dst_w); outbuf = Rast_allocate_d_output_buf(); /* open new map */ outfile = Rast_open_new(rastout->answer, DCELL_TYPE); switch (neighbors) { case 1: /* nearest */ for (row = 0; row < dst_w.rows; row++) { double north = Rast_row_to_northing(row + 0.5, &dst_w); double maprow_f = Rast_northing_to_row(north, &src_w) - 0.5; int maprow0 = (int)floor(maprow_f + 0.5); G_percent(row, dst_w.rows, 2); read_rows(infile, maprow0); for (col = 0; col < dst_w.cols; col++) { double east = Rast_col_to_easting(col + 0.5, &dst_w); double mapcol_f = Rast_easting_to_col(east, &src_w) - 0.5; int mapcol0 = (int)floor(mapcol_f + 0.5); double c = bufs[0][mapcol0]; if (Rast_is_d_null_value(&c)) { Rast_set_d_null_value(&outbuf[col], 1); } else { outbuf[col] = c; } } Rast_put_d_row(outfile, outbuf); } break; case 2: /* bilinear */ for (row = 0; row < dst_w.rows; row++) { double north = Rast_row_to_northing(row + 0.5, &dst_w); double maprow_f = Rast_northing_to_row(north, &src_w) - 0.5; int maprow0 = (int)floor(maprow_f); double v = maprow_f - maprow0; G_percent(row, dst_w.rows, 2); read_rows(infile, maprow0); for (col = 0; col < dst_w.cols; col++) { double east = Rast_col_to_easting(col + 0.5, &dst_w); double mapcol_f = Rast_easting_to_col(east, &src_w) - 0.5; int mapcol0 = (int)floor(mapcol_f); int mapcol1 = mapcol0 + 1; double u = mapcol_f - mapcol0; double c00 = bufs[0][mapcol0]; double c01 = bufs[0][mapcol1]; double c10 = bufs[1][mapcol0]; double c11 = bufs[1][mapcol1]; if (Rast_is_d_null_value(&c00) || Rast_is_d_null_value(&c01) || Rast_is_d_null_value(&c10) || Rast_is_d_null_value(&c11)) { Rast_set_d_null_value(&outbuf[col], 1); } else { outbuf[col] = Rast_interp_bilinear(u, v, c00, c01, c10, c11); } } Rast_put_d_row(outfile, outbuf); } break; case 4: /* bicubic */ for (row = 0; row < dst_w.rows; row++) { double north = Rast_row_to_northing(row + 0.5, &dst_w); double maprow_f = Rast_northing_to_row(north, &src_w) - 0.5; int maprow1 = (int)floor(maprow_f); int maprow0 = maprow1 - 1; double v = maprow_f - maprow1; G_percent(row, dst_w.rows, 2); read_rows(infile, maprow0); for (col = 0; col < dst_w.cols; col++) { double east = Rast_col_to_easting(col + 0.5, &dst_w); double mapcol_f = Rast_easting_to_col(east, &src_w) - 0.5; int mapcol1 = (int)floor(mapcol_f); int mapcol0 = mapcol1 - 1; int mapcol2 = mapcol1 + 1; int mapcol3 = mapcol1 + 2; double u = mapcol_f - mapcol1; double c00 = bufs[0][mapcol0]; double c01 = bufs[0][mapcol1]; double c02 = bufs[0][mapcol2]; double c03 = bufs[0][mapcol3]; double c10 = bufs[1][mapcol0]; double c11 = bufs[1][mapcol1]; double c12 = bufs[1][mapcol2]; double c13 = bufs[1][mapcol3]; double c20 = bufs[2][mapcol0]; double c21 = bufs[2][mapcol1]; double c22 = bufs[2][mapcol2]; double c23 = bufs[2][mapcol3]; double c30 = bufs[3][mapcol0]; double c31 = bufs[3][mapcol1]; double c32 = bufs[3][mapcol2]; double c33 = bufs[3][mapcol3]; if (Rast_is_d_null_value(&c00) || Rast_is_d_null_value(&c01) || Rast_is_d_null_value(&c02) || Rast_is_d_null_value(&c03) || Rast_is_d_null_value(&c10) || Rast_is_d_null_value(&c11) || Rast_is_d_null_value(&c12) || Rast_is_d_null_value(&c13) || Rast_is_d_null_value(&c20) || Rast_is_d_null_value(&c21) || Rast_is_d_null_value(&c22) || Rast_is_d_null_value(&c23) || Rast_is_d_null_value(&c30) || Rast_is_d_null_value(&c31) || Rast_is_d_null_value(&c32) || Rast_is_d_null_value(&c33)) { Rast_set_d_null_value(&outbuf[col], 1); } else { outbuf[col] = Rast_interp_bicubic(u, v, c00, c01, c02, c03, c10, c11, c12, c13, c20, c21, c22, c23, c30, c31, c32, c33); } } Rast_put_d_row(outfile, outbuf); } break; case 5: /* lanczos */ for (row = 0; row < dst_w.rows; row++) { double north = Rast_row_to_northing(row + 0.5, &dst_w); double maprow_f = Rast_northing_to_row(north, &src_w) - 0.5; int maprow1 = (int)floor(maprow_f + 0.5); int maprow0 = maprow1 - 2; double v = maprow_f - maprow1; G_percent(row, dst_w.rows, 2); read_rows(infile, maprow0); for (col = 0; col < dst_w.cols; col++) { double east = Rast_col_to_easting(col + 0.5, &dst_w); double mapcol_f = Rast_easting_to_col(east, &src_w) - 0.5; int mapcol2 = (int)floor(mapcol_f + 0.5); int mapcol0 = mapcol2 - 2; int mapcol4 = mapcol2 + 2; double u = mapcol_f - mapcol2; double c[25]; int ci = 0, i, j, do_lanczos = 1; for (i = 0; i < 5; i++) { for (j = mapcol0; j <= mapcol4; j++) { c[ci] = bufs[i][j]; if (Rast_is_d_null_value(&(c[ci]))) { Rast_set_d_null_value(&outbuf[col], 1); do_lanczos = 0; break; } ci++; } if (!do_lanczos) break; } if (do_lanczos) { outbuf[col] = Rast_interp_lanczos(u, v, c); } } Rast_put_d_row(outfile, outbuf); } break; } G_percent(dst_w.rows, dst_w.rows, 2); Rast_close(infile); Rast_close(outfile); /* record map metadata/history info */ sprintf(title, "Resample by %s interpolation", method->answer); Rast_put_cell_title(rastout->answer, title); Rast_short_history(rastout->answer, "raster", &history); Rast_set_history(&history, HIST_DATSRC_1, rastin->answer); G_format_resolution(src_w.ns_res, buf_nsres, src_w.proj); G_format_resolution(src_w.ew_res, buf_ewres, src_w.proj); Rast_format_history(&history, HIST_DATSRC_2, "Source map NS res: %s EW res: %s", buf_nsres, buf_ewres); Rast_command_history(&history); Rast_write_history(rastout->answer, &history); /* copy color table from source map */ if (Rast_read_colors(rastin->answer, "", &colors) < 0) G_fatal_error(_("Unable to read color table for %s"), rastin->answer); Rast_mark_colors_as_fp(&colors); Rast_write_colors(rastout->answer, G_mapset(), &colors); return (EXIT_SUCCESS); }
int close_maps(char *stream_rast, char *stream_vect, char *dir_rast) { int stream_fd, dir_fd, r, c, i; CELL *cell_buf1, *cell_buf2; struct History history; CELL stream_id; ASP_FLAG af; /* cheating... */ stream_fd = dir_fd = -1; cell_buf1 = cell_buf2 = NULL; G_message(_("Writing output raster maps...")); /* write requested output rasters */ if (stream_rast) { stream_fd = Rast_open_new(stream_rast, CELL_TYPE); cell_buf1 = Rast_allocate_c_buf(); } if (dir_rast) { dir_fd = Rast_open_new(dir_rast, CELL_TYPE); cell_buf2 = Rast_allocate_c_buf(); } for (r = 0; r < nrows; r++) { G_percent(r, nrows, 2); if (stream_rast) Rast_set_c_null_value(cell_buf1, ncols); /* reset row to all NULL */ if (dir_rast) Rast_set_c_null_value(cell_buf2, ncols); /* reset row to all NULL */ for (c = 0; c < ncols; c++) { if (stream_rast) { cseg_get(&stream, &stream_id, r, c); if (stream_id) cell_buf1[c] = stream_id; } if (dir_rast) { seg_get(&aspflag, (char *)&af, r, c); if (!FLAG_GET(af.flag, NULLFLAG)) { cell_buf2[c] = af.asp; } } } if (stream_rast) Rast_put_row(stream_fd, cell_buf1, CELL_TYPE); if (dir_rast) Rast_put_row(dir_fd, cell_buf2, CELL_TYPE); } G_percent(nrows, nrows, 2); /* finish it */ if (stream_rast) { Rast_close(stream_fd); G_free(cell_buf1); Rast_short_history(stream_rast, "raster", &history); Rast_command_history(&history); Rast_write_history(stream_rast, &history); } if (dir_rast) { struct Colors colors; Rast_close(dir_fd); G_free(cell_buf2); Rast_short_history(dir_rast, "raster", &history); Rast_command_history(&history); Rast_write_history(dir_rast, &history); Rast_init_colors(&colors); Rast_make_aspect_colors(&colors, -8, 8); Rast_write_colors(dir_rast, G_mapset(), &colors); } /* close stream vector */ if (stream_vect) { if (close_streamvect(stream_vect) < 0) G_fatal_error(_("Unable to write vector map <%s>"), stream_vect); } /* rearranging desk chairs on the Titanic... */ G_free(outlets); /* free stream nodes */ for (i = 1; i <= n_stream_nodes; i++) { if (stream_node[i].n_alloc > 0) { G_free(stream_node[i].trib); } } G_free(stream_node); return 1; }
int main(int argc, char *argv[]) { struct GModule *module; struct Option *coord, *out_file, *min, *max, *mult; struct Flag *flag; int *int_buf; struct Cell_head w; struct History history; int cellfile; double east, north, pt[2], cur[2], row, col, fmult; double fmin, fmax; int binary; G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("raster")); G_add_keyword(_("buffer")); G_add_keyword(_("geometry")); G_add_keyword(_("circle")); module->description = _("Creates a raster map containing concentric " "rings around a given point."); out_file = G_define_standard_option(G_OPT_R_OUTPUT); coord = G_define_standard_option(G_OPT_M_COORDS); coord->required = YES; coord->description = _("The coordinate of the center (east,north)"); min = G_define_option(); min->key = "min"; min->type = TYPE_DOUBLE; min->required = NO; min->description = _("Minimum radius for ring/circle map (in meters)"); max = G_define_option(); max->key = "max"; max->type = TYPE_DOUBLE; max->required = NO; max->description = _("Maximum radius for ring/circle map (in meters)"); mult = G_define_option(); mult->key = "multiplier"; mult->type = TYPE_DOUBLE; mult->required = NO; mult->description = _("Data value multiplier"); flag = G_define_flag(); flag->key = 'b'; flag->description = _("Generate binary raster map"); if (G_parser(argc, argv)) exit(EXIT_FAILURE); G_scan_easting(coord->answers[0], &east, G_projection()); G_scan_northing(coord->answers[1], &north, G_projection()); pt[0] = east; pt[1] = north; fmult = 1.0; if (min->answer) sscanf(min->answer, "%lf", &fmin); else fmin = 0; if (max->answer) sscanf(max->answer, "%lf", &fmax); else fmax = HUGE_VAL; if (fmin > fmax) G_fatal_error(_("Please specify a radius in which min < max")); if (mult->answer) if (1 != sscanf(mult->answer, "%lf", &fmult)) fmult = 1.0; /* nonsense test */ if (flag->answer && (!min->answer && !max->answer)) G_fatal_error(_("Please specify min and/or max radius when " "using the binary flag")); if (flag->answer) binary = 1; /* generate binary pattern only, useful for MASK */ else binary = 0; G_get_set_window(&w); cellfile = Rast_open_c_new(out_file->answer); int_buf = (int *)G_malloc(w.cols * sizeof(int)); { int c; for (row = 0; row < w.rows; row++) { G_percent(row, w.rows, 2); cur[1] = Rast_row_to_northing(row + 0.5, &w); for (col = 0; col < w.cols; col++) { c = col; cur[0] = Rast_col_to_easting(col + 0.5, &w); int_buf[c] = (int)(distance(pt, cur, fmin, fmax, binary) * fmult); if (int_buf[c] == 0) Rast_set_null_value(&int_buf[c], 1, CELL_TYPE); } Rast_put_row(cellfile, int_buf, CELL_TYPE); } } G_free(int_buf); Rast_close(cellfile); Rast_short_history(out_file->answer, "raster", &history); Rast_command_history(&history); Rast_write_history(out_file->answer, &history); G_done_msg(_("Raster map <%s> created."), out_file->answer); return (EXIT_SUCCESS); }
int main( int argc, char **argv ) { char *name = nullptr; struct Option *map; struct Cell_head window; G_gisinit( argv[0] ); G_define_module(); map = G_define_standard_option( G_OPT_R_OUTPUT ); if ( G_parser( argc, argv ) ) exit( EXIT_FAILURE ); name = map->answer; #ifdef Q_OS_WIN _setmode( _fileno( stdin ), _O_BINARY ); _setmode( _fileno( stdout ), _O_BINARY ); //setvbuf( stdin, NULL, _IONBF, BUFSIZ ); // setting _IONBF on stdout works on windows correctly, data written immediately even without fflush(stdout) //setvbuf( stdout, NULL, _IONBF, BUFSIZ ); #endif QgsGrassDataFile stdinFile; stdinFile.open( stdin ); QDataStream stdinStream( &stdinFile ); QFile stdoutFile; stdoutFile.open( stdout, QIODevice::WriteOnly | QIODevice::Unbuffered ); QDataStream stdoutStream( &stdoutFile ); qint32 proj, zone; stdinStream >> proj >> zone; QgsRectangle extent; qint32 rows, cols; stdinStream >> extent >> cols >> rows; checkStream( stdinStream ); QString err = QgsGrass::setRegion( &window, extent, rows, cols ); if ( !err.isEmpty() ) { G_fatal_error( "Cannot set region: %s", err.toUtf8().constData() ); } window.proj = ( int ) proj; window.zone = ( int ) zone; G_set_window( &window ); Qgis::DataType qgis_type; qint32 type; stdinStream >> type; checkStream( stdinStream ); qgis_type = ( Qgis::DataType )type; RASTER_MAP_TYPE grass_type; switch ( qgis_type ) { case Qgis::Int32: grass_type = CELL_TYPE; break; case Qgis::Float32: grass_type = FCELL_TYPE; break; case Qgis::Float64: grass_type = DCELL_TYPE; break; default: G_fatal_error( "QGIS data type %d not supported", qgis_type ); return 1; } cf = Rast_open_new( name, grass_type ); if ( cf < 0 ) { G_fatal_error( "Unable to create raster map <%s>", name ); return 1; } void *buf = Rast_allocate_buf( grass_type ); int expectedSize = cols * QgsRasterBlock::typeSize( qgis_type ); bool isCanceled = false; QByteArray byteArray; for ( int row = 0; row < rows; row++ ) { stdinStream >> isCanceled; checkStream( stdinStream ); if ( isCanceled ) { break; } double noDataValue; stdinStream >> noDataValue; stdinStream >> byteArray; checkStream( stdinStream ); if ( byteArray.size() != expectedSize ) { G_fatal_error( "Wrong byte array size, expected %d bytes, got %d, row %d / %d", expectedSize, byteArray.size(), row, rows ); return 1; } qint32 *cell = nullptr; float *fcell = nullptr; double *dcell = nullptr; if ( grass_type == CELL_TYPE ) cell = ( qint32 * ) byteArray.data(); else if ( grass_type == FCELL_TYPE ) fcell = ( float * ) byteArray.data(); else if ( grass_type == DCELL_TYPE ) dcell = ( double * ) byteArray.data(); void *ptr = buf; for ( int col = 0; col < cols; col++ ) { if ( grass_type == CELL_TYPE ) { if ( ( CELL )cell[col] == ( CELL )noDataValue ) { Rast_set_c_null_value( ( CELL * )ptr, 1 ); } else { Rast_set_c_value( ptr, ( CELL )( cell[col] ), grass_type ); } } else if ( grass_type == FCELL_TYPE ) { if ( ( FCELL )fcell[col] == ( FCELL )noDataValue ) { Rast_set_f_null_value( ( FCELL * )ptr, 1 ); } else { Rast_set_f_value( ptr, ( FCELL )( fcell[col] ), grass_type ); } } else if ( grass_type == DCELL_TYPE ) { if ( ( DCELL )dcell[col] == ( DCELL )noDataValue ) { Rast_set_d_null_value( ( DCELL * )ptr, 1 ); } else { Rast_set_d_value( ptr, ( DCELL )dcell[col], grass_type ); } } ptr = G_incr_void_ptr( ptr, Rast_cell_size( grass_type ) ); } Rast_put_row( cf, buf, grass_type ); #ifndef Q_OS_WIN // Because stdin is somewhere buffered on Windows (not clear if in QProcess or by Windows) // we cannot in QgsGrassImport wait for this because it hangs. Setting _IONBF on stdin does not help // and there is no flush() on QProcess. // OTOH, smaller stdin buffer is probably blocking QgsGrassImport so that the import can be canceled immediately. stdoutStream << ( bool )true; // row written stdoutFile.flush(); #endif } if ( isCanceled ) { Rast_unopen( cf ); } else { Rast_close( cf ); struct History history; Rast_short_history( name, "raster", &history ); Rast_command_history( &history ); Rast_write_history( name, &history ); } exit( EXIT_SUCCESS ); }
int main(int argc, char *argv[]) { int fd, maskfd; CELL *cell, *mask; struct Cell_head window; int row, col; double north, east; double dx, dy; double maxdist, dist; double sum1, sum2; int i, n, max; struct GModule *module; struct History history; struct { struct Option *input, *npoints, *output; } parm; G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("raster")); G_add_keyword(_("surface")); G_add_keyword(_("interpolation")); G_add_keyword(_("IDW")); module->description = _("Surface generation program."); parm.input = G_define_standard_option(G_OPT_R_INPUT); parm.output = G_define_standard_option(G_OPT_R_OUTPUT); parm.npoints = G_define_option(); parm.npoints->key = "npoints"; parm.npoints->key_desc = "count"; parm.npoints->type = TYPE_INTEGER; parm.npoints->required = NO; parm.npoints->description = _("Number of interpolation points"); parm.npoints->answer = "12"; if (G_parser(argc, argv)) exit(EXIT_FAILURE); /* Make sure that the current projection is not lat/long */ if ((G_projection() == PROJECTION_LL)) G_fatal_error(_("Lat/long databases not supported by r.surf.idw2. Use r.surf.idw instead!")); if (sscanf(parm.npoints->answer, "%d", &search_points) != 1 || search_points < 1) G_fatal_error(_("%s=%s - illegal number of interpolation points"), parm.npoints->key, parm.npoints->answer); list = (struct Point *)G_calloc(search_points, sizeof(struct Point)); /* read the elevation points from the input raster map */ read_cell(parm.input->answer); if (npoints == 0) G_fatal_error(_("%s: no data points found"), G_program_name()); nsearch = npoints < search_points ? npoints : search_points; /* get the window, allocate buffers, etc. */ G_get_set_window(&window); cell = Rast_allocate_c_buf(); if ((maskfd = Rast_maskfd()) >= 0) mask = Rast_allocate_c_buf(); else mask = NULL; fd = Rast_open_c_new(parm.output->answer); G_message(_("Interpolating raster map <%s>... %d rows... "), parm.output->answer, window.rows); north = window.north - window.ns_res / 2.0; for (row = 0; row < window.rows; row++) { G_percent(row, window.rows, 2); if (mask) Rast_get_c_row(maskfd, mask, row); north += window.ns_res; east = window.west - window.ew_res / 2.0; for (col = 0; col < window.cols; col++) { east += window.ew_res; /* don't interpolate outside of the mask */ if (mask && mask[col] == 0) { cell[col] = 0; continue; } /* fill list with first nsearch points */ for (i = 0; i < nsearch; i++) { dy = points[i].north - north; dx = points[i].east - east; list[i].dist = dy * dy + dx * dx; list[i].z = points[i].z; } /* find the maximum distance */ maxdist = list[max = 0].dist; for (n = 1; n < nsearch; n++) { if (maxdist < list[n].dist) maxdist = list[max = n].dist; } /* go thru rest of the points now */ for (; i < npoints; i++) { dy = points[i].north - north; dx = points[i].east - east; dist = dy * dy + dx * dx; if (dist < maxdist) { /* replace the largest dist */ list[max].z = points[i].z; list[max].dist = dist; maxdist = list[max = 0].dist; for (n = 1; n < nsearch; n++) { if (maxdist < list[n].dist) maxdist = list[max = n].dist; } } } /* interpolate */ sum1 = 0.0; sum2 = 0.0; for (n = 0; n < nsearch; n++) { if ((dist = list[n].dist)) { sum1 += list[n].z / dist; sum2 += 1.0 / dist; } else { sum1 = list[n].z; sum2 = 1.0; break; } } cell[col] = (CELL) (sum1 / sum2 + 0.5); } Rast_put_row(fd, cell, CELL_TYPE); } G_free(points); G_free(cell); Rast_close(fd); /* writing history file */ Rast_short_history(parm.output->answer, "raster", &history); Rast_command_history(&history); Rast_write_history(parm.output->answer, &history); G_done_msg(" "); exit(EXIT_SUCCESS); }
int main(int argc, char *argv[]) { int out_fd, base_raster; char *infile, *outmap; int percent; double zrange_min, zrange_max, d_tmp; double irange_min, irange_max; unsigned long estimated_lines; RASTER_MAP_TYPE rtype, base_raster_data_type; struct History history; char title[64]; SEGMENT base_segment; struct PointBinning point_binning; void *base_array; void *raster_row; struct Cell_head region; struct Cell_head input_region; int rows, last_rows, row0, cols; /* scan box size */ int row; /* counters */ int pass, npasses; unsigned long line, line_total; unsigned int counter; unsigned long n_invalid; char buff[BUFFSIZE]; double x, y, z; double intensity; int arr_row, arr_col; unsigned long count, count_total; int point_class; double zscale = 1.0; double iscale = 1.0; double res = 0.0; struct BinIndex bin_index_nodes; bin_index_nodes.num_nodes = 0; bin_index_nodes.max_nodes = 0; bin_index_nodes.nodes = 0; struct GModule *module; struct Option *input_opt, *output_opt, *percent_opt, *type_opt, *filter_opt, *class_opt; struct Option *method_opt, *base_raster_opt; struct Option *zrange_opt, *zscale_opt; struct Option *irange_opt, *iscale_opt; struct Option *trim_opt, *pth_opt, *res_opt; struct Option *file_list_opt; struct Flag *print_flag, *scan_flag, *shell_style, *over_flag, *extents_flag; struct Flag *intens_flag, *intens_import_flag; struct Flag *set_region_flag; struct Flag *base_rast_res_flag; struct Flag *only_valid_flag; /* LAS */ LASReaderH LAS_reader; LASHeaderH LAS_header; LASSRSH LAS_srs; LASPointH LAS_point; int return_filter; const char *projstr; struct Cell_head cellhd, loc_wind; unsigned int n_filtered; G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("raster")); G_add_keyword(_("import")); G_add_keyword(_("LIDAR")); G_add_keyword(_("statistics")); G_add_keyword(_("conversion")); G_add_keyword(_("aggregation")); G_add_keyword(_("binning")); module->description = _("Creates a raster map from LAS LiDAR points using univariate statistics."); input_opt = G_define_standard_option(G_OPT_F_BIN_INPUT); input_opt->required = NO; input_opt->label = _("LAS input file"); input_opt->description = _("LiDAR input files in LAS format (*.las or *.laz)"); input_opt->guisection = _("Input"); output_opt = G_define_standard_option(G_OPT_R_OUTPUT); output_opt->required = NO; output_opt->guisection = _("Output"); file_list_opt = G_define_standard_option(G_OPT_F_INPUT); file_list_opt->key = "file"; file_list_opt->label = _("File containing names of LAS input files"); file_list_opt->description = _("LiDAR input files in LAS format (*.las or *.laz)"); file_list_opt->required = NO; file_list_opt->guisection = _("Input"); method_opt = G_define_option(); method_opt->key = "method"; method_opt->type = TYPE_STRING; method_opt->required = NO; method_opt->description = _("Statistic to use for raster values"); method_opt->options = "n,min,max,range,sum,mean,stddev,variance,coeff_var,median,percentile,skewness,trimmean"; method_opt->answer = "mean"; method_opt->guisection = _("Statistic"); G_asprintf((char **)&(method_opt->descriptions), "n;%s;" "min;%s;" "max;%s;" "range;%s;" "sum;%s;" "mean;%s;" "stddev;%s;" "variance;%s;" "coeff_var;%s;" "median;%s;" "percentile;%s;" "skewness;%s;" "trimmean;%s", _("Number of points in cell"), _("Minimum value of point values in cell"), _("Maximum value of point values in cell"), _("Range of point values in cell"), _("Sum of point values in cell"), _("Mean (average) value of point values in cell"), _("Standard deviation of point values in cell"), _("Variance of point values in cell"), _("Coefficient of variance of point values in cell"), _("Median value of point values in cell"), _("pth (nth) percentile of point values in cell"), _("Skewness of point values in cell"), _("Trimmed mean of point values in cell")); type_opt = G_define_standard_option(G_OPT_R_TYPE); type_opt->required = NO; type_opt->answer = "FCELL"; base_raster_opt = G_define_standard_option(G_OPT_R_INPUT); base_raster_opt->key = "base_raster"; base_raster_opt->required = NO; base_raster_opt->label = _("Subtract raster values from the Z coordinates"); base_raster_opt->description = _("The scale for Z is applied beforehand, the range filter for" " Z afterwards"); base_raster_opt->guisection = _("Transform"); zrange_opt = G_define_option(); zrange_opt->key = "zrange"; zrange_opt->type = TYPE_DOUBLE; zrange_opt->required = NO; zrange_opt->key_desc = "min,max"; zrange_opt->description = _("Filter range for Z data (min,max)"); zrange_opt->guisection = _("Selection"); zscale_opt = G_define_option(); zscale_opt->key = "zscale"; zscale_opt->type = TYPE_DOUBLE; zscale_opt->required = NO; zscale_opt->answer = "1.0"; zscale_opt->description = _("Scale to apply to Z data"); zscale_opt->guisection = _("Transform"); irange_opt = G_define_option(); irange_opt->key = "intensity_range"; irange_opt->type = TYPE_DOUBLE; irange_opt->required = NO; irange_opt->key_desc = "min,max"; irange_opt->description = _("Filter range for intensity values (min,max)"); irange_opt->guisection = _("Selection"); iscale_opt = G_define_option(); iscale_opt->key = "intensity_scale"; iscale_opt->type = TYPE_DOUBLE; iscale_opt->required = NO; iscale_opt->answer = "1.0"; iscale_opt->description = _("Scale to apply to intensity values"); iscale_opt->guisection = _("Transform"); percent_opt = G_define_option(); percent_opt->key = "percent"; percent_opt->type = TYPE_INTEGER; percent_opt->required = NO; percent_opt->answer = "100"; percent_opt->options = "1-100"; percent_opt->description = _("Percent of map to keep in memory"); /* I would prefer to call the following "percentile", but that has too * much namespace overlap with the "percent" option above */ pth_opt = G_define_option(); pth_opt->key = "pth"; pth_opt->type = TYPE_INTEGER; pth_opt->required = NO; pth_opt->options = "1-100"; pth_opt->description = _("pth percentile of the values"); pth_opt->guisection = _("Statistic"); trim_opt = G_define_option(); trim_opt->key = "trim"; trim_opt->type = TYPE_DOUBLE; trim_opt->required = NO; trim_opt->options = "0-50"; trim_opt->label = _("Discard given percentage of the smallest and largest values"); trim_opt->description = _("Discard <trim> percent of the smallest and <trim> percent of the largest observations"); trim_opt->guisection = _("Statistic"); res_opt = G_define_option(); res_opt->key = "resolution"; res_opt->type = TYPE_DOUBLE; res_opt->required = NO; res_opt->description = _("Output raster resolution"); res_opt->guisection = _("Output"); filter_opt = G_define_option(); filter_opt->key = "return_filter"; filter_opt->type = TYPE_STRING; filter_opt->required = NO; filter_opt->label = _("Only import points of selected return type"); filter_opt->description = _("If not specified, all points are imported"); filter_opt->options = "first,last,mid"; filter_opt->guisection = _("Selection"); class_opt = G_define_option(); class_opt->key = "class_filter"; class_opt->type = TYPE_INTEGER; class_opt->multiple = YES; class_opt->required = NO; class_opt->label = _("Only import points of selected class(es)"); class_opt->description = _("Input is comma separated integers. " "If not specified, all points are imported."); class_opt->guisection = _("Selection"); print_flag = G_define_flag(); print_flag->key = 'p'; print_flag->description = _("Print LAS file info and exit"); extents_flag = G_define_flag(); extents_flag->key = 'e'; extents_flag->label = _("Use the extent of the input for the raster extent"); extents_flag->description = _("Set internally computational region extents based on the" " point cloud"); extents_flag->guisection = _("Output"); set_region_flag = G_define_flag(); set_region_flag->key = 'n'; set_region_flag->label = _("Set computation region to match the new raster map"); set_region_flag->description = _("Set computation region to match the 2D extent and resolution" " of the newly created new raster map"); set_region_flag->guisection = _("Output"); over_flag = G_define_flag(); over_flag->key = 'o'; over_flag->label = _("Override projection check (use current location's projection)"); over_flag->description = _("Assume that the dataset has same projection as the current location"); scan_flag = G_define_flag(); scan_flag->key = 's'; scan_flag->description = _("Scan data file for extent then exit"); shell_style = G_define_flag(); shell_style->key = 'g'; shell_style->description = _("In scan mode, print using shell script style"); intens_flag = G_define_flag(); intens_flag->key = 'i'; intens_flag->label = _("Use intensity values rather than Z values"); intens_flag->description = _("Uses intensity values everywhere as if they would be Z" " coordinates"); intens_import_flag = G_define_flag(); intens_import_flag->key = 'j'; intens_import_flag->description = _("Use Z values for filtering, but intensity values for statistics"); base_rast_res_flag = G_define_flag(); base_rast_res_flag->key = 'd'; base_rast_res_flag->label = _("Use base raster resolution instead of computational region"); base_rast_res_flag->description = _("For getting values from base raster, use its actual" " resolution instead of computational region resolution"); only_valid_flag = G_define_flag(); only_valid_flag->key = 'v'; only_valid_flag->label = _("Use only valid points"); only_valid_flag->description = _("Points invalid according to APSRS LAS specification will be" " filtered out"); only_valid_flag->guisection = _("Selection"); G_option_required(input_opt, file_list_opt, NULL); G_option_exclusive(input_opt, file_list_opt, NULL); G_option_required(output_opt, print_flag, scan_flag, shell_style, NULL); G_option_exclusive(intens_flag, intens_import_flag, NULL); G_option_requires(base_rast_res_flag, base_raster_opt, NULL); if (G_parser(argc, argv)) exit(EXIT_FAILURE); int only_valid = FALSE; n_invalid = 0; if (only_valid_flag->answer) only_valid = TRUE; /* we could use rules but this gives more info and allows continuing */ if (set_region_flag->answer && !(extents_flag->answer || res_opt->answer)) { G_warning(_("Flag %c makes sense only with %s option or -%c flag"), set_region_flag->key, res_opt->key, extents_flag->key); /* avoid the call later on */ set_region_flag->answer = '\0'; } struct StringList infiles; if (file_list_opt->answer) { if (access(file_list_opt->answer, F_OK) != 0) G_fatal_error(_("File <%s> does not exist"), file_list_opt->answer); string_list_from_file(&infiles, file_list_opt->answer); } else { string_list_from_one_item(&infiles, input_opt->answer); } /* parse input values */ outmap = output_opt->answer; if (shell_style->answer && !scan_flag->answer) { scan_flag->answer = 1; /* pointer not int, so set = shell_style->answer ? */ } /* check zrange and extent relation */ if (scan_flag->answer || extents_flag->answer) { if (zrange_opt->answer) G_warning(_("zrange will not be taken into account during scan")); } Rast_get_window(®ion); /* G_get_window seems to be unreliable if the location has been changed */ G_get_set_window(&loc_wind); /* TODO: v.in.lidar uses G_get_default_window() */ estimated_lines = 0; int i; for (i = 0; i < infiles.num_items; i++) { infile = infiles.items[i]; /* don't if file not found */ if (access(infile, F_OK) != 0) G_fatal_error(_("Input file <%s> does not exist"), infile); /* Open LAS file*/ LAS_reader = LASReader_Create(infile); if (LAS_reader == NULL) G_fatal_error(_("Unable to open file <%s> as a LiDAR point cloud"), infile); LAS_header = LASReader_GetHeader(LAS_reader); if (LAS_header == NULL) { G_fatal_error(_("Unable to read LAS header of <%s>"), infile); } LAS_srs = LASHeader_GetSRS(LAS_header); /* print info or check projection if we are actually importing */ if (print_flag->answer) { /* print filename when there is more than one file */ if (infiles.num_items > 1) fprintf(stdout, "File: %s\n", infile); /* Print LAS header */ print_lasinfo(LAS_header, LAS_srs); } else { /* report that we are checking more files */ if (i == 1) G_message(_("First file's projection checked," " checking projection of the other files...")); /* Fetch input map projection in GRASS form. */ projstr = LASSRS_GetWKT_CompoundOK(LAS_srs); /* we are printing the non-warning messages only for first file */ projection_check_wkt(cellhd, loc_wind, projstr, over_flag->answer, shell_style->answer || i); /* if there is a problem in some other file, first OK message * is printed but than a warning, this is not ideal but hopefully * not so confusing when importing multiple files */ } if (scan_flag->answer || extents_flag->answer) { /* we assign to the first one (i==0) but update for the rest */ scan_bounds(LAS_reader, shell_style->answer, extents_flag->answer, i, zscale, ®ion); } /* number of estimated point across all files */ /* TODO: this should be ull which won't work with percent report */ estimated_lines += LASHeader_GetPointRecordsCount(LAS_header); /* We are closing all again and we will be opening them later, * so we don't have to worry about limit for open files. */ LASSRS_Destroy(LAS_srs); LASHeader_Destroy(LAS_header); LASReader_Destroy(LAS_reader); } /* if we are not importing, end */ if (print_flag->answer || scan_flag->answer) exit(EXIT_SUCCESS); return_filter = LAS_ALL; if (filter_opt->answer) { if (strcmp(filter_opt->answer, "first") == 0) return_filter = LAS_FIRST; else if (strcmp(filter_opt->answer, "last") == 0) return_filter = LAS_LAST; else if (strcmp(filter_opt->answer, "mid") == 0) return_filter = LAS_MID; else G_fatal_error(_("Unknown filter option <%s>"), filter_opt->answer); } struct ReturnFilter return_filter_struct; return_filter_struct.filter = return_filter; struct ClassFilter class_filter; class_filter_create_from_strings(&class_filter, class_opt->answers); percent = atoi(percent_opt->answer); /* TODO: we already used zscale */ /* TODO: we don't report intensity range */ if (zscale_opt->answer) zscale = atof(zscale_opt->answer); if (iscale_opt->answer) iscale = atof(iscale_opt->answer); /* parse zrange */ if (zrange_opt->answer != NULL) { if (zrange_opt->answers[0] == NULL) G_fatal_error(_("Invalid zrange")); sscanf(zrange_opt->answers[0], "%lf", &zrange_min); sscanf(zrange_opt->answers[1], "%lf", &zrange_max); if (zrange_min > zrange_max) { d_tmp = zrange_max; zrange_max = zrange_min; zrange_min = d_tmp; } } /* parse irange */ if (irange_opt->answer != NULL) { if (irange_opt->answers[0] == NULL) G_fatal_error(_("Invalid %s"), irange_opt->key); sscanf(irange_opt->answers[0], "%lf", &irange_min); sscanf(irange_opt->answers[1], "%lf", &irange_max); if (irange_min > irange_max) { d_tmp = irange_max; irange_max = irange_min; irange_min = d_tmp; } } point_binning_set(&point_binning, method_opt->answer, pth_opt->answer, trim_opt->answer, FALSE); base_array = NULL; if (strcmp("CELL", type_opt->answer) == 0) rtype = CELL_TYPE; else if (strcmp("DCELL", type_opt->answer) == 0) rtype = DCELL_TYPE; else rtype = FCELL_TYPE; if (point_binning.method == METHOD_N) rtype = CELL_TYPE; if (res_opt->answer) { /* align to resolution */ res = atof(res_opt->answer); if (!G_scan_resolution(res_opt->answer, &res, region.proj)) G_fatal_error(_("Invalid input <%s=%s>"), res_opt->key, res_opt->answer); if (res <= 0) G_fatal_error(_("Option '%s' must be > 0.0"), res_opt->key); region.ns_res = region.ew_res = res; region.north = ceil(region.north / res) * res; region.south = floor(region.south / res) * res; region.east = ceil(region.east / res) * res; region.west = floor(region.west / res) * res; G_adjust_Cell_head(®ion, 0, 0); } else if (extents_flag->answer) { /* align to current region */ Rast_align_window(®ion, &loc_wind); } Rast_set_output_window(®ion); rows = last_rows = region.rows; npasses = 1; if (percent < 100) { rows = (int)(region.rows * (percent / 100.0)); npasses = region.rows / rows; last_rows = region.rows - npasses * rows; if (last_rows) npasses++; else last_rows = rows; } cols = region.cols; G_debug(2, "region.n=%f region.s=%f region.ns_res=%f", region.north, region.south, region.ns_res); G_debug(2, "region.rows=%d [box_rows=%d] region.cols=%d", region.rows, rows, region.cols); /* using row-based chunks (used for output) when input and output * region matches and using segment library when they don't */ int use_segment = 0; int use_base_raster_res = 0; /* TODO: see if the input region extent is smaller than the raster * if yes, the we need to load the whole base raster if the -e * flag was defined (alternatively clip the regions) */ if (base_rast_res_flag->answer) use_base_raster_res = 1; if (base_raster_opt->answer && (res_opt->answer || use_base_raster_res || extents_flag->answer)) use_segment = 1; if (base_raster_opt->answer && !use_segment) { /* TODO: do we need to test existence first? mapset? */ base_raster = Rast_open_old(base_raster_opt->answer, ""); base_raster_data_type = Rast_get_map_type(base_raster); base_array = G_calloc((size_t)rows * (cols + 1), Rast_cell_size(base_raster_data_type)); } if (base_raster_opt->answer && use_segment) { if (use_base_raster_res) { /* read raster actual extent and resolution */ Rast_get_cellhd(base_raster_opt->answer, "", &input_region); /* TODO: make it only as small as the output is or points are */ Rast_set_input_window(&input_region); /* we have split window */ } else { Rast_get_input_window(&input_region); } rast_segment_open(&base_segment, base_raster_opt->answer, &base_raster_data_type); } if (!scan_flag->answer) { if (!check_rows_cols_fit_to_size_t(rows, cols)) G_fatal_error(_("Unable to process the hole map at once. " "Please set the '%s' option to some value lower than 100."), percent_opt->key); point_binning_memory_test(&point_binning, rows, cols, rtype); } /* open output map */ out_fd = Rast_open_new(outmap, rtype); /* allocate memory for a single row of output data */ raster_row = Rast_allocate_output_buf(rtype); G_message(_("Reading data ...")); count_total = line_total = 0; /* main binning loop(s) */ for (pass = 1; pass <= npasses; pass++) { if (npasses > 1) G_message(_("Pass #%d (of %d) ..."), pass, npasses); /* figure out segmentation */ row0 = (pass - 1) * rows; if (pass == npasses) { rows = last_rows; } if (base_array) { G_debug(2, "filling base raster array"); for (row = 0; row < rows; row++) { Rast_get_row(base_raster, base_array + ((size_t) row * cols * Rast_cell_size(base_raster_data_type)), row, base_raster_data_type); } } G_debug(2, "pass=%d/%d rows=%d", pass, npasses, rows); point_binning_allocate(&point_binning, rows, cols, rtype); line = 0; count = 0; counter = 0; G_percent_reset(); /* loop of input files */ for (i = 0; i < infiles.num_items; i++) { infile = infiles.items[i]; /* we already know file is there, so just do basic checks */ LAS_reader = LASReader_Create(infile); if (LAS_reader == NULL) G_fatal_error(_("Unable to open file <%s>"), infile); while ((LAS_point = LASReader_GetNextPoint(LAS_reader)) != NULL) { line++; counter++; if (counter == 100000) { /* speed */ if (line < estimated_lines) G_percent(line, estimated_lines, 3); counter = 0; } /* We always count them and report because behavior * changed in between 7.0 and 7.2 from undefined (but skipping * invalid points) to filtering them out only when requested. */ if (!LASPoint_IsValid(LAS_point)) { n_invalid++; if (only_valid) continue; } x = LASPoint_GetX(LAS_point); y = LASPoint_GetY(LAS_point); if (intens_flag->answer) /* use intensity as z here to allow all filters (and * modifications) below to be applied for intensity */ z = LASPoint_GetIntensity(LAS_point); else z = LASPoint_GetZ(LAS_point); int return_n = LASPoint_GetReturnNumber(LAS_point); int n_returns = LASPoint_GetNumberOfReturns(LAS_point); if (return_filter_is_out(&return_filter_struct, return_n, n_returns)) { n_filtered++; continue; } point_class = (int) LASPoint_GetClassification(LAS_point); if (class_filter_is_out(&class_filter, point_class)) continue; if (y <= region.south || y > region.north) { continue; } if (x < region.west || x >= region.east) { continue; } /* find the bin in the current array box */ arr_row = (int)((region.north - y) / region.ns_res) - row0; if (arr_row < 0 || arr_row >= rows) continue; arr_col = (int)((x - region.west) / region.ew_res); z = z * zscale; if (base_array) { double base_z; if (row_array_get_value_row_col(base_array, arr_row, arr_col, cols, base_raster_data_type, &base_z)) z -= base_z; else continue; } else if (use_segment) { double base_z; if (rast_segment_get_value_xy(&base_segment, &input_region, base_raster_data_type, x, y, &base_z)) z -= base_z; else continue; } if (zrange_opt->answer) { if (z < zrange_min || z > zrange_max) { continue; } } if (intens_import_flag->answer || irange_opt->answer) { intensity = LASPoint_GetIntensity(LAS_point); intensity *= iscale; if (irange_opt->answer) { if (intensity < irange_min || intensity > irange_max) { continue; } } /* use intensity for statistics */ if (intens_import_flag->answer) z = intensity; } count++; /* G_debug(5, "x: %f, y: %f, z: %f", x, y, z); */ update_value(&point_binning, &bin_index_nodes, cols, arr_row, arr_col, rtype, x, y, z); } /* while !EOF of one input file */ /* close input LAS file */ LASReader_Destroy(LAS_reader); } /* end of loop for all input files files */ G_percent(1, 1, 1); /* flush */ G_debug(2, "pass %d finished, %lu coordinates in box", pass, count); count_total += count; line_total += line; /* calc stats and output */ G_message(_("Writing to map ...")); for (row = 0; row < rows; row++) { /* potentially vector writing can be independent on the binning */ write_values(&point_binning, &bin_index_nodes, raster_row, row, cols, rtype, NULL); /* write out line of raster data */ Rast_put_row(out_fd, raster_row, rtype); } /* free memory */ point_binning_free(&point_binning, &bin_index_nodes); } /* passes loop */ if (base_array) Rast_close(base_raster); if (use_segment) Segment_close(&base_segment); G_percent(1, 1, 1); /* flush */ G_free(raster_row); /* close raster file & write history */ Rast_close(out_fd); sprintf(title, "Raw X,Y,Z data binned into a raster grid by cell %s", method_opt->answer); Rast_put_cell_title(outmap, title); Rast_short_history(outmap, "raster", &history); Rast_command_history(&history); Rast_set_history(&history, HIST_DATSRC_1, infile); Rast_write_history(outmap, &history); /* set computation region to the new raster map */ /* TODO: should be in the done message */ if (set_region_flag->answer) G_put_window(®ion); if (n_invalid && only_valid) G_message(_("%lu input points were invalid and filtered out"), n_invalid); if (n_invalid && !only_valid) G_message(_("%lu input points were invalid, use -%c flag to filter" " them out"), n_invalid, only_valid_flag->key); if (infiles.num_items > 1) { sprintf(buff, _("Raster map <%s> created." " %lu points from %d files found in region."), outmap, count_total, infiles.num_items); } else { sprintf(buff, _("Raster map <%s> created." " %lu points found in region."), outmap, count_total); } G_done_msg("%s", buff); G_debug(1, "Processed %lu points.", line_total); string_list_free(&infiles); exit(EXIT_SUCCESS); }
int main(int argc, char *argv[]) { struct Cell_head cellhd; /* buffer for in out raster */ DCELL *inrast_T, *inrast_RH, *inrast_u2; DCELL *inrast_Rn, *inrast_DEM, *inrast_hc, *outrast; char *EPo; int nrows, ncols; int row, col; int infd_T, infd_RH, infd_u2, infd_Rn, infd_DEM, infd_hc; int outfd; char *T, *RH, *u2, *Rn, *DEM, *hc; DCELL d_T, d_RH, d_u2, d_Rn, d_Z, d_hc; DCELL d_EPo; int d_night; struct History history; struct GModule *module; struct Option *input_DEM, *input_T, *input_RH; struct Option *input_u2, *input_Rn, *input_hc, *output; struct Flag *day, *zero; G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("imagery")); G_add_keyword(_("evapotranspiration")); module->description = _("Computes potential evapotranspiration calculation with hourly Penman-Monteith."); /* Define different options */ input_DEM = G_define_standard_option(G_OPT_R_ELEV); input_DEM->description = _("Name of input elevation raster map [m a.s.l.]"); input_T = G_define_standard_option(G_OPT_R_INPUT); input_T->key = "temperature"; input_T->description = _("Name of input temperature raster map [C]"); input_RH = G_define_standard_option(G_OPT_R_INPUT); input_RH->key = "relativehumidity"; input_RH->description = _("Name of input relative humidity raster map [%]"); input_u2 = G_define_standard_option(G_OPT_R_INPUT); input_u2->key = "windspeed"; input_u2->description = _("Name of input wind speed raster map [m/s]"); input_Rn = G_define_standard_option(G_OPT_R_INPUT); input_Rn->key = "netradiation"; input_Rn->description = _("Name of input net solar radiation raster map [MJ/m2/h]"); input_hc = G_define_standard_option(G_OPT_R_INPUT); input_hc->key = "cropheight"; input_hc->description = _("Name of input crop height raster map [m]"); output = G_define_standard_option(G_OPT_R_OUTPUT); _("Name for output raster map [mm/h]"); zero = G_define_flag(); zero->key = 'z'; zero->description = _("Set negative evapotranspiration to zero"); day = G_define_flag(); day->key = 'n'; day->description = _("Use Night-time"); if (G_parser(argc, argv)) exit(EXIT_FAILURE); /* get entered parameters */ T = input_T->answer; RH = input_RH->answer; u2 = input_u2->answer; Rn = input_Rn->answer; EPo = output->answer; DEM = input_DEM->answer; hc = input_hc->answer; if (day->answer) { d_night = TRUE; } else { d_night = FALSE; } infd_T = Rast_open_old(T, ""); infd_RH = Rast_open_old(RH, ""); infd_u2 = Rast_open_old(u2, ""); infd_Rn = Rast_open_old(Rn, ""); infd_DEM = Rast_open_old(DEM, ""); infd_hc = Rast_open_old(hc, ""); Rast_get_cellhd(T, "", &cellhd); Rast_get_cellhd(RH, "", &cellhd); Rast_get_cellhd(u2, "", &cellhd); Rast_get_cellhd(Rn, "", &cellhd); Rast_get_cellhd(DEM, "", &cellhd); Rast_get_cellhd(hc, "", &cellhd); /* Allocate input buffer */ inrast_T = Rast_allocate_d_buf(); inrast_RH = Rast_allocate_d_buf(); inrast_u2 = Rast_allocate_d_buf(); inrast_Rn = Rast_allocate_d_buf(); inrast_DEM = Rast_allocate_d_buf(); inrast_hc = Rast_allocate_d_buf(); /* Allocate output buffer */ nrows = Rast_window_rows(); ncols = Rast_window_cols(); outrast = Rast_allocate_d_buf(); outfd = Rast_open_new(EPo, DCELL_TYPE); for (row = 0; row < nrows; row++) { /* read a line input maps into buffers */ Rast_get_d_row(infd_T, inrast_T, row); Rast_get_d_row(infd_RH, inrast_RH, row); Rast_get_d_row(infd_u2, inrast_u2, row); Rast_get_d_row(infd_Rn, inrast_Rn, row); Rast_get_d_row(infd_DEM, inrast_DEM, row); Rast_get_d_row(infd_hc, inrast_hc, row); /* read every cell in the line buffers */ for (col = 0; col < ncols; col++) { d_T = ((DCELL *) inrast_T)[col]; d_RH = ((DCELL *) inrast_RH)[col]; d_u2 = ((DCELL *) inrast_u2)[col]; d_Rn = ((DCELL *) inrast_Rn)[col]; d_Z = ((DCELL *) inrast_DEM)[col]; d_hc = ((DCELL *) inrast_hc)[col]; /* calculate evapotranspiration */ if (d_hc < 0) { /* calculate evaporation */ d_EPo = calc_openwaterETp(d_T, d_Z, d_u2, d_Rn, d_night, d_RH, d_hc); } else { /* calculate evapotranspiration */ d_EPo = calc_ETp(d_T, d_Z, d_u2, d_Rn, d_night, d_RH, d_hc); } if (zero->answer && d_EPo < 0) d_EPo = 0; ((DCELL *) outrast)[col] = d_EPo; } Rast_put_d_row(outfd, outrast); } G_free(inrast_T); G_free(inrast_RH); G_free(inrast_u2); G_free(inrast_Rn); G_free(inrast_DEM); G_free(inrast_hc); G_free(outrast); Rast_close(infd_T); Rast_close(infd_RH); Rast_close(infd_u2); Rast_close(infd_Rn); Rast_close(infd_DEM); Rast_close(infd_hc); Rast_close(outfd); /* add command line incantation to history file */ Rast_short_history(EPo, "raster", &history); Rast_command_history(&history); Rast_write_history(EPo, &history); exit(EXIT_SUCCESS); }
int main(int argc, char *argv[]) { int r, c; DCELL con1, con2; double d1, d2; DCELL *alt_row; const char *con_name, *alt_name; int file_fd; DCELL value; struct History history; struct GModule *module; struct Option *opt1, *opt2; G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("raster")); G_add_keyword(_("surface")); G_add_keyword(_("interpolation")); module->description = _("Generates surface raster map from rasterized contours."); opt1 = G_define_standard_option(G_OPT_R_INPUT); opt1->description = _("Name of input raster map containing contours"); opt2 = G_define_standard_option(G_OPT_R_OUTPUT); if (G_parser(argc, argv)) exit(EXIT_FAILURE); con_name = opt1->answer; alt_name = opt2->answer; nrows = Rast_window_rows(); ncols = Rast_window_cols(); i_val_l_f = nrows + ncols; con = read_cell(con_name); alt_row = (DCELL *) G_malloc(ncols * sizeof(DCELL)); seen = flag_create(nrows, ncols); mask = flag_create(nrows, ncols); if (NULL != G_find_file("cell", "MASK", G_mapset())) { file_fd = Rast_open_old("MASK", G_mapset()); for (r = 0; r < nrows; r++) { Rast_get_d_row_nomask(file_fd, alt_row, r); for (c = 0; c < ncols; c++) if (Rast_is_d_null_value(&(alt_row[c])) || alt_row[c] == 0) FLAG_SET(mask, r, c); } Rast_close(file_fd); } zero = (NODE *) G_malloc(INIT_AR * sizeof(NODE)); minc = minr = 0; maxc = ncols - 1; maxr = nrows - 1; array_size = INIT_AR; file_fd = Rast_open_new(alt_name, DCELL_TYPE); for (r = 0; r < nrows; r++) { G_percent(r, nrows, 1); Rast_set_d_null_value(alt_row, ncols); for (c = 0; c < ncols; c++) { if (FLAG_GET(mask, r, c)) continue; value = con[r][c]; if (!Rast_is_d_null_value(&value)) { alt_row[c] = value; continue; } find_con(r, c, &d1, &d2, &con1, &con2); if (!Rast_is_d_null_value(&con2)) alt_row[c] = d2 * con1 / (d1 + d2) + d1 * con2 / (d1 + d2); else alt_row[c] = con1; } Rast_put_row(file_fd, alt_row, DCELL_TYPE); } G_percent(1, 1, 1); free_cell(con); flag_destroy(seen); flag_destroy(mask); Rast_close(file_fd); Rast_short_history(alt_name, "raster", &history); Rast_command_history(&history); Rast_write_history(alt_name, &history); exit(EXIT_SUCCESS); }
int main(int argc, char **argv) { unsigned char *hue_n, *hue_r, *hue_g, *hue_b; unsigned char *int_n, *int_r; unsigned char *sat_n, *sat_r; unsigned char *dummy; CELL *r_array, *g_array, *b_array; char *name_h, *name_i, *name_s; int intensity; int saturation; int atrow, atcol; int hue_file; int int_file = 0; int int_used; int sat_file = 0; int sat_used; char *name_r, *name_g, *name_b; int r_file = 0; int r_used; int g_file = 0; int g_used; int b_file = 0; int b_used; struct Cell_head window; struct Colors hue_colors; struct Colors int_colors; struct Colors sat_colors; struct Colors gray_colors; struct History history; struct GModule *module; struct Option *opt_h, *opt_i, *opt_s; struct Option *opt_r, *opt_g, *opt_b; struct Flag *nulldraw; G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("raster")); G_add_keyword(_("color transformation")); G_add_keyword(_("RGB")); G_add_keyword(_("HIS")); module->description = _("Generates red, green and blue raster map layers " "combining hue, intensity and saturation (HIS) " "values from user-specified input raster map layers."); opt_h = G_define_option(); opt_h->key = "h_map"; opt_h->type = TYPE_STRING; opt_h->required = YES; opt_h->gisprompt = "old,cell,raster"; opt_h->description = _("Name of layer to be used for HUE"); opt_i = G_define_option(); opt_i->key = "i_map"; opt_i->type = TYPE_STRING; opt_i->required = NO; opt_i->gisprompt = "old,cell,raster"; opt_i->description = _("Name of layer to be used for INTENSITY"); opt_s = G_define_option(); opt_s->key = "s_map"; opt_s->type = TYPE_STRING; opt_s->required = NO; opt_s->gisprompt = "old,cell,raster"; opt_s->description = _("Name of layer to be used for SATURATION"); opt_r = G_define_option(); opt_r->key = "r_map"; opt_r->type = TYPE_STRING; opt_r->required = YES; opt_r->gisprompt = "new,cell,raster"; opt_r->description = _("Name of output layer to be used for RED"); opt_g = G_define_option(); opt_g->key = "g_map"; opt_g->type = TYPE_STRING; opt_g->required = YES; opt_g->gisprompt = "new,cell,raster"; opt_g->description = _("Name of output layer to be used for GREEN"); opt_b = G_define_option(); opt_b->key = "b_map"; opt_b->type = TYPE_STRING; opt_b->required = YES; opt_b->gisprompt = "new,cell,raster"; opt_b->description = _("Name of output layer to be used for BLUE"); nulldraw = G_define_flag(); nulldraw->key = 'n'; nulldraw->description = _("Respect NULL values while drawing"); if (G_parser(argc, argv)) exit(EXIT_FAILURE); /* read in current window */ G_get_window(&window); /* Get name of layer to be used for hue */ name_h = opt_h->answer; /* Make sure map is available */ hue_file = Rast_open_old(name_h, ""); hue_r = G_malloc(window.cols); hue_g = G_malloc(window.cols); hue_b = G_malloc(window.cols); hue_n = G_malloc(window.cols); dummy = G_malloc(window.cols); /* Reading color lookup table */ if (Rast_read_colors(name_h, "", &hue_colors) == -1) G_fatal_error(_("Color file for <%s> not available"), name_h); int_used = 0; if (opt_i->answer != NULL) { /* Get name of layer to be used for intensity */ name_i = opt_i->answer; int_used = 1; /* Make sure map is available */ int_file = Rast_open_old(name_i, ""); int_r = G_malloc(window.cols); int_n = G_malloc(window.cols); /* Reading color lookup table */ if (Rast_read_colors(name_i, "", &int_colors) == -1) G_fatal_error(_("Color file for <%s> not available"), name_i); } sat_used = 0; if (opt_s->answer != NULL) { /* Get name of layer to be used for saturation */ name_s = opt_s->answer; sat_used = 1; /* Make sure map is available */ sat_file = Rast_open_old(name_s, ""); sat_r = G_malloc(window.cols); sat_n = G_malloc(window.cols); /* Reading color lookup table */ if (Rast_read_colors(name_s, "", &sat_colors) == -1) G_fatal_error(_("Color file for <%s> not available"), name_s); } r_used = 0; if (opt_r->answer != NULL) { name_r = opt_r->answer; r_file = Rast_open_c_new(name_r); r_used = 1; } g_used = 0; if (opt_g->answer != NULL) { name_g = opt_g->answer; g_file = Rast_open_c_new(name_g); g_used = 1; } b_used = 0; if (opt_b->answer != NULL) { name_b = opt_b->answer; b_file = Rast_open_c_new(name_b); b_used = 1; } r_array = Rast_allocate_c_buf(); g_array = Rast_allocate_c_buf(); b_array = Rast_allocate_c_buf(); /* Make color table */ make_gray_scale(&gray_colors); /* Now do the work */ intensity = 255; /* default is to not change intensity */ saturation = 255; /* default is to not change saturation */ for (atrow = 0; atrow < window.rows; atrow++) { G_percent(atrow, window.rows, 2); Rast_get_row_colors(hue_file, atrow, &hue_colors, hue_r, hue_g, hue_b, hue_n); if (int_used) Rast_get_row_colors(int_file, atrow, &int_colors, int_r, dummy, dummy, int_n); if (sat_used) Rast_get_row_colors(sat_file, atrow, &sat_colors, sat_r, dummy, dummy, sat_n); for (atcol = 0; atcol < window.cols; atcol++) { if (nulldraw->answer) { if (hue_n[atcol] || (int_used && int_n[atcol]) || (sat_used && sat_n[atcol])) { Rast_set_c_null_value(&r_array[atcol], 1); Rast_set_c_null_value(&g_array[atcol], 1); Rast_set_c_null_value(&b_array[atcol], 1); continue; } } if (int_used) intensity = int_r[atcol]; if (sat_used) saturation = sat_r[atcol]; HIS_to_RGB(hue_r[atcol], hue_g[atcol], hue_b[atcol], intensity, saturation, &r_array[atcol], &g_array[atcol], &b_array[atcol]); } if (r_used) Rast_put_row(r_file, r_array, CELL_TYPE); if (g_used) Rast_put_row(g_file, g_array, CELL_TYPE); if (b_used) Rast_put_row(b_file, b_array, CELL_TYPE); } G_percent(window.rows, window.rows, 5); /* Close the cell files */ Rast_close(hue_file); if (int_used) Rast_close(int_file); if (sat_used) Rast_close(sat_file); if (r_used) { Rast_close(r_file); Rast_write_colors(name_r, G_mapset(), &gray_colors); Rast_short_history(name_r, "raster", &history); Rast_command_history(&history); Rast_write_history(name_r, &history); Rast_put_cell_title(name_r, "Red extracted from HIS"); } if (g_used) { Rast_close(g_file); Rast_write_colors(name_g, G_mapset(), &gray_colors); Rast_short_history(name_g, "raster", &history); Rast_command_history(&history); Rast_write_history(name_g, &history); Rast_put_cell_title(name_g, "Green extracted from HIS"); } if (b_used) { Rast_close(b_file); Rast_write_colors(name_b, G_mapset(), &gray_colors); Rast_short_history(name_b, "raster", &history); Rast_command_history(&history); Rast_write_history(name_b, &history); Rast_put_cell_title(name_b, "Blue extracted from HIS"); } return EXIT_SUCCESS; }
int main(int argc, char *argv[]) { int fd, maskfd; CELL *mask; DCELL *dcell; struct GModule *module; struct History history; int row, col; int searchrow, searchcolumn, pointsfound; int *shortlistrows = NULL, *shortlistcolumns = NULL; long ncells = 0; double north, east; double dist; double sum1, sum2, interp_value; int n; double p; struct { struct Option *input, *npoints, *power, *output, *dfield, *col; } parm; struct { struct Flag *noindex; } flag; struct cell_list { int row, column; struct cell_list *next; }; struct cell_list **search_list = NULL, **search_list_start = NULL; int max_radius, radius; int searchallpoints = 0; char *tmpstr1, *tmpstr2; G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("vector")); G_add_keyword(_("surface")); G_add_keyword(_("interpolation")); G_add_keyword(_("IDW")); module->description = _("Provides surface interpolation from vector point data by Inverse " "Distance Squared Weighting."); parm.input = G_define_standard_option(G_OPT_V_INPUT); parm.dfield = G_define_standard_option(G_OPT_V_FIELD); parm.col = G_define_standard_option(G_OPT_DB_COLUMN); parm.col->required = NO; parm.col->label = _("Name of attribute column with values to interpolate"); parm.col->description = _("If not given and input is 2D vector map then category values are used. " "If input is 3D vector map then z-coordinates are used."); parm.col->guisection = _("Values"); parm.output = G_define_standard_option(G_OPT_R_OUTPUT); parm.npoints = G_define_option(); parm.npoints->key = "npoints"; parm.npoints->key_desc = "count"; parm.npoints->type = TYPE_INTEGER; parm.npoints->required = NO; parm.npoints->description = _("Number of interpolation points"); parm.npoints->answer = "12"; parm.npoints->guisection = _("Settings"); parm.power = G_define_option(); parm.power->key = "power"; parm.power->type = TYPE_DOUBLE; parm.power->answer = "2.0"; parm.power->label = _("Power parameter"); parm.power->description = _("Greater values assign greater influence to closer points"); parm.power->guisection = _("Settings"); flag.noindex = G_define_flag(); flag.noindex->key = 'n'; flag.noindex->label = _("Don't index points by raster cell"); flag.noindex->description = _("Slower but uses" " less memory and includes points from outside region" " in the interpolation"); flag.noindex->guisection = _("Settings"); if (G_parser(argc, argv)) exit(EXIT_FAILURE); if (sscanf(parm.npoints->answer, "%d", &search_points) != 1 || search_points < 1) G_fatal_error(_("Illegal number (%s) of interpolation points"), parm.npoints->answer); list = (struct list_Point *) G_calloc((size_t) search_points, sizeof(struct list_Point)); p = atof(parm.power->answer); /* get the window, dimension arrays */ G_get_window(&window); if (!flag.noindex->answer) { npoints_currcell = (long **)G_malloc(window.rows * sizeof(long *)); points = (struct Point ***)G_malloc(window.rows * sizeof(struct Point **)); for (row = 0; row < window.rows; row++) { npoints_currcell[row] = (long *)G_malloc(window.cols * sizeof(long)); points[row] = (struct Point **)G_malloc(window.cols * sizeof(struct Point *)); for (col = 0; col < window.cols; col++) { npoints_currcell[row][col] = 0; points[row][col] = NULL; } } } /* read the elevation points from the input sites file */ read_sites(parm.input->answer, parm.dfield->answer, parm.col->answer, flag.noindex->answer); if (npoints == 0) G_fatal_error(_("No points found")); nsearch = npoints < search_points ? npoints : search_points; if (!flag.noindex->answer) { /* Arbitrary point to switch between searching algorithms. Could do * with refinement PK */ if ((window.rows * window.cols) / npoints > 400) { /* Using old algorithm.... */ searchallpoints = 1; ncells = 0; /* Make an array to contain the row and column indices that have * sites in them; later will just search through all these. */ for (searchrow = 0; searchrow < window.rows; searchrow++) for (searchcolumn = 0; searchcolumn < window.cols; searchcolumn++) if (npoints_currcell[searchrow][searchcolumn] > 0) { shortlistrows = (int *)G_realloc(shortlistrows, (1 + ncells) * sizeof(int)); shortlistcolumns = (int *)G_realloc(shortlistcolumns, (1 + ncells) * sizeof(int)); shortlistrows[ncells] = searchrow; shortlistcolumns[ncells] = searchcolumn; ncells++; } } else { /* Fill look-up table of row and column offsets for * doing a circular region growing search looking for sites */ /* Use units of column width */ max_radius = (int)(0.5 + sqrt(window.cols * window.cols + (window.rows * window.ns_res / window.ew_res) * (window.rows * window.ns_res / window.ew_res))); search_list = (struct cell_list **)G_malloc(max_radius * sizeof(struct cell_list *)); search_list_start = (struct cell_list **)G_malloc(max_radius * sizeof(struct cell_list *)); for (radius = 0; radius < max_radius; radius++) search_list[radius] = NULL; for (row = 0; row < window.rows; row++) for (col = 0; col < window.cols; col++) { radius = (int)sqrt(col * col + (row * window.ns_res / window.ew_res) * (row * window.ns_res / window.ew_res)); if (search_list[radius] == NULL) search_list[radius] = search_list_start[radius] = G_malloc(sizeof(struct cell_list)); else search_list[radius] = search_list[radius]->next = G_malloc(sizeof(struct cell_list)); search_list[radius]->row = row; search_list[radius]->column = col; search_list[radius]->next = NULL; } } } /* allocate buffers, etc. */ dcell = Rast_allocate_d_buf(); if ((maskfd = Rast_maskfd()) >= 0) mask = Rast_allocate_c_buf(); else mask = NULL; fd = Rast_open_new(parm.output->answer, DCELL_TYPE); /* GTC Count of window rows */ G_asprintf(&tmpstr1, n_("%d row", "%d rows", window.rows), window.rows); /* GTC Count of window columns */ G_asprintf(&tmpstr2, n_("%d column", "%d columns", window.cols), window.cols); /* GTC First argument is map name, second - message about number of rows, third - columns. */ G_important_message(_("Interpolating raster map <%s> (%s, %s)..."), parm.output->answer, tmpstr1, tmpstr2); G_free(tmpstr1); G_free(tmpstr2); north = window.north + window.ns_res / 2.0; for (row = 0; row < window.rows; row++) { G_percent(row, window.rows, 1); if (mask) Rast_get_c_row(maskfd, mask, row); north -= window.ns_res; east = window.west - window.ew_res / 2.0; for (col = 0; col < window.cols; col++) { east += window.ew_res; /* don't interpolate outside of the mask */ if (mask && mask[col] == 0) { Rast_set_d_null_value(&dcell[col], 1); continue; } /* If current cell contains more than nsearch points just average * all the points in this cell and don't look in any others */ if (!(flag.noindex->answer) && npoints_currcell[row][col] >= nsearch) { sum1 = 0.0; for (i = 0; i < npoints_currcell[row][col]; i++) sum1 += points[row][col][i].z; interp_value = sum1 / npoints_currcell[row][col]; } else { if (flag.noindex->answer) calculate_distances_noindex(north, east); else { pointsfound = 0; i = 0; if (searchallpoints == 1) { /* If there aren't many sites just check them all to find * the nearest */ for (n = 0; n < ncells; n++) calculate_distances(shortlistrows[n], shortlistcolumns[n], north, east, &pointsfound); } else { radius = 0; while (pointsfound < nsearch) { /* Keep widening the search window until we find * enough points */ search_list[radius] = search_list_start[radius]; while (search_list[radius] != NULL) { /* Always */ if (row < (window.rows - search_list[radius]->row) && col < (window.cols - search_list[radius]->column)) { searchrow = row + search_list[radius]->row; searchcolumn = col + search_list[radius]->column; calculate_distances(searchrow, searchcolumn, north, east, &pointsfound); } /* Only if at least one offset is not 0 */ if ((search_list[radius]->row > 0 || search_list[radius]->column > 0) && row >= search_list[radius]->row && col >= search_list[radius]->column) { searchrow = row - search_list[radius]->row; searchcolumn = col - search_list[radius]->column; calculate_distances(searchrow, searchcolumn, north, east, &pointsfound); } /* Only if both offsets are not 0 */ if (search_list[radius]->row > 0 && search_list[radius]->column > 0) { if (row < (window.rows - search_list[radius]->row) && col >= search_list[radius]->column) { searchrow = row + search_list[radius]->row; searchcolumn = col - search_list[radius]->column; calculate_distances(searchrow, searchcolumn, north, east, &pointsfound); } if (row >= search_list[radius]->row && col < (window.cols - search_list[radius]->column)) { searchrow = row - search_list[radius]->row; searchcolumn = col + search_list[radius]->column; calculate_distances(searchrow, searchcolumn, north, east, &pointsfound); } } search_list[radius] = search_list[radius]->next; } radius++; } } } /* interpolate */ sum1 = 0.0; sum2 = 0.0; for (n = 0; n < nsearch; n++) { if ((dist = sqrt(list[n].dist))) { sum1 += list[n].z / pow(dist, p); sum2 += 1.0 / pow(dist, p); } else { /* If one site is dead on the centre of the cell, ignore * all the other sites and just use this value. * (Unlikely when using floating point numbers?) */ sum1 = list[n].z; sum2 = 1.0; break; } } interp_value = sum1 / sum2; } dcell[col] = (DCELL) interp_value; } Rast_put_d_row(fd, dcell); } G_percent(1, 1, 1); Rast_close(fd); /* writing history file */ Rast_short_history(parm.output->answer, "raster", &history); Rast_command_history(&history); Rast_write_history(parm.output->answer, &history); G_done_msg(" "); exit(EXIT_SUCCESS); }
int main(int argc, char *argv[]) { struct Cell_head cellhd; /*region+header info */ char *mapset; /*mapset name */ int nrows, ncols; int row, col; struct GModule *module; struct Option *input1, *input2, *input3, *input4, *input5; struct Option *input6, *input7, *input8, *input9, *output1; struct Flag *flag1; struct History history; /*metadata */ struct Colors colors; /*Color rules */ char *name; /*input raster name */ char *result; /*output raster name */ int infd_albedo, infd_ndvi, infd_tempk, infd_time, infd_dtair; int infd_emissivity, infd_tsw, infd_doy, infd_sunzangle; int outfd; char *albedo, *ndvi, *tempk, *time, *dtair, *emissivity; char *tsw, *doy, *sunzangle; int i = 0, j = 0; void *inrast_albedo, *inrast_ndvi, *inrast_tempk, *inrast_rnet; void *inrast_time, *inrast_dtair, *inrast_emissivity, *inrast_tsw; void *inrast_doy, *inrast_sunzangle; DCELL * outrast; CELL val1,val2; /*For color range*/ G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("imagery")); G_add_keyword(_("energy balance")); G_add_keyword(_("net radiation")); G_add_keyword(_("SEBAL")); module->description = _("Net radiation approximation (Bastiaanssen, 1995)."); /* Define the different options */ input1 = G_define_standard_option(G_OPT_R_INPUT); input1->key = "albedo"; input1->description = _("Name of albedo raster map [0.0;1.0]"); input2 = G_define_standard_option(G_OPT_R_INPUT); input2->key = "ndvi"; input2->description = _("Name of NDVI raster map [-1.0;+1.0]"); input3 = G_define_standard_option(G_OPT_R_INPUT); input3->key = "temperature"; input3->description = _("Name of surface temperature raster map [K]"); input4 = G_define_standard_option(G_OPT_R_INPUT); input4->key = "localutctime"; input4->description = _("Name of time of satellite overpass raster map [local time in UTC]"); input5 = G_define_standard_option(G_OPT_R_INPUT); input5->key = "temperaturedifference2m"; input5->description = _("Name of the difference map of temperature from surface skin to about 2 m height [K]"); input6 = G_define_standard_option(G_OPT_R_INPUT); input6->key = "emissivity"; input6->description = _("Name of the emissivity map [-]"); input7 = G_define_standard_option(G_OPT_R_INPUT); input7->key = "transmissivity_singleway"; input7->description = _("Name of the single-way atmospheric transmissivitymap [-]"); input8 = G_define_standard_option(G_OPT_R_INPUT); input8->key = "dayofyear"; input8->description = _("Name of the Day Of Year (DOY) map [-]"); input9 = G_define_standard_option(G_OPT_R_INPUT); input9->key = "sunzenithangle"; input9->description = _("Name of the sun zenith angle map [degrees]"); output1 = G_define_standard_option(G_OPT_R_OUTPUT); output1->description = _("Name of the output net radiation layer"); /********************/ if (G_parser(argc, argv)) exit(EXIT_FAILURE); albedo = input1->answer; ndvi = input2->answer; tempk = input3->answer; time = input4->answer; dtair = input5->answer; emissivity = input6->answer; tsw = input7->answer; doy = input8->answer; sunzangle = input9->answer; result = output1->answer; /* Open access to image files and allocate row access memory */ infd_albedo = Rast_open_old(albedo, ""); inrast_albedo = Rast_allocate_d_buf(); infd_ndvi = Rast_open_old(ndvi, ""); inrast_ndvi = Rast_allocate_d_buf(); infd_tempk = Rast_open_old(tempk, ""); inrast_tempk = Rast_allocate_d_buf(); infd_dtair = Rast_open_old(dtair, ""); inrast_dtair = Rast_allocate_d_buf(); infd_time = Rast_open_old(time, ""); inrast_time = Rast_allocate_d_buf(); infd_emissivity = Rast_open_old(emissivity, ""); inrast_emissivity = Rast_allocate_d_buf(); infd_tsw = Rast_open_old(tsw, ""); inrast_tsw = Rast_allocate_d_buf(); infd_doy = Rast_open_old(doy, ""); inrast_doy = Rast_allocate_d_buf(); infd_sunzangle = Rast_open_old(sunzangle, ""); inrast_sunzangle = Rast_allocate_d_buf(); nrows = Rast_window_rows(); ncols = Rast_window_cols(); outfd = Rast_open_new(result, DCELL_TYPE); outrast = Rast_allocate_d_buf(); /* Process pixels */ for (row = 0; row < nrows; row++) { DCELL d; DCELL d_albedo; DCELL d_ndvi; DCELL d_tempk; DCELL d_dtair; DCELL d_time; DCELL d_emissivity; DCELL d_tsw; DCELL d_doy; DCELL d_sunzangle; /* Display row process percentage */ G_percent(row, nrows, 2); /* Load rows for each input image */ Rast_get_d_row(infd_albedo, inrast_albedo, row); Rast_get_d_row(infd_ndvi, inrast_ndvi, row); Rast_get_d_row(infd_tempk, inrast_tempk, row); Rast_get_d_row(infd_dtair, inrast_dtair, row); Rast_get_d_row(infd_time, inrast_time, row); Rast_get_d_row(infd_emissivity, inrast_emissivity, row); Rast_get_d_row(infd_tsw, inrast_tsw, row); Rast_get_d_row(infd_doy, inrast_doy, row); Rast_get_d_row(infd_sunzangle, inrast_sunzangle, row); /*process the data */ for (col = 0; col < ncols; col++) { d_albedo = (double)((DCELL *) inrast_albedo)[col]; d_ndvi = (double)((DCELL *) inrast_ndvi)[col]; d_tempk = (double)((DCELL *) inrast_tempk)[col]; d_dtair = (double)((DCELL *) inrast_dtair)[col]; d_time = (double)((DCELL *) inrast_time)[col]; d_emissivity = (double)((DCELL *) inrast_emissivity)[col]; d_tsw = (double)((DCELL *) inrast_tsw)[col]; d_doy = (double)((DCELL *) inrast_doy)[col]; d_sunzangle = (double)((DCELL *) inrast_sunzangle)[col]; /* process NULL Values */ if (Rast_is_d_null_value(&d_albedo) || Rast_is_d_null_value(&d_ndvi) || Rast_is_d_null_value(&d_tempk) || Rast_is_d_null_value(&d_dtair) || Rast_is_d_null_value(&d_time) || Rast_is_d_null_value(&d_emissivity) || Rast_is_d_null_value(&d_tsw) || Rast_is_d_null_value(&d_doy) || Rast_is_d_null_value(&d_sunzangle)) { Rast_set_d_null_value(&outrast[col], 1); } else { /************************************/ /* calculate the net radiation */ d = r_net(d_albedo, d_ndvi, d_tempk, d_dtair, d_emissivity, d_tsw, d_doy, d_time, d_sunzangle); outrast[col] = d; } } Rast_put_d_row(outfd, outrast); } G_free(inrast_albedo); G_free(inrast_ndvi); G_free(inrast_tempk); G_free(inrast_dtair); G_free(inrast_time); G_free(inrast_emissivity); G_free(inrast_tsw); G_free(inrast_doy); G_free(inrast_sunzangle); Rast_close(infd_albedo); Rast_close(infd_ndvi); Rast_close(infd_tempk); Rast_close(infd_dtair); Rast_close(infd_time); Rast_close(infd_emissivity); Rast_close(infd_tsw); Rast_close(infd_doy); Rast_close(infd_sunzangle); G_free(outrast); Rast_close(outfd); /* Colors in grey shade */ Rast_init_colors(&colors); val1=0; val2=900; Rast_add_c_color_rule(&val1, 0, 0, 0, &val2, 255, 255, 255, &colors); /* Metadata */ Rast_short_history(result, "raster", &history); Rast_command_history(&history); Rast_write_history(result, &history); exit(EXIT_SUCCESS); }
int main(int argc, char *argv[]) { /* buffer for input-output rasters */ void *inrast_TEMPKA, *inrast_PATM, *inrast_RNET, *inrast_G0; DCELL *outrast; /* pointers to input-output raster files */ int infd_TEMPKA, infd_PATM, infd_RNET, infd_G0; int outfd; /* names of input-output raster files */ char *RNET, *TEMPKA, *PATM, *G0; char *ETa; /* input-output cell values */ DCELL d_tempka, d_pt_patm, d_rnet, d_g0; DCELL d_pt_alpha, d_pt_delta, d_pt_ghamma, d_daily_et; /* region information and handler */ struct Cell_head cellhd; int nrows, ncols; int row, col; /* parser stuctures definition */ struct GModule *module; struct Option *input_RNET, *input_TEMPKA, *input_PATM, *input_G0, *input_PT; struct Option *output; struct Flag *zero; struct Colors color; struct History history; /* Initialize the GIS calls */ G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("imagery")); G_add_keyword(_("evapotranspiration")); module->description = _("Computes evapotranspiration calculation " "Priestley and Taylor formulation, 1972."); /* Define different options */ input_RNET = G_define_standard_option(G_OPT_R_INPUT); input_RNET->key = "net_radiation"; input_RNET->description = _("Name of input net radiation raster map [W/m2]"); input_G0 = G_define_standard_option(G_OPT_R_INPUT); input_G0->key = "soil_heatflux"; input_G0->description = _("Name of input soil heat flux raster map [W/m2]"); input_TEMPKA = G_define_standard_option(G_OPT_R_INPUT); input_TEMPKA->key = "air_temperature"; input_TEMPKA->description = _("Name of input air temperature raster map [K]"); input_PATM = G_define_standard_option(G_OPT_R_INPUT); input_PATM->key = "atmospheric_pressure"; input_PATM->description = _("Name of input atmospheric pressure raster map [millibars]"); input_PT = G_define_option(); input_PT->key = "priestley_taylor_coeff"; input_PT->type = TYPE_DOUBLE; input_PT->required = YES; input_PT->description = _("Priestley-Taylor coefficient"); input_PT->answer = "1.26"; output = G_define_standard_option(G_OPT_R_OUTPUT); output->description = _("Name of output evapotranspiration raster map [mm/d]"); /* Define the different flags */ zero = G_define_flag(); zero->key = 'z'; zero->description = _("Set negative ETa to zero"); if (G_parser(argc, argv)) exit(EXIT_FAILURE); /* get entered parameters */ RNET = input_RNET->answer; TEMPKA = input_TEMPKA->answer; PATM = input_PATM->answer; G0 = input_G0->answer; d_pt_alpha = atof(input_PT->answer); ETa = output->answer; /* open pointers to input raster files */ infd_RNET = Rast_open_old(RNET, ""); infd_TEMPKA = Rast_open_old(TEMPKA, ""); infd_PATM = Rast_open_old(PATM, ""); infd_G0 = Rast_open_old(G0, ""); /* read headers of raster files */ Rast_get_cellhd(RNET, "", &cellhd); Rast_get_cellhd(TEMPKA, "", &cellhd); Rast_get_cellhd(PATM, "", &cellhd); Rast_get_cellhd(G0, "", &cellhd); /* Allocate input buffer */ inrast_RNET = Rast_allocate_d_buf(); inrast_TEMPKA = Rast_allocate_d_buf(); inrast_PATM = Rast_allocate_d_buf(); inrast_G0 = Rast_allocate_d_buf(); /* get rows and columns number of the current region */ nrows = Rast_window_rows(); ncols = Rast_window_cols(); /* allocate output buffer */ outrast = Rast_allocate_d_buf(); /* open pointers to output raster files */ outfd = Rast_open_new(ETa, DCELL_TYPE); /* start the loop through cells */ for (row = 0; row < nrows; row++) { G_percent(row, nrows, 2); /* read input raster row into line buffer */ Rast_get_d_row(infd_RNET, inrast_RNET, row); Rast_get_d_row(infd_TEMPKA, inrast_TEMPKA, row); Rast_get_d_row(infd_PATM, inrast_PATM, row); Rast_get_d_row(infd_G0, inrast_G0, row); for (col = 0; col < ncols; col++) { /* read current cell from line buffer */ d_rnet = ((DCELL *) inrast_RNET)[col]; d_tempka = ((DCELL *) inrast_TEMPKA)[col]; d_pt_patm = ((DCELL *) inrast_PATM)[col]; d_g0 = ((DCELL *) inrast_G0)[col]; /*Delta_pt and Ghamma_pt */ d_pt_delta = pt_delta(d_tempka); d_pt_ghamma = pt_ghamma(d_tempka, d_pt_patm); /*Calculate ET */ d_daily_et = pt_daily_et(d_pt_alpha, d_pt_delta, d_pt_ghamma, d_rnet, d_g0, d_tempka); if (zero->answer && d_daily_et < 0) d_daily_et = 0.0; /* write calculated ETP to output line buffer */ outrast[col] = d_daily_et; } /* write output line buffer to output raster file */ Rast_put_d_row(outfd, outrast); } /* free buffers and close input maps */ G_free(inrast_RNET); G_free(inrast_TEMPKA); G_free(inrast_PATM); G_free(inrast_G0); Rast_close(infd_RNET); Rast_close(infd_TEMPKA); Rast_close(infd_PATM); Rast_close(infd_G0); /* generate color table between -20 and 20 */ Rast_make_rainbow_colors(&color, -20, 20); Rast_write_colors(ETa, G_mapset(), &color); Rast_short_history(ETa, "raster", &history); Rast_command_history(&history); Rast_write_history(ETa, &history); /* free buffers and close output map */ G_free(outrast); Rast_close(outfd); return (EXIT_SUCCESS); }
void Indep(void) { int Count, DRow, DCol; int Found, R, C; double RowDist, RowDistSq, ColDist; struct History history; G_debug(2, "indep()"); Count = 0; Found = 0; while (CellCount > 0) { G_debug(3, "(CellCount):%d", CellCount); G_debug(3, "(Count):%d", Count); DRow = DoNext[Count].R; DCol = DoNext[Count++].C; if (0 != FlagGet(Cells, DRow, DCol)) { /* FLAG_SET( Out, DRow, DCol); */ Out[DRow][DCol] = ++Found; for (R = DRow; R < Rs; R++) { RowDist = NS * (R - DRow); if (RowDist > MaxDistSq) { R = Rs; } else { RowDistSq = RowDist * RowDist; for (C = DCol; C < Cs; C++) { ColDist = EW * (C - DCol); G_debug(3, "(RowDistSq):%.12lf", RowDistSq); G_debug(3, "(ColDist):%.12lf", ColDist); G_debug(3, "(MaxDistSq):%.12lf", MaxDistSq); if (MaxDistSq >= RowDistSq + ColDist * ColDist) { if (0 != FlagGet(Cells, R, C)) { G_debug(2, "unset()"); FLAG_UNSET(Cells, R, C); CellCount--; } } else { C = Cs; } } } } G_debug(2, "it1()"); for (R = DRow - 1; R >= 0; R--) { RowDist = NS * (DRow - R); if (RowDist > MaxDistSq) { R = 0; } else { RowDistSq = RowDist * RowDist; for (C = DCol; C < Cs; C++) { ColDist = EW * (C - DCol); if (MaxDistSq >= RowDistSq + ColDist * ColDist) { if (0 != FlagGet(Cells, R, C)) { G_debug(2, "unset()"); FLAG_UNSET(Cells, R, C); CellCount--; } } else { C = Cs; } } } } G_debug(2, "it2()"); for (R = DRow; R < Rs; R++) { RowDist = NS * (R - DRow); if (RowDist > MaxDistSq) { R = Rs; } else { RowDistSq = RowDist * RowDist; for (C = DCol - 1; C >= 0; C--) { ColDist = EW * (DCol - C); if (MaxDistSq >= RowDistSq + ColDist * ColDist) { if (0 != FlagGet(Cells, R, C)) { G_debug(2, "unset()"); FLAG_UNSET(Cells, R, C); CellCount--; } } else { C = 0; } } } } G_debug(2, "it3()"); for (R = DRow - 1; R >= 0; R--) { RowDist = NS * (DRow - R); if (RowDist > MaxDistSq) { R = 0; } else { RowDistSq = RowDist * RowDist; for (C = DCol - 1; C >= 0; C--) { ColDist = EW * (DCol - C); if (MaxDistSq >= RowDistSq + ColDist * ColDist) { if (0 != FlagGet(Cells, R, C)) { G_debug(2, "unset()"); FLAG_UNSET(Cells, R, C); CellCount--; } } else { C = 0; } } } } } } G_debug(2, "outputting()"); OutFD = Rast_open_c_new(Output->answer); G_message(_("Writing raster map <%s>..."), Output->answer); for (R = 0; R < Rs; R++) { G_percent(R, Rs, 2); for (C = 0; C < Cs; C++) { CellBuffer[C] = Out[R][C]; } Rast_put_row(OutFD, CellBuffer, CELL_TYPE); } G_percent(1, 1, 1); Rast_close(OutFD); Rast_short_history(Output->answer, "raster", &history); Rast_command_history(&history); Rast_write_history(Output->answer, &history); }
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 GModule *module; struct { struct Option *rastin, *rastout, *method, *quantile; } parm; struct { struct Flag *nulls, *weight; } flag; struct History history; char title[64]; char buf_nsres[100], buf_ewres[100]; struct Colors colors; int row; G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("raster")); G_add_keyword(_("resample")); module->description = _("Resamples raster map layers to a coarser grid using aggregation."); parm.rastin = G_define_standard_option(G_OPT_R_INPUT); parm.rastout = G_define_standard_option(G_OPT_R_OUTPUT); parm.method = G_define_option(); parm.method->key = "method"; parm.method->type = TYPE_STRING; parm.method->required = NO; parm.method->description = _("Aggregation method"); parm.method->options = build_method_list(); parm.method->answer = "average"; parm.quantile = G_define_option(); parm.quantile->key = "quantile"; parm.quantile->type = TYPE_DOUBLE; parm.quantile->required = NO; parm.quantile->description = _("Quantile to calculate for method=quantile"); parm.quantile->options = "0.0-1.0"; parm.quantile->answer = "0.5"; flag.nulls = G_define_flag(); flag.nulls->key = 'n'; flag.nulls->description = _("Propagate NULLs"); flag.weight = G_define_flag(); flag.weight->key = 'w'; flag.weight->description = _("Weight according to area (slower)"); if (G_parser(argc, argv)) exit(EXIT_FAILURE); nulls = flag.nulls->answer; method = find_method(parm.method->answer); if (method < 0) G_fatal_error(_("Unknown method <%s>"), parm.method->answer); if (menu[method].method == c_quant) { quantile = atoi(parm.quantile->answer); closure = &quantile; } G_get_set_window(&dst_w); /* set window to old map */ Rast_get_cellhd(parm.rastin->answer, "", &src_w); /* enlarge source window */ { int r0 = (int)floor(Rast_northing_to_row(dst_w.north, &src_w)); int r1 = (int)ceil(Rast_northing_to_row(dst_w.south, &src_w)); int c0 = (int)floor(Rast_easting_to_col(dst_w.west, &src_w)); int c1 = (int)ceil(Rast_easting_to_col(dst_w.east, &src_w)); src_w.south -= src_w.ns_res * (r1 - src_w.rows); src_w.north += src_w.ns_res * (-r0); src_w.west -= src_w.ew_res * (-c0); src_w.east += src_w.ew_res * (c1 - src_w.cols); src_w.rows = r1 - r0; src_w.cols = c1 - c0; } Rast_set_input_window(&src_w); Rast_set_output_window(&dst_w); row_scale = 2 + ceil(dst_w.ns_res / src_w.ns_res); col_scale = 2 + ceil(dst_w.ew_res / src_w.ew_res); /* allocate buffers for input rows */ bufs = G_malloc(row_scale * sizeof(DCELL *)); for (row = 0; row < row_scale; row++) bufs[row] = Rast_allocate_d_input_buf(); /* open old map */ infile = Rast_open_old(parm.rastin->answer, ""); /* allocate output buffer */ outbuf = Rast_allocate_d_output_buf(); /* open new map */ outfile = Rast_open_new(parm.rastout->answer, DCELL_TYPE); if (flag.weight->answer && menu[method].method_w) resamp_weighted(); else resamp_unweighted(); G_percent(dst_w.rows, dst_w.rows, 2); Rast_close(infile); Rast_close(outfile); /* record map metadata/history info */ sprintf(title, "Aggregate resample by %s", parm.method->answer); Rast_put_cell_title(parm.rastout->answer, title); Rast_short_history(parm.rastout->answer, "raster", &history); Rast_set_history(&history, HIST_DATSRC_1, parm.rastin->answer); G_format_resolution(src_w.ns_res, buf_nsres, src_w.proj); G_format_resolution(src_w.ew_res, buf_ewres, src_w.proj); Rast_format_history(&history, HIST_DATSRC_2, "Source map NS res: %s EW res: %s", buf_nsres, buf_ewres); Rast_command_history(&history); Rast_write_history(parm.rastout->answer, &history); /* copy color table from source map */ if (strcmp(parm.method->answer, "sum") != 0) { if (Rast_read_colors(parm.rastin->answer, "", &colors) < 0) G_fatal_error(_("Unable to read color table for %s"), parm.rastin->answer); Rast_mark_colors_as_fp(&colors); Rast_write_colors(parm.rastout->answer, G_mapset(), &colors); } return (EXIT_SUCCESS); }
int main(int argc, char *argv[]) { struct 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) { MELEMENT *rowlist; SHORT nrows, ncols; SHORT datarows; int npoints; struct GModule *module; struct History history; struct { struct Option *input, *output, *npoints; } parm; struct { struct Flag *e; } flag; int n, fd, maskfd; /* Initialize the GIS calls */ G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("raster")); G_add_keyword(_("surface")); G_add_keyword(_("interpolation")); G_add_keyword(_("IDW")); module->description = _("Surface interpolation utility for raster map."); parm.input = G_define_standard_option(G_OPT_R_INPUT); parm.output = G_define_standard_option(G_OPT_R_OUTPUT); parm.npoints = G_define_option(); parm.npoints->key = "npoints"; parm.npoints->type = TYPE_INTEGER; parm.npoints->required = NO; parm.npoints->description = _("Number of interpolation points"); parm.npoints->answer = "12"; flag.e = G_define_flag(); flag.e->key = 'e'; flag.e->description = _("Output is the interpolation error"); if (G_parser(argc, argv)) exit(EXIT_FAILURE); if (sscanf(parm.npoints->answer, "%d", &n) != 1 || n <= 0) G_fatal_error(_("Illegal value for '%s' (%s)"), parm.npoints->key, parm.npoints->answer); npoints = n; error_flag = flag.e->answer; input = parm.input->answer; output = parm.output->answer; /* Get database window parameters */ G_get_window(&window); /* find number of rows and columns in window */ nrows = Rast_window_rows(); ncols = Rast_window_cols(); /* create distance squared or latitude lookup tables */ /* initialize function pointers */ lookup_and_function_ptrs(nrows, ncols); /* allocate buffers for row i/o */ cell = Rast_allocate_c_buf(); if ((maskfd = Rast_maskfd()) >= 0 || error_flag) { /* apply mask to output */ if (error_flag) /* use input as mask when -e option chosen */ maskfd = Rast_open_old(input, ""); mask = Rast_allocate_c_buf(); } else mask = NULL; /* Open input cell layer for reading */ fd = Rast_open_old(input, ""); /* Store input data in array-indexed doubly-linked lists and close input file */ rowlist = row_lists(nrows, ncols, &datarows, &n, fd, cell); Rast_close(fd); if (npoints > n) npoints = n; /* open cell layer for writing output */ fd = Rast_open_c_new(output); /* call the interpolation function */ interpolate(rowlist, nrows, ncols, datarows, npoints, fd, maskfd); /* free allocated memory */ free_row_lists(rowlist, nrows); G_free(rowlook); G_free(collook); if (ll) free_dist_params(); Rast_close(fd); /* writing history file */ Rast_short_history(output, "raster", &history); Rast_command_history(&history); Rast_write_history(output, &history); G_done_msg(" "); exit(EXIT_SUCCESS); }
int main(int argc, char *argv[]) { char *input, *output; int convertNull; char nullValue[256]; int useTypeDefault, type, useCompressionDefault, doCompression; int usePrecisionDefault, precision, useDimensionDefault, tileX, tileY, tileZ; RASTER3D_Region region; FILE *fp; struct GModule *module; struct History history; map = NULL; G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("raster3d")); G_add_keyword(_("import")); G_add_keyword(_("voxel")); G_add_keyword(_("conversion")); G_add_keyword("ASCII"); module->description = _("Converts a 3D ASCII raster text file into a (binary) 3D raster map."); setParams(); Rast3d_set_standard3d_input_params(); if (G_parser(argc, argv)) exit(EXIT_FAILURE); getParams(&input, &output, &convertNull, nullValue); if (!Rast3d_get_standard3d_params(&useTypeDefault, &type, &useCompressionDefault, &doCompression, &usePrecisionDefault, &precision, &useDimensionDefault, &tileX, &tileY, &tileZ)) fatalError("Error getting standard parameters"); Rast3d_init_defaults(); fp = openAscii(input, ®ion); /*Open the new RASTER3D map */ map = Rast3d_open_new_param(output, RASTER3D_TILE_SAME_AS_FILE, RASTER3D_USE_CACHE_XY, ®ion, type, doCompression, precision, tileX, tileY, tileZ); if (map == NULL) fatalError(_("Unable to open 3D raster map")); /*Create the new RASTER3D Map */ asciiToG3d(fp, ®ion, convertNull, nullValue); if (!Rast3d_close(map)) fatalError(_("Unable to close 3D raster map")); /* write input name to map history */ Rast3d_read_history(output, G_mapset(), &history); Rast_command_history(&history); Rast_set_history(&history, HIST_DATSRC_1, input); Rast3d_write_history(output, &history); map = NULL; if (fclose(fp)) fatalError(_("Unable to close ASCII file")); return EXIT_SUCCESS; }
/*--------------------------------------------------------------------*/ int main(int argc, char *argv[]) { /* Variable declarations */ int nsply, nsplx, nrows, ncols, nsplx_adj, nsply_adj; int nsubregion_col, nsubregion_row, subregion_row, subregion_col; int subregion = 0, nsubregions = 0; int last_row, last_column, grid, bilin, ext, flag_auxiliar, cross; /* booleans */ double stepN, stepE, lambda, mean; double N_extension, E_extension, edgeE, edgeN; const char *mapset, *drv, *db, *vector, *map; char table_name[GNAME_MAX], title[64]; char xname[GNAME_MAX], xmapset[GMAPSET_MAX]; int dim_vect, nparameters, BW; int *lineVect; /* Vector restoring primitive's ID */ double *TN, *Q, *parVect; /* Interpolating and least-square vectors */ double **N, **obsVect; /* Interpolation and least-square matrix */ SEGMENT out_seg, mask_seg; const char *out_file, *mask_file; int out_fd, mask_fd; double seg_size; int seg_mb, segments_in_memory; int have_mask; /* Structs declarations */ int raster; struct Map_info In, In_ext, Out; struct History history; struct GModule *module; struct Option *in_opt, *in_ext_opt, *out_opt, *out_map_opt, *stepE_opt, *stepN_opt, *lambda_f_opt, *type_opt, *dfield_opt, *col_opt, *mask_opt, *memory_opt, *solver, *error, *iter; struct Flag *cross_corr_flag, *spline_step_flag; struct Reg_dimens dims; struct Cell_head elaboration_reg, original_reg; struct bound_box general_box, overlap_box, original_box; struct Point *observ; struct line_cats *Cats; dbCatValArray cvarr; int with_z; int nrec, ctype = 0; struct field_info *Fi; dbDriver *driver, *driver_cats; /*----------------------------------------------------------------*/ /* Options declarations */ module = G_define_module(); G_add_keyword(_("vector")); G_add_keyword(_("surface")); G_add_keyword(_("interpolation")); G_add_keyword(_("LIDAR")); module->description = _("Performs bicubic or bilinear spline interpolation with Tykhonov regularization."); cross_corr_flag = G_define_flag(); cross_corr_flag->key = 'c'; cross_corr_flag->description = _("Find the best Tykhonov regularizing parameter using a \"leave-one-out\" cross validation method"); spline_step_flag = G_define_flag(); spline_step_flag->key = 'e'; spline_step_flag->label = _("Estimate point density and distance"); spline_step_flag->description = _("Estimate point density and distance for the input vector points within the current region extends and quit"); in_opt = G_define_standard_option(G_OPT_V_INPUT); in_opt->label = _("Name of input vector point map"); dfield_opt = G_define_standard_option(G_OPT_V_FIELD); dfield_opt->guisection = _("Settings"); col_opt = G_define_standard_option(G_OPT_DB_COLUMN); col_opt->required = NO; col_opt->label = _("Name of the attribute column with values to be used for approximation"); col_opt->description = _("If not given and input is 3D vector map then z-coordinates are used."); col_opt->guisection = _("Settings"); in_ext_opt = G_define_standard_option(G_OPT_V_INPUT); in_ext_opt->key = "sparse_input"; in_ext_opt->required = NO; in_ext_opt->label = _("Name of input vector map with sparse points"); out_opt = G_define_standard_option(G_OPT_V_OUTPUT); out_opt->required = NO; out_opt->guisection = _("Outputs"); out_map_opt = G_define_standard_option(G_OPT_R_OUTPUT); out_map_opt->key = "raster_output"; out_map_opt->required = NO; out_map_opt->guisection = _("Outputs"); mask_opt = G_define_standard_option(G_OPT_R_INPUT); mask_opt->key = "mask"; mask_opt->label = _("Raster map to use for masking (applies to raster output only)"); mask_opt->description = _("Only cells that are not NULL and not zero are interpolated"); mask_opt->required = NO; stepE_opt = G_define_option(); stepE_opt->key = "ew_step"; stepE_opt->type = TYPE_DOUBLE; stepE_opt->required = NO; stepE_opt->answer = "4"; stepE_opt->description = _("Length of each spline step in the east-west direction"); stepE_opt->guisection = _("Settings"); stepN_opt = G_define_option(); stepN_opt->key = "ns_step"; stepN_opt->type = TYPE_DOUBLE; stepN_opt->required = NO; stepN_opt->answer = "4"; stepN_opt->description = _("Length of each spline step in the north-south direction"); stepN_opt->guisection = _("Settings"); type_opt = G_define_option(); type_opt->key = "method"; type_opt->description = _("Spline interpolation algorithm"); type_opt->type = TYPE_STRING; type_opt->options = "bilinear,bicubic"; type_opt->answer = "bilinear"; type_opt->guisection = _("Settings"); G_asprintf((char **) &(type_opt->descriptions), "bilinear;%s;bicubic;%s", _("Bilinear interpolation"), _("Bicubic interpolation")); lambda_f_opt = G_define_option(); lambda_f_opt->key = "lambda_i"; lambda_f_opt->type = TYPE_DOUBLE; lambda_f_opt->required = NO; lambda_f_opt->description = _("Tykhonov regularization parameter (affects smoothing)"); lambda_f_opt->answer = "0.01"; lambda_f_opt->guisection = _("Settings"); solver = N_define_standard_option(N_OPT_SOLVER_SYMM); solver->options = "cholesky,cg"; solver->answer = "cholesky"; iter = N_define_standard_option(N_OPT_MAX_ITERATIONS); error = N_define_standard_option(N_OPT_ITERATION_ERROR); memory_opt = G_define_option(); memory_opt->key = "memory"; memory_opt->type = TYPE_INTEGER; memory_opt->required = NO; memory_opt->answer = "300"; memory_opt->label = _("Maximum memory to be used (in MB)"); memory_opt->description = _("Cache size for raster rows"); /*----------------------------------------------------------------*/ /* Parsing */ G_gisinit(argv[0]); if (G_parser(argc, argv)) exit(EXIT_FAILURE); vector = out_opt->answer; map = out_map_opt->answer; if (vector && map) G_fatal_error(_("Choose either vector or raster output, not both")); if (!vector && !map && !cross_corr_flag->answer) G_fatal_error(_("No raster or vector or cross-validation output")); if (!strcmp(type_opt->answer, "linear")) bilin = P_BILINEAR; else bilin = P_BICUBIC; stepN = atof(stepN_opt->answer); stepE = atof(stepE_opt->answer); lambda = atof(lambda_f_opt->answer); flag_auxiliar = FALSE; drv = db_get_default_driver_name(); if (!drv) { if (db_set_default_connection() != DB_OK) G_fatal_error(_("Unable to set default DB connection")); drv = db_get_default_driver_name(); } db = db_get_default_database_name(); if (!db) G_fatal_error(_("No default DB defined")); /* Set auxiliary table's name */ if (vector) { if (G_name_is_fully_qualified(out_opt->answer, xname, xmapset)) { sprintf(table_name, "%s_aux", xname); } else sprintf(table_name, "%s_aux", out_opt->answer); } /* Something went wrong in a previous v.surf.bspline execution */ if (db_table_exists(drv, db, table_name)) { /* Start driver and open db */ driver = db_start_driver_open_database(drv, db); if (driver == NULL) G_fatal_error(_("No database connection for driver <%s> is defined. Run db.connect."), drv); db_set_error_handler_driver(driver); if (P_Drop_Aux_Table(driver, table_name) != DB_OK) G_fatal_error(_("Old auxiliary table could not be dropped")); db_close_database_shutdown_driver(driver); } /* Open input vector */ if ((mapset = G_find_vector2(in_opt->answer, "")) == NULL) G_fatal_error(_("Vector map <%s> not found"), in_opt->answer); Vect_set_open_level(1); /* WITHOUT TOPOLOGY */ if (1 > Vect_open_old(&In, in_opt->answer, mapset)) G_fatal_error(_("Unable to open vector map <%s> at the topological level"), in_opt->answer); bspline_field = 0; /* assume 3D input */ bspline_column = col_opt->answer; with_z = !bspline_column && Vect_is_3d(&In); if (Vect_is_3d(&In)) { if (!with_z) G_verbose_message(_("Input is 3D: using attribute values instead of z-coordinates for approximation")); else G_verbose_message(_("Input is 3D: using z-coordinates for approximation")); } else { /* 2D */ if (!bspline_column) G_fatal_error(_("Input vector map is 2D. Parameter <%s> required."), col_opt->key); } if (!with_z) { bspline_field = Vect_get_field_number(&In, dfield_opt->answer); } /* Estimate point density and mean distance for current region */ if (spline_step_flag->answer) { double dens, dist; if (P_estimate_splinestep(&In, &dens, &dist) == 0) { fprintf(stdout, _("Estimated point density: %.4g"), dens); fprintf(stdout, _("Estimated mean distance between points: %.4g"), dist); } else { fprintf(stdout, _("No points in current region")); } Vect_close(&In); exit(EXIT_SUCCESS); } /*----------------------------------------------------------------*/ /* Cross-correlation begins */ if (cross_corr_flag->answer) { G_debug(1, "CrossCorrelation()"); cross = cross_correlation(&In, stepE, stepN); if (cross != TRUE) G_fatal_error(_("Cross validation didn't finish correctly")); else { G_debug(1, "Cross validation finished correctly"); Vect_close(&In); G_done_msg(_("Cross validation finished for ew_step = %f and ns_step = %f"), stepE, stepN); exit(EXIT_SUCCESS); } } /* Open input ext vector */ ext = FALSE; if (in_ext_opt->answer) { ext = TRUE; G_message(_("Vector map <%s> of sparse points will be interpolated"), in_ext_opt->answer); if ((mapset = G_find_vector2(in_ext_opt->answer, "")) == NULL) G_fatal_error(_("Vector map <%s> not found"), in_ext_opt->answer); Vect_set_open_level(1); /* WITHOUT TOPOLOGY */ if (1 > Vect_open_old(&In_ext, in_ext_opt->answer, mapset)) G_fatal_error(_("Unable to open vector map <%s> at the topological level"), in_opt->answer); } /* Open output map */ /* vector output */ if (vector && !map) { if (strcmp(drv, "dbf") == 0) G_fatal_error(_("Sorry, the <%s> driver is not compatible with " "the vector output of this module. " "Try with raster output or another driver."), drv); Vect_check_input_output_name(in_opt->answer, out_opt->answer, G_FATAL_EXIT); grid = FALSE; if (0 > Vect_open_new(&Out, out_opt->answer, WITH_Z)) G_fatal_error(_("Unable to create vector map <%s>"), out_opt->answer); /* Copy vector Head File */ if (ext == FALSE) { Vect_copy_head_data(&In, &Out); Vect_hist_copy(&In, &Out); } else { Vect_copy_head_data(&In_ext, &Out); Vect_hist_copy(&In_ext, &Out); } Vect_hist_command(&Out); G_verbose_message(_("Points in input vector map <%s> will be interpolated"), vector); } /* read z values from attribute table */ if (bspline_field > 0) { G_message(_("Reading values from attribute table...")); db_CatValArray_init(&cvarr); Fi = Vect_get_field(&In, bspline_field); if (Fi == NULL) G_fatal_error(_("Cannot read layer info")); driver_cats = db_start_driver_open_database(Fi->driver, Fi->database); /*G_debug (0, _("driver=%s db=%s"), Fi->driver, Fi->database); */ if (driver_cats == NULL) G_fatal_error(_("Unable to open database <%s> by driver <%s>"), Fi->database, Fi->driver); db_set_error_handler_driver(driver_cats); nrec = db_select_CatValArray(driver_cats, Fi->table, Fi->key, col_opt->answer, NULL, &cvarr); G_debug(3, "nrec = %d", nrec); ctype = cvarr.ctype; if (ctype != DB_C_TYPE_INT && ctype != DB_C_TYPE_DOUBLE) G_fatal_error(_("Column type not supported")); if (nrec < 0) G_fatal_error(_("Unable to select data from table")); G_verbose_message(_("%d records selected from table"), nrec); db_close_database_shutdown_driver(driver_cats); } /*----------------------------------------------------------------*/ /* Interpolation begins */ G_debug(1, "Interpolation()"); /* Open driver and database */ driver = db_start_driver_open_database(drv, db); if (driver == NULL) G_fatal_error(_("No database connection for driver <%s> is defined. " "Run db.connect."), drv); db_set_error_handler_driver(driver); /* Create auxiliary table */ if (vector) { if ((flag_auxiliar = P_Create_Aux4_Table(driver, table_name)) == FALSE) { P_Drop_Aux_Table(driver, table_name); G_fatal_error(_("Interpolation: Creating table: " "It was impossible to create table <%s>."), table_name); } /* db_create_index2(driver, table_name, "ID"); */ /* sqlite likes that ??? */ db_close_database_shutdown_driver(driver); driver = db_start_driver_open_database(drv, db); } /* raster output */ raster = -1; Rast_set_fp_type(DCELL_TYPE); if (!vector && map) { grid = TRUE; raster = Rast_open_fp_new(out_map_opt->answer); G_verbose_message(_("Cells for raster map <%s> will be interpolated"), map); } /* Setting regions and boxes */ G_debug(1, "Interpolation: Setting regions and boxes"); G_get_window(&original_reg); G_get_window(&elaboration_reg); Vect_region_box(&original_reg, &original_box); Vect_region_box(&elaboration_reg, &overlap_box); Vect_region_box(&elaboration_reg, &general_box); nrows = Rast_window_rows(); ncols = Rast_window_cols(); /* Alloc raster matrix */ have_mask = 0; out_file = mask_file = NULL; out_fd = mask_fd = -1; if (grid == TRUE) { int row; DCELL *drastbuf; seg_mb = atoi(memory_opt->answer); if (seg_mb < 3) G_fatal_error(_("Memory in MB must be >= 3")); if (mask_opt->answer) seg_size = sizeof(double) + sizeof(char); else seg_size = sizeof(double); seg_size = (seg_size * SEGSIZE * SEGSIZE) / (1 << 20); segments_in_memory = seg_mb / seg_size + 0.5; G_debug(1, "%d %dx%d segments held in memory", segments_in_memory, SEGSIZE, SEGSIZE); out_file = G_tempfile(); out_fd = creat(out_file, 0666); if (Segment_format(out_fd, nrows, ncols, SEGSIZE, SEGSIZE, sizeof(double)) != 1) G_fatal_error(_("Can not create temporary file")); close(out_fd); out_fd = open(out_file, 2); if (Segment_init(&out_seg, out_fd, segments_in_memory) != 1) G_fatal_error(_("Can not initialize temporary file")); /* initialize output */ G_message(_("Initializing output...")); drastbuf = Rast_allocate_buf(DCELL_TYPE); Rast_set_d_null_value(drastbuf, ncols); for (row = 0; row < nrows; row++) { G_percent(row, nrows, 2); Segment_put_row(&out_seg, drastbuf, row); } G_percent(row, nrows, 2); if (mask_opt->answer) { int row, col, maskfd; DCELL dval, *drastbuf; char mask_val; G_message(_("Load masking map")); mask_file = G_tempfile(); mask_fd = creat(mask_file, 0666); if (Segment_format(mask_fd, nrows, ncols, SEGSIZE, SEGSIZE, sizeof(char)) != 1) G_fatal_error(_("Can not create temporary file")); close(mask_fd); mask_fd = open(mask_file, 2); if (Segment_init(&mask_seg, mask_fd, segments_in_memory) != 1) G_fatal_error(_("Can not initialize temporary file")); maskfd = Rast_open_old(mask_opt->answer, ""); drastbuf = Rast_allocate_buf(DCELL_TYPE); for (row = 0; row < nrows; row++) { G_percent(row, nrows, 2); Rast_get_d_row(maskfd, drastbuf, row); for (col = 0; col < ncols; col++) { dval = drastbuf[col]; if (Rast_is_d_null_value(&dval) || dval == 0) mask_val = 0; else mask_val = 1; Segment_put(&mask_seg, &mask_val, row, col); } } G_percent(row, nrows, 2); G_free(drastbuf); Rast_close(maskfd); have_mask = 1; } } /*------------------------------------------------------------------ | Subdividing and working with tiles: | Each original region will be divided into several subregions. | Each one will be overlaped by its neighbouring subregions. | The overlapping is calculated as a fixed OVERLAP_SIZE times | the largest spline step plus 2 * edge ----------------------------------------------------------------*/ /* Fixing parameters of the elaboration region */ P_zero_dim(&dims); /* Set dim struct to zero */ nsplx_adj = NSPLX_MAX; nsply_adj = NSPLY_MAX; if (stepN > stepE) dims.overlap = OVERLAP_SIZE * stepN; else dims.overlap = OVERLAP_SIZE * stepE; P_get_edge(bilin, &dims, stepE, stepN); P_set_dim(&dims, stepE, stepN, &nsplx_adj, &nsply_adj); G_verbose_message(_("Adjusted EW splines %d"), nsplx_adj); G_verbose_message(_("Adjusted NS splines %d"), nsply_adj); /* calculate number of subregions */ edgeE = dims.ew_size - dims.overlap - 2 * dims.edge_v; edgeN = dims.sn_size - dims.overlap - 2 * dims.edge_h; N_extension = original_reg.north - original_reg.south; E_extension = original_reg.east - original_reg.west; nsubregion_col = ceil(E_extension / edgeE) + 0.5; nsubregion_row = ceil(N_extension / edgeN) + 0.5; if (nsubregion_col < 0) nsubregion_col = 0; if (nsubregion_row < 0) nsubregion_row = 0; nsubregions = nsubregion_row * nsubregion_col; /* Creating line and categories structs */ Cats = Vect_new_cats_struct(); Vect_cat_set(Cats, 1, 0); subregion_row = 0; elaboration_reg.south = original_reg.north; last_row = FALSE; while (last_row == FALSE) { /* For each subregion row */ subregion_row++; P_set_regions(&elaboration_reg, &general_box, &overlap_box, dims, GENERAL_ROW); if (elaboration_reg.north > original_reg.north) { /* First row */ P_set_regions(&elaboration_reg, &general_box, &overlap_box, dims, FIRST_ROW); } if (elaboration_reg.south <= original_reg.south) { /* Last row */ P_set_regions(&elaboration_reg, &general_box, &overlap_box, dims, LAST_ROW); last_row = TRUE; } nsply = ceil((elaboration_reg.north - elaboration_reg.south) / stepN) + 0.5; G_debug(1, "Interpolation: nsply = %d", nsply); /* if (nsply > NSPLY_MAX) nsply = NSPLY_MAX; */ elaboration_reg.east = original_reg.west; last_column = FALSE; subregion_col = 0; /* TODO: process each subregion using its own thread (via OpenMP or pthreads) */ /* I'm not sure about pthreads, but you can tell OpenMP to start all at the same time and it will keep num_workers supplied with the next job as free cpus become available */ while (last_column == FALSE) { /* For each subregion column */ int npoints = 0; /* needed for sparse points interpolation */ int npoints_ext, *lineVect_ext = NULL; double **obsVect_ext; /*, mean_ext = .0; */ struct Point *observ_ext; subregion_col++; subregion++; if (nsubregions > 1) G_message(_("Processing subregion %d of %d..."), subregion, nsubregions); P_set_regions(&elaboration_reg, &general_box, &overlap_box, dims, GENERAL_COLUMN); if (elaboration_reg.west < original_reg.west) { /* First column */ P_set_regions(&elaboration_reg, &general_box, &overlap_box, dims, FIRST_COLUMN); } if (elaboration_reg.east >= original_reg.east) { /* Last column */ P_set_regions(&elaboration_reg, &general_box, &overlap_box, dims, LAST_COLUMN); last_column = TRUE; } nsplx = ceil((elaboration_reg.east - elaboration_reg.west) / stepE) + 0.5; G_debug(1, "Interpolation: nsplx = %d", nsplx); /* if (nsplx > NSPLX_MAX) nsplx = NSPLX_MAX; */ G_debug(1, "Interpolation: (%d,%d): subregion bounds", subregion_row, subregion_col); G_debug(1, "Interpolation: \t\tNORTH:%.2f\t", elaboration_reg.north); G_debug(1, "Interpolation: WEST:%.2f\t\tEAST:%.2f", elaboration_reg.west, elaboration_reg.east); G_debug(1, "Interpolation: \t\tSOUTH:%.2f", elaboration_reg.south); #ifdef DEBUG_SUBREGIONS fprintf(stdout, "B 5\n"); fprintf(stdout, " %.11g %.11g\n", elaboration_reg.east, elaboration_reg.north); fprintf(stdout, " %.11g %.11g\n", elaboration_reg.west, elaboration_reg.north); fprintf(stdout, " %.11g %.11g\n", elaboration_reg.west, elaboration_reg.south); fprintf(stdout, " %.11g %.11g\n", elaboration_reg.east, elaboration_reg.south); fprintf(stdout, " %.11g %.11g\n", elaboration_reg.east, elaboration_reg.north); fprintf(stdout, "C 1 1\n"); fprintf(stdout, " %.11g %.11g\n", (elaboration_reg.west + elaboration_reg.east) / 2, (elaboration_reg.south + elaboration_reg.north) / 2); fprintf(stdout, " 1 %d\n", subregion); #endif /* reading points in interpolation region */ dim_vect = nsplx * nsply; observ_ext = NULL; if (grid == FALSE && ext == TRUE) { observ_ext = P_Read_Vector_Region_Map(&In_ext, &elaboration_reg, &npoints_ext, dim_vect, 1); } else npoints_ext = 1; if (grid == TRUE && have_mask) { /* any unmasked cells in general region ? */ mean = 0; observ_ext = P_Read_Raster_Region_masked(&mask_seg, &original_reg, original_box, general_box, &npoints_ext, dim_vect, mean); } observ = NULL; if (npoints_ext > 0) { observ = P_Read_Vector_Region_Map(&In, &elaboration_reg, &npoints, dim_vect, bspline_field); } else npoints = 1; G_debug(1, "Interpolation: (%d,%d): Number of points in <elaboration_box> is %d", subregion_row, subregion_col, npoints); if (npoints > 0) G_verbose_message(_("%d points found in this subregion"), npoints); /* only interpolate if there are any points in current subregion */ if (npoints > 0 && npoints_ext > 0) { int i; nparameters = nsplx * nsply; BW = P_get_BandWidth(bilin, nsply); /* Least Squares system */ N = G_alloc_matrix(nparameters, BW); /* Normal matrix */ TN = G_alloc_vector(nparameters); /* vector */ parVect = G_alloc_vector(nparameters); /* Parameters vector */ obsVect = G_alloc_matrix(npoints, 3); /* Observation vector */ Q = G_alloc_vector(npoints); /* "a priori" var-cov matrix */ lineVect = G_alloc_ivector(npoints); /* */ for (i = 0; i < npoints; i++) { /* Setting obsVect vector & Q matrix */ double dval; Q[i] = 1; /* Q=I */ lineVect[i] = observ[i].lineID; obsVect[i][0] = observ[i].coordX; obsVect[i][1] = observ[i].coordY; /* read z coordinates from attribute table */ if (bspline_field > 0) { int cat, ival, ret; cat = observ[i].cat; if (cat < 0) continue; if (ctype == DB_C_TYPE_INT) { ret = db_CatValArray_get_value_int(&cvarr, cat, &ival); obsVect[i][2] = ival; observ[i].coordZ = ival; } else { /* DB_C_TYPE_DOUBLE */ ret = db_CatValArray_get_value_double(&cvarr, cat, &dval); obsVect[i][2] = dval; observ[i].coordZ = dval; } if (ret != DB_OK) { G_warning(_("Interpolation: (%d,%d): No record for point (cat = %d)"), subregion_row, subregion_col, cat); continue; } } /* use z coordinates of 3D vector */ else { obsVect[i][2] = observ[i].coordZ; } } /* Mean calculation for every point */ mean = P_Mean_Calc(&elaboration_reg, observ, npoints); G_debug(1, "Interpolation: (%d,%d): mean=%lf", subregion_row, subregion_col, mean); G_free(observ); for (i = 0; i < npoints; i++) obsVect[i][2] -= mean; /* Bilinear interpolation */ if (bilin) { G_debug(1, "Interpolation: (%d,%d): Bilinear interpolation...", subregion_row, subregion_col); normalDefBilin(N, TN, Q, obsVect, stepE, stepN, nsplx, nsply, elaboration_reg.west, elaboration_reg.south, npoints, nparameters, BW); nCorrectGrad(N, lambda, nsplx, nsply, stepE, stepN); } /* Bicubic interpolation */ else { G_debug(1, "Interpolation: (%d,%d): Bicubic interpolation...", subregion_row, subregion_col); normalDefBicubic(N, TN, Q, obsVect, stepE, stepN, nsplx, nsply, elaboration_reg.west, elaboration_reg.south, npoints, nparameters, BW); nCorrectGrad(N, lambda, nsplx, nsply, stepE, stepN); } if(G_strncasecmp(solver->answer, "cg", 2) == 0) G_math_solver_cg_sband(N, parVect, TN, nparameters, BW, atoi(iter->answer), atof(error->answer)); else G_math_solver_cholesky_sband(N, parVect, TN, nparameters, BW); G_free_matrix(N); G_free_vector(TN); G_free_vector(Q); if (grid == TRUE) { /* GRID INTERPOLATION ==> INTERPOLATION INTO A RASTER */ G_debug(1, "Interpolation: (%d,%d): Regular_Points...", subregion_row, subregion_col); if (!have_mask) { P_Regular_Points(&elaboration_reg, &original_reg, general_box, overlap_box, &out_seg, parVect, stepN, stepE, dims.overlap, mean, nsplx, nsply, nrows, ncols, bilin); } else { P_Sparse_Raster_Points(&out_seg, &elaboration_reg, &original_reg, general_box, overlap_box, observ_ext, parVect, stepE, stepN, dims.overlap, nsplx, nsply, npoints_ext, bilin, mean); } } else { /* OBSERVATION POINTS INTERPOLATION */ if (ext == FALSE) { G_debug(1, "Interpolation: (%d,%d): Sparse_Points...", subregion_row, subregion_col); P_Sparse_Points(&Out, &elaboration_reg, general_box, overlap_box, obsVect, parVect, lineVect, stepE, stepN, dims.overlap, nsplx, nsply, npoints, bilin, Cats, driver, mean, table_name); } else { /* FLAG_EXT == TRUE */ /* done that earlier */ /* int npoints_ext, *lineVect_ext = NULL; double **obsVect_ext; struct Point *observ_ext; observ_ext = P_Read_Vector_Region_Map(&In_ext, &elaboration_reg, &npoints_ext, dim_vect, 1); */ obsVect_ext = G_alloc_matrix(npoints_ext, 3); /* Observation vector_ext */ lineVect_ext = G_alloc_ivector(npoints_ext); for (i = 0; i < npoints_ext; i++) { /* Setting obsVect_ext vector & Q matrix */ obsVect_ext[i][0] = observ_ext[i].coordX; obsVect_ext[i][1] = observ_ext[i].coordY; obsVect_ext[i][2] = observ_ext[i].coordZ - mean; lineVect_ext[i] = observ_ext[i].lineID; } G_free(observ_ext); G_debug(1, "Interpolation: (%d,%d): Sparse_Points...", subregion_row, subregion_col); P_Sparse_Points(&Out, &elaboration_reg, general_box, overlap_box, obsVect_ext, parVect, lineVect_ext, stepE, stepN, dims.overlap, nsplx, nsply, npoints_ext, bilin, Cats, driver, mean, table_name); G_free_matrix(obsVect_ext); G_free_ivector(lineVect_ext); } /* END FLAG_EXT == TRUE */ } /* END GRID == FALSE */ G_free_vector(parVect); G_free_matrix(obsVect); G_free_ivector(lineVect); } else { if (observ) G_free(observ); if (observ_ext) G_free(observ_ext); if (npoints == 0) G_warning(_("No data within this subregion. " "Consider increasing spline step values.")); } } /*! END WHILE; last_column = TRUE */ } /*! END WHILE; last_row = TRUE */ G_verbose_message(_("Writing output...")); /* Writing the output raster map */ if (grid == TRUE) { int row, col; DCELL *drastbuf, dval; if (have_mask) { Segment_release(&mask_seg); /* release memory */ close(mask_fd); unlink(mask_file); } drastbuf = Rast_allocate_buf(DCELL_TYPE); for (row = 0; row < nrows; row++) { G_percent(row, nrows, 2); for (col = 0; col < ncols; col++) { Segment_get(&out_seg, &dval, row, col); drastbuf[col] = dval; } Rast_put_d_row(raster, drastbuf); } Rast_close(raster); Segment_release(&out_seg); /* release memory */ close(out_fd); unlink(out_file); /* set map title */ sprintf(title, "%s interpolation with Tykhonov regularization", type_opt->answer); Rast_put_cell_title(out_map_opt->answer, title); /* write map history */ Rast_short_history(out_map_opt->answer, "raster", &history); Rast_command_history(&history); Rast_write_history(out_map_opt->answer, &history); } /* Writing to the output vector map the points from the overlapping zones */ else if (flag_auxiliar == TRUE) { if (ext == FALSE) P_Aux_to_Vector(&In, &Out, driver, table_name); else P_Aux_to_Vector(&In_ext, &Out, driver, table_name); /* Drop auxiliary table */ G_debug(1, "%s: Dropping <%s>", argv[0], table_name); if (P_Drop_Aux_Table(driver, table_name) != DB_OK) G_fatal_error(_("Auxiliary table could not be dropped")); } db_close_database_shutdown_driver(driver); Vect_close(&In); if (ext != FALSE) Vect_close(&In_ext); if (vector) Vect_close(&Out); G_done_msg(" "); exit(EXIT_SUCCESS); } /*END MAIN */
int main(int argc, char *argv[]) { char *terrainmap, *seedmap, *lakemap; int rows, cols, in_terran_fd, out_fd, lake_fd, row, col, pases, pass; int lastcount, curcount, start_col = 0, start_row = 0; double east, north, area = 0, volume = 0; FCELL **in_terran, **out_water, water_level, max_depth = 0, min_depth = 0; FCELL water_window[3][3]; struct Option *tmap_opt, *smap_opt, *wlvl_opt, *lake_opt, *sdxy_opt; struct Flag *negative_flag, *overwrite_flag; struct GModule *module; struct Colors colr; struct Cell_head window; struct History history; G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("raster")); G_add_keyword(_("hydrology")); G_add_keyword(_("hazard")); G_add_keyword(_("flood")); module->description = _("Fills lake at given point to given level."); tmap_opt = G_define_standard_option(G_OPT_R_ELEV); wlvl_opt = G_define_option(); wlvl_opt->key = "water_level"; wlvl_opt->description = _("Water level"); wlvl_opt->type = TYPE_DOUBLE; wlvl_opt->required = YES; lake_opt = G_define_standard_option(G_OPT_R_OUTPUT); lake_opt->key = "lake"; lake_opt->required = NO; lake_opt->guisection = _("Output"); sdxy_opt = G_define_standard_option(G_OPT_M_COORDS); sdxy_opt->label = _("Seed point coordinates"); sdxy_opt->description = _("Either this coordinates pair or a seed" " map have to be specified"); sdxy_opt->required = NO; sdxy_opt->multiple = NO; sdxy_opt->guisection = _("Seed"); smap_opt = G_define_standard_option(G_OPT_R_MAP); smap_opt->key = "seed"; smap_opt->label = _("Input raster map with given starting point(s) (at least 1 cell > 0)"); smap_opt->description = _("Either this parameter or a coordinates pair have to be specified"); smap_opt->required = NO; smap_opt->guisection = _("Seed"); negative_flag = G_define_flag(); negative_flag->key = 'n'; negative_flag->description = _("Use negative depth values for lake raster map"); overwrite_flag = G_define_flag(); overwrite_flag->key = 'o'; overwrite_flag->description = _("Overwrite seed map with result (lake) map"); overwrite_flag->guisection = _("Output"); if (G_parser(argc, argv)) /* Returns 0 if successful, non-zero otherwise */ exit(EXIT_FAILURE); if (smap_opt->answer && sdxy_opt->answer) G_fatal_error(_("Both seed map and coordinates cannot be specified")); if (!smap_opt->answer && !sdxy_opt->answer) G_fatal_error(_("Seed map or seed coordinates must be set!")); if (sdxy_opt->answer && !lake_opt->answer) G_fatal_error(_("Seed coordinates and output map lake= must be set!")); if (lake_opt->answer && overwrite_flag->answer) G_fatal_error(_("Both lake and overwrite cannot be specified")); if (!lake_opt->answer && !overwrite_flag->answer) G_fatal_error(_("Output lake map or overwrite flag must be set!")); terrainmap = tmap_opt->answer; seedmap = smap_opt->answer; sscanf(wlvl_opt->answer, "%f", &water_level); lakemap = lake_opt->answer; /* If lakemap is set, write to it, else is set overwrite flag and we should write to seedmap. */ if (lakemap) lake_fd = Rast_open_new(lakemap, 1); rows = Rast_window_rows(); cols = Rast_window_cols(); /* If we use x,y as seed... */ if (sdxy_opt->answer) { G_get_window(&window); east = window.east; north = window.north; G_scan_easting(sdxy_opt->answers[0], &east, G_projection()); G_scan_northing(sdxy_opt->answers[1], &north, G_projection()); start_col = (int)Rast_easting_to_col(east, &window); start_row = (int)Rast_northing_to_row(north, &window); if (start_row < 0 || start_row > rows || start_col < 0 || start_col > cols) G_fatal_error(_("Seed point outside the current region")); } /* Open terrain map */ in_terran_fd = Rast_open_old(terrainmap, ""); /* Open seed map */ if (smap_opt->answer) out_fd = Rast_open_old(seedmap, ""); /* Pointers to rows. Row = ptr to 'col' size array. */ in_terran = (FCELL **) G_malloc(rows * sizeof(FCELL *)); out_water = (FCELL **) G_malloc(rows * sizeof(FCELL *)); if (in_terran == NULL || out_water == NULL) G_fatal_error(_("G_malloc: out of memory")); G_debug(1, "Loading maps..."); /* foo_rows[row] == array with data (2d array). */ for (row = 0; row < rows; row++) { in_terran[row] = (FCELL *) G_malloc(cols * sizeof(FCELL)); out_water[row] = (FCELL *) G_calloc(cols, sizeof(FCELL)); /* In newly created space load data from file. */ Rast_get_f_row(in_terran_fd, in_terran[row], row); if (smap_opt->answer) Rast_get_f_row(out_fd, out_water[row], row); G_percent(row + 1, rows, 5); } /* Set seed point */ if (sdxy_opt->answer) /* Check is water level higher than seed point */ if (in_terran[start_row][start_col] >= water_level) G_fatal_error(_("Given water level at seed point is below earth surface. " "Increase water level or move seed point.")); out_water[start_row][start_col] = 1; /* Close seed map for reading. */ if (smap_opt->answer) Rast_close(out_fd); /* Open output map for writing. */ if (lakemap) out_fd = lake_fd; else out_fd = Rast_open_new(seedmap, 1); /* More pases are renudant. Real pases count is controlled by altered cell count. */ pases = (int)(rows * cols) / 2; G_debug(1, "Starting lake filling at level of %8.4f in %d passes. Percent done:", water_level, pases); lastcount = 0; for (pass = 0; pass < pases; pass++) { G_debug(3, "Pass: %d", pass); curcount = 0; /* Move from left upper corner to right lower corner. */ for (row = 0; row < rows; row++) { for (col = 0; col < cols; col++) { /* Loading water data into window. */ load_window_values(out_water, water_window, rows, cols, row, col); /* Cheking presence of water. */ if (is_near_water(water_window) == 1) { if (in_terran[row][col] < water_level) { out_water[row][col] = water_level - in_terran[row][col]; curcount++; } else { out_water[row][col] = 0; /* Cell is higher than water level -> NULL. */ } } } } if (curcount == lastcount) break; /* We done. */ lastcount = curcount; curcount = 0; /* Move backwards - from lower right corner to upper left corner. */ for (row = rows - 1; row >= 0; row--) { for (col = cols - 1; col >= 0; col--) { load_window_values(out_water, water_window, rows, cols, row, col); if (is_near_water(water_window) == 1) { if (in_terran[row][col] < water_level) { out_water[row][col] = water_level - in_terran[row][col]; curcount++; } else { out_water[row][col] = 0; } } } } G_percent(pass + 1, pases, 10); if (curcount == lastcount) break; /* We done. */ lastcount = curcount; } /*pases */ G_percent(pases, pases, 10); /* Show 100%. */ save_map(out_water, out_fd, rows, cols, negative_flag->answer, &min_depth, &max_depth, &area, &volume); G_message(_("Lake depth from %f to %f (specified water level is taken as zero)"), min_depth, max_depth); G_message(_("Lake area %f square meters"), area); G_message(_("Lake volume %f cubic meters"), volume); G_important_message(_("Volume is correct only if lake depth (terrain raster map) is in meters")); /* Close all files. Lake map gets written only now. */ Rast_close(in_terran_fd); Rast_close(out_fd); /* Add blue color gradient from light bank to dark depth */ Rast_init_colors(&colr); if (negative_flag->answer == 1) { Rast_add_f_color_rule(&max_depth, 0, 240, 255, &min_depth, 0, 50, 170, &colr); } else { Rast_add_f_color_rule(&min_depth, 0, 240, 255, &max_depth, 0, 50, 170, &colr); } Rast_write_colors(lakemap, G_mapset(), &colr); Rast_short_history(lakemap, "raster", &history); Rast_command_history(&history); Rast_write_history(lakemap, &history); return EXIT_SUCCESS; }
/* ************************************************************************* */ 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[]) { struct Cell_head cellhd; /* buffer for in, tmp and out raster */ void *inrast_Rn, *inrast_g0; void *inrast_z0m, *inrast_t0dem; DCELL *outrast; int nrows, ncols; int row, col; int row_wet, col_wet; int row_dry, col_dry; double m_row_wet, m_col_wet; double m_row_dry, m_col_dry; int infd_Rn, infd_g0; int infd_z0m, infd_t0dem; int outfd; char *Rn, *g0; char *z0m, *t0dem; char *h0; double ustar, ea; struct History history; struct GModule *module; struct Option *input_Rn, *input_g0; struct Option *input_z0m, *input_t0dem, *input_ustar; struct Option *input_ea, *output; struct Option *input_row_wet, *input_col_wet; struct Option *input_row_dry, *input_col_dry; struct Flag *flag2, *flag3; /********************************/ double xp, yp; double xmin, ymin; double xmax, ymax; double stepx, stepy; double latitude, longitude; int rowDry, colDry, rowWet, colWet; /********************************/ G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("imagery")); G_add_keyword(_("energy balance")); G_add_keyword(_("soil moisture")); G_add_keyword(_("evaporative fraction")); G_add_keyword(_("SEBAL")); module->description = _("Computes sensible heat flux iteration SEBAL 01."); /* Define different options */ input_Rn = G_define_standard_option(G_OPT_R_INPUT); input_Rn->key = "netradiation"; input_Rn->description = _("Name of instantaneous Net Radiation raster map [W/m2]"); input_g0 = G_define_standard_option(G_OPT_R_INPUT); input_g0->key = "soilheatflux"; input_g0->description = _("Name of instantaneous soil heat flux raster map [W/m2]"); input_z0m = G_define_standard_option(G_OPT_R_INPUT); input_z0m->key = "aerodynresistance"; input_z0m->description = _("Name of aerodynamic resistance to heat momentum raster map [s/m]"); input_t0dem = G_define_standard_option(G_OPT_R_INPUT); input_t0dem->key = "temperaturemeansealevel"; input_t0dem->description = _("Name of altitude corrected surface temperature raster map [K]"); input_ustar = G_define_option(); input_ustar->key = "frictionvelocitystar"; input_ustar->type = TYPE_DOUBLE; input_ustar->required = YES; input_ustar->gisprompt = "old,value"; input_ustar->answer = "0.32407"; input_ustar->description = _("Value of the height independent friction velocity (u*) [m/s]"); input_ustar->guisection = _("Parameters"); input_ea = G_define_option(); input_ea->key = "vapourpressureactual"; input_ea->type = TYPE_DOUBLE; input_ea->required = YES; input_ea->answer = "1.511"; input_ea->description = _("Value of the actual vapour pressure (e_act) [KPa]"); input_ea->guisection = _("Parameters"); input_row_wet = G_define_option(); input_row_wet->key = "row_wet_pixel"; input_row_wet->type = TYPE_DOUBLE; input_row_wet->required = NO; input_row_wet->description = _("Row value of the wet pixel"); input_row_wet->guisection = _("Parameters"); input_col_wet = G_define_option(); input_col_wet->key = "column_wet_pixel"; input_col_wet->type = TYPE_DOUBLE; input_col_wet->required = NO; input_col_wet->description = _("Column value of the wet pixel"); input_col_wet->guisection = _("Parameters"); input_row_dry = G_define_option(); input_row_dry->key = "row_dry_pixel"; input_row_dry->type = TYPE_DOUBLE; input_row_dry->required = NO; input_row_dry->description = _("Row value of the dry pixel"); input_row_dry->guisection = _("Parameters"); input_col_dry = G_define_option(); input_col_dry->key = "column_dry_pixel"; input_col_dry->type = TYPE_DOUBLE; input_col_dry->required = NO; input_col_dry->description = _("Column value of the dry pixel"); input_col_dry->guisection = _("Parameters"); output = G_define_standard_option(G_OPT_R_OUTPUT); output->description = _("Name for output sensible heat flux raster map [W/m2]"); /* Define the different flags */ flag2 = G_define_flag(); flag2->key = 'a'; flag2->description = _("Automatic wet/dry pixel (careful!)"); flag3 = G_define_flag(); flag3->key = 'c'; flag3->description = _("Dry/Wet pixels coordinates are in image projection, not row/col"); if (G_parser(argc, argv)) exit(EXIT_FAILURE); /* get entered parameters */ Rn = input_Rn->answer; g0 = input_g0->answer; z0m = input_z0m->answer; t0dem = input_t0dem->answer; h0 = output->answer; ustar = atof(input_ustar->answer); ea = atof(input_ea->answer); if(input_row_wet->answer&& input_col_wet->answer&& input_row_dry->answer&& input_col_dry->answer){ m_row_wet = atof(input_row_wet->answer); m_col_wet = atof(input_col_wet->answer); m_row_dry = atof(input_row_dry->answer); m_col_dry = atof(input_col_dry->answer); } if ((!input_row_wet->answer || !input_col_wet->answer || !input_row_dry->answer || !input_col_dry->answer) && !flag2->answer) { G_fatal_error(_("Either auto-mode either wet/dry pixels coordinates should be provided!")); } if (flag3->answer) { G_message(_("Manual wet/dry pixels in image coordinates")); G_message(_("Wet Pixel=> x:%f y:%f"), m_col_wet, m_row_wet); G_message(_("Dry Pixel=> x:%f y:%f"), m_col_dry, m_row_dry); } else { if(flag2->answer) G_message(_("Automatic mode selected")); else { G_message(_("Wet Pixel=> row:%.0f col:%.0f"), m_row_wet, m_col_wet); G_message(_("Dry Pixel=> row:%.0f col:%.0f"), m_row_dry, m_col_dry); } } /* check legal output name */ if (G_legal_filename(h0) < 0) G_fatal_error(_("<%s> is an illegal name"), h0); infd_Rn = Rast_open_old(Rn, ""); infd_g0 = Rast_open_old(g0, ""); infd_z0m = Rast_open_old(z0m, ""); infd_t0dem = Rast_open_old(t0dem, ""); Rast_get_cellhd(Rn, "", &cellhd); Rast_get_cellhd(g0, "", &cellhd); Rast_get_cellhd(z0m, "", &cellhd); Rast_get_cellhd(t0dem, "", &cellhd); /* Allocate input buffer */ inrast_Rn = Rast_allocate_d_buf(); inrast_g0 = Rast_allocate_d_buf(); inrast_z0m = Rast_allocate_d_buf(); inrast_t0dem = Rast_allocate_d_buf(); /***************************************************/ /* Setup pixel location variables */ /***************************************************/ stepx = cellhd.ew_res; stepy = cellhd.ns_res; xmin = cellhd.west; xmax = cellhd.east; ymin = cellhd.south; ymax = cellhd.north; nrows = Rast_window_rows(); ncols = Rast_window_cols(); /***************************************************/ /* Allocate output buffer */ /***************************************************/ outrast = Rast_allocate_d_buf(); outfd = Rast_open_new(h0, DCELL_TYPE); /***************************************************/ /* Allocate memory for temporary images */ double **d_Roh, **d_Rah; if ((d_Roh = G_alloc_matrix(nrows, ncols)) == NULL) G_message("Unable to allocate memory for temporary d_Roh image"); if ((d_Rah = G_alloc_matrix(nrows, ncols)) == NULL) G_message("Unable to allocate memory for temporary d_Rah image"); /***************************************************/ /* MANUAL T0DEM WET/DRY PIXELS */ DCELL d_Rn_dry,d_g0_dry; DCELL d_t0dem_dry,d_t0dem_wet; if (flag2->answer) { /* Process tempk min / max pixels */ /* Internal use only */ DCELL d_Rn_wet,d_g0_wet; DCELL d_Rn,d_g0,d_h0; DCELL t0dem_min,t0dem_max; /*********************/ for (row = 0; row < nrows; row++) { DCELL d_t0dem; G_percent(row, nrows, 2); Rast_get_d_row(infd_t0dem,inrast_t0dem,row); Rast_get_d_row(infd_Rn,inrast_Rn,row); Rast_get_d_row(infd_g0,inrast_g0,row); /*process the data */ for (col = 0; col < ncols; col++) { d_t0dem = ((DCELL *) inrast_t0dem)[col]; d_Rn = ((DCELL *) inrast_Rn)[col]; d_g0 = ((DCELL *) inrast_g0)[col]; if (Rast_is_d_null_value(&d_t0dem) || Rast_is_d_null_value(&d_Rn) || Rast_is_d_null_value(&d_g0)) { /* do nothing */ } else { if (d_t0dem <= 250.0) { /* do nothing */ } else { d_h0 = d_Rn - d_g0; if (d_t0dem < t0dem_min && d_Rn > 0.0 && d_g0 > 0.0 && d_h0 > 0.0 && d_h0 < 100.0) { t0dem_min = d_t0dem; d_t0dem_wet = d_t0dem; d_Rn_wet = d_Rn; d_g0_wet = d_g0; m_col_wet = col; m_row_wet = row; } if (d_t0dem > t0dem_max && d_Rn > 0.0 && d_g0 > 0.0 && d_h0 > 100.0 && d_h0 < 500.0) { t0dem_max = d_t0dem; d_t0dem_dry = d_t0dem; d_Rn_dry = d_Rn; d_g0_dry = d_g0; m_col_dry = col; m_row_dry = row; } } } } } G_message("row_wet=%d\tcol_wet=%d", row_wet, col_wet); G_message("row_dry=%d\tcol_dry=%d", row_dry, col_dry); G_message("g0_wet=%f", d_g0_wet); G_message("Rn_wet=%f", d_Rn_wet); G_message("LE_wet=%f", d_Rn_wet - d_g0_wet); G_message("t0dem_dry=%f", d_t0dem_dry); G_message("rnet_dry=%f", d_Rn_dry); G_message("g0_dry=%f", d_g0_dry); G_message("h0_dry=%f", d_Rn_dry - d_g0_dry); }/* END OF FLAG2 */ G_message("Passed here"); /* MANUAL T0DEM WET/DRY PIXELS */ /*DRY PIXEL */ if (flag3->answer) { /*Calculate coordinates of row/col from projected ones */ row = (int)((ymax - m_row_dry) / (double)stepy); col = (int)((m_col_dry - xmin) / (double)stepx); G_message("Dry Pixel | row:%i col:%i", row, col); } else { row = (int)m_row_dry; col = (int)m_col_dry; G_message("Dry Pixel | row:%i col:%i", row, col); } rowDry = row; colDry = col; Rast_get_d_row(infd_Rn, inrast_Rn, row); Rast_get_d_row(infd_g0, inrast_g0, row); Rast_get_d_row(infd_t0dem, inrast_t0dem, row); d_Rn_dry = ((DCELL *) inrast_Rn)[col]; d_g0_dry = ((DCELL *) inrast_g0)[col]; d_t0dem_dry = ((DCELL *) inrast_t0dem)[col]; /*WET PIXEL */ if (flag3->answer) { /*Calculate coordinates of row/col from projected ones */ row = (int)((ymax - m_row_wet) / (double)stepy); col = (int)((m_col_wet - xmin) / (double)stepx); G_message("Wet Pixel | row:%i col:%i", row, col); } else { row = m_row_wet; col = m_col_wet; G_message("Wet Pixel | row:%i col:%i", row, col); } rowWet = row; colWet = col; Rast_get_d_row(infd_t0dem, inrast_t0dem, row); d_t0dem_wet = ((DCELL *) inrast_t0dem)[col]; /* END OF MANUAL WET/DRY PIXELS */ double h_dry; h_dry = d_Rn_dry - d_g0_dry; G_message("h_dry = %f", h_dry); G_message("t0dem_dry = %f", d_t0dem_dry); G_message("t0dem_wet = %f", d_t0dem_wet); DCELL d_rah_dry; DCELL d_roh_dry; /* INITIALIZATION */ for (row = 0; row < nrows; row++) { DCELL d_t0dem,d_z0m; DCELL d_rah1,d_roh1; DCELL d_u5; G_percent(row, nrows, 2); /* read a line input maps into buffers */ Rast_get_d_row(infd_z0m, inrast_z0m, row); Rast_get_d_row(infd_t0dem, inrast_t0dem,row); /* read every cell in the line buffers */ for (col = 0; col < ncols; col++) { d_z0m = ((DCELL *) inrast_z0m)[col]; d_t0dem = ((DCELL *) inrast_t0dem)[col]; if (Rast_is_d_null_value(&d_t0dem) || Rast_is_d_null_value(&d_z0m)) { /* do nothing */ d_Roh[row][col] = -999.9; d_Rah[row][col] = -999.9; } else { d_u5 = (ustar / 0.41) * log(5 / d_z0m); d_rah1=(1/(d_u5*pow(0.41,2)))*log(5/d_z0m)*log(5/(d_z0m*0.1)); d_roh1=((998-ea)/(d_t0dem*2.87))+(ea/(d_t0dem*4.61)); if (d_roh1 > 5) d_roh1 = 1.0; else d_roh1=((1000-4.65)/(d_t0dem*2.87))+(4.65/(d_t0dem*4.61)); if (row == rowDry && col == colDry) { /*collect dry pix info */ d_rah_dry = d_rah1; d_roh_dry = d_roh1; G_message("d_rah_dry=%f d_roh_dry=%f",d_rah_dry,d_roh_dry); } d_Roh[row][col] = d_roh1; d_Rah[row][col] = d_rah1; } } } DCELL d_dT_dry; /*Calculate dT_dry */ d_dT_dry = (h_dry * d_rah_dry) / (1004 * d_roh_dry); double a, b; /*Calculate coefficients for next dT equation */ /*a = 1.0/ ((d_dT_dry-0.0) / (d_t0dem_dry-d_t0dem_wet)); */ /*b = ( a * d_t0dem_wet ) * (-1.0); */ double sumx = d_t0dem_wet + d_t0dem_dry; double sumy = d_dT_dry + 0.0; double sumx2 = pow(d_t0dem_wet, 2) + pow(d_t0dem_dry, 2); double sumxy = (d_t0dem_wet * 0.0) + (d_t0dem_dry * d_dT_dry); a = (sumxy - ((sumx * sumy) / 2.0)) / (sumx2 - (pow(sumx, 2) / 2.0)); b = (sumy - (a * sumx)) / 2.0; G_message("d_dT_dry=%f", d_dT_dry); G_message("dT1=%f * t0dem + (%f)", a, b); DCELL d_h_dry; /* ITERATION 1 */ for (row = 0; row < nrows; row++) { DCELL d_t0dem,d_z0m; DCELL d_h1,d_rah1,d_rah2,d_roh1; DCELL d_L,d_x,d_psih,d_psim; DCELL d_u5; G_percent(row, nrows, 2); /* read a line input maps into buffers */ Rast_get_d_row(infd_z0m, inrast_z0m, row); Rast_get_d_row(infd_t0dem, inrast_t0dem,row); /* read every cell in the line buffers */ for (col = 0; col < ncols; col++) { d_z0m = ((DCELL *) inrast_z0m)[col]; d_t0dem = ((DCELL *) inrast_t0dem)[col]; d_rah1 = d_Rah[row][col]; d_roh1 = d_Roh[row][col]; if (Rast_is_d_null_value(&d_t0dem) || Rast_is_d_null_value(&d_z0m)) { /* do nothing */ } else { if (d_rah1 < 1.0) d_h1 = 0.0; else d_h1 = (1004 * d_roh1) * (a * d_t0dem + b) / d_rah1; d_L =-1004*d_roh1*pow(ustar,3)*d_t0dem/(d_h1*9.81*0.41); d_x = pow((1-16*(5/d_L)),0.25); d_psim =2*log((1+d_x)/2)+log((1+pow(d_x,2))/2)-2*atan(d_x)+0.5*M_PI; d_psih =2*log((1+pow(d_x,2))/2); d_u5 =(ustar/0.41)*log(5/d_z0m); d_rah2 = (1/(d_u5*pow(0.41,2)))*log((5/d_z0m)-d_psim) *log((5/(d_z0m*0.1))-d_psih); if (row == rowDry && col == colDry) {/*collect dry pix info */ d_rah_dry = d_rah2; d_h_dry = d_h1; } d_Rah[row][col] = d_rah1; } } } /*Calculate dT_dry */ d_dT_dry = (d_h_dry * d_rah_dry) / (1004 * d_roh_dry); /*Calculate coefficients for next dT equation */ /* a = (d_dT_dry-0)/(d_t0dem_dry-d_t0dem_wet); */ /* b = (-1.0) * ( a * d_t0dem_wet ); */ /* G_message("d_dT_dry=%f",d_dT_dry); */ /* G_message("dT2=%f * t0dem + (%f)", a, b); */ sumx = d_t0dem_wet + d_t0dem_dry; sumy = d_dT_dry + 0.0; sumx2 = pow(d_t0dem_wet, 2) + pow(d_t0dem_dry, 2); sumxy = (d_t0dem_wet * 0.0) + (d_t0dem_dry * d_dT_dry); a = (sumxy - ((sumx * sumy) / 2.0)) / (sumx2 - (pow(sumx, 2) / 2.0)); b = (sumy - (a * sumx)) / 2.0; G_message("d_dT_dry=%f", d_dT_dry); G_message("dT1=%f * t0dem + (%f)", a, b); /* ITERATION 2 */ /***************************************************/ /***************************************************/ for (row = 0; row < nrows; row++) { DCELL d_t0dem; DCELL d_z0m; DCELL d_rah2; DCELL d_rah3; DCELL d_roh1; DCELL d_h2; DCELL d_L; DCELL d_x; DCELL d_psih; DCELL d_psim; DCELL d_u5; G_percent(row, nrows, 2); /* read a line input maps into buffers */ Rast_get_d_row(infd_z0m,inrast_z0m,row); Rast_get_d_row(infd_t0dem,inrast_t0dem,row); /* read every cell in the line buffers */ for (col = 0; col < ncols; col++) { d_z0m = ((DCELL *) inrast_z0m)[col]; d_t0dem = ((DCELL *) inrast_t0dem)[col]; d_rah2 = d_Rah[row][col]; d_roh1 = d_Roh[row][col]; if (Rast_is_d_null_value(&d_t0dem) || Rast_is_d_null_value(&d_z0m)) { /* do nothing */ } else { if (d_rah2 < 1.0) { d_h2 = 0.0; } else { d_h2 =(1004*d_roh1)*(a*d_t0dem+b)/d_rah2; } d_L =-1004*d_roh1*pow(ustar,3)*d_t0dem/(d_h2*9.81*0.41); d_x = pow((1 - 16 * (5 / d_L)), 0.25); d_psim =2*log((1+d_x)/2)+log((1+pow(d_x,2))/2)- 2*atan(d_x)+0.5*M_PI; d_psih =2*log((1+pow(d_x,2))/2); d_u5 =(ustar/0.41)*log(5/d_z0m); d_rah3=(1/(d_u5*pow(0.41,2)))*log((5/d_z0m)-d_psim)* log((5/(d_z0m*0.1))-d_psih); if (row == rowDry && col == colDry) {/*collect dry pix info */ d_rah_dry = d_rah2; d_h_dry = d_h2; } d_Rah[row][col] = d_rah2; } } } /*Calculate dT_dry */ d_dT_dry = (d_h_dry * d_rah_dry) / (1004 * d_roh_dry); /*Calculate coefficients for next dT equation */ /* a = (d_dT_dry-0)/(d_t0dem_dry-d_t0dem_wet); */ /* b = (-1.0) * ( a * d_t0dem_wet ); */ /* G_message("d_dT_dry=%f",d_dT_dry); */ /* G_message("dT3=%f * t0dem + (%f)", a, b); */ sumx = d_t0dem_wet + d_t0dem_dry; sumy = d_dT_dry + 0.0; sumx2 = pow(d_t0dem_wet, 2) + pow(d_t0dem_dry, 2); sumxy = (d_t0dem_wet * 0.0) + (d_t0dem_dry * d_dT_dry); a = (sumxy - ((sumx * sumy) / 2.0)) / (sumx2 - (pow(sumx, 2) / 2.0)); b = (sumy - (a * sumx)) / 2.0; G_message("d_dT_dry=%f", d_dT_dry); G_message("dT1=%f * t0dem + (%f)", a, b); /* ITERATION 3 */ /***************************************************/ /***************************************************/ for (row = 0; row < nrows; row++) { DCELL d_t0dem; DCELL d_z0m; DCELL d_rah3; DCELL d_roh1; DCELL d_h3; DCELL d_L; DCELL d_x; DCELL d_psih; DCELL d_psim; DCELL d; /* Output pixel */ G_percent(row, nrows, 2); /* read a line input maps into buffers */ Rast_get_d_row(infd_z0m, inrast_z0m, row); Rast_get_d_row(infd_t0dem,inrast_t0dem,row); /* read every cell in the line buffers */ for (col = 0; col < ncols; col++) { d_z0m = ((DCELL *) inrast_z0m)[col]; d_t0dem = ((DCELL *) inrast_t0dem)[col]; d_rah3 = d_Rah[row][col]; d_roh1 = d_Roh[row][col]; if (Rast_is_d_null_value(&d_t0dem) || Rast_is_d_null_value(&d_z0m)) { Rast_set_d_null_value(&outrast[col], 1); } else { if (d_rah3 < 1.0) { d_h3 = 0.0; } else { d_h3 = (1004 * d_roh1) * (a * d_t0dem + b) / d_rah3; } if (d_h3 < 0 && d_h3 > -50) { d_h3 = 0.0; } if (d_h3 < -50 || d_h3 > 1000) { Rast_set_d_null_value(&outrast[col], 1); } outrast[col] = d_h3; } } Rast_put_d_row(outfd, outrast); } G_free(inrast_z0m); Rast_close(infd_z0m); G_free(inrast_t0dem); Rast_close(infd_t0dem); G_free(outrast); Rast_close(outfd); /* add command line incantation to history file */ Rast_short_history(h0, "raster", &history); Rast_command_history(&history); Rast_write_history(h0, &history); exit(EXIT_SUCCESS); }
int camera_angle(char *name) { int row, col, nrows, ncols; double XC = group.XC; double YC = group.YC; double ZC = group.ZC; double c_angle, c_angle_min, c_alt, c_az, slope, aspect; double radians_to_degrees = 180.0 / M_PI; /* double degrees_to_radians = M_PI / 180.0; */ DCELL e1, e2, e3, e4, e5, e6, e7, e8, e9; double factor, V, H, dx, dy, dz, key; double north, south, east, west, ns_med; FCELL *fbuf0, *fbuf1, *fbuf2, *tmpbuf, *outbuf; int elevfd, outfd; struct Cell_head cellhd; struct Colors colr; FCELL clr_min, clr_max; struct History hist; char *type; G_message(_("Calculating camera angle to local surface...")); select_target_env(); /* align target window to elevation map, otherwise we get artefacts * like in r.slope.aspect -a */ Rast_get_cellhd(elev_name, elev_mapset, &cellhd); Rast_align_window(&target_window, &cellhd); Rast_set_window(&target_window); elevfd = Rast_open_old(elev_name, elev_mapset); if (elevfd < 0) { G_fatal_error(_("Could not open elevation raster")); return 1; } nrows = target_window.rows; ncols = target_window.cols; outfd = Rast_open_new(name, FCELL_TYPE); fbuf0 = Rast_allocate_buf(FCELL_TYPE); fbuf1 = Rast_allocate_buf(FCELL_TYPE); fbuf2 = Rast_allocate_buf(FCELL_TYPE); outbuf = Rast_allocate_buf(FCELL_TYPE); /* give warning if location units are different from meters and zfactor=1 */ factor = G_database_units_to_meters_factor(); if (factor != 1.0) G_warning(_("Converting units to meters, factor=%.6f"), factor); G_begin_distance_calculations(); north = Rast_row_to_northing(0.5, &target_window); ns_med = Rast_row_to_northing(1.5, &target_window); south = Rast_row_to_northing(2.5, &target_window); east = Rast_col_to_easting(2.5, &target_window); west = Rast_col_to_easting(0.5, &target_window); V = G_distance(east, north, east, south) * 4; H = G_distance(east, ns_med, west, ns_med) * 4; c_angle_min = 90; Rast_get_row(elevfd, fbuf1, 0, FCELL_TYPE); Rast_get_row(elevfd, fbuf2, 1, FCELL_TYPE); for (row = 0; row < nrows; row++) { G_percent(row, nrows, 2); Rast_set_null_value(outbuf, ncols, FCELL_TYPE); /* first and last row */ if (row == 0 || row == nrows - 1) { Rast_put_row(outfd, outbuf, FCELL_TYPE); continue; } tmpbuf = fbuf0; fbuf0 = fbuf1; fbuf1 = fbuf2; fbuf2 = tmpbuf; Rast_get_row(elevfd, fbuf2, row + 1, FCELL_TYPE); north = Rast_row_to_northing(row + 0.5, &target_window); for (col = 1; col < ncols - 1; col++) { e1 = fbuf0[col - 1]; if (Rast_is_d_null_value(&e1)) continue; e2 = fbuf0[col]; if (Rast_is_d_null_value(&e2)) continue; e3 = fbuf0[col + 1]; if (Rast_is_d_null_value(&e3)) continue; e4 = fbuf1[col - 1]; if (Rast_is_d_null_value(&e4)) continue; e5 = fbuf1[col]; if (Rast_is_d_null_value(&e5)) continue; e6 = fbuf1[col + 1]; if (Rast_is_d_null_value(&e6)) continue; e7 = fbuf2[col - 1]; if (Rast_is_d_null_value(&e7)) continue; e8 = fbuf2[col]; if (Rast_is_d_null_value(&e8)) continue; e9 = fbuf2[col + 1]; if (Rast_is_d_null_value(&e9)) continue; dx = ((e1 + e4 + e4 + e7) - (e3 + e6 + e6 + e9)) / H; dy = ((e7 + e8 + e8 + e9) - (e1 + e2 + e2 + e3)) / V; /* compute topographic parameters */ key = dx * dx + dy * dy; /* slope in radians */ slope = atan(sqrt(key)); /* aspect in radians */ if (key == 0.) aspect = 0.; else if (dx == 0) { if (dy > 0) aspect = M_PI / 2; else aspect = 1.5 * M_PI; } else { aspect = atan2(dy, dx); if (aspect <= 0.) aspect = 2 * M_PI + aspect; } /* camera altitude angle in radians */ east = Rast_col_to_easting(col + 0.5, &target_window); dx = east - XC; dy = north - YC; dz = ZC - e5; c_alt = atan(sqrt(dx * dx + dy * dy) / dz); /* camera azimuth angle in radians */ c_az = atan(dy / dx); if (east < XC && north != YC) c_az += M_PI; else if (north < YC && east > XC) c_az += 2 * M_PI; /* camera angle to real ground */ /* orthogonal to ground: 90 degrees */ /* parallel to ground: 0 degrees */ c_angle = asin(cos(c_alt) * cos(slope) - sin(c_alt) * sin(slope) * cos(c_az - aspect)); outbuf[col] = c_angle * radians_to_degrees; if (c_angle_min > outbuf[col]) c_angle_min = outbuf[col]; } Rast_put_row(outfd, outbuf, FCELL_TYPE); } G_percent(row, nrows, 2); Rast_close(elevfd); Rast_close(outfd); G_free(fbuf0); G_free(fbuf1); G_free(fbuf2); G_free(outbuf); type = "raster"; Rast_short_history(name, type, &hist); Rast_command_history(&hist); Rast_write_history(name, &hist); Rast_init_colors(&colr); if (c_angle_min < 0) { clr_min = (FCELL)((int)(c_angle_min / 10 - 1)) * 10; clr_max = 0; Rast_add_f_color_rule(&clr_min, 0, 0, 0, &clr_max, 0, 0, 0, &colr); } clr_min = 0; clr_max = 10; Rast_add_f_color_rule(&clr_min, 0, 0, 0, &clr_max, 255, 0, 0, &colr); clr_min = 10; clr_max = 40; Rast_add_f_color_rule(&clr_min, 255, 0, 0, &clr_max, 255, 255, 0, &colr); clr_min = 40; clr_max = 90; Rast_add_f_color_rule(&clr_min, 255, 255, 0, &clr_max, 0, 255, 0, &colr); Rast_write_colors(name, G_mapset(), &colr); select_current_env(); return 1; }
int main(int argc, char *argv[]) { int nrows, ncols; int row, col; char *nameflag; /*Switch for particular method */ struct GModule *module; struct Option *input1, *input2, *output; struct History history; /*metadata */ /************************************/ char *result; /*output raster name */ int infd_annual_pmm; int outfd; char *annual_pmm; void *inrast_annual_pmm; DCELL * outrast; /************************************/ G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("raster")); G_add_keyword(_("hydrology")); G_add_keyword(_("rainfall")); G_add_keyword(_("erosion")); module->description = _("Computes USLE R factor, Rainfall erosivity index."); input2 = G_define_standard_option(G_OPT_R_INPUT); input2->description = _("Name of annual precipitation raster map [mm/year]"); output = G_define_standard_option(G_OPT_R_OUTPUT); output->description = _("Name for output USLE R raster map [MJ.mm/ha.hr.year]"); /* Define the different options */ input1 = G_define_option(); input1->key = "method"; input1->type = TYPE_STRING; input1->required = YES; input1->description = _("Name of USLE R equation"); input1->options = "roose, morgan, foster, elswaify"; input1->descriptions = _("roose;Roosle (1975);" "morgan;Morgan (1974);" "foster;Foster (1981);" "elswaify;El-Swaify (1985)"); input1->answer = "morgan"; /********************/ if (G_parser(argc, argv)) exit(EXIT_FAILURE); nameflag = input1->answer; annual_pmm = input2->answer; result = output->answer; /***************************************************/ infd_annual_pmm = Rast_open_old(annual_pmm, ""); inrast_annual_pmm = Rast_allocate_d_buf(); /***************************************************/ nrows = Rast_window_rows(); ncols = Rast_window_cols(); outrast = Rast_allocate_d_buf(); /* Create New raster files */ outfd = Rast_open_new(result, DCELL_TYPE); /* Process pixels */ for (row = 0; row < nrows; row++) { DCELL d; DCELL d_annual_pmm; G_percent(row, nrows, 2); /* read input map */ Rast_get_d_row(infd_annual_pmm, inrast_annual_pmm, row); /*process the data */ for (col = 0; col < ncols; col++) { d_annual_pmm = ((DCELL *) inrast_annual_pmm)[col]; if (Rast_is_d_null_value(&d_annual_pmm)) Rast_set_d_null_value(&outrast[col], 1); else { /*calculate morgan */ if (!strcmp(nameflag, "morgan")) d = morgan_1974(d_annual_pmm); /*calculate roose */ if (!strcmp(nameflag, "roose")) d = roose_1975(d_annual_pmm); /*calculate foster */ if (!strcmp(nameflag, "foster")) d = foster_1981(d_annual_pmm); /*calculate elswaify */ if (!strcmp(nameflag, "elswaify")) d = elswaify_1985(d_annual_pmm); outrast[col] = d ; } } Rast_put_d_row(outfd, outrast); } G_free(inrast_annual_pmm); Rast_close(infd_annual_pmm); G_free(outrast); Rast_close(outfd); Rast_short_history(result, "raster", &history); Rast_command_history(&history); Rast_write_history(result, &history); exit(EXIT_SUCCESS); }
int main(int argc, char **argv) { char *mapname, /* ptr to name of output layer */ *setname, /* ptr to name of input mapset */ *ipolname; /* name of interpolation method */ int fdi, /* input map file descriptor */ fdo, /* output map file descriptor */ method, /* position of method in table */ permissions, /* mapset permissions */ cell_type, /* output celltype */ cell_size, /* size of a cell in bytes */ row, col, /* counters */ irows, icols, /* original rows, cols */ orows, ocols, have_colors, /* Input map has a colour table */ overwrite, /* Overwrite */ curr_proj; /* output projection (see gis.h) */ void *obuffer, /* buffer that holds one output row */ *obufptr; /* column ptr in output buffer */ struct cache *ibuffer; /* buffer that holds the input map */ func interpolate; /* interpolation routine */ double xcoord1, xcoord2, /* temporary x coordinates */ ycoord1, ycoord2, /* temporary y coordinates */ col_idx, /* column index in input matrix */ row_idx, /* row index in input matrix */ onorth, osouth, /* save original border coords */ oeast, owest, inorth, isouth, ieast, iwest; char north_str[30], south_str[30], east_str[30], west_str[30]; struct Colors colr; /* Input map colour table */ struct History history; struct pj_info iproj, /* input map proj parameters */ oproj; /* output map proj parameters */ struct Key_Value *in_proj_info, /* projection information of */ *in_unit_info, /* input and output mapsets */ *out_proj_info, *out_unit_info; struct GModule *module; struct Flag *list, /* list files in source location */ *nocrop, /* don't crop output map */ *print_bounds, /* print output bounds and exit */ *gprint_bounds; /* same but print shell style */ struct Option *imapset, /* name of input mapset */ *inmap, /* name of input layer */ *inlocation, /* name of input location */ *outmap, /* name of output layer */ *indbase, /* name of input database */ *interpol, /* interpolation method: nearest neighbor, bilinear, cubic */ *memory, /* amount of memory for cache */ *res; /* resolution of target map */ struct Cell_head incellhd, /* cell header of input map */ outcellhd; /* and output map */ G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("raster")); G_add_keyword(_("projection")); G_add_keyword(_("transformation")); module->description = _("Re-projects a raster map from given location to the current location."); inmap = G_define_standard_option(G_OPT_R_INPUT); inmap->description = _("Name of input raster map to re-project"); inmap->required = NO; inmap->guisection = _("Source"); inlocation = G_define_option(); inlocation->key = "location"; inlocation->type = TYPE_STRING; inlocation->required = YES; inlocation->description = _("Location containing input raster map"); inlocation->gisprompt = "old,location,location"; inlocation->key_desc = "name"; imapset = G_define_standard_option(G_OPT_M_MAPSET); imapset->label = _("Mapset containing input raster map"); imapset->description = _("default: name of current mapset"); imapset->guisection = _("Source"); indbase = G_define_option(); indbase->key = "dbase"; indbase->type = TYPE_STRING; indbase->required = NO; indbase->description = _("Path to GRASS database of input location"); indbase->gisprompt = "old,dbase,dbase"; indbase->key_desc = "path"; indbase->guisection = _("Source"); outmap = G_define_standard_option(G_OPT_R_OUTPUT); outmap->required = NO; outmap->description = _("Name for output raster map (default: same as 'input')"); outmap->guisection = _("Target"); ipolname = make_ipol_list(); interpol = G_define_option(); interpol->key = "method"; interpol->type = TYPE_STRING; interpol->required = NO; interpol->answer = "nearest"; interpol->options = ipolname; interpol->description = _("Interpolation method to use"); interpol->guisection = _("Target"); interpol->descriptions = make_ipol_desc(); memory = G_define_option(); memory->key = "memory"; memory->type = TYPE_INTEGER; memory->required = NO; memory->description = _("Cache size (MiB)"); res = G_define_option(); res->key = "resolution"; res->type = TYPE_DOUBLE; res->required = NO; res->description = _("Resolution of output raster map"); res->guisection = _("Target"); list = G_define_flag(); list->key = 'l'; list->description = _("List raster maps in input location and exit"); nocrop = G_define_flag(); nocrop->key = 'n'; nocrop->description = _("Do not perform region cropping optimization"); print_bounds = G_define_flag(); print_bounds->key = 'p'; print_bounds->description = _("Print input map's bounds in the current projection and exit"); print_bounds->guisection = _("Target"); gprint_bounds = G_define_flag(); gprint_bounds->key = 'g'; gprint_bounds->description = _("Print input map's bounds in the current projection and exit (shell style)"); gprint_bounds->guisection = _("Target"); /* The parser checks if the map already exists in current mapset, we switch out the check and do it in the module after the parser */ overwrite = G_check_overwrite(argc, argv); if (G_parser(argc, argv)) exit(EXIT_FAILURE); /* get the method */ for (method = 0; (ipolname = menu[method].name); method++) if (strcmp(ipolname, interpol->answer) == 0) break; if (!ipolname) G_fatal_error(_("<%s=%s> unknown %s"), interpol->key, interpol->answer, interpol->key); interpolate = menu[method].method; mapname = outmap->answer ? outmap->answer : inmap->answer; if (mapname && !list->answer && !overwrite && G_find_raster(mapname, G_mapset())) G_fatal_error(_("option <%s>: <%s> exists."), "output", mapname); setname = imapset->answer ? imapset->answer : G_store(G_mapset()); if (strcmp(inlocation->answer, G_location()) == 0 && (!indbase->answer || strcmp(indbase->answer, G_gisdbase()) == 0)) #if 0 G_fatal_error(_("Input and output locations can not be the same")); #else G_warning(_("Input and output locations are the same")); #endif G_get_window(&outcellhd); if(gprint_bounds->answer && !print_bounds->answer) print_bounds->answer = gprint_bounds->answer; curr_proj = G_projection(); /* Get projection info for output mapset */ if ((out_proj_info = G_get_projinfo()) == NULL) G_fatal_error(_("Unable to get projection info of output raster map")); if ((out_unit_info = G_get_projunits()) == NULL) G_fatal_error(_("Unable to get projection units of output raster map")); if (pj_get_kv(&oproj, out_proj_info, out_unit_info) < 0) G_fatal_error(_("Unable to get projection key values of output raster map")); /* Change the location */ G__create_alt_env(); G__setenv("GISDBASE", indbase->answer ? indbase->answer : G_gisdbase()); G__setenv("LOCATION_NAME", inlocation->answer); permissions = G__mapset_permissions(setname); if (permissions < 0) /* can't access mapset */ G_fatal_error(_("Mapset <%s> in input location <%s> - %s"), setname, inlocation->answer, permissions == 0 ? _("permission denied") : _("not found")); /* if requested, list the raster maps in source location - MN 5/2001 */ if (list->answer) { int i; char **list; G_verbose_message(_("Checking location <%s> mapset <%s>"), inlocation->answer, setname); list = G_list(G_ELEMENT_RASTER, G__getenv("GISDBASE"), G__getenv("LOCATION_NAME"), setname); for (i = 0; list[i]; i++) { fprintf(stdout, "%s\n", list[i]); } fflush(stdout); exit(EXIT_SUCCESS); /* leave r.proj after listing */ } if (!inmap->answer) G_fatal_error(_("Required parameter <%s> not set"), inmap->key); if (!G_find_raster(inmap->answer, setname)) G_fatal_error(_("Raster map <%s> in location <%s> in mapset <%s> not found"), inmap->answer, inlocation->answer, setname); /* Read input map colour table */ have_colors = Rast_read_colors(inmap->answer, setname, &colr); /* Get projection info for input mapset */ if ((in_proj_info = G_get_projinfo()) == NULL) G_fatal_error(_("Unable to get projection info of input map")); if ((in_unit_info = G_get_projunits()) == NULL) G_fatal_error(_("Unable to get projection units of input map")); if (pj_get_kv(&iproj, in_proj_info, in_unit_info) < 0) G_fatal_error(_("Unable to get projection key values of input map")); G_free_key_value(in_proj_info); G_free_key_value(in_unit_info); G_free_key_value(out_proj_info); G_free_key_value(out_unit_info); if (G_verbose() > G_verbose_std()) pj_print_proj_params(&iproj, &oproj); /* this call causes r.proj to read the entire map into memeory */ Rast_get_cellhd(inmap->answer, setname, &incellhd); Rast_set_input_window(&incellhd); if (G_projection() == PROJECTION_XY) G_fatal_error(_("Unable to work with unprojected data (xy location)")); /* Save default borders so we can show them later */ inorth = incellhd.north; isouth = incellhd.south; ieast = incellhd.east; iwest = incellhd.west; irows = incellhd.rows; icols = incellhd.cols; onorth = outcellhd.north; osouth = outcellhd.south; oeast = outcellhd.east; owest = outcellhd.west; orows = outcellhd.rows; ocols = outcellhd.cols; if (print_bounds->answer) { G_message(_("Input map <%s@%s> in location <%s>:"), inmap->answer, setname, inlocation->answer); if (pj_do_proj(&iwest, &isouth, &iproj, &oproj) < 0) G_fatal_error(_("Error in pj_do_proj (projection of input coordinate pair)")); if (pj_do_proj(&ieast, &inorth, &iproj, &oproj) < 0) G_fatal_error(_("Error in pj_do_proj (projection of input coordinate pair)")); G_format_northing(inorth, north_str, curr_proj); G_format_northing(isouth, south_str, curr_proj); G_format_easting(ieast, east_str, curr_proj); G_format_easting(iwest, west_str, curr_proj); if(gprint_bounds->answer) { fprintf(stdout, "n=%s s=%s w=%s e=%s rows=%d cols=%d\n", north_str, south_str, west_str, east_str, irows, icols); } else { fprintf(stdout, "Source cols: %d\n", icols); fprintf(stdout, "Source rows: %d\n", irows); fprintf(stdout, "Local north: %s\n", north_str); fprintf(stdout, "Local south: %s\n", south_str); fprintf(stdout, "Local west: %s\n", west_str); fprintf(stdout, "Local east: %s\n", east_str); } /* somehow approximate local ewres, nsres ?? (use 'g.region -m' on lat/lon side) */ exit(EXIT_SUCCESS); } /* Cut non-overlapping parts of input map */ if (!nocrop->answer) bordwalk(&outcellhd, &incellhd, &oproj, &iproj); /* Add 2 cells on each side for bilinear/cubic & future interpolation methods */ /* (should probably be a factor based on input and output resolution) */ incellhd.north += 2 * incellhd.ns_res; incellhd.east += 2 * incellhd.ew_res; incellhd.south -= 2 * incellhd.ns_res; incellhd.west -= 2 * incellhd.ew_res; if (incellhd.north > inorth) incellhd.north = inorth; if (incellhd.east > ieast) incellhd.east = ieast; if (incellhd.south < isouth) incellhd.south = isouth; if (incellhd.west < iwest) incellhd.west = iwest; Rast_set_input_window(&incellhd); /* And switch back to original location */ G__switch_env(); /* Adjust borders of output map */ if (!nocrop->answer) bordwalk(&incellhd, &outcellhd, &iproj, &oproj); #if 0 outcellhd.west = outcellhd.south = HUGE_VAL; outcellhd.east = outcellhd.north = -HUGE_VAL; for (row = 0; row < incellhd.rows; row++) { ycoord1 = Rast_row_to_northing((double)(row + 0.5), &incellhd); for (col = 0; col < incellhd.cols; col++) { xcoord1 = Rast_col_to_easting((double)(col + 0.5), &incellhd); pj_do_proj(&xcoord1, &ycoord1, &iproj, &oproj); if (xcoord1 > outcellhd.east) outcellhd.east = xcoord1; if (ycoord1 > outcellhd.north) outcellhd.north = ycoord1; if (xcoord1 < outcellhd.west) outcellhd.west = xcoord1; if (ycoord1 < outcellhd.south) outcellhd.south = ycoord1; } } #endif if (res->answer != NULL) /* set user defined resolution */ outcellhd.ns_res = outcellhd.ew_res = atof(res->answer); G_adjust_Cell_head(&outcellhd, 0, 0); Rast_set_output_window(&outcellhd); G_message(" "); G_message(_("Input:")); G_message(_("Cols: %d (%d)"), incellhd.cols, icols); G_message(_("Rows: %d (%d)"), incellhd.rows, irows); G_message(_("North: %f (%f)"), incellhd.north, inorth); G_message(_("South: %f (%f)"), incellhd.south, isouth); G_message(_("West: %f (%f)"), incellhd.west, iwest); G_message(_("East: %f (%f)"), incellhd.east, ieast); G_message(_("EW-res: %f"), incellhd.ew_res); G_message(_("NS-res: %f"), incellhd.ns_res); G_message(" "); G_message(_("Output:")); G_message(_("Cols: %d (%d)"), outcellhd.cols, ocols); G_message(_("Rows: %d (%d)"), outcellhd.rows, orows); G_message(_("North: %f (%f)"), outcellhd.north, onorth); G_message(_("South: %f (%f)"), outcellhd.south, osouth); G_message(_("West: %f (%f)"), outcellhd.west, owest); G_message(_("East: %f (%f)"), outcellhd.east, oeast); G_message(_("EW-res: %f"), outcellhd.ew_res); G_message(_("NS-res: %f"), outcellhd.ns_res); G_message(" "); /* open and read the relevant parts of the input map and close it */ G__switch_env(); Rast_set_input_window(&incellhd); fdi = Rast_open_old(inmap->answer, setname); cell_type = Rast_get_map_type(fdi); ibuffer = readcell(fdi, memory->answer); Rast_close(fdi); G__switch_env(); Rast_set_output_window(&outcellhd); if (strcmp(interpol->answer, "nearest") == 0) { fdo = Rast_open_new(mapname, cell_type); obuffer = (CELL *) Rast_allocate_output_buf(cell_type); } else { fdo = Rast_open_fp_new(mapname); cell_type = FCELL_TYPE; obuffer = (FCELL *) Rast_allocate_output_buf(cell_type); } cell_size = Rast_cell_size(cell_type); xcoord1 = xcoord2 = outcellhd.west + (outcellhd.ew_res / 2); /**/ ycoord1 = ycoord2 = outcellhd.north - (outcellhd.ns_res / 2); /**/ G_important_message(_("Projecting...")); G_percent(0, outcellhd.rows, 2); for (row = 0; row < outcellhd.rows; row++) { obufptr = obuffer; for (col = 0; col < outcellhd.cols; col++) { /* project coordinates in output matrix to */ /* coordinates in input matrix */ if (pj_do_proj(&xcoord1, &ycoord1, &oproj, &iproj) < 0) Rast_set_null_value(obufptr, 1, cell_type); else { /* convert to row/column indices of input matrix */ col_idx = (xcoord1 - incellhd.west) / incellhd.ew_res; row_idx = (incellhd.north - ycoord1) / incellhd.ns_res; /* and resample data point */ interpolate(ibuffer, obufptr, cell_type, &col_idx, &row_idx, &incellhd); } obufptr = G_incr_void_ptr(obufptr, cell_size); xcoord2 += outcellhd.ew_res; xcoord1 = xcoord2; ycoord1 = ycoord2; } Rast_put_row(fdo, obuffer, cell_type); xcoord1 = xcoord2 = outcellhd.west + (outcellhd.ew_res / 2); ycoord2 -= outcellhd.ns_res; ycoord1 = ycoord2; G_percent(row, outcellhd.rows - 1, 2); } Rast_close(fdo); if (have_colors > 0) { Rast_write_colors(mapname, G_mapset(), &colr); Rast_free_colors(&colr); } Rast_short_history(mapname, "raster", &history); Rast_command_history(&history); Rast_write_history(mapname, &history); G_done_msg(NULL); exit(EXIT_SUCCESS); }
int main(int argc, char *argv[]) { struct Cell_head cellhd; /*region+header info */ char *mapset; /*mapset name */ int nrows, ncols; int row, col; struct GModule *module; struct Option *input, *input1, *input2, *input3, *input4, *input5, *output; struct History history; /*metadata */ struct Colors colors; /*Color rules */ /************************************/ char *name, *name1, *name2; /*input raster name */ char *result; /*output raster name */ /*File Descriptors */ int nfiles, nfiles1, nfiles2; int infd[MAXFILES], infd1[MAXFILES], infd2[MAXFILES]; int outfd; /****************************************/ /* Pointers for file names */ char **names; char **ptr; char **names1; char **ptr1; char **names2; char **ptr2; /****************************************/ int DOYbeforeETa[MAXFILES], DOYafterETa[MAXFILES]; int bfr, aft; /****************************************/ int ok; int i = 0, j = 0; double etodoy; /*minimum ETo DOY */ double startperiod, endperiod; /*first and last days (DOYs) of the period studied */ void *inrast[MAXFILES], *inrast1[MAXFILES], *inrast2[MAXFILES]; DCELL *outrast; CELL val1, val2; RASTER_MAP_TYPE in_data_type[MAXFILES]; /* ETa */ RASTER_MAP_TYPE in_data_type1[MAXFILES]; /* DOY of ETa */ RASTER_MAP_TYPE in_data_type2[MAXFILES]; /* ETo */ RASTER_MAP_TYPE out_data_type = DCELL_TYPE; /************************************/ G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("imagery")); G_add_keyword(_("evapotranspiration")); module->description =_("Computes temporal integration of satellite " "ET actual (ETa) following the daily ET reference " "(ETo) from meteorological station(s)."); /* Define the different options */ input = G_define_standard_option(G_OPT_R_INPUTS); input->key = "eta"; input->description = _("Names of satellite ETa raster maps [mm/d or cm/d]"); input1 = G_define_standard_option(G_OPT_R_INPUTS); input1->key = "eta_doy"; input1->description = _("Names of satellite ETa Day of Year (DOY) raster maps [0-400] [-]"); input2 = G_define_standard_option(G_OPT_R_INPUTS); input2->key = "eto"; input2->description = _("Names of meteorological station ETo raster maps [0-400] [mm/d or cm/d]"); input3 = G_define_option(); input3->key = "eto_doy_min"; input3->type = TYPE_DOUBLE; input3->required = YES; input3->description = _("Value of DOY for ETo first day"); input4 = G_define_option(); input4->key = "start_period"; input4->type = TYPE_DOUBLE; input4->required = YES; input4->description = _("Value of DOY for the first day of the period studied"); input5 = G_define_option(); input5->key = "end_period"; input5->type = TYPE_DOUBLE; input5->required = YES; input5->description = _("Value of DOY for the last day of the period studied"); output = G_define_standard_option(G_OPT_R_OUTPUT); /* init nfiles */ nfiles = 1; nfiles1 = 1; nfiles2 = 1; /********************/ if (G_parser(argc, argv)) exit(EXIT_FAILURE); ok = 1; names = input->answers; ptr = input->answers; names1 = input1->answers; ptr1 = input1->answers; names2 = input2->answers; ptr2 = input2->answers; etodoy = atof(input3->answer); startperiod = atof(input4->answer); endperiod = atof(input5->answer); result = output->answer; /****************************************/ if (endperiod<startperiod) { G_fatal_error(_("The DOY for end_period can not be smaller than start_period")); ok = 0; } if (etodoy>startperiod) { G_fatal_error(_("The DOY for start_period can not be smaller than eto_doy_min")); ok = 0; } for (; *ptr != NULL; ptr++) { if (nfiles > MAXFILES) G_fatal_error(_("Too many ETa files. Only %d allowed."), MAXFILES); name = *ptr; /* Allocate input buffer */ infd[nfiles] = Rast_open_old(name, ""); Rast_get_cellhd(name, "", &cellhd); inrast[nfiles] = Rast_allocate_d_buf(); nfiles++; } nfiles--; if (nfiles <= 1) G_fatal_error(_("The min specified input map is two")); /****************************************/ for (; *ptr1 != NULL; ptr1++) { if (nfiles1 > MAXFILES) G_fatal_error(_("Too many ETa_doy files. Only %d allowed."), MAXFILES); name1 = *ptr1; /* Allocate input buffer */ infd1[nfiles1] = Rast_open_old(name1, ""); Rast_get_cellhd(name1, "", &cellhd); inrast1[nfiles1] = Rast_allocate_d_buf(); nfiles1++; } nfiles1--; if (nfiles1 <= 1) G_fatal_error(_("The min specified input map is two")); /****************************************/ if (nfiles != nfiles1) G_fatal_error(_("ETa and ETa_DOY file numbers are not equal!")); /****************************************/ for (; *ptr2 != NULL; ptr2++) { if (nfiles > MAXFILES) G_fatal_error(_("Too many ETo files. Only %d allowed."), MAXFILES); name2 = *ptr2; /* Allocate input buffer */ infd2[nfiles2] = Rast_open_old(name2, ""); Rast_get_cellhd(name2, "", &cellhd); inrast2[nfiles2] = Rast_allocate_d_buf(); nfiles2++; } nfiles2--; if (nfiles2 <= 1) G_fatal_error(_("The min specified input map is two")); /* Allocate output buffer, use input map data_type */ nrows = Rast_window_rows(); ncols = Rast_window_cols(); outrast = Rast_allocate_d_buf(); /* Create New raster files */ outfd = Rast_open_new(result, 1); /*******************/ /* Process pixels */ double doy[MAXFILES]; double sum[MAXFILES]; for (row = 0; row < nrows; row++) { DCELL d_out; DCELL d_ETrF[MAXFILES]; DCELL d[MAXFILES]; DCELL d1[MAXFILES]; DCELL d2[MAXFILES]; G_percent(row, nrows, 2); /* read input map */ for (i = 1; i <= nfiles; i++) Rast_get_d_row(infd[i], inrast[i], row); for (i = 1; i <= nfiles1; i++) Rast_get_d_row(infd1[i], inrast1[i], row); for (i = 1; i <= nfiles2; i++) Rast_get_d_row (infd2[i], inrast2[i], row); /*process the data */ for (col = 0; col < ncols; col++) { int d1_null=0; int d_null=0; for (i = 1; i <= nfiles; i++) { if (Rast_is_d_null_value(&((DCELL *) inrast[i])[col])) d_null=1; else d[i] = ((DCELL *) inrast[i])[col]; } for (i = 1; i <= nfiles1; i++) { if (Rast_is_d_null_value(&((DCELL *) inrast1[i])[col])) d1_null=1; else d1[i] = ((DCELL *) inrast1[i])[col]; } for (i = 1; i <= nfiles2; i++) d2[i] = ((DCELL *) inrast2[i])[col]; /* Find out the DOY of the eto image */ for (i = 1; i <= nfiles1; i++) { if ( d_null==1 || d1_null==1 ) Rast_set_d_null_value(&outrast[col],1); else { doy[i] = d1[i] - etodoy+1; if (Rast_is_d_null_value(&d2[(int)doy[i]]) || d2[(int)doy[i]]==0 ) Rast_set_d_null_value(&outrast[col],1); else d_ETrF[i] = d[i] / d2[(int)doy[i]]; } } for (i = 1; i <= nfiles1; i++) { /* do nothing */ if ( d_null==1 || d1_null==1) { /*G_message(" null value ");*/ } else { DOYbeforeETa[i]=0; DOYafterETa[i]=0; if (i == 1) DOYbeforeETa[i] = startperiod; else { int k=i-1; while (d1[k]>=startperiod ) { if (d1[k]<0) // case were d1[k] is null k=k-1; else { DOYbeforeETa[i] = 1+((d1[i] + d1[k])/2.0); break; } } } if (i == nfiles1) DOYafterETa[i] = endperiod; else { int k=i+1; while (d1[k]<=endperiod) { if (d1[k]<0) // case were d1[k] is null k=k+1; else { DOYafterETa[i] = (d1[i] + d1[k]) / 2.0; break; } } } } } sum[MAXFILES] = 0.0; for (i = 1; i <= nfiles1; i++) { if(d_null==1 || d1_null==1) { /* do nothing */ } else { if (DOYbeforeETa[i]==0 || DOYbeforeETa[i]==0 ) Rast_set_d_null_value(&outrast[col],1); else { bfr = (int)DOYbeforeETa[i]; aft = (int)DOYafterETa[i]; sum[i]=0.0; for (j = bfr; j < aft; j++) sum[i] += d2[(int)(j-etodoy+1)]; } } } d_out = 0.0; for (i = 1; i <= nfiles1; i++) { if(d_null==1 || d_null==1) Rast_set_d_null_value(&outrast[col],1); else { d_out += d_ETrF[i] * sum[i]; outrast[col] = d_out; } } } Rast_put_row(outfd, outrast, out_data_type); } for (i = 1; i <= nfiles; i++) { G_free(inrast[i]); Rast_close(infd[i]); } for (i = 1; i <= nfiles1; i++) { G_free(inrast1[i]); Rast_close(infd1[i]); } for (i = 1; i <= nfiles2; i++) { G_free(inrast2[i]); Rast_close(infd2[i]); } G_free(outrast); Rast_close(outfd); /* Color table from 0.0 to 10.0 */ Rast_init_colors(&colors); val1 = 0; val2 = 10; Rast_add_c_color_rule(&val1, 0, 0, 0, &val2, 255, 255, 255, &colors); /* Metadata */ Rast_short_history(result, "raster", &history); Rast_command_history(&history); Rast_write_history(result, &history); exit(EXIT_SUCCESS); }