int output_raster(int fd) { int i; for (i = 0; i < page.rows; i++, at_row++) { G_percent(i, page.rows, 2); switch (format) { case USE_CELL: cell = raster.cell[i]; /* insert the NULL values */ Rast_insert_c_null_values(cell, null_flags[i], page.cols); Rast_put_c_row(fd, cell); break; case USE_DCELL: dcell = raster.dcell[i]; /* insert the NULL values */ Rast_insert_d_null_values(dcell, null_flags[i], page.cols); Rast_put_d_row(fd, dcell); break; } } G_percent(1, 1, 1); return configure_plot(); }
int randsurf(char *out, /* Name of raster maps to be opened. */ int min, int max, /* Minimum and maximum cell values. */ int int_map) { /* if map is to be written as a CELL map */ int nrows, ncols; /* Number of cell rows and columns */ DCELL *row_out_D; /* Buffer just large enough to hold one */ CELL *row_out_C; /* row of the raster map layer. */ int fd_out; /* File descriptor - used to identify */ /* open raster maps. */ int row_count, col_count; /****** INITIALISE RANDOM NUMBER GENERATOR ******/ G_math_rand(-1 * getpid()); /****** OPEN CELL FILES AND GET CELL DETAILS ******/ fd_out = Rast_open_new(out, int_map ? CELL_TYPE : DCELL_TYPE); nrows = Rast_window_rows(); ncols = Rast_window_cols(); if (int_map) row_out_C = Rast_allocate_c_buf(); else row_out_D = Rast_allocate_d_buf(); /****** PASS THROUGH EACH CELL ASSIGNING RANDOM VALUE ******/ for (row_count = 0; row_count < nrows; row_count++) { G_percent(row_count, nrows, 2); for (col_count = 0; col_count < ncols; col_count++) { if (int_map) *(row_out_C + col_count) = (CELL) (G_math_rand(2742) * (max + 1 - min) + min); /* under represents first and last bin */ /* *(row_out_C + col_count) = (CELL) floor(rand1(2742)*(max-min)+min +0.5); */ else *(row_out_D + col_count) = (DCELL) (G_math_rand(2742) * (max - min) + min); } /* Write contents row by row */ if (int_map) Rast_put_c_row(fd_out, (CELL *) row_out_C); else Rast_put_d_row(fd_out, (DCELL *) row_out_D); } G_percent(1, 1, 1); Rast_close(fd_out); return 0; }
static void convert_and_write_fd(int fd, const void *vbuf) { const FCELL *buf = vbuf; struct fileinfo *fcb = &R__.fileinfo[fd]; DCELL *p = (DCELL *) fcb->data; int i; for (i = 0; i < fcb->cellhd.cols; i++) if (Rast_is_f_null_value(&buf[i])) Rast_set_d_null_value(&p[i], 1); else p[i] = (DCELL) buf[i]; Rast_put_d_row(fd, p); }
static void do_output(int base_fd, char **outputs, const char *covermap) { int *out_fd = G_malloc(num_quants * sizeof(int)); CELL *base_buf = Rast_allocate_c_buf(); DCELL *out_buf = Rast_allocate_d_buf(); const char *mapset = G_mapset(); struct Colors colors; int have_colors; int quant; int row, col; G_message(_("Writing output maps")); for (quant = 0; quant < num_quants; quant++) { const char *output = outputs[quant]; out_fd[quant] = Rast_open_fp_new(output); } have_colors = Rast_read_colors(covermap, "", &colors) > 0; for (row = 0; row < rows; row++) { Rast_get_c_row(base_fd, base_buf, row); for (quant = 0; quant < num_quants; quant++) { for (col = 0; col < cols; col++) if (Rast_is_c_null_value(&base_buf[col])) Rast_set_d_null_value(&out_buf[col], 1); else out_buf[col] = basecats[base_buf[col] - min].quants[quant]; Rast_put_d_row(out_fd[quant], out_buf); } G_percent(row, rows, 2); } G_percent(row, rows, 2); for (quant = 0; quant < num_quants; quant++) { Rast_close(out_fd[quant]); if (have_colors) Rast_write_colors(outputs[quant], mapset, &colors); } }
/*---------------------------------------------------------------------------------------*/ void P_Aux_to_Raster(double **matrix, int fd) { int ncols, col, nrows, row; void *ptr, *raster; nrows = Rast_window_rows(); ncols = Rast_window_cols(); raster = Rast_allocate_buf(DCELL_TYPE); for (row = 0; row < nrows; row++) { G_percent(row, nrows, 2); Rast_set_d_null_value(raster, ncols); for (col = 0, ptr = raster; col < ncols; col++, ptr = G_incr_void_ptr(ptr, Rast_cell_size(DCELL_TYPE))) { Rast_set_d_value(ptr, (DCELL) (matrix[row][col]), DCELL_TYPE); } Rast_put_d_row(fd, raster); } G_percent(row, nrows, 2); }
int main(int argc, char *argv[]) { /* buffer for input-output rasters */ void *inrast_TEMPKA, *inrast_PATM, *inrast_RNET, *inrast_G0; DCELL *outrast; /* pointers to input-output raster files */ int infd_TEMPKA, infd_PATM, infd_RNET, infd_G0; int outfd; /* names of input-output raster files */ char *RNET, *TEMPKA, *PATM, *G0; char *ETa; /* input-output cell values */ DCELL d_tempka, d_pt_patm, d_rnet, d_g0; DCELL d_pt_alpha, d_pt_delta, d_pt_ghamma, d_daily_et; /* region information and handler */ struct Cell_head cellhd; int nrows, ncols; int row, col; /* parser stuctures definition */ struct GModule *module; struct Option *input_RNET, *input_TEMPKA, *input_PATM, *input_G0, *input_PT; struct Option *output; struct Flag *zero; struct Colors color; struct History history; /* Initialize the GIS calls */ G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("imagery")); G_add_keyword(_("evapotranspiration")); module->description = _("Computes evapotranspiration calculation " "Priestley and Taylor formulation, 1972."); /* Define different options */ input_RNET = G_define_standard_option(G_OPT_R_INPUT); input_RNET->key = "net_radiation"; input_RNET->description = _("Name of input net radiation raster map [W/m2]"); input_G0 = G_define_standard_option(G_OPT_R_INPUT); input_G0->key = "soil_heatflux"; input_G0->description = _("Name of input soil heat flux raster map [W/m2]"); input_TEMPKA = G_define_standard_option(G_OPT_R_INPUT); input_TEMPKA->key = "air_temperature"; input_TEMPKA->description = _("Name of input air temperature raster map [K]"); input_PATM = G_define_standard_option(G_OPT_R_INPUT); input_PATM->key = "atmospheric_pressure"; input_PATM->description = _("Name of input atmospheric pressure raster map [millibars]"); input_PT = G_define_option(); input_PT->key = "priestley_taylor_coeff"; input_PT->type = TYPE_DOUBLE; input_PT->required = YES; input_PT->description = _("Priestley-Taylor coefficient"); input_PT->answer = "1.26"; output = G_define_standard_option(G_OPT_R_OUTPUT); output->description = _("Name of output evapotranspiration raster map [mm/d]"); /* Define the different flags */ zero = G_define_flag(); zero->key = 'z'; zero->description = _("Set negative ETa to zero"); if (G_parser(argc, argv)) exit(EXIT_FAILURE); /* get entered parameters */ RNET = input_RNET->answer; TEMPKA = input_TEMPKA->answer; PATM = input_PATM->answer; G0 = input_G0->answer; d_pt_alpha = atof(input_PT->answer); ETa = output->answer; /* open pointers to input raster files */ infd_RNET = Rast_open_old(RNET, ""); infd_TEMPKA = Rast_open_old(TEMPKA, ""); infd_PATM = Rast_open_old(PATM, ""); infd_G0 = Rast_open_old(G0, ""); /* read headers of raster files */ Rast_get_cellhd(RNET, "", &cellhd); Rast_get_cellhd(TEMPKA, "", &cellhd); Rast_get_cellhd(PATM, "", &cellhd); Rast_get_cellhd(G0, "", &cellhd); /* Allocate input buffer */ inrast_RNET = Rast_allocate_d_buf(); inrast_TEMPKA = Rast_allocate_d_buf(); inrast_PATM = Rast_allocate_d_buf(); inrast_G0 = Rast_allocate_d_buf(); /* get rows and columns number of the current region */ nrows = Rast_window_rows(); ncols = Rast_window_cols(); /* allocate output buffer */ outrast = Rast_allocate_d_buf(); /* open pointers to output raster files */ outfd = Rast_open_new(ETa, DCELL_TYPE); /* start the loop through cells */ for (row = 0; row < nrows; row++) { G_percent(row, nrows, 2); /* read input raster row into line buffer */ Rast_get_d_row(infd_RNET, inrast_RNET, row); Rast_get_d_row(infd_TEMPKA, inrast_TEMPKA, row); Rast_get_d_row(infd_PATM, inrast_PATM, row); Rast_get_d_row(infd_G0, inrast_G0, row); for (col = 0; col < ncols; col++) { /* read current cell from line buffer */ d_rnet = ((DCELL *) inrast_RNET)[col]; d_tempka = ((DCELL *) inrast_TEMPKA)[col]; d_pt_patm = ((DCELL *) inrast_PATM)[col]; d_g0 = ((DCELL *) inrast_G0)[col]; /*Delta_pt and Ghamma_pt */ d_pt_delta = pt_delta(d_tempka); d_pt_ghamma = pt_ghamma(d_tempka, d_pt_patm); /*Calculate ET */ d_daily_et = pt_daily_et(d_pt_alpha, d_pt_delta, d_pt_ghamma, d_rnet, d_g0, d_tempka); if (zero->answer && d_daily_et < 0) d_daily_et = 0.0; /* write calculated ETP to output line buffer */ outrast[col] = d_daily_et; } /* write output line buffer to output raster file */ Rast_put_d_row(outfd, outrast); } /* free buffers and close input maps */ G_free(inrast_RNET); G_free(inrast_TEMPKA); G_free(inrast_PATM); G_free(inrast_G0); Rast_close(infd_RNET); Rast_close(infd_TEMPKA); Rast_close(infd_PATM); Rast_close(infd_G0); /* generate color table between -20 and 20 */ Rast_make_rainbow_colors(&color, -20, 20); Rast_write_colors(ETa, G_mapset(), &color); Rast_short_history(ETa, "raster", &history); Rast_command_history(&history); Rast_write_history(ETa, &history); /* free buffers and close output map */ G_free(outrast); Rast_close(outfd); return (EXIT_SUCCESS); }
int main(int argc, char *argv[]) { int nrows, ncols; int row, col; struct GModule *module; struct Option *input1, *input2, *input3, *input4, *input5, *input6; struct Option *output1; struct History history; /*metadata */ struct Colors colors; char *result1; /*output raster name */ int infd_fpar, infd_luf, infd_lat; int infd_doy, infd_tsw, infd_wa; int outfd1; char *fpar, *luf, *lat, *doy, *tsw, *wa; void *inrast_fpar, *inrast_luf, *inrast_lat; void *inrast_doy, *inrast_tsw, *inrast_wa; DCELL * outrast1; CELL val1, val2; /************************************/ G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("imagery")); G_add_keyword(_("biomass")); G_add_keyword(_("fpar")); G_add_keyword(_("yield")); module->description = _("Computes biomass growth, precursor of crop yield calculation."); /* Define the different options */ input1 = G_define_standard_option(G_OPT_R_INPUT); input1->key = "fpar"; input1->description = _("Name of fPAR raster map"); input2 = G_define_standard_option(G_OPT_R_INPUT); input2->key = "lightuseefficiency"; input2->description = _("Name of light use efficiency raster map (UZB:cotton=1.9)"); input3 = G_define_standard_option(G_OPT_R_INPUT); input3->key = "latitude"; input3->description = _("Name of degree latitude raster map [dd.ddd]"); input4 = G_define_standard_option(G_OPT_R_INPUT); input4->key = "dayofyear"; input4->description = _("Name of Day of Year raster map [1-366]"); input5 = G_define_standard_option(G_OPT_R_INPUT); input5->key = "transmissivitysingleway"; input5->description = _("Name of single-way transmissivity raster map [0.0-1.0]"); input6 = G_define_standard_option(G_OPT_R_INPUT); input6->key = "wateravailability"; input6->description = _("Value of water availability raster map [0.0-1.0]"); output1 = G_define_standard_option(G_OPT_R_OUTPUT); output1->description = _("Name for output daily biomass growth raster map [kg/ha/d]"); /********************/ if (G_parser(argc, argv)) exit(EXIT_FAILURE); fpar = input1->answer; luf = input2->answer; lat = input3->answer; doy = input4->answer; tsw = input5->answer; wa = input6->answer; result1 = output1->answer; /***************************************************/ infd_fpar = Rast_open_old(fpar, ""); inrast_fpar = Rast_allocate_d_buf(); infd_luf = Rast_open_old(luf, ""); inrast_luf = Rast_allocate_d_buf(); infd_lat = Rast_open_old(lat, ""); inrast_lat = Rast_allocate_d_buf(); infd_doy = Rast_open_old(doy, ""); inrast_doy = Rast_allocate_d_buf(); infd_tsw = Rast_open_old(tsw, ""); inrast_tsw = Rast_allocate_d_buf(); infd_wa = Rast_open_old(wa, ""); inrast_wa = Rast_allocate_d_buf(); nrows = Rast_window_rows(); ncols = Rast_window_cols(); outrast1 = Rast_allocate_d_buf(); /* Create New raster files */ outfd1 = Rast_open_new(result1, DCELL_TYPE); /* Process pixels */ for (row = 0; row < nrows; row++) { DCELL d; DCELL d_fpar; DCELL d_luf; DCELL d_lat; DCELL d_doy; DCELL d_tsw; DCELL d_solar; DCELL d_wa; G_percent(row, nrows, 2); /* read input maps */ Rast_get_d_row(infd_fpar, inrast_fpar, row); Rast_get_d_row(infd_luf,inrast_luf,row); Rast_get_d_row(infd_lat, inrast_lat, row); Rast_get_d_row(infd_doy, inrast_doy, row); Rast_get_d_row(infd_tsw, inrast_tsw, row); Rast_get_d_row(infd_wa,inrast_wa,row); /*process the data */ for (col = 0; col < ncols; col++) { d_fpar = ((DCELL *) inrast_fpar)[col]; d_luf = ((DCELL *) inrast_luf)[col]; d_lat = ((DCELL *) inrast_lat)[col]; d_doy = ((DCELL *) inrast_doy)[col]; d_tsw = ((DCELL *) inrast_tsw)[col]; d_wa = ((DCELL *) inrast_wa)[col]; if (Rast_is_d_null_value(&d_fpar) || Rast_is_d_null_value(&d_luf) || Rast_is_d_null_value(&d_lat) || Rast_is_d_null_value(&d_doy) || Rast_is_d_null_value(&d_tsw) || Rast_is_d_null_value(&d_wa)) Rast_set_d_null_value(&outrast1[col], 1); else { d_solar = solar_day(d_lat, d_doy, d_tsw); d = biomass(d_fpar,d_solar,d_wa,d_luf); outrast1[col] = d; } } Rast_put_d_row(outfd1, outrast1); } /* Color table for biomass */ Rast_init_colors(&colors); val1 = 0; val2 = 1; Rast_add_c_color_rule(&val1, 0, 0, 0, &val2, 255, 255, 255, &colors); G_free(inrast_fpar); G_free(inrast_luf); G_free(inrast_lat); G_free(inrast_doy); G_free(inrast_tsw); G_free(inrast_wa); G_free(outrast1); Rast_close(infd_fpar); Rast_close(infd_luf); Rast_close(infd_lat); Rast_close(infd_doy); Rast_close(infd_tsw); Rast_close(infd_wa); Rast_close(outfd1); Rast_short_history(result1, "raster", &history); Rast_command_history(&history); Rast_write_history(result1, &history); exit(EXIT_SUCCESS); }
/* ************************************************************************* */ void g3d_to_raster(void *map, RASTER3D_Region region, int *fd) { DCELL d1 = 0; FCELL f1 = 0; int x, y, z; int rows, cols, depths, typeIntern, pos = 0; FCELL *fcell = NULL; DCELL *dcell = NULL; rows = region.rows; cols = region.cols; depths = region.depths; G_debug(2, "g3d_to_raster: Writing %i raster maps with %i rows %i cols.", depths, rows, cols); typeIntern = Rast3d_tile_type_map(map); if (typeIntern == FCELL_TYPE) fcell = Rast_allocate_f_buf(); else if (typeIntern == DCELL_TYPE) dcell = Rast_allocate_d_buf(); pos = 0; /*Every Rastermap */ for (z = 0; z < depths; z++) { /*From the bottom to the top */ G_debug(2, "Writing raster map %d of %d", z + 1, depths); for (y = 0; y < rows; y++) { G_percent(y, rows - 1, 10); for (x = 0; x < cols; x++) { if (typeIntern == FCELL_TYPE) { Rast3d_get_value(map, x, y, z, &f1, typeIntern); if (Rast3d_is_null_value_num(&f1, FCELL_TYPE)) Rast_set_null_value(&fcell[x], 1, FCELL_TYPE); else fcell[x] = f1; } else { Rast3d_get_value(map, x, y, z, &d1, typeIntern); if (Rast3d_is_null_value_num(&d1, DCELL_TYPE)) Rast_set_null_value(&dcell[x], 1, DCELL_TYPE); else dcell[x] = d1; } } if (typeIntern == FCELL_TYPE) Rast_put_f_row(fd[pos], fcell); if (typeIntern == DCELL_TYPE) Rast_put_d_row(fd[pos], dcell); } G_debug(2, "Finished writing map %d.", z + 1); pos++; } if (dcell) G_free(dcell); if (fcell) G_free(fcell); }
/*--------------------------------------------------------------------*/ 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 */
static void resamp_weighted(void) { stat_func_w *method_fn; DCELL(*values)[2]; double *col_map, *row_map; int row, col; method_fn = menu[method].method_w; values = G_malloc(row_scale * col_scale * 2 * sizeof(DCELL)); col_map = G_malloc((dst_w.cols + 1) * sizeof(double)); row_map = G_malloc((dst_w.rows + 1) * sizeof(double)); for (col = 0; col <= dst_w.cols; col++) { double x = Rast_col_to_easting(col, &dst_w); col_map[col] = Rast_easting_to_col(x, &src_w); } for (row = 0; row <= dst_w.rows; row++) { double y = Rast_row_to_northing(row, &dst_w); row_map[row] = Rast_northing_to_row(y, &src_w); } for (row = 0; row < dst_w.rows; row++) { double y0 = row_map[row + 0]; double y1 = row_map[row + 1]; int maprow0 = (int)floor(y0); int maprow1 = (int)ceil(y1); int count = maprow1 - maprow0; int i; G_percent(row, dst_w.rows, 2); for (i = 0; i < count; i++) Rast_get_d_row(infile, bufs[i], maprow0 + i); for (col = 0; col < dst_w.cols; col++) { double x0 = col_map[col + 0]; double x1 = col_map[col + 1]; int mapcol0 = (int)floor(x0); int mapcol1 = (int)ceil(x1); int null = 0; int n = 0; int i, j; for (i = maprow0; i < maprow1; i++) { double ky = (i == maprow0) ? 1 - (y0 - maprow0) : (i == maprow1 - 1) ? 1 - (maprow1 - y1) : 1; for (j = mapcol0; j < mapcol1; j++) { double kx = (j == mapcol0) ? 1 - (x0 - mapcol0) : (j == mapcol1 - 1) ? 1 - (mapcol1 - x1) : 1; DCELL *src = &bufs[i - maprow0][j]; DCELL *dst = &values[n++][0]; if (Rast_is_d_null_value(src)) { Rast_set_d_null_value(&dst[0], 1); null = 1; } else { dst[0] = *src; dst[1] = kx * ky; } } } if (null && nulls) Rast_set_d_null_value(&outbuf[col], 1); else (*method_fn) (&outbuf[col], values, n, closure); } Rast_put_d_row(outfile, outbuf); } }
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[]) { 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 main(int argc, char *argv[]) { int nrows, ncols; int row, col; char *viflag; /*Switch for particular index */ char *desc; struct GModule *module; struct { struct Option *viname, *red, *nir, *green, *blue, *chan5, *chan7, *sl_slope, *sl_int, *sl_red, *bits, *output; } opt; struct History history; /*metadata */ struct Colors colors; /*Color rules */ char *result; /*output raster name */ int infd_redchan, infd_nirchan, infd_greenchan; int infd_bluechan, infd_chan5chan, infd_chan7chan; int outfd; char *bluechan, *greenchan, *redchan, *nirchan, *chan5chan, *chan7chan; DCELL *inrast_redchan, *inrast_nirchan, *inrast_greenchan; DCELL *inrast_bluechan, *inrast_chan5chan, *inrast_chan7chan; DCELL *outrast; RASTER_MAP_TYPE data_type_redchan; RASTER_MAP_TYPE data_type_nirchan, data_type_greenchan; RASTER_MAP_TYPE data_type_bluechan; RASTER_MAP_TYPE data_type_chan5chan, data_type_chan7chan; DCELL msavip1, msavip2, msavip3, dnbits; CELL val1, val2; G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("imagery")); G_add_keyword(_("vegetation index")); G_add_keyword(_("biophysical parameters")); module->label = _("Calculates different types of vegetation indices."); module->description = _("Uses red and nir bands mostly, " "and some indices require additional bands."); /* Define the different options */ opt.red = G_define_standard_option(G_OPT_R_INPUT); opt.red->key = "red"; opt.red->label = _("Name of input red channel surface reflectance map"); opt.red->description = _("Range: [0.0;1.0]"); opt.output = G_define_standard_option(G_OPT_R_OUTPUT); opt.viname = G_define_option(); opt.viname->key = "viname"; opt.viname->type = TYPE_STRING; opt.viname->required = YES; opt.viname->description = _("Type of vegetation index"); desc = NULL; G_asprintf(&desc, "arvi;%s;dvi;%s;evi;%s;evi2;%s;gvi;%s;gari;%s;gemi;%s;ipvi;%s;msavi;%s;" "msavi2;%s;ndvi;%s;pvi;%s;savi;%s;sr;%s;vari;%s;wdvi;%s", _("Atmospherically Resistant Vegetation Index"), _("Difference Vegetation Index"), _("Enhanced Vegetation Index"), _("Enhanced Vegetation Index 2"), _("Green Vegetation Index"), _("Green Atmospherically Resistant Vegetation Index"), _("Global Environmental Monitoring Index"), _("Infrared Percentage Vegetation Index"), _("Modified Soil Adjusted Vegetation Index"), _("second Modified Soil Adjusted Vegetation Index"), _("Normalized Difference Vegetation Index"), _("Perpendicular Vegetation Index"), _("Soil Adjusted Vegetation Index"), _("Simple Ratio"), _("Visible Atmospherically Resistant Index"), _("Weighted Difference Vegetation Index")); opt.viname->descriptions = desc; opt.viname->options = "arvi,dvi,evi,evi2,gvi,gari,gemi,ipvi,msavi,msavi2,ndvi,pvi,savi,sr,vari,wdvi"; opt.viname->answer = "ndvi"; opt.viname->key_desc = _("type"); opt.nir = G_define_standard_option(G_OPT_R_INPUT); opt.nir->key = "nir"; opt.nir->required = NO; opt.nir->label = _("Name of input nir channel surface reflectance map"); opt.nir->description = _("Range: [0.0;1.0]"); opt.nir->guisection = _("Optional inputs"); opt.green = G_define_standard_option(G_OPT_R_INPUT); opt.green->key = "green"; opt.green->required = NO; opt.green->label = _("Name of input green channel surface reflectance map"); opt.green->description = _("Range: [0.0;1.0]"); opt.green->guisection = _("Optional inputs"); opt.blue = G_define_standard_option(G_OPT_R_INPUT); opt.blue->key = "blue"; opt.blue->required = NO; opt.blue->label = _("Name of input blue channel surface reflectance map"); opt.blue->description = _("Range: [0.0;1.0]"); opt.blue->guisection = _("Optional inputs"); opt.chan5 = G_define_standard_option(G_OPT_R_INPUT); opt.chan5->key = "band5"; opt.chan5->required = NO; opt.chan5->label = _("Name of input 5th channel surface reflectance map"); opt.chan5->description = _("Range: [0.0;1.0]"); opt.chan5->guisection = _("Optional inputs"); opt.chan7 = G_define_standard_option(G_OPT_R_INPUT); opt.chan7->key = "band7"; opt.chan7->required = NO; opt.chan7->label = _("Name of input 7th channel surface reflectance map"); opt.chan7->description = _("Range: [0.0;1.0]"); opt.chan7->guisection = _("Optional inputs"); opt.sl_slope = G_define_option(); opt.sl_slope->key = "soil_line_slope"; opt.sl_slope->type = TYPE_DOUBLE; opt.sl_slope->required = NO; opt.sl_slope->description = _("Value of the slope of the soil line (MSAVI only)"); opt.sl_slope->guisection = _("MSAVI settings"); opt.sl_int = G_define_option(); opt.sl_int->key = "soil_line_intercept"; opt.sl_int->type = TYPE_DOUBLE; opt.sl_int->required = NO; opt.sl_int->description = _("Value of the intercept of the soil line (MSAVI only)"); opt.sl_int->guisection = _("MSAVI settings"); opt.sl_red = G_define_option(); opt.sl_red->key = "soil_noise_reduction"; opt.sl_red->type = TYPE_DOUBLE; opt.sl_red->required = NO; opt.sl_red->description = _("Value of the factor of reduction of soil noise (MSAVI only)"); opt.sl_red->guisection = _("MSAVI settings"); opt.bits = G_define_option(); opt.bits->key = "storage_bit"; opt.bits->type = TYPE_INTEGER; opt.bits->required = NO; opt.bits->label = _("Maximum bits for digital numbers"); opt.bits->description = _("If data is in Digital Numbers (i.e. integer type), give the max bits (i.e. 8 for Landsat -> [0-255])"); opt.bits->options = "7,8,10,16"; opt.bits->answer = "8"; if (G_parser(argc, argv)) exit(EXIT_FAILURE); viflag = opt.viname->answer; redchan = opt.red->answer; nirchan = opt.nir->answer; greenchan = opt.green->answer; bluechan = opt.blue->answer; chan5chan = opt.chan5->answer; chan7chan = opt.chan7->answer; if(opt.sl_slope->answer) msavip1 = atof(opt.sl_slope->answer); if(opt.sl_int->answer) msavip2 = atof(opt.sl_int->answer); if(opt.sl_red->answer) msavip3 = atof(opt.sl_red->answer); if(opt.bits->answer) dnbits = atof(opt.bits->answer); result = opt.output->answer; G_verbose_message(_("Calculating %s..."), viflag); if (!strcasecmp(viflag, "sr") && (!(opt.red->answer) || !(opt.nir->answer)) ) G_fatal_error(_("sr index requires red and nir maps")); if (!strcasecmp(viflag, "ndvi") && (!(opt.red->answer) || !(opt.nir->answer)) ) G_fatal_error(_("ndvi index requires red and nir maps")); if (!strcasecmp(viflag, "ipvi") && (!(opt.red->answer) || !(opt.nir->answer)) ) G_fatal_error(_("ipvi index requires red and nir maps")); if (!strcasecmp(viflag, "dvi") && (!(opt.red->answer) || !(opt.nir->answer)) ) G_fatal_error(_("dvi index requires red and nir maps")); if (!strcasecmp(viflag, "pvi") && (!(opt.red->answer) || !(opt.nir->answer)) ) G_fatal_error(_("pvi index requires red and nir maps")); if (!strcasecmp(viflag, "wdvi") && (!(opt.red->answer) || !(opt.nir->answer)) ) G_fatal_error(_("wdvi index requires red and nir maps")); if (!strcasecmp(viflag, "savi") && (!(opt.red->answer) || !(opt.nir->answer)) ) G_fatal_error(_("savi index requires red and nir maps")); if (!strcasecmp(viflag, "msavi") && (!(opt.red->answer) || !(opt.nir->answer) || !(opt.sl_slope->answer) || !(opt.sl_int->answer) || !(opt.sl_red->answer)) ) G_fatal_error(_("msavi index requires red and nir maps, and 3 parameters related to soil line")); if (!strcasecmp(viflag, "msavi2") && (!(opt.red->answer) || !(opt.nir->answer)) ) G_fatal_error(_("msavi2 index requires red and nir maps")); if (!strcasecmp(viflag, "gemi") && (!(opt.red->answer) || !(opt.nir->answer)) ) G_fatal_error(_("gemi index requires red and nir maps")); if (!strcasecmp(viflag, "arvi") && (!(opt.red->answer) || !(opt.nir->answer) || !(opt.blue->answer)) ) G_fatal_error(_("arvi index requires blue, red and nir maps")); if (!strcasecmp(viflag, "evi") && (!(opt.red->answer) || !(opt.nir->answer) || !(opt.blue->answer)) ) G_fatal_error(_("evi index requires blue, red and nir maps")); if (!strcasecmp(viflag, "evi2") && (!(opt.red->answer) || !(opt.nir->answer) ) ) G_fatal_error(_("evi2 index requires red and nir maps")); if (!strcasecmp(viflag, "vari") && (!(opt.red->answer) || !(opt.green->answer) || !(opt.blue->answer)) ) G_fatal_error(_("vari index requires blue, green and red maps")); if (!strcasecmp(viflag, "gari") && (!(opt.red->answer) || !(opt.nir->answer) || !(opt.green->answer) || !(opt.blue->answer)) ) G_fatal_error(_("gari index requires blue, green, red and nir maps")); if (!strcasecmp(viflag, "gvi") && (!(opt.red->answer) || !(opt.nir->answer) || !(opt.green->answer) || !(opt.blue->answer) || !(opt.chan5->answer) || !(opt.chan7->answer)) ) G_fatal_error(_("gvi index requires blue, green, red, nir, chan5 and chan7 maps")); infd_redchan = Rast_open_old(redchan, ""); data_type_redchan = Rast_map_type(redchan, ""); inrast_redchan = Rast_allocate_buf(data_type_redchan); if (nirchan) { infd_nirchan = Rast_open_old(nirchan, ""); data_type_nirchan = Rast_map_type(nirchan, ""); inrast_nirchan = Rast_allocate_buf(data_type_nirchan); } if (greenchan) { infd_greenchan = Rast_open_old(greenchan, ""); data_type_greenchan = Rast_map_type(greenchan, ""); inrast_greenchan = Rast_allocate_buf(data_type_greenchan); } if (bluechan) { infd_bluechan = Rast_open_old(bluechan, ""); data_type_bluechan = Rast_map_type(bluechan, ""); inrast_bluechan = Rast_allocate_buf(data_type_bluechan); } if (chan5chan) { infd_chan5chan = Rast_open_old(chan5chan, ""); data_type_chan5chan = Rast_map_type(chan5chan, ""); inrast_chan5chan = Rast_allocate_buf(data_type_chan5chan); } if (chan7chan) { infd_chan7chan = Rast_open_old(chan7chan, ""); data_type_chan7chan = Rast_map_type(chan7chan, ""); inrast_chan7chan = Rast_allocate_buf(data_type_chan7chan); } nrows = Rast_window_rows(); ncols = Rast_window_cols(); /* Create New raster files */ outfd = Rast_open_new(result, DCELL_TYPE); outrast = Rast_allocate_d_buf(); /* Process pixels */ for (row = 0; row < nrows; row++) { DCELL d_bluechan; DCELL d_greenchan; DCELL d_redchan; DCELL d_nirchan; DCELL d_chan5chan; DCELL d_chan7chan; G_percent(row, nrows, 2); /* read input maps */ Rast_get_row(infd_redchan,inrast_redchan,row,data_type_redchan); if (nirchan) { Rast_get_row(infd_nirchan,inrast_nirchan,row,data_type_nirchan); } if (bluechan) { Rast_get_row(infd_bluechan,inrast_bluechan,row,data_type_bluechan); } if (greenchan) { Rast_get_row(infd_greenchan,inrast_greenchan,row,data_type_greenchan); } if (chan5chan) { Rast_get_row(infd_chan5chan,inrast_chan5chan,row,data_type_chan5chan); } if (chan7chan) { Rast_get_row(infd_chan7chan,inrast_chan7chan,row,data_type_chan7chan); } /* process the data */ for (col = 0; col < ncols; col++) { switch(data_type_redchan){ case CELL_TYPE: d_redchan = (double) ((CELL *) inrast_redchan)[col]; if(opt.bits->answer) d_redchan *= 1.0/(pow(2,dnbits)-1); break; case FCELL_TYPE: d_redchan = (double) ((FCELL *) inrast_redchan)[col]; break; case DCELL_TYPE: d_redchan = ((DCELL *) inrast_redchan)[col]; break; } if (nirchan) { switch(data_type_nirchan){ case CELL_TYPE: d_nirchan = (double) ((CELL *) inrast_nirchan)[col]; if(opt.bits->answer) d_nirchan *= 1.0/(pow(2,dnbits)-1); break; case FCELL_TYPE: d_nirchan = (double) ((FCELL *) inrast_nirchan)[col]; break; case DCELL_TYPE: d_nirchan = ((DCELL *) inrast_nirchan)[col]; break; } } if (greenchan) { switch(data_type_greenchan){ case CELL_TYPE: d_greenchan = (double) ((CELL *) inrast_greenchan)[col]; if(opt.bits->answer) d_greenchan *= 1.0/(pow(2,dnbits)-1); break; case FCELL_TYPE: d_greenchan = (double) ((FCELL *) inrast_greenchan)[col]; break; case DCELL_TYPE: d_greenchan = ((DCELL *) inrast_greenchan)[col]; break; } } if (bluechan) { switch(data_type_bluechan){ case CELL_TYPE: d_bluechan = (double) ((CELL *) inrast_bluechan)[col]; if(opt.bits->answer) d_bluechan *= 1.0/(pow(2,dnbits)-1); break; case FCELL_TYPE: d_bluechan = (double) ((FCELL *) inrast_bluechan)[col]; break; case DCELL_TYPE: d_bluechan = ((DCELL *) inrast_bluechan)[col]; break; } } if (chan5chan) { switch(data_type_chan5chan){ case CELL_TYPE: d_chan5chan = (double) ((CELL *) inrast_chan5chan)[col]; if(opt.bits->answer) d_chan5chan *= 1.0/(pow(2,dnbits)-1); break; case FCELL_TYPE: d_chan5chan = (double) ((FCELL *) inrast_chan5chan)[col]; break; case DCELL_TYPE: d_chan5chan = ((DCELL *) inrast_chan5chan)[col]; break; } } if (chan7chan) { switch(data_type_chan7chan){ case CELL_TYPE: d_chan7chan = (double) ((CELL *) inrast_chan7chan)[col]; if(opt.bits->answer) d_chan7chan *= 1.0/(pow(2,dnbits)-1); break; case FCELL_TYPE: d_chan7chan = (double) ((FCELL *) inrast_chan7chan)[col]; break; case DCELL_TYPE: d_chan7chan = ((DCELL *) inrast_chan7chan)[col]; break; } } if (Rast_is_d_null_value(&d_redchan) || ((nirchan) && Rast_is_d_null_value(&d_nirchan)) || ((greenchan) && Rast_is_d_null_value(&d_greenchan)) || ((bluechan) && Rast_is_d_null_value(&d_bluechan)) || ((chan5chan) && Rast_is_d_null_value(&d_chan5chan)) || ((chan7chan) && Rast_is_d_null_value(&d_chan7chan))) { Rast_set_d_null_value(&outrast[col], 1); } else { /* calculate simple_ratio */ if (!strcasecmp(viflag, "sr")) outrast[col] = s_r(d_redchan, d_nirchan); /* calculate ndvi */ if (!strcasecmp(viflag, "ndvi")) { if (d_redchan + d_nirchan < 0.001) Rast_set_d_null_value(&outrast[col], 1); else outrast[col] = nd_vi(d_redchan, d_nirchan); } if (!strcasecmp(viflag, "ipvi")) outrast[col] = ip_vi(d_redchan, d_nirchan); if (!strcasecmp(viflag, "dvi")) outrast[col] = d_vi(d_redchan, d_nirchan); if (!strcasecmp(viflag, "evi")) outrast[col] = e_vi(d_bluechan, d_redchan, d_nirchan); if (!strcasecmp(viflag, "evi2")) outrast[col] = e_vi2(d_redchan, d_nirchan); if (!strcasecmp(viflag, "pvi")) outrast[col] = p_vi(d_redchan, d_nirchan); if (!strcasecmp(viflag, "wdvi")) outrast[col] = wd_vi(d_redchan, d_nirchan); if (!strcasecmp(viflag, "savi")) outrast[col] = sa_vi(d_redchan, d_nirchan); if (!strcasecmp(viflag, "msavi")) outrast[col] = msa_vi(d_redchan, d_nirchan, msavip1, msavip2, msavip3); if (!strcasecmp(viflag, "msavi2")) outrast[col] = msa_vi2(d_redchan, d_nirchan); if (!strcasecmp(viflag, "gemi")) outrast[col] = ge_mi(d_redchan, d_nirchan); if (!strcasecmp(viflag, "arvi")) outrast[col] = ar_vi(d_redchan, d_nirchan, d_bluechan); if (!strcasecmp(viflag, "gvi")) outrast[col] = g_vi(d_bluechan, d_greenchan, d_redchan, d_nirchan, d_chan5chan, d_chan7chan); if (!strcasecmp(viflag, "gari")) outrast[col] = ga_ri(d_redchan, d_nirchan, d_bluechan, d_greenchan); if (!strcasecmp(viflag, "vari")) outrast[col] = va_ri(d_redchan, d_greenchan, d_bluechan); } } Rast_put_d_row(outfd, outrast); } G_percent(1, 1, 1); G_free(inrast_redchan); Rast_close(infd_redchan); if (nirchan) { G_free(inrast_nirchan); Rast_close(infd_nirchan); } if (greenchan) { G_free(inrast_greenchan); Rast_close(infd_greenchan); } if (bluechan) { G_free(inrast_bluechan); Rast_close(infd_bluechan); } if (chan5chan) { G_free(inrast_chan5chan); Rast_close(infd_chan5chan); } if (chan7chan) { G_free(inrast_chan7chan); Rast_close(infd_chan7chan); } G_free(outrast); Rast_close(outfd); if (!strcasecmp(viflag, "ndvi")) { /* apply predefined NDVI color table */ const char *style = "ndvi"; if (G_find_color_rule("ndvi")) { Rast_make_fp_colors(&colors, style, -1.0, 1.0); } else G_fatal_error(_("Unknown color request '%s'"), style); } else { /* Color from -1.0 to +1.0 in grey */ Rast_init_colors(&colors); val1 = -1; val2 = 1; Rast_add_c_color_rule(&val1, 0, 0, 0, &val2, 255, 255, 255, &colors); } Rast_write_colors(result, G_mapset(), &colors); Rast_short_history(result, "raster", &history); Rast_command_history(&history); Rast_write_history(result, &history); exit(EXIT_SUCCESS); }
int main(int argc, char *argv[]) { int nrows, ncols; int row, col; int makin = 0; /*Makin Flag for root zone soil moisture output */ struct GModule *module; struct Option *input1, *input2, *input3, *output1, *output2; struct Flag *flag1; struct History history; /*metadata */ char *result1, *result2; /*output raster name */ int infd_rnet, infd_g0, infd_h0; int outfd1, outfd2; char *rnet, *g0, *h0; void *inrast_rnet, *inrast_g0, *inrast_h0; DCELL * outrast1, *outrast2; /************************************/ 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 evaporative fraction (Bastiaanssen, 1995) and " "root zone soil moisture (Makin, Molden and Bastiaanssen, 2001)."); /* Define the different options */ input1 = G_define_standard_option(G_OPT_R_INPUT); input1->key = "netradiation"; input1->description = _("Name of Net Radiation raster map [W/m2]"); input2 = G_define_standard_option(G_OPT_R_INPUT); input2->key = "soilheatflux"; input2->description = _("Name of soil heat flux raster map [W/m2]"); input3 = G_define_standard_option(G_OPT_R_INPUT); input3->key = "sensibleheatflux"; input3->description = _("Name of sensible heat flux raster map [W/m2]"); output1 = G_define_standard_option(G_OPT_R_OUTPUT); output1->key = "evaporativefraction"; output1->description = _("Name for output evaporative fraction raster map"); output2 = G_define_standard_option(G_OPT_R_OUTPUT); output2->key = "soilmoisture"; output2->required = NO; output2->description = _("Name for output root zone soil moisture raster map"); flag1 = G_define_flag(); flag1->key = 'm'; flag1->description = _("Root zone soil moisture output (Makin, Molden and Bastiaanssen, 2001)"); /********************/ if (G_parser(argc, argv)) exit(EXIT_FAILURE); rnet = input1->answer; g0 = input2->answer; h0 = input3->answer; result1 = output1->answer; result2 = output2->answer; makin = flag1->answer; /***************************************************/ infd_rnet = Rast_open_old(rnet, ""); inrast_rnet = Rast_allocate_d_buf(); /***************************************************/ infd_g0 = Rast_open_old(g0, ""); inrast_g0 = Rast_allocate_d_buf(); /***************************************************/ infd_h0 = Rast_open_old(h0, ""); inrast_h0 = Rast_allocate_d_buf(); /***************************************************/ nrows = Rast_window_rows(); ncols = Rast_window_cols(); outrast1 = Rast_allocate_d_buf(); if (makin) outrast2 = Rast_allocate_d_buf(); /* Create New raster files */ outfd1 = Rast_open_new(result1, DCELL_TYPE); if (makin) outfd2 = Rast_open_new(result2, DCELL_TYPE); /* Process pixels */ for (row = 0; row < nrows; row++) { DCELL d; DCELL d_rnet; DCELL d_g0; DCELL d_h0; G_percent(row, nrows, 2); /* read input maps */ Rast_get_d_row(infd_rnet, inrast_rnet, row); Rast_get_d_row(infd_g0, inrast_g0, row); Rast_get_d_row(infd_h0, inrast_h0, row); /*process the data */ for (col = 0; col < ncols; col++) { d_rnet = ((DCELL *) inrast_rnet)[col]; d_g0 = ((DCELL *) inrast_g0)[col]; d_h0 = ((DCELL *) inrast_h0)[col]; if (Rast_is_d_null_value(&d_rnet) || Rast_is_d_null_value(&d_g0) || Rast_is_d_null_value(&d_h0)) { Rast_set_d_null_value(&outrast1[col], 1); if (makin) Rast_set_d_null_value(&outrast2[col], 1); } else { /* calculate evaporative fraction */ d = evap_fr(d_rnet, d_g0, d_h0); outrast1[col] = d; /* calculate soil moisture */ if (makin) { d = soilmoisture(d); outrast2[col] = d; } } } Rast_put_d_row(outfd1, outrast1); if (makin) Rast_put_d_row(outfd2, outrast2); } G_free(inrast_rnet); G_free(inrast_g0); G_free(inrast_h0); Rast_close(infd_rnet); Rast_close(infd_g0); Rast_close(infd_h0); G_free(outrast1); Rast_close(outfd1); if (makin) { G_free(outrast2); Rast_close(outfd2); } Rast_short_history(result1, "raster", &history); Rast_command_history(&history); Rast_write_history(result1, &history); if (makin) { Rast_short_history(result2, "raster", &history); Rast_command_history(&history); Rast_write_history(result2, &history); } exit(EXIT_SUCCESS); }
int main(int argc, char *argv[]) { struct GModule *module; struct { struct Option *input, *output, *method, *quantile, *range; } parm; struct { struct Flag *nulls; } flag; int i; int num_inputs; struct input *inputs; int num_outputs; struct output *outputs; struct History history; DCELL *values, *values_tmp; int nrows, ncols; int row, col; double lo, hi; G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("raster")); G_add_keyword(_("series")); module->description = _("Makes each output cell value a " "function of the values assigned to the corresponding cells " "in the input raster map layers."); parm.input = G_define_standard_option(G_OPT_R_INPUTS); parm.output = G_define_standard_option(G_OPT_R_OUTPUT); parm.output->multiple = YES; parm.method = G_define_option(); parm.method->key = "method"; parm.method->type = TYPE_STRING; parm.method->required = YES; parm.method->options = build_method_list(); parm.method->description = _("Aggregate operation"); parm.method->multiple = YES; 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->multiple = YES; parm.range = G_define_option(); parm.range->key = "range"; parm.range->type = TYPE_DOUBLE; parm.range->key_desc = "lo,hi"; parm.range->description = _("Ignore values outside this range"); flag.nulls = G_define_flag(); flag.nulls->key = 'n'; flag.nulls->description = _("Propagate NULLs"); if (G_parser(argc, argv)) exit(EXIT_FAILURE); if (parm.range->answer) { lo = atof(parm.range->answers[0]); hi = atof(parm.range->answers[1]); } /* process the input maps */ for (i = 0; parm.input->answers[i]; i++) ; num_inputs = i; if (num_inputs < 1) G_fatal_error(_("Raster map not found")); inputs = G_malloc(num_inputs * sizeof(struct input)); for (i = 0; i < num_inputs; i++) { struct input *p = &inputs[i]; p->name = parm.input->answers[i]; G_message(_("Reading raster map <%s>..."), p->name); p->fd = Rast_open_old(p->name, ""); p->buf = Rast_allocate_d_buf(); } /* process the output maps */ for (i = 0; parm.output->answers[i]; i++) ; num_outputs = i; for (i = 0; parm.method->answers[i]; i++) ; if (num_outputs != i) G_fatal_error(_("output= and method= must have the same number of values")); outputs = G_calloc(num_outputs, sizeof(struct output)); for (i = 0; i < num_outputs; i++) { struct output *out = &outputs[i]; const char *output_name = parm.output->answers[i]; const char *method_name = parm.method->answers[i]; int method = find_method(method_name); out->name = output_name; out->method_fn = menu[method].method; out->quantile = (parm.quantile->answer && parm.quantile->answers[i]) ? atof(parm.quantile->answers[i]) : 0; out->buf = Rast_allocate_d_buf(); out->fd = Rast_open_new(output_name, menu[method].is_int ? CELL_TYPE : DCELL_TYPE); } /* initialise variables */ values = G_malloc(num_inputs * sizeof(DCELL)); values_tmp = G_malloc(num_inputs * sizeof(DCELL)); nrows = Rast_window_rows(); ncols = Rast_window_cols(); /* process the data */ G_verbose_message(_("Percent complete...")); for (row = 0; row < nrows; row++) { G_percent(row, nrows, 2); for (i = 0; i < num_inputs; i++) Rast_get_d_row(inputs[i].fd, inputs[i].buf, row); for (col = 0; col < ncols; col++) { int null = 0; for (i = 0; i < num_inputs; i++) { DCELL v = inputs[i].buf[col]; if (Rast_is_d_null_value(&v)) null = 1; else if (parm.range->answer && (v < lo || v > hi)) { Rast_set_d_null_value(&v, 1); null = 1; } values[i] = v; } for (i = 0; i < num_outputs; i++) { struct output *out = &outputs[i]; if (null && flag.nulls->answer) Rast_set_d_null_value(&out->buf[col], 1); else { memcpy(values_tmp, values, num_inputs * sizeof(DCELL)); (*out->method_fn)(&out->buf[col], values_tmp, num_inputs, &out->quantile); } } } for (i = 0; i < num_outputs; i++) Rast_put_d_row(outputs[i].fd, outputs[i].buf); } G_percent(row, nrows, 2); /* close maps */ for (i = 0; i < num_outputs; i++) { struct output *out = &outputs[i]; Rast_close(out->fd); Rast_short_history(out->name, "raster", &history); Rast_command_history(&history); Rast_write_history(out->name, &history); } for (i = 0; i < num_inputs; i++) Rast_close(inputs[i].fd); exit(EXIT_SUCCESS); }
int main(int argc, char *argv[]) { unsigned int r, c, rows, cols, n_valid; /* totals */ int *mapx_fd, mapy_fd, mapres_fd, mapest_fd; int i, j, k, n_predictors; double *sumX, sumY, *sumsqX, sumsqY, *sumXY; double *meanX, meanY, *varX, varY, *sdX, sdY; double yest, yres; /* estimated y, residual */ double sumYest, *SSerr_without; double SE; double meanYest, meanYres, varYest, varYres, sdYest, sdYres; double SStot, SSerr, SSreg; double **a; struct MATRIX *m, *m_all; double **B, Rsq, Rsqadj, F, t, AIC, AICc, BIC; unsigned int count = 0; DCELL **mapx_buf, *mapy_buf, *mapx_val, mapy_val, *mapres_buf, *mapest_buf; char *name; struct Option *input_mapx, *input_mapy, *output_res, *output_est, *output_opt; struct Flag *shell_style; struct Cell_head region; struct GModule *module; G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("raster")); G_add_keyword(_("statistics")); G_add_keyword(_("regression")); module->description = _("Calculates multiple linear regression from raster maps."); /* Define the different options */ input_mapx = G_define_standard_option(G_OPT_R_INPUTS); input_mapx->key = "mapx"; input_mapx->description = (_("Map for x coefficient")); input_mapy = G_define_standard_option(G_OPT_R_INPUT); input_mapy->key = "mapy"; input_mapy->description = (_("Map for y coefficient")); output_res = G_define_standard_option(G_OPT_R_OUTPUT); output_res->key = "residuals"; output_res->required = NO; output_res->description = (_("Map to store residuals")); output_est = G_define_standard_option(G_OPT_R_OUTPUT); output_est->key = "estimates"; output_est->required = NO; output_est->description = (_("Map to store estimates")); output_opt = G_define_standard_option(G_OPT_F_OUTPUT); output_opt->key = "output"; output_opt->required = NO; output_opt->description = (_("ASCII file for storing regression coefficients (output to screen if file not specified).")); shell_style = G_define_flag(); shell_style->key = 'g'; shell_style->description = _("Print in shell script style"); if (G_parser(argc, argv)) exit(EXIT_FAILURE); name = output_opt->answer; if (name != NULL && strcmp(name, "-") != 0) { if (NULL == freopen(name, "w", stdout)) { G_fatal_error(_("Unable to open file <%s> for writing"), name); } } G_get_window(®ion); rows = region.rows; cols = region.cols; /* count x maps */ for (i = 0; input_mapx->answers[i]; i++); n_predictors = i; /* allocate memory for x maps */ mapx_fd = (int *)G_malloc(n_predictors * sizeof(int)); sumX = (double *)G_malloc(n_predictors * sizeof(double)); sumsqX = (double *)G_malloc(n_predictors * sizeof(double)); sumXY = (double *)G_malloc(n_predictors * sizeof(double)); SSerr_without = (double *)G_malloc(n_predictors * sizeof(double)); meanX = (double *)G_malloc(n_predictors * sizeof(double)); varX = (double *)G_malloc(n_predictors * sizeof(double)); sdX = (double *)G_malloc(n_predictors * sizeof(double)); mapx_buf = (DCELL **)G_malloc(n_predictors * sizeof(DCELL *)); mapx_val = (DCELL *)G_malloc((n_predictors + 1) * sizeof(DCELL)); /* ordinary least squares */ m = NULL; m_all = (struct MATRIX *)G_malloc((n_predictors + 1) * sizeof(struct MATRIX)); a = (double **)G_malloc((n_predictors + 1) * sizeof(double *)); B = (double **)G_malloc((n_predictors + 1) * sizeof(double *)); m = &(m_all[0]); m->n = n_predictors + 1; m->v = (double *)G_malloc(m->n * m->n * sizeof(double)); a[0] = (double *)G_malloc(m->n * sizeof(double)); B[0] = (double *)G_malloc(m->n * sizeof(double)); for (i = 0; i < m->n; i++) { for (j = i; j < m->n; j++) M(m, i, j) = 0.0; a[0][i] = 0.0; B[0][i] = 0.0; } for (k = 1; k <= n_predictors; k++) { m = &(m_all[k]); m->n = n_predictors; m->v = (double *)G_malloc(m->n * m->n * sizeof(double)); a[k] = (double *)G_malloc(m->n * sizeof(double)); B[k] = (double *)G_malloc(m->n * sizeof(double)); for (i = 0; i < m->n; i++) { for (j = i; j < m->n; j++) M(m, i, j) = 0.0; a[k][i] = 0.0; B[k][i] = 0.0; } } /* open maps */ G_debug(1, "open maps"); for (i = 0; i < n_predictors; i++) { mapx_fd[i] = Rast_open_old(input_mapx->answers[i], ""); } mapy_fd = Rast_open_old(input_mapy->answer, ""); for (i = 0; i < n_predictors; i++) mapx_buf[i] = Rast_allocate_d_buf(); mapy_buf = Rast_allocate_d_buf(); for (i = 0; i < n_predictors; i++) { sumX[i] = sumsqX[i] = sumXY[i] = 0.0; meanX[i] = varX[i] = sdX[i] = 0.0; SSerr_without[i] = 0.0; } sumY = sumsqY = meanY = varY = sdY = 0.0; sumYest = meanYest = varYest = sdYest = 0.0; meanYres = varYres = sdYres = 0.0; /* read input maps */ G_message(_("First pass...")); n_valid = 0; mapx_val[0] = 1.0; for (r = 0; r < rows; r++) { G_percent(r, rows, 2); for (i = 0; i < n_predictors; i++) Rast_get_d_row(mapx_fd[i], mapx_buf[i], r); Rast_get_d_row(mapy_fd, mapy_buf, r); for (c = 0; c < cols; c++) { int isnull = 0; for (i = 0; i < n_predictors; i++) { mapx_val[i + 1] = mapx_buf[i][c]; if (Rast_is_d_null_value(&(mapx_val[i + 1]))) { isnull = 1; break; } } if (isnull) continue; mapy_val = mapy_buf[c]; if (Rast_is_d_null_value(&mapy_val)) continue; for (i = 0; i <= n_predictors; i++) { double val1 = mapx_val[i]; for (j = i; j <= n_predictors; j++) { double val2 = mapx_val[j]; m = &(m_all[0]); M(m, i, j) += val1 * val2; /* linear model without predictor k */ for (k = 1; k <= n_predictors; k++) { if (k != i && k != j) { int i2 = k > i ? i : i - 1; int j2 = k > j ? j : j - 1; m = &(m_all[k]); M(m, i2, j2) += val1 * val2; } } } a[0][i] += mapy_val * val1; for (k = 1; k <= n_predictors; k++) { if (k != i) { int i2 = k > i ? i : i - 1; a[k][i2] += mapy_val * val1; } } if (i > 0) { sumX[i - 1] += val1; sumsqX[i - 1] += val1 * val1; sumXY[i - 1] += val1 * mapy_val; } } sumY += mapy_val; sumsqY += mapy_val * mapy_val; count++; } } G_percent(rows, rows, 2); if (count < n_predictors + 1) G_fatal_error(_("Not enough valid cells available")); for (k = 0; k <= n_predictors; k++) { m = &(m_all[k]); /* TRANSPOSE VALUES IN UPPER HALF OF M TO OTHER HALF */ for (i = 1; i < m->n; i++) for (j = 0; j < i; j++) M(m, i, j) = M(m, j, i); if (!solvemat(m, a[k], B[k])) { for (i = 0; i <= n_predictors; i++) { fprintf(stdout, "b%d=0.0\n", i); } G_fatal_error(_("Multiple regression failed")); } } /* second pass */ G_message(_("Second pass...")); /* residuals output */ if (output_res->answer) { mapres_fd = Rast_open_new(output_res->answer, DCELL_TYPE); mapres_buf = Rast_allocate_d_buf(); } else { mapres_fd = -1; mapres_buf = NULL; } /* estimates output */ if (output_est->answer) { mapest_fd = Rast_open_new(output_est->answer, DCELL_TYPE); mapest_buf = Rast_allocate_d_buf(); } else { mapest_fd = -1; mapest_buf = NULL; } for (i = 0; i < n_predictors; i++) meanX[i] = sumX[i] / count; meanY = sumY / count; SStot = SSerr = SSreg = 0.0; for (r = 0; r < rows; r++) { G_percent(r, rows, 2); for (i = 0; i < n_predictors; i++) Rast_get_d_row(mapx_fd[i], mapx_buf[i], r); Rast_get_d_row(mapy_fd, mapy_buf, r); if (mapres_buf) Rast_set_d_null_value(mapres_buf, cols); if (mapest_buf) Rast_set_d_null_value(mapest_buf, cols); for (c = 0; c < cols; c++) { int isnull = 0; for (i = 0; i < n_predictors; i++) { mapx_val[i + 1] = mapx_buf[i][c]; if (Rast_is_d_null_value(&(mapx_val[i + 1]))) { isnull = 1; break; } } if (isnull) continue; yest = 0.0; for (i = 0; i <= n_predictors; i++) { yest += B[0][i] * mapx_val[i]; } if (mapest_buf) mapest_buf[c] = yest; mapy_val = mapy_buf[c]; if (Rast_is_d_null_value(&mapy_val)) continue; yres = mapy_val - yest; if (mapres_buf) mapres_buf[c] = yres; SStot += (mapy_val - meanY) * (mapy_val - meanY); SSreg += (yest - meanY) * (yest - meanY); SSerr += yres * yres; for (k = 1; k <= n_predictors; k++) { double yesti = 0.0; double yresi; /* linear model without predictor k */ for (i = 0; i <= n_predictors; i++) { if (i != k) { j = k > i ? i : i - 1; yesti += B[k][j] * mapx_val[i]; } } yresi = mapy_val - yesti; /* linear model without predictor k */ SSerr_without[k - 1] += yresi * yresi; varX[k - 1] = (mapx_val[k] - meanX[k - 1]) * (mapx_val[k] - meanX[k - 1]); } } if (mapres_buf) Rast_put_d_row(mapres_fd, mapres_buf); if (mapest_buf) Rast_put_d_row(mapest_fd, mapest_buf); } G_percent(rows, rows, 2); fprintf(stdout, "n=%d\n", count); /* coefficient of determination aka R squared */ Rsq = 1 - (SSerr / SStot); fprintf(stdout, "Rsq=%f\n", Rsq); /* adjusted coefficient of determination */ Rsqadj = 1 - ((SSerr * (count - 1)) / (SStot * (count - n_predictors - 1))); fprintf(stdout, "Rsqadj=%f\n", Rsqadj); /* F statistic */ /* F = ((SStot - SSerr) / (n_predictors)) / (SSerr / (count - n_predictors)); * , or: */ F = ((SStot - SSerr) * (count - n_predictors - 1)) / (SSerr * (n_predictors)); fprintf(stdout, "F=%f\n", F); i = 0; /* constant aka estimate for intercept in R */ fprintf(stdout, "b%d=%f\n", i, B[0][i]); /* t score for R squared of the full model, unused */ t = sqrt(Rsq) * sqrt((count - 2) / (1 - Rsq)); /* fprintf(stdout, "t%d=%f\n", i, t); */ /* AIC, corrected AIC, and BIC information criteria for the full model */ AIC = count * log(SSerr / count) + 2 * (n_predictors + 1); fprintf(stdout, "AIC=%f\n", AIC); AICc = AIC + (2 * n_predictors * (n_predictors + 1)) / (count - n_predictors - 1); fprintf(stdout, "AICc=%f\n", AICc); BIC = count * log(SSerr / count) + log(count) * (n_predictors + 1); fprintf(stdout, "BIC=%f\n", BIC); /* error variance of the model, identical to R */ SE = SSerr / (count - n_predictors - 1); /* fprintf(stdout, "SE=%f\n", SE); fprintf(stdout, "SSerr=%f\n", SSerr); */ for (i = 0; i < n_predictors; i++) { fprintf(stdout, "\npredictor%d=%s\n", i + 1, input_mapx->answers[i]); fprintf(stdout, "b%d=%f\n", i + 1, B[0][i + 1]); if (n_predictors > 1) { double Rsqi, SEi, sumsqX_corr; /* corrected sum of squares for predictor [i] */ sumsqX_corr = sumsqX[i] - sumX[i] * sumX[i] / (count - n_predictors - 1); /* standard error SE for predictor [i] */ /* SE[i] with only one predictor: sqrt(SE / sumsqX_corr) * this does not work with more than one predictor */ /* in R, SEi is sqrt(diag(R) * resvar) with * R = ??? * resvar = rss / rdf = SE global * rss = sum of squares of the residuals * rdf = residual degrees of freedom = count - n_predictors - 1 */ SEi = sqrt(SE / (Rsq * sumsqX_corr)); /* fprintf(stdout, "SE%d=%f\n", i + 1, SEi); */ /* Sum of squares for predictor [i] */ /* fprintf(stdout, "SSerr%d=%f\n", i + 1, SSerr_without[i] - SSerr); */ /* R squared of the model without predictor [i] */ /* Rsqi = 1 - SSerr_without[i] / SStot; */ /* the additional amount of variance explained * when including predictor [i] : * Rsq - Rsqi */ Rsqi = (SSerr_without[i] - SSerr) / SStot; fprintf(stdout, "Rsq%d=%f\n", i + 1, Rsqi); /* t score for Student's t distribution, unused */ t = (B[0][i + 1]) / SEi; /* fprintf(stdout, "t%d=%f\n", i + 1, t); */ /* F score for Fisher's F distribution * here: F score to test if including predictor [i] * yields a significant improvement * after Lothar Sachs, Angewandte Statistik: * F = (Rsq - Rsqi) * (count - n_predictors - 1) / (1 - Rsq) */ /* same like Sumsq / SE */ /* same like (SSerr_without[i] / SSerr - 1) * (count - n_predictors - 1) */ /* same like R-stats when entered in R-stats as last predictor */ F = (SSerr_without[i] / SSerr - 1) * (count - n_predictors - 1); fprintf(stdout, "F%d=%f\n", i + 1, F); /* AIC, corrected AIC, and BIC information criteria for * the model without predictor [i] */ AIC = count * log(SSerr_without[i] / count) + 2 * (n_predictors); fprintf(stdout, "AIC%d=%f\n", i + 1, AIC); AICc = AIC + (2 * (n_predictors - 1) * n_predictors) / (count - n_predictors - 2); fprintf(stdout, "AICc%d=%f\n", i + 1, AICc); BIC = count * log(SSerr_without[i] / count) + (n_predictors - 1) * log(count); fprintf(stdout, "BIC%d=%f\n", i + 1, BIC); } } for (i = 0; i < n_predictors; i++) { Rast_close(mapx_fd[i]); G_free(mapx_buf[i]); } Rast_close(mapy_fd); G_free(mapy_buf); if (mapres_fd > -1) { struct History history; Rast_close(mapres_fd); G_free(mapres_buf); Rast_short_history(output_res->answer, "raster", &history); Rast_command_history(&history); Rast_write_history(output_res->answer, &history); } if (mapest_fd > -1) { struct History history; Rast_close(mapest_fd); G_free(mapest_buf); Rast_short_history(output_est->answer, "raster", &history); Rast_command_history(&history); Rast_write_history(output_est->answer, &history); } exit(EXIT_SUCCESS); }
/* ************************************************************************* */ void rast3d_cross_section(void *map,RASTER3D_Region region, int elevfd, int outfd) { int col, row; int rows, cols, depths, typeIntern; FCELL *fcell = NULL; DCELL *dcell = NULL; void *elevrast; void *ptr; int intvalue; float fvalue; double dvalue; double elevation = 0; double north, east; struct Cell_head window; Rast_get_window(&window); rows = region.rows; cols = region.cols; depths = region.depths; /*Typ of the RASTER3D Tile */ typeIntern = Rast3d_tile_type_map(map); /*Allocate mem for the output maps row */ if (typeIntern == FCELL_TYPE) fcell = Rast_allocate_f_buf(); else if (typeIntern == DCELL_TYPE) dcell = Rast_allocate_d_buf(); /*Mem for the input map row */ elevrast = Rast_allocate_buf(globalElevMapType); for (row = 0; row < rows; row++) { G_percent(row, rows - 1, 10); /*Read the input map row */ Rast_get_row(elevfd, elevrast, row, globalElevMapType); for (col = 0, ptr = elevrast; col < cols; col++, ptr = G_incr_void_ptr(ptr, Rast_cell_size(globalElevMapType))) { if (Rast_is_null_value(ptr, globalElevMapType)) { if (typeIntern == FCELL_TYPE) Rast_set_null_value(&fcell[col], 1, FCELL_TYPE); else if (typeIntern == DCELL_TYPE) Rast_set_null_value(&dcell[col], 1, DCELL_TYPE); continue; } /*Read the elevation value */ if (globalElevMapType == CELL_TYPE) { intvalue = *(CELL *) ptr; elevation = intvalue; } else if (globalElevMapType == FCELL_TYPE) { fvalue = *(FCELL *) ptr; elevation = fvalue; } else if (globalElevMapType == DCELL_TYPE) { dvalue = *(DCELL *) ptr; elevation = dvalue; } /* Compute the coordinates */ north = Rast_row_to_northing((double)row + 0.5, &window); east = Rast_col_to_easting((double)col + 0.5, &window); /* Get the voxel value */ if (typeIntern == FCELL_TYPE) Rast3d_get_region_value(map, north, east, elevation, &fcell[col], FCELL_TYPE); if (typeIntern == DCELL_TYPE) Rast3d_get_region_value(map, north, east, elevation, &dcell[col], DCELL_TYPE); } /*Write the data to the output map */ if (typeIntern == FCELL_TYPE) Rast_put_f_row(outfd, fcell); if (typeIntern == DCELL_TYPE) Rast_put_d_row(outfd, dcell); } G_debug(3, "\nDone\n"); /*Free the mem */ if (elevrast) G_free(elevrast); if (dcell) G_free(dcell); if (fcell) G_free(fcell); }
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); }
static void resamp_unweighted(void) { stat_func *method_fn; DCELL *values; int *col_map, *row_map; int row, col; method_fn = menu[method].method; values = G_malloc(row_scale * col_scale * sizeof(DCELL)); col_map = G_malloc((dst_w.cols + 1) * sizeof(int)); row_map = G_malloc((dst_w.rows + 1) * sizeof(int)); for (col = 0; col <= dst_w.cols; col++) { double x = Rast_col_to_easting(col, &dst_w); col_map[col] = (int)floor(Rast_easting_to_col(x, &src_w) + 0.5); } for (row = 0; row <= dst_w.rows; row++) { double y = Rast_row_to_northing(row, &dst_w); row_map[row] = (int)floor(Rast_northing_to_row(y, &src_w) + 0.5); } for (row = 0; row < dst_w.rows; row++) { int maprow0 = row_map[row + 0]; int maprow1 = row_map[row + 1]; int count = maprow1 - maprow0; int i; G_percent(row, dst_w.rows, 2); for (i = 0; i < count; i++) Rast_get_d_row(infile, bufs[i], maprow0 + i); for (col = 0; col < dst_w.cols; col++) { int mapcol0 = col_map[col + 0]; int mapcol1 = col_map[col + 1]; int null = 0; int n = 0; int i, j; for (i = maprow0; i < maprow1; i++) for (j = mapcol0; j < mapcol1; j++) { DCELL *src = &bufs[i - maprow0][j]; DCELL *dst = &values[n++]; if (Rast_is_d_null_value(src)) { Rast_set_d_null_value(dst, 1); null = 1; } else *dst = *src; } if (null && nulls) Rast_set_d_null_value(&outbuf[col], 1); else (*method_fn) (&outbuf[col], values, n, closure); } Rast_put_d_row(outfile, outbuf); } }
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[]) { /* Global variable & function declarations */ struct GModule *module; struct { struct Option *orig, *real, *imag; } opt; const char *Cellmap_real, *Cellmap_imag; const char *Cellmap_orig; int realfd, imagfd, outputfd, maskfd; /* the input and output file descriptors */ struct Cell_head realhead, imaghead; DCELL *cell_real, *cell_imag; CELL *maskbuf; int i, j; /* Loop control variables */ int rows, cols; /* number of rows & columns */ long totsize; /* Total number of data points */ double (*data)[2]; /* Data structure containing real & complex values of FFT */ G_gisinit(argv[0]); /* Set description */ module = G_define_module(); G_add_keyword(_("imagery")); G_add_keyword(_("transformation")); G_add_keyword(_("Fast Fourier Transform")); module->description = _("Inverse Fast Fourier Transform (IFFT) for image processing."); /* define options */ opt.real = G_define_standard_option(G_OPT_R_INPUT); opt.real->key = "real"; opt.real->description = _("Name of input raster map (image fft, real part)"); opt.imag = G_define_standard_option(G_OPT_R_INPUT); opt.imag->key = "imaginary"; opt.imag->description = _("Name of input raster map (image fft, imaginary part"); opt.orig = G_define_standard_option(G_OPT_R_OUTPUT); opt.orig->description = _("Name for output raster map"); /*call parser */ if (G_parser(argc, argv)) exit(EXIT_FAILURE); Cellmap_real = opt.real->answer; Cellmap_imag = opt.imag->answer; Cellmap_orig = opt.orig->answer; /* get and compare the original window data */ Rast_get_cellhd(Cellmap_real, "", &realhead); Rast_get_cellhd(Cellmap_imag, "", &imaghead); if (realhead.proj != imaghead.proj || realhead.zone != imaghead.zone || realhead.north != imaghead.north || realhead.south != imaghead.south || realhead.east != imaghead.east || realhead.west != imaghead.west || realhead.ew_res != imaghead.ew_res || realhead.ns_res != imaghead.ns_res) G_fatal_error(_("The real and imaginary original windows did not match")); Rast_set_window(&realhead); /* set the window to the whole cell map */ /* open input raster map */ realfd = Rast_open_old(Cellmap_real, ""); imagfd = Rast_open_old(Cellmap_imag, ""); /* get the rows and columns in the current window */ rows = Rast_window_rows(); cols = Rast_window_cols(); totsize = rows * cols; /* Allocate appropriate memory for the structure containing the real and complex components of the FFT. DATA[0] will contain the real, and DATA[1] the complex component. */ data = G_malloc(rows * cols * 2 * sizeof(double)); /* allocate the space for one row of cell map data */ cell_real = Rast_allocate_d_buf(); cell_imag = Rast_allocate_d_buf(); #define C(i, j) ((i) * cols + (j)) /* Read in cell map values */ G_message(_("Reading raster maps...")); for (i = 0; i < rows; i++) { Rast_get_d_row(realfd, cell_real, i); Rast_get_d_row(imagfd, cell_imag, i); for (j = 0; j < cols; j++) { data[C(i, j)][0] = cell_real[j]; data[C(i, j)][1] = cell_imag[j]; } G_percent(i+1, rows, 2); } /* close input cell maps */ Rast_close(realfd); Rast_close(imagfd); /* Read in cell map values */ G_message(_("Masking raster maps...")); maskfd = Rast_maskfd(); if (maskfd >= 0) { maskbuf = Rast_allocate_c_buf(); for (i = 0; i < rows; i++) { Rast_get_c_row(maskfd, maskbuf, i); for (j = 0; j < cols; j++) { if (maskbuf[j] == 0) { data[C(i, j)][0] = 0.0; data[C(i, j)][1] = 0.0; } } G_percent(i+1, rows, 2); } Rast_close(maskfd); G_free(maskbuf); } #define SWAP1(a, b) \ do { \ double temp = (a); \ (a) = (b); \ (b) = temp; \ } while (0) #define SWAP2(a, b) \ do { \ SWAP1(data[(a)][0], data[(b)][0]); \ SWAP1(data[(a)][1], data[(b)][1]); \ } while (0) /* rotate the data array for standard display */ G_message(_("Rotating data...")); for (i = 0; i < rows; i++) for (j = 0; j < cols / 2; j++) SWAP2(C(i, j), C(i, j + cols / 2)); for (i = 0; i < rows / 2; i++) for (j = 0; j < cols; j++) SWAP2(C(i, j), C(i + rows / 2, j)); /* perform inverse FFT */ G_message(_("Starting Inverse FFT...")); fft2(1, data, totsize, cols, rows); /* open the output cell map */ outputfd = Rast_open_fp_new(Cellmap_orig); /* Write out result to a new cell map */ G_message(_("Writing raster map <%s>..."), Cellmap_orig); for (i = 0; i < rows; i++) { for (j = 0; j < cols; j++) cell_real[j] = data[C(i, j)][0]; Rast_put_d_row(outputfd, cell_real); G_percent(i+1, rows, 2); } Rast_close(outputfd); G_free(cell_real); G_free(cell_imag); fft_colors(Cellmap_orig); /* Release memory resources */ G_free(data); G_done_msg(" "); exit(EXIT_SUCCESS); }
int main(int argc, char *argv[]) { 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) { static DCELL *count, *sum, *mean, *sumu, *sum2, *sum3, *sum4, *min, *max; DCELL *result; struct GModule *module; struct { struct Option *method, *basemap, *covermap, *output; } opt; struct { struct Flag *c, *r; } flag; char methods[2048]; const char *basemap, *covermap, *output; int usecats; int reclass; int base_fd, cover_fd; struct Categories cats; CELL *base_buf; DCELL *cover_buf; struct Range range; CELL mincat, ncats; int method; int rows, cols; int row, col, i; G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("raster")); G_add_keyword(_("statistics")); module->description = _("Calculates category or object oriented statistics (accumulator-based statistics)."); opt.basemap = G_define_standard_option(G_OPT_R_BASE); opt.covermap = G_define_standard_option(G_OPT_R_COVER); opt.method = G_define_option(); opt.method->key = "method"; opt.method->type = TYPE_STRING; opt.method->required = YES; opt.method->description = _("Method of object-based statistic"); for (i = 0; menu[i].name; i++) { if (i) strcat(methods, ","); else *(methods) = 0; strcat(methods, menu[i].name); } opt.method->options = G_store(methods); for (i = 0; menu[i].name; i++) { if (i) strcat(methods, ";"); else *(methods) = 0; strcat(methods, menu[i].name); strcat(methods, ";"); strcat(methods, menu[i].text); } opt.method->descriptions = G_store(methods); opt.output = G_define_standard_option(G_OPT_R_OUTPUT); opt.output->description = _("Resultant raster map"); opt.output->required = YES; flag.c = G_define_flag(); flag.c->key = 'c'; flag.c->description = _("Cover values extracted from the category labels of the cover map"); flag.r = G_define_flag(); flag.r->key = 'r'; flag.r->description = _("Create reclass map with statistics as category labels"); if (G_parser(argc, argv)) exit(EXIT_FAILURE); basemap = opt.basemap->answer; covermap = opt.covermap->answer; output = opt.output->answer; usecats = flag.c->answer; reclass = flag.r->answer; for (i = 0; menu[i].name; i++) if (strcmp(menu[i].name, opt.method->answer) == 0) break; if (!menu[i].name) { G_warning(_("<%s=%s> unknown %s"), opt.method->key, opt.method->answer, opt.method->key); G_usage(); exit(EXIT_FAILURE); } method = menu[i].val; base_fd = Rast_open_old(basemap, ""); cover_fd = Rast_open_old(covermap, ""); if (usecats && Rast_read_cats(covermap, "", &cats) < 0) G_fatal_error(_("Unable to read category file of cover map <%s>"), covermap); if (Rast_map_is_fp(basemap, "") != 0) G_fatal_error(_("The base map must be an integer (CELL) map")); if (Rast_read_range(basemap, "", &range) < 0) G_fatal_error(_("Unable to read range of base map <%s>"), basemap); mincat = range.min; ncats = range.max - range.min + 1; rows = Rast_window_rows(); cols = Rast_window_cols(); switch (method) { case COUNT: count = G_calloc(ncats, sizeof(DCELL)); break; case SUM: sum = G_calloc(ncats, sizeof(DCELL)); break; case MIN: min = G_malloc(ncats * sizeof(DCELL)); break; case MAX: max = G_malloc(ncats * sizeof(DCELL)); break; case RANGE: min = G_malloc(ncats * sizeof(DCELL)); max = G_malloc(ncats * sizeof(DCELL)); break; case AVERAGE: case ADEV: case VARIANCE2: case STDDEV2: case SKEWNESS2: case KURTOSIS2: count = G_calloc(ncats, sizeof(DCELL)); sum = G_calloc(ncats, sizeof(DCELL)); break; case VARIANCE1: case STDDEV1: count = G_calloc(ncats, sizeof(DCELL)); sum = G_calloc(ncats, sizeof(DCELL)); sum2 = G_calloc(ncats, sizeof(DCELL)); break; case SKEWNESS1: count = G_calloc(ncats, sizeof(DCELL)); sum = G_calloc(ncats, sizeof(DCELL)); sum2 = G_calloc(ncats, sizeof(DCELL)); sum3 = G_calloc(ncats, sizeof(DCELL)); break; case KURTOSIS1: count = G_calloc(ncats, sizeof(DCELL)); sum = G_calloc(ncats, sizeof(DCELL)); sum2 = G_calloc(ncats, sizeof(DCELL)); sum4 = G_calloc(ncats, sizeof(DCELL)); break; } if (min) for (i = 0; i < ncats; i++) min[i] = 1e300; if (max) for (i = 0; i < ncats; i++) max[i] = -1e300; base_buf = Rast_allocate_c_buf(); cover_buf = Rast_allocate_d_buf(); G_message(_("First pass")); for (row = 0; row < rows; row++) { Rast_get_c_row(base_fd, base_buf, row); Rast_get_d_row(cover_fd, cover_buf, row); for (col = 0; col < cols; col++) { int n; DCELL v; if (Rast_is_c_null_value(&base_buf[col])) continue; if (Rast_is_d_null_value(&cover_buf[col])) continue; n = base_buf[col] - mincat; if (n < 0 || n >= ncats) continue; v = cover_buf[col]; if (usecats) sscanf(Rast_get_c_cat((CELL *) &v, &cats), "%lf", &v); if (count) count[n]++; if (sum) sum[n] += v; if (sum2) sum2[n] += v * v; if (sum3) sum3[n] += v * v * v; if (sum4) sum4[n] += v * v * v * v; if (min && min[n] > v) min[n] = v; if (max && max[n] < v) max[n] = v; } G_percent(row, rows, 2); } G_percent(row, rows, 2); result = G_calloc(ncats, sizeof(DCELL)); switch (method) { case ADEV: case VARIANCE2: case STDDEV2: case SKEWNESS2: case KURTOSIS2: mean = G_calloc(ncats, sizeof(DCELL)); for (i = 0; i < ncats; i++) mean[i] = sum[i] / count[i]; G_free(sum); break; } switch (method) { case ADEV: sumu = G_calloc(ncats, sizeof(DCELL)); break; case VARIANCE2: case STDDEV2: sum2 = G_calloc(ncats, sizeof(DCELL)); break; case SKEWNESS2: sum2 = G_calloc(ncats, sizeof(DCELL)); sum3 = G_calloc(ncats, sizeof(DCELL)); break; case KURTOSIS2: sum2 = G_calloc(ncats, sizeof(DCELL)); sum4 = G_calloc(ncats, sizeof(DCELL)); break; } if (mean) { G_message(_("Second pass")); for (row = 0; row < rows; row++) { Rast_get_c_row(base_fd, base_buf, row); Rast_get_d_row(cover_fd, cover_buf, row); for (col = 0; col < cols; col++) { int n; DCELL v, d; if (Rast_is_c_null_value(&base_buf[col])) continue; if (Rast_is_d_null_value(&cover_buf[col])) continue; n = base_buf[col] - mincat; if (n < 0 || n >= ncats) continue; v = cover_buf[col]; if (usecats) sscanf(Rast_get_c_cat((CELL *) &v, &cats), "%lf", &v); d = v - mean[n]; if (sumu) sumu[n] += fabs(d); if (sum2) sum2[n] += d * d; if (sum3) sum3[n] += d * d * d; if (sum4) sum4[n] += d * d * d * d; } G_percent(row, rows, 2); } G_percent(row, rows, 2); G_free(mean); G_free(cover_buf); } switch (method) { case COUNT: for (i = 0; i < ncats; i++) result[i] = count[i]; break; case SUM: for (i = 0; i < ncats; i++) result[i] = sum[i]; break; case AVERAGE: for (i = 0; i < ncats; i++) result[i] = sum[i] / count[i]; break; case MIN: for (i = 0; i < ncats; i++) result[i] = min[i]; break; case MAX: for (i = 0; i < ncats; i++) result[i] = max[i]; break; case RANGE: for (i = 0; i < ncats; i++) result[i] = max[i] - min[i]; break; case VARIANCE1: for (i = 0; i < ncats; i++) { double n = count[i]; double var = (sum2[i] - sum[i] * sum[i] / n) / (n - 1); result[i] = var; } break; case STDDEV1: for (i = 0; i < ncats; i++) { double n = count[i]; double var = (sum2[i] - sum[i] * sum[i] / n) / (n - 1); result[i] = sqrt(var); } break; case SKEWNESS1: for (i = 0; i < ncats; i++) { double n = count[i]; double var = (sum2[i] - sum[i] * sum[i] / n) / (n - 1); double skew = (sum3[i] / n - 3 * sum[i] * sum2[i] / (n * n) + 2 * sum[i] * sum[i] * sum[i] / (n * n * n)) / (pow(var, 1.5)); result[i] = skew; } break; case KURTOSIS1: for (i = 0; i < ncats; i++) { double n = count[i]; double var = (sum2[i] - sum[i] * sum[i] / n) / (n - 1); double kurt = (sum4[i] / n - 4 * sum[i] * sum3[i] / (n * n) + 6 * sum[i] * sum[i] * sum2[i] / (n * n * n) - 3 * sum[i] * sum[i] * sum[i] * sum[i] / (n * n * n * n)) / (var * var) - 3; result[i] = kurt; } break; case ADEV: for (i = 0; i < ncats; i++) result[i] = sumu[i] / count[i]; break; case VARIANCE2: for (i = 0; i < ncats; i++) result[i] = sum2[i] / (count[i] - 1); break; case STDDEV2: for (i = 0; i < ncats; i++) result[i] = sqrt(sum2[i] / (count[i] - 1)); break; case SKEWNESS2: for (i = 0; i < ncats; i++) { double n = count[i]; double var = sum2[i] / (n - 1); double sdev = sqrt(var); result[i] = sum3[i] / (sdev * sdev * sdev) / n; } G_free(count); G_free(sum2); G_free(sum3); break; case KURTOSIS2: for (i = 0; i < ncats; i++) { double n = count[i]; double var = sum2[i] / (n - 1); result[i] = sum4[i] / (var * var) / n - 3; } G_free(count); G_free(sum2); G_free(sum4); break; } if (reclass) { const char *tempfile = G_tempfile(); char *input_arg = G_malloc(strlen(basemap) + 7); char *output_arg = G_malloc(strlen(output) + 8); char *rules_arg = G_malloc(strlen(tempfile) + 7); FILE *fp; G_message(_("Generating reclass map")); sprintf(input_arg, "input=%s", basemap); sprintf(output_arg, "output=%s", output); sprintf(rules_arg, "rules=%s", tempfile); fp = fopen(tempfile, "w"); if (!fp) G_fatal_error(_("Unable to open temporary file")); for (i = 0; i < ncats; i++) fprintf(fp, "%d = %d %f\n", mincat + i, mincat + i, result[i]); fclose(fp); G_spawn("r.reclass", "r.reclass", input_arg, output_arg, rules_arg, NULL); } else { int out_fd; DCELL *out_buf; struct Colors colors; G_message(_("Writing output map")); out_fd = Rast_open_fp_new(output); out_buf = Rast_allocate_d_buf(); for (row = 0; row < rows; row++) { Rast_get_c_row(base_fd, base_buf, row); for (col = 0; col < cols; col++) if (Rast_is_c_null_value(&base_buf[col])) Rast_set_d_null_value(&out_buf[col], 1); else out_buf[col] = result[base_buf[col] - mincat]; Rast_put_d_row(out_fd, out_buf); G_percent(row, rows, 2); } G_percent(row, rows, 2); Rast_close(out_fd); if (Rast_read_colors(covermap, "", &colors) > 0) Rast_write_colors(output, G_mapset(), &colors); } return 0; }
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 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[]) { /* buffer for input-output rasters */ void *inrast_TEMPKAVG, *inrast_TEMPKMIN, *inrast_TEMPKMAX, *inrast_RNET, *inrast_P; DCELL *outrast; /* pointers to input-output raster files */ int infd_TEMPKAVG, infd_TEMPKMIN, infd_TEMPKMAX, infd_RNET, infd_P; int outfd; /* names of input-output raster files */ char *RNET, *TEMPKAVG, *TEMPKMIN, *TEMPKMAX, *P; char *ETa; /* input-output cell values */ DCELL d_tempkavg, d_tempkmin, d_tempkmax, d_rnet, d_p; DCELL 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_TEMPKAVG, *input_TEMPKMIN; struct Option *input_TEMPKMAX, *input_P; struct Option *output; struct Flag *zero, *original, *samani; 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 " "modified or original Hargreaves formulation, 2001."); /* Define different options */ input_RNET = G_define_standard_option(G_OPT_R_INPUT); input_RNET->key = "netradiation_diurnal"; input_RNET->description = _("Name of input diurnal net radiation raster map [W/m2/d]"); input_TEMPKAVG = G_define_standard_option(G_OPT_R_INPUT); input_TEMPKAVG->key = "average_temperature"; input_TEMPKAVG->description = _("Name of input average air temperature raster map [C]"); input_TEMPKMIN = G_define_standard_option(G_OPT_R_INPUT); input_TEMPKMIN->key = "minimum_temperature"; input_TEMPKMIN->description = _("Name of input minimum air temperature raster map [C]"); input_TEMPKMAX = G_define_standard_option(G_OPT_R_INPUT); input_TEMPKMAX->key = "maximum_temperature"; input_TEMPKMAX->description = _("Name of input maximum air temperature raster map [C]"); input_P = G_define_standard_option(G_OPT_R_INPUT); input_P->required = NO; input_P->key = "precipitation"; input_P->label = _("Name of precipitation raster map [mm/month]"); input_P->description = _("Disabled for original Hargreaves (1985)"); output = G_define_standard_option(G_OPT_R_OUTPUT); output->description = _("Name for output raster map [mm/d]"); /* Define the different flags */ zero = G_define_flag(); zero->key = 'z'; zero->description = _("Set negative ETa to zero"); original = G_define_flag(); original->key = 'h'; original->description = _("Use original Hargreaves (1985)"); samani = G_define_flag(); samani->key = 's'; samani->description = _("Use Hargreaves-Samani (1985)"); if (G_parser(argc, argv)) exit(EXIT_FAILURE); /* get entered parameters */ RNET = input_RNET->answer; TEMPKAVG = input_TEMPKAVG->answer; TEMPKMIN = input_TEMPKMIN->answer; TEMPKMAX = input_TEMPKMAX->answer; P = input_P->answer; ETa = output->answer; /* open pointers to input raster files */ infd_RNET = Rast_open_old(RNET, ""); infd_TEMPKAVG = Rast_open_old(TEMPKAVG, ""); infd_TEMPKMIN = Rast_open_old(TEMPKMIN, ""); infd_TEMPKMAX = Rast_open_old(TEMPKMAX, ""); if (!original->answer) { infd_P = Rast_open_old(P, ""); } /* read headers of raster files */ Rast_get_cellhd(RNET, "", &cellhd); Rast_get_cellhd(TEMPKAVG, "", &cellhd); Rast_get_cellhd(TEMPKMIN, "", &cellhd); Rast_get_cellhd(TEMPKMAX, "", &cellhd); if (!original->answer) { Rast_get_cellhd(P, "", &cellhd); } /* Allocate input buffer */ inrast_RNET = Rast_allocate_d_buf(); inrast_TEMPKAVG = Rast_allocate_d_buf(); inrast_TEMPKMIN = Rast_allocate_d_buf(); inrast_TEMPKMAX = Rast_allocate_d_buf(); if (!original->answer) { inrast_P = 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_TEMPKAVG, inrast_TEMPKAVG, row); Rast_get_d_row(infd_TEMPKMIN, inrast_TEMPKMIN, row); Rast_get_d_row(infd_TEMPKMAX, inrast_TEMPKMAX, row); if (!original->answer) { Rast_get_d_row(infd_P, inrast_P, row); } for (col = 0; col < ncols; col++) { /* read current cell from line buffer */ d_rnet = ((DCELL *) inrast_RNET)[col]; d_tempkavg = ((DCELL *) inrast_TEMPKAVG)[col]; d_tempkmin = ((DCELL *) inrast_TEMPKMIN)[col]; d_tempkmax = ((DCELL *) inrast_TEMPKMAX)[col]; if (!original->answer) { d_p = ((DCELL *) inrast_P)[col]; } if (Rast_is_d_null_value(&d_rnet) || Rast_is_d_null_value(&d_tempkavg) || Rast_is_d_null_value(&d_tempkmin) || Rast_is_d_null_value(&d_tempkmax) || Rast_is_d_null_value(&d_p)) { Rast_set_d_null_value(&outrast[col], 1); } else { if (original->answer) { d_daily_et = mh_original(d_rnet, d_tempkavg, d_tempkmax, d_tempkmin, d_p); } else if (samani->answer) { d_daily_et = mh_samani(d_rnet, d_tempkavg, d_tempkmax, d_tempkmin); } else { d_daily_et = mh_eto(d_rnet, d_tempkavg, d_tempkmax, d_tempkmin, d_p); } 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_TEMPKAVG); G_free(inrast_TEMPKMIN); G_free(inrast_TEMPKMAX); if (!original->answer) { G_free(inrast_P); } Rast_close(infd_RNET); Rast_close(infd_TEMPKAVG); Rast_close(infd_TEMPKMIN); Rast_close(infd_TEMPKMAX); if (!original->answer) { Rast_close(infd_P); } /* 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); }