static int get_cell(DCELL *result, int fd, double x, double y) { static DCELL *row1, *row2; static int cur_row = -1; static int row, col; DCELL *tmp; if (!row1) { row1 = Rast_allocate_d_buf(); row2 = Rast_allocate_d_buf(); } col = (int)floor(x - 0.5); row = (int)floor(y - 0.5); x -= col + 0.5; y -= row + 0.5; if (row < 0 || row + 1 >= Rast_window_rows() || col < 0 || col + 1 >= Rast_window_cols()) { Rast_set_d_null_value(result, 1); return 0; } if (cur_row != row) { if (cur_row == row + 1) { tmp = row1; row1 = row2; row2 = tmp; Rast_get_d_row(fd, row1, row); } else if (cur_row == row - 1) { tmp = row1; row1 = row2; row2 = tmp; Rast_get_d_row(fd, row2, row + 1); } else { Rast_get_d_row(fd, row1, row); Rast_get_d_row(fd, row2, row + 1); } cur_row = row; } if (Rast_is_d_null_value(&row1[col]) || Rast_is_d_null_value(&row1[col+1]) || Rast_is_d_null_value(&row2[col]) || Rast_is_d_null_value(&row2[col+1])) { Rast_set_d_null_value(result, 1); return 0; } *result = Rast_interp_bilinear(x, y, row1[col], row1[col+1], row2[col], row2[col+1]); return 1; }
static void read_rows(int infile, int row) { int end_row = cur_row + neighbors; int first_row = row; int last_row = row + neighbors; int offset = first_row - cur_row; int keep = end_row - first_row; int i; if (end_row >= last_row) return; if (keep > 0 && offset > 0) for (i = 0; i < keep; i++) { DCELL *tmp = bufs[i]; bufs[i] = bufs[i + offset]; bufs[i + offset] = tmp; } if (keep < 0) keep = 0; for (i = keep; i < neighbors; i++) Rast_get_d_row(infile, bufs[i], first_row + i); cur_row = first_row; }
static void fill_bins(int basefile, int coverfile) { CELL *basebuf = Rast_allocate_c_buf(); DCELL *coverbuf = Rast_allocate_d_buf(); int row, col; G_message(_("Binning data")); for (row = 0; row < rows; row++) { Rast_get_c_row(basefile, basebuf, row); Rast_get_d_row(coverfile, coverbuf, row); for (col = 0; col < cols; col++) { struct basecat *bc; int i, bin; struct bin *b; if (Rast_is_c_null_value(&basebuf[col])) continue; if (Rast_is_d_null_value(&coverbuf[col])) continue; i = get_slot(coverbuf[col]); bc = &basecats[basebuf[col] - min]; if (!bc->slot_bins[i]) continue; bin = bc->slot_bins[i] - 1; b = &bc->bins[bin]; bc->values[b->base + b->count++] = coverbuf[col]; } G_percent(row, rows, 2); } G_percent(rows, rows, 2); G_free(basebuf); G_free(coverbuf); }
static void get_region_range(int fd) { DCELL *buf = Rast_allocate_d_buf(); int nrows = Rast_window_rows(); int ncols = Rast_window_cols(); int row, col; min = 1e300; max = -1e300; for (row = 0; row < nrows; row++) { Rast_get_d_row(fd, buf, row); for (col = 0; col < ncols; col++) { if (min > buf[col]) min = buf[col]; if (max < buf[col]) max = buf[col]; } } }
/*! * \brief Extract a cell value from raster map (neighbor interpolation) * * Extract a cell value from raster map at given northing and easting * with a sampled 3x3 window using a neighbor interpolation. * * \param fd file descriptor * \param window region settings * \param cats categories * \param north northing position * \param east easting position * \param usedesc flag to scan category label * * \return cell value at given position */ DCELL Rast_get_sample_nearest(int fd, const struct Cell_head * window, struct Categories * cats, double north, double east, int usedesc) { int row, col; DCELL result; DCELL *maprow = Rast_allocate_d_buf(); /* convert northing and easting to row and col, resp */ row = (int)floor(Rast_northing_to_row(north, window)); col = (int)floor(Rast_easting_to_col(east, window)); if (row < 0 || row >= Rast_window_rows() || col < 0 || col >= Rast_window_cols()) { Rast_set_d_null_value(&result, 1); goto done; } Rast_get_d_row(fd, maprow, row); if (Rast_is_d_null_value(&maprow[col])) { Rast_set_d_null_value(&result, 1); goto done; } if (usedesc) { char *buf = Rast_get_c_cat((CELL *) & (maprow[col]), cats); G_squeeze(buf); result = scancatlabel(buf); } else result = maprow[col]; done: G_free(maprow); return result; }
int read_data(struct files *files, struct SigSet *S) { int n; int b; int nrows, ncols, row, col; CELL *class; struct ClassData *Data; nrows = Rast_window_rows(); ncols = Rast_window_cols(); class = (CELL *) G_calloc(ncols, sizeof(CELL)); G_message(_("Reading raster maps...")); for (row = 0; row < nrows; row++) { G_percent(row, nrows, 2); read_training_map(class, row, ncols, files); for (b = 0; b < files->nbands; b++) Rast_get_d_row(files->band_fd[b], files->band_cell[b], row); for (col = 0; col < ncols; col++) { n = class[col]; if (n < 0) continue; Data = &S->ClassSig[n].ClassData; for (b = 0; b < files->nbands; b++) { if (Rast_is_d_null_value(&files->band_cell[b][col])) Rast_set_d_null_value(&Data->x[Data->count][b], 1); else Data->x[Data->count][b] = files->band_cell[b][col]; } Data->count++; } } G_percent(nrows, nrows, 2); G_free(class); return 0; }
static void get_slot_counts(int basefile, int coverfile) { CELL *basebuf = Rast_allocate_c_buf(); DCELL *coverbuf = Rast_allocate_d_buf(); int row, col; G_message(_("Computing histograms")); for (row = 0; row < rows; row++) { Rast_get_c_row(basefile, basebuf, row); Rast_get_d_row(coverfile, coverbuf, row); for (col = 0; col < cols; col++) { struct basecat *bc; int i; if (Rast_is_c_null_value(&basebuf[col])) continue; if (Rast_is_d_null_value(&coverbuf[col])) continue; i = get_slot(coverbuf[col]); bc = &basecats[basebuf[col] - min]; bc->slots[i]++; bc->total++; } G_percent(row, rows, 2); } G_percent(rows, rows, 2); G_free(basebuf); G_free(coverbuf); }
int main(int argc, char *argv[]) { struct Cell_head cellhd; /*region+header info */ char *mapset; /*mapset name */ int nrows, ncols; int row, col; struct GModule *module; struct Option *input, *input1, *input2, *input3, *input4, *input5, *output; struct History history; /*metadata */ struct Colors colors; /*Color rules */ /************************************/ char *name, *name1, *name2; /*input raster name */ char *result; /*output raster name */ /*File Descriptors */ int nfiles, nfiles1, nfiles2; int infd[MAXFILES], infd1[MAXFILES], infd2[MAXFILES]; int outfd; /****************************************/ /* Pointers for file names */ char **names; char **ptr; char **names1; char **ptr1; char **names2; char **ptr2; /****************************************/ int DOYbeforeETa[MAXFILES], DOYafterETa[MAXFILES]; int bfr, aft; /****************************************/ int ok; int i = 0, j = 0; double etodoy; /*minimum ETo DOY */ double startperiod, endperiod; /*first and last days (DOYs) of the period studied */ void *inrast[MAXFILES], *inrast1[MAXFILES], *inrast2[MAXFILES]; DCELL *outrast; CELL val1, val2; RASTER_MAP_TYPE in_data_type[MAXFILES]; /* ETa */ RASTER_MAP_TYPE in_data_type1[MAXFILES]; /* DOY of ETa */ RASTER_MAP_TYPE in_data_type2[MAXFILES]; /* ETo */ RASTER_MAP_TYPE out_data_type = DCELL_TYPE; /************************************/ G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("imagery")); G_add_keyword(_("evapotranspiration")); module->description =_("Computes temporal integration of satellite " "ET actual (ETa) following the daily ET reference " "(ETo) from meteorological station(s)."); /* Define the different options */ input = G_define_standard_option(G_OPT_R_INPUTS); input->key = "eta"; input->description = _("Names of satellite ETa raster maps [mm/d or cm/d]"); input1 = G_define_standard_option(G_OPT_R_INPUTS); input1->key = "eta_doy"; input1->description = _("Names of satellite ETa Day of Year (DOY) raster maps [0-400] [-]"); input2 = G_define_standard_option(G_OPT_R_INPUTS); input2->key = "eto"; input2->description = _("Names of meteorological station ETo raster maps [0-400] [mm/d or cm/d]"); input3 = G_define_option(); input3->key = "eto_doy_min"; input3->type = TYPE_DOUBLE; input3->required = YES; input3->description = _("Value of DOY for ETo first day"); input4 = G_define_option(); input4->key = "start_period"; input4->type = TYPE_DOUBLE; input4->required = YES; input4->description = _("Value of DOY for the first day of the period studied"); input5 = G_define_option(); input5->key = "end_period"; input5->type = TYPE_DOUBLE; input5->required = YES; input5->description = _("Value of DOY for the last day of the period studied"); output = G_define_standard_option(G_OPT_R_OUTPUT); /* init nfiles */ nfiles = 1; nfiles1 = 1; nfiles2 = 1; /********************/ if (G_parser(argc, argv)) exit(EXIT_FAILURE); ok = 1; names = input->answers; ptr = input->answers; names1 = input1->answers; ptr1 = input1->answers; names2 = input2->answers; ptr2 = input2->answers; etodoy = atof(input3->answer); startperiod = atof(input4->answer); endperiod = atof(input5->answer); result = output->answer; /****************************************/ if (endperiod<startperiod) { G_fatal_error(_("The DOY for end_period can not be smaller than start_period")); ok = 0; } if (etodoy>startperiod) { G_fatal_error(_("The DOY for start_period can not be smaller than eto_doy_min")); ok = 0; } for (; *ptr != NULL; ptr++) { if (nfiles > MAXFILES) G_fatal_error(_("Too many ETa files. Only %d allowed."), MAXFILES); name = *ptr; /* Allocate input buffer */ infd[nfiles] = Rast_open_old(name, ""); Rast_get_cellhd(name, "", &cellhd); inrast[nfiles] = Rast_allocate_d_buf(); nfiles++; } nfiles--; if (nfiles <= 1) G_fatal_error(_("The min specified input map is two")); /****************************************/ for (; *ptr1 != NULL; ptr1++) { if (nfiles1 > MAXFILES) G_fatal_error(_("Too many ETa_doy files. Only %d allowed."), MAXFILES); name1 = *ptr1; /* Allocate input buffer */ infd1[nfiles1] = Rast_open_old(name1, ""); Rast_get_cellhd(name1, "", &cellhd); inrast1[nfiles1] = Rast_allocate_d_buf(); nfiles1++; } nfiles1--; if (nfiles1 <= 1) G_fatal_error(_("The min specified input map is two")); /****************************************/ if (nfiles != nfiles1) G_fatal_error(_("ETa and ETa_DOY file numbers are not equal!")); /****************************************/ for (; *ptr2 != NULL; ptr2++) { if (nfiles > MAXFILES) G_fatal_error(_("Too many ETo files. Only %d allowed."), MAXFILES); name2 = *ptr2; /* Allocate input buffer */ infd2[nfiles2] = Rast_open_old(name2, ""); Rast_get_cellhd(name2, "", &cellhd); inrast2[nfiles2] = Rast_allocate_d_buf(); nfiles2++; } nfiles2--; if (nfiles2 <= 1) G_fatal_error(_("The min specified input map is two")); /* Allocate output buffer, use input map data_type */ nrows = Rast_window_rows(); ncols = Rast_window_cols(); outrast = Rast_allocate_d_buf(); /* Create New raster files */ outfd = Rast_open_new(result, 1); /*******************/ /* Process pixels */ double doy[MAXFILES]; double sum[MAXFILES]; for (row = 0; row < nrows; row++) { DCELL d_out; DCELL d_ETrF[MAXFILES]; DCELL d[MAXFILES]; DCELL d1[MAXFILES]; DCELL d2[MAXFILES]; G_percent(row, nrows, 2); /* read input map */ for (i = 1; i <= nfiles; i++) Rast_get_d_row(infd[i], inrast[i], row); for (i = 1; i <= nfiles1; i++) Rast_get_d_row(infd1[i], inrast1[i], row); for (i = 1; i <= nfiles2; i++) Rast_get_d_row (infd2[i], inrast2[i], row); /*process the data */ for (col = 0; col < ncols; col++) { int d1_null=0; int d_null=0; for (i = 1; i <= nfiles; i++) { if (Rast_is_d_null_value(&((DCELL *) inrast[i])[col])) d_null=1; else d[i] = ((DCELL *) inrast[i])[col]; } for (i = 1; i <= nfiles1; i++) { if (Rast_is_d_null_value(&((DCELL *) inrast1[i])[col])) d1_null=1; else d1[i] = ((DCELL *) inrast1[i])[col]; } for (i = 1; i <= nfiles2; i++) d2[i] = ((DCELL *) inrast2[i])[col]; /* Find out the DOY of the eto image */ for (i = 1; i <= nfiles1; i++) { if ( d_null==1 || d1_null==1 ) Rast_set_d_null_value(&outrast[col],1); else { doy[i] = d1[i] - etodoy+1; if (Rast_is_d_null_value(&d2[(int)doy[i]]) || d2[(int)doy[i]]==0 ) Rast_set_d_null_value(&outrast[col],1); else d_ETrF[i] = d[i] / d2[(int)doy[i]]; } } for (i = 1; i <= nfiles1; i++) { /* do nothing */ if ( d_null==1 || d1_null==1) { /*G_message(" null value ");*/ } else { DOYbeforeETa[i]=0; DOYafterETa[i]=0; if (i == 1) DOYbeforeETa[i] = startperiod; else { int k=i-1; while (d1[k]>=startperiod ) { if (d1[k]<0) // case were d1[k] is null k=k-1; else { DOYbeforeETa[i] = 1+((d1[i] + d1[k])/2.0); break; } } } if (i == nfiles1) DOYafterETa[i] = endperiod; else { int k=i+1; while (d1[k]<=endperiod) { if (d1[k]<0) // case were d1[k] is null k=k+1; else { DOYafterETa[i] = (d1[i] + d1[k]) / 2.0; break; } } } } } sum[MAXFILES] = 0.0; for (i = 1; i <= nfiles1; i++) { if(d_null==1 || d1_null==1) { /* do nothing */ } else { if (DOYbeforeETa[i]==0 || DOYbeforeETa[i]==0 ) Rast_set_d_null_value(&outrast[col],1); else { bfr = (int)DOYbeforeETa[i]; aft = (int)DOYafterETa[i]; sum[i]=0.0; for (j = bfr; j < aft; j++) sum[i] += d2[(int)(j-etodoy+1)]; } } } d_out = 0.0; for (i = 1; i <= nfiles1; i++) { if(d_null==1 || d_null==1) Rast_set_d_null_value(&outrast[col],1); else { d_out += d_ETrF[i] * sum[i]; outrast[col] = d_out; } } } Rast_put_row(outfd, outrast, out_data_type); } for (i = 1; i <= nfiles; i++) { G_free(inrast[i]); Rast_close(infd[i]); } for (i = 1; i <= nfiles1; i++) { G_free(inrast1[i]); Rast_close(infd1[i]); } for (i = 1; i <= nfiles2; i++) { G_free(inrast2[i]); Rast_close(infd2[i]); } G_free(outrast); Rast_close(outfd); /* Color table from 0.0 to 10.0 */ Rast_init_colors(&colors); val1 = 0; val2 = 10; Rast_add_c_color_rule(&val1, 0, 0, 0, &val2, 255, 255, 255, &colors); /* Metadata */ Rast_short_history(result, "raster", &history); Rast_command_history(&history); Rast_write_history(result, &history); exit(EXIT_SUCCESS); }
int MyApp::load_files(void) { DCELL *dcell; unsigned char *tr, *tg, *tb, *tset; int tsiz, coff; int rowoff, row, col, vxoff, vyoff; int cnt, ret, fd; int vnum; const char *name; struct Colors colors; dcell = Rast_allocate_d_buf(); tsiz = Rast_window_cols(); /* allocate memory */ tr = (unsigned char *) G_malloc(tsiz * sizeof(char)); tg = (unsigned char *) G_malloc(tsiz * sizeof(char)); tb = (unsigned char *) G_malloc(tsiz * sizeof(char)); tset = (unsigned char *) G_malloc(tsiz * sizeof(char)); wxImage img(ncols, nrows); for (cnt = 0; cnt < frames; cnt++) { if (cnt > MAXIMAGES) { cnt--; break; } for (vnum = 0; vnum < numviews; vnum++) { if (icols == vcols) { vxoff = BORDER_W; vyoff = (irows == vrows) ? BORDER_W : BORDER_W + vnum * (BORDER_W + vrows); } else if (irows == vrows) { vxoff = (icols == vcols) ? BORDER_W : BORDER_W + vnum * (BORDER_W + vcols); vyoff = BORDER_W; } else { /* 4 views */ /* assumes we want : view1 view2 view3 view4 */ vxoff = vnum % 2 ? BORDER_W : vcols + 2 * BORDER_W; vyoff = vnum > 1 ? vrows + 2 * BORDER_W : BORDER_W; } if (!cnt) { LabelPos[vnum][0] = vxoff; LabelPos[vnum][1] = vyoff + vrows - 1; } name = vfiles[vnum][cnt]; G_message(_("Reading file [%s]..."), name); fd = Rast_open_old(name, ""); if (fd < 0) G_fatal_error(_("Unable to open raster map <%s>"), name); /* strcpy(title[cnt],G_get_cell_title(name, mapset)); */ ret = Rast_read_colors(name, "", &colors); if (ret < 0) G_fatal_error(_("Unable to read color file")); for (row = 0; row < vrows; row++) { Rast_get_d_row(fd, dcell, (int)(row / vscale)); rowoff = (vyoff + row) * ncols; Rast_lookup_d_colors(dcell, tr, tg, tb, tset, tsiz, &colors); for (col = 0; col < vcols; col++) { coff = (int)(col / vscale); if (!tset[coff]) img.SetRGB(vxoff + col, vyoff + row, 255, 255, 255); else img.SetRGB(vxoff + col, vyoff + row, tr[coff], tg[coff], tb[coff]); } } Rast_close(fd); } wxBitmap *bmp = new wxBitmap(img); pic_array[cnt] = bmp; mainwin->canvas->draw_image(bmp); mainwin->change_label(frame[cnt]); } G_free(dcell); G_free(tr); G_free(tg); G_free(tb); G_free(tset); return cnt; }
/*! * \brief Extract a cell value from raster map (bilinear interpolation). * * Extract a cell value from raster map at given northing and easting * with a sampled 3x3 window using a bilinear interpolation. * * \param fd file descriptor * \param window region settings * \param cats categories * \param north northing position * \param east easting position * \param usedesc flag to scan category label * * \return cell value at given position */ DCELL Rast_get_sample_bilinear(int fd, const struct Cell_head * window, struct Categories * cats, double north, double east, int usedesc) { int row, col; double grid[2][2]; DCELL *arow = Rast_allocate_d_buf(); DCELL *brow = Rast_allocate_d_buf(); double frow, fcol, trow, tcol; DCELL result; frow = Rast_northing_to_row(north, window); fcol = Rast_easting_to_col(east, window); /* convert northing and easting to row and col, resp */ row = (int)floor(frow - 0.5); col = (int)floor(fcol - 0.5); trow = frow - row - 0.5; tcol = fcol - col - 0.5; if (row < 0 || row + 1 >= Rast_window_rows() || col < 0 || col + 1 >= Rast_window_cols()) { Rast_set_d_null_value(&result, 1); goto done; } Rast_get_d_row(fd, arow, row); Rast_get_d_row(fd, brow, row + 1); if (Rast_is_d_null_value(&arow[col]) || Rast_is_d_null_value(&arow[col + 1]) || Rast_is_d_null_value(&brow[col]) || Rast_is_d_null_value(&brow[col + 1])) { Rast_set_d_null_value(&result, 1); goto done; } /*- * now were ready to do bilinear interpolation over * arow[col], arow[col+1], * brow[col], brow[col+1] */ if (usedesc) { char *buf; G_squeeze(buf = Rast_get_c_cat((int *)&(arow[col]), cats)); grid[0][0] = scancatlabel(buf); G_squeeze(buf = Rast_get_c_cat((CELL *) & (arow[col + 1]), cats)); grid[0][1] = scancatlabel(buf); G_squeeze(buf = Rast_get_c_cat((CELL *) & (brow[col]), cats)); grid[1][0] = scancatlabel(buf); G_squeeze(buf = Rast_get_c_cat((CELL *) & (brow[col + 1]), cats)); grid[1][1] = scancatlabel(buf); } else { grid[0][0] = arow[col]; grid[0][1] = arow[col + 1]; grid[1][0] = brow[col]; grid[1][1] = brow[col + 1]; } result = Rast_interp_bilinear(tcol, trow, grid[0][0], grid[0][1], grid[1][0], grid[1][1]); done: G_free(arow); G_free(brow); return result; }
/*! * \brief Extract a cell value from raster map (cubic interpolation). * * Extract a cell value from raster map at given northing and easting * with a sampled 3x3 window using a cubic interpolation. * * \param fd file descriptor * \param window region settings * \param cats categories * \param north northing position * \param east easting position * \param usedesc flag to scan category label * * \return cell value at given position */ DCELL Rast_get_sample_cubic(int fd, const struct Cell_head * window, struct Categories * cats, double north, double east, int usedesc) { int i, j, row, col; double grid[4][4]; DCELL *rows[4]; double frow, fcol, trow, tcol; DCELL result; for (i = 0; i < 4; i++) rows[i] = Rast_allocate_d_buf(); frow = Rast_northing_to_row(north, window); fcol = Rast_easting_to_col(east, window); /* convert northing and easting to row and col, resp */ row = (int)floor(frow - 1.5); col = (int)floor(fcol - 1.5); trow = frow - row - 1.5; tcol = fcol - col - 1.5; if (row < 0 || row + 3 >= Rast_window_rows() || col < 0 || col + 3 >= Rast_window_cols()) { Rast_set_d_null_value(&result, 1); goto done; } for (i = 0; i < 4; i++) Rast_get_d_row(fd, rows[i], row + i); for (i = 0; i < 4; i++) for (j = 0; j < 4; j++) if (Rast_is_d_null_value(&rows[i][col + j])) { Rast_set_d_null_value(&result, 1); goto done; } /* * now were ready to do cubic interpolation over * arow[col], arow[col+1], arow[col+2], arow[col+3], * brow[col], brow[col+1], brow[col+2], brow[col+3], * crow[col], crow[col+1], crow[col+2], crow[col+3], * drow[col], drow[col+1], drow[col+2], drow[col+3], */ if (usedesc) { char *buf; for (i = 0; i < 4; i++) { for (j = 0; j < 4; j++) { G_squeeze(buf = Rast_get_c_cat((CELL *) & (rows[i][col + j]), cats)); grid[i][j] = scancatlabel(buf); } } } else { for (i = 0; i < 4; i++) for (j = 0; j < 4; j++) grid[i][j] = rows[i][col + j]; } result = Rast_interp_bicubic(tcol, trow, grid[0][0], grid[0][1], grid[0][2], grid[0][3], grid[1][0], grid[1][1], grid[1][2], grid[1][3], grid[2][0], grid[2][1], grid[2][2], grid[2][3], grid[3][0], grid[3][1], grid[3][2], grid[3][3]); done: for (i = 0; i < 4; i++) G_free(rows[i]); return result; }
/*! \brief Get categories/labels Formats label as in d.what.rast -> (catval) catlabel \param filename raster map name \param drow \param dcol \param catstr category string \return 1 on success \return 0 on failure */ int Gs_get_cat_label(const char *filename, int drow, int dcol, char *catstr) { struct Categories cats; const char *mapset; CELL *buf; DCELL *dbuf; RASTER_MAP_TYPE map_type; int fd = -1; if ((mapset = G_find_raster2(filename, "")) == NULL) { G_warning(_("Raster map <%s> not found"), filename); return 0; } if (-1 != Rast_read_cats(filename, mapset, &cats)) { fd = Rast_open_old(filename, mapset); map_type = Rast_get_map_type(fd); if (map_type == CELL_TYPE) { buf = Rast_allocate_c_buf(); Rast_get_c_row(fd, buf, drow); if (Rast_is_c_null_value(&buf[dcol])) { sprintf(catstr, "(NULL) %s", Rast_get_c_cat(&buf[dcol], &cats)); } else { sprintf(catstr, "(%d) %s", buf[dcol], Rast_get_c_cat(&buf[dcol], &cats)); } G_free(buf); } else { /* fp map */ dbuf = Rast_allocate_d_buf(); Rast_get_d_row(fd, dbuf, drow); if (Rast_is_d_null_value(&dbuf[dcol])) { sprintf(catstr, "(NULL) %s", Rast_get_d_cat(&dbuf[dcol], &cats)); } else { sprintf(catstr, "(%g) %s", dbuf[dcol], Rast_get_d_cat(&dbuf[dcol], &cats)); } G_free(dbuf); } } else { strcpy(catstr, "no category label"); return 0; } /* TODO: may want to keep these around for multiple queries */ Rast_free_cats(&cats); if (fd >= 0) Rast_close(fd); return (1); }
int main(int argc, char *argv[]) { /* variables */ DCELL *data_buf; CELL *clump_buf; CELL i, max; int row, col, rows, cols; int out_mode, use_MASK, *n, *e; long int *count; int fd_data, fd_clump; const char *datamap, *clumpmap, *centroidsmap; double avg, vol, total_vol, east, north, *sum; struct Cell_head window; struct Map_info *fd_centroids; struct line_pnts *Points; struct line_cats *Cats; struct field_info *Fi; char buf[DB_SQL_MAX]; dbString sql; dbDriver *driver; struct GModule *module; struct { struct Option *input, *clump, *centroids, *output; } opt; struct { struct Flag *report; } flag; /* define parameters and flags */ G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("raster")); G_add_keyword(_("volume")); G_add_keyword(_("clumps")); module->label = _("Calculates the volume of data \"clumps\"."); module->description = _("Optionally produces a GRASS vector points map " "containing the calculated centroids of these clumps."); opt.input = G_define_standard_option(G_OPT_R_INPUT); opt.input->description = _("Name of input raster map representing data that will be summed within clumps"); opt.clump = G_define_standard_option(G_OPT_R_INPUT); opt.clump->key = "clump"; opt.clump->required = NO; opt.clump->label = _("Name of input clump raster map"); opt.clump->description = _("Preferably the output of r.clump. " "If no clump map is given than MASK is used."); opt.centroids = G_define_standard_option(G_OPT_V_OUTPUT); opt.centroids->key = "centroids"; opt.centroids->required = NO; opt.centroids->description = _("Name for output vector points map to contain clump centroids"); opt.output = G_define_standard_option(G_OPT_F_OUTPUT); opt.output->required = NO; opt.output->label = _("Name for output file to hold the report"); opt.output->description = _("If no output file given report is printed to standard output"); flag.report = G_define_flag(); flag.report->key = 'f'; flag.report->description = _("Generate unformatted report (items separated by colon)"); if (G_parser(argc, argv)) exit(EXIT_FAILURE); /* get arguments */ datamap = opt.input->answer; clumpmap = NULL; if (opt.clump->answer) clumpmap = opt.clump->answer; centroidsmap = NULL; fd_centroids = NULL; Points = NULL; Cats = NULL; driver = NULL; if (opt.centroids->answer) { centroidsmap = opt.centroids->answer; fd_centroids = G_malloc(sizeof(struct Map_info)); } out_mode = (!flag.report->answer); /* * see if MASK or a separate "clumpmap" raster map is to be used * -- it must(!) be one of those two choices. */ use_MASK = 0; if (!clumpmap) { clumpmap = "MASK"; use_MASK = 1; if (!G_find_raster2(clumpmap, G_mapset())) G_fatal_error(_("No MASK found. If no clump map is given than the MASK is required. " "You need to define a clump raster map or create a MASK by r.mask command.")); G_important_message(_("No clump map given, using MASK")); } /* open input and clump raster maps */ fd_data = Rast_open_old(datamap, ""); fd_clump = Rast_open_old(clumpmap, use_MASK ? G_mapset() : ""); /* initialize vector map (for centroids) if needed */ if (centroidsmap) { if (Vect_open_new(fd_centroids, centroidsmap, WITHOUT_Z) < 0) G_fatal_error(_("Unable to create vector map <%s>"), centroidsmap); Points = Vect_new_line_struct(); Cats = Vect_new_cats_struct(); /* initialize data structures */ Vect_append_point(Points, 0., 0., 0.); Vect_cat_set(Cats, 1, 1); } /* initialize output file */ if (opt.output->answer && strcmp(opt.output->answer, "-") != 0) { if (freopen(opt.output->answer, "w", stdout) == NULL) { perror(opt.output->answer); exit(EXIT_FAILURE); } } /* initialize data accumulation arrays */ max = Rast_get_max_c_cat(clumpmap, use_MASK ? G_mapset() : ""); sum = (double *)G_malloc((max + 1) * sizeof(double)); count = (long int *)G_malloc((max + 1) * sizeof(long int)); G_zero(sum, (max + 1) * sizeof(double)); G_zero(count, (max + 1) * sizeof(long int)); data_buf = Rast_allocate_d_buf(); clump_buf = Rast_allocate_c_buf(); /* get window size */ G_get_window(&window); rows = window.rows; cols = window.cols; /* now get the data -- first pass */ for (row = 0; row < rows; row++) { G_percent(row, rows, 2); Rast_get_d_row(fd_data, data_buf, row); Rast_get_c_row(fd_clump, clump_buf, row); for (col = 0; col < cols; col++) { i = clump_buf[col]; if (i > max) G_fatal_error(_("Invalid category value %d (max=%d): row=%d col=%d"), i, max, row, col); if (i < 1) { G_debug(3, "row=%d col=%d: zero or negs ignored", row, col); continue; /* ignore zeros and negs */ } if (Rast_is_d_null_value(&data_buf[col])) { G_debug(3, "row=%d col=%d: NULL ignored", row, col); continue; } sum[i] += data_buf[col]; count[i]++; } } G_percent(1, 1, 1); /* free some buffer space */ G_free(data_buf); G_free(clump_buf); /* data lists for centroids of clumps */ e = (int *)G_malloc((max + 1) * sizeof(int)); n = (int *)G_malloc((max + 1) * sizeof(int)); i = centroids(fd_clump, e, n, 1, max); /* close raster maps */ Rast_close(fd_data); Rast_close(fd_clump); /* got everything, now do output */ if (centroidsmap) { G_message(_("Creating vector point map <%s>..."), centroidsmap); /* set comment */ sprintf(buf, _("From '%s' on raster map <%s> using clumps from <%s>"), argv[0], datamap, clumpmap); Vect_set_comment(fd_centroids, buf); /* create attribute table */ Fi = Vect_default_field_info(fd_centroids, 1, NULL, GV_1TABLE); driver = db_start_driver_open_database(Fi->driver, Vect_subst_var(Fi->database, fd_centroids)); if (driver == NULL) { G_fatal_error(_("Unable to open database <%s> by driver <%s>"), Vect_subst_var(Fi->database, fd_centroids), Fi->driver); } db_set_error_handler_driver(driver); db_begin_transaction(driver); db_init_string(&sql); sprintf(buf, "create table %s (cat integer, volume double precision, " "average double precision, sum double precision, count integer)", Fi->table); db_set_string(&sql, buf); Vect_map_add_dblink(fd_centroids, 1, NULL, Fi->table, GV_KEY_COLUMN, Fi->database, Fi->driver); G_debug(3, "%s", db_get_string(&sql)); if (db_execute_immediate(driver, &sql) != DB_OK) { G_fatal_error(_("Unable to create table: %s"), db_get_string(&sql)); } } /* print header */ if (out_mode) { fprintf(stdout, _("\nVolume report on data from <%s> using clumps on <%s> raster map"), datamap, clumpmap); fprintf(stdout, "\n\n"); fprintf(stdout, _("Category Average Data # Cells Centroid Total\n")); fprintf(stdout, _("Number in clump Total in clump Easting Northing Volume")); fprintf(stdout, "\n%s\n", SEP); } total_vol = 0.0; /* print output, write centroids */ for (i = 1; i <= max; i++) { if (count[i]) { avg = sum[i] / (double)count[i]; vol = sum[i] * window.ew_res * window.ns_res; total_vol += vol; east = window.west + (e[i] + 0.5) * window.ew_res; north = window.north - (n[i] + 0.5) * window.ns_res; if (fd_centroids) { /* write centroids if requested */ Points->x[0] = east; Points->y[0] = north; Cats->cat[0] = i; Vect_write_line(fd_centroids, GV_POINT, Points, Cats); sprintf(buf, "insert into %s values (%d, %f, %f, %f, %ld)", Fi->table, i, vol, avg, sum[i], count[i]); db_set_string(&sql, buf); if (db_execute_immediate(driver, &sql) != DB_OK) G_fatal_error(_("Cannot insert new row: %s"), db_get_string(&sql)); } if (out_mode) fprintf(stdout, "%8d%10.2f%10.0f %7ld %10.2f %10.2f %16.2f\n", i, avg, sum[i], count[i], east, north, vol); else fprintf(stdout, "%d:%.2f:%.0f:%ld:%.2f:%.2f:%.2f\n", i, avg, sum[i], count[i], east, north, vol); } } /* write centroid attributes and close the map*/ if (fd_centroids) { db_commit_transaction(driver); Vect_close(fd_centroids); } /* print total value */ if (total_vol > 0.0 && out_mode) { fprintf(stdout, "%s\n", SEP); fprintf(stdout, "%60s = %14.2f", _("Total Volume"), total_vol); fprintf(stdout, "\n"); } 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[]) { /* Variable declarations */ int nsply, nsplx, nrows, ncols, nsplx_adj, nsply_adj; int nsubregion_col, nsubregion_row, subregion_row, subregion_col; int subregion = 0, nsubregions = 0; int last_row, last_column, grid, bilin, ext, flag_auxiliar, cross; /* booleans */ double stepN, stepE, lambda, mean; double N_extension, E_extension, edgeE, edgeN; const char *mapset, *drv, *db, *vector, *map; char table_name[GNAME_MAX], title[64]; char xname[GNAME_MAX], xmapset[GMAPSET_MAX]; int dim_vect, nparameters, BW; int *lineVect; /* Vector restoring primitive's ID */ double *TN, *Q, *parVect; /* Interpolating and least-square vectors */ double **N, **obsVect; /* Interpolation and least-square matrix */ SEGMENT out_seg, mask_seg; const char *out_file, *mask_file; int out_fd, mask_fd; double seg_size; int seg_mb, segments_in_memory; int have_mask; /* Structs declarations */ int raster; struct Map_info In, In_ext, Out; struct History history; struct GModule *module; struct Option *in_opt, *in_ext_opt, *out_opt, *out_map_opt, *stepE_opt, *stepN_opt, *lambda_f_opt, *type_opt, *dfield_opt, *col_opt, *mask_opt, *memory_opt, *solver, *error, *iter; struct Flag *cross_corr_flag, *spline_step_flag; struct Reg_dimens dims; struct Cell_head elaboration_reg, original_reg; struct bound_box general_box, overlap_box, original_box; struct Point *observ; struct line_cats *Cats; dbCatValArray cvarr; int with_z; int nrec, ctype = 0; struct field_info *Fi; dbDriver *driver, *driver_cats; /*----------------------------------------------------------------*/ /* Options declarations */ module = G_define_module(); G_add_keyword(_("vector")); G_add_keyword(_("surface")); G_add_keyword(_("interpolation")); G_add_keyword(_("LIDAR")); module->description = _("Performs bicubic or bilinear spline interpolation with Tykhonov regularization."); cross_corr_flag = G_define_flag(); cross_corr_flag->key = 'c'; cross_corr_flag->description = _("Find the best Tykhonov regularizing parameter using a \"leave-one-out\" cross validation method"); spline_step_flag = G_define_flag(); spline_step_flag->key = 'e'; spline_step_flag->label = _("Estimate point density and distance"); spline_step_flag->description = _("Estimate point density and distance for the input vector points within the current region extends and quit"); in_opt = G_define_standard_option(G_OPT_V_INPUT); in_opt->label = _("Name of input vector point map"); dfield_opt = G_define_standard_option(G_OPT_V_FIELD); dfield_opt->guisection = _("Settings"); col_opt = G_define_standard_option(G_OPT_DB_COLUMN); col_opt->required = NO; col_opt->label = _("Name of the attribute column with values to be used for approximation"); col_opt->description = _("If not given and input is 3D vector map then z-coordinates are used."); col_opt->guisection = _("Settings"); in_ext_opt = G_define_standard_option(G_OPT_V_INPUT); in_ext_opt->key = "sparse_input"; in_ext_opt->required = NO; in_ext_opt->label = _("Name of input vector map with sparse points"); out_opt = G_define_standard_option(G_OPT_V_OUTPUT); out_opt->required = NO; out_opt->guisection = _("Outputs"); out_map_opt = G_define_standard_option(G_OPT_R_OUTPUT); out_map_opt->key = "raster_output"; out_map_opt->required = NO; out_map_opt->guisection = _("Outputs"); mask_opt = G_define_standard_option(G_OPT_R_INPUT); mask_opt->key = "mask"; mask_opt->label = _("Raster map to use for masking (applies to raster output only)"); mask_opt->description = _("Only cells that are not NULL and not zero are interpolated"); mask_opt->required = NO; stepE_opt = G_define_option(); stepE_opt->key = "ew_step"; stepE_opt->type = TYPE_DOUBLE; stepE_opt->required = NO; stepE_opt->answer = "4"; stepE_opt->description = _("Length of each spline step in the east-west direction"); stepE_opt->guisection = _("Settings"); stepN_opt = G_define_option(); stepN_opt->key = "ns_step"; stepN_opt->type = TYPE_DOUBLE; stepN_opt->required = NO; stepN_opt->answer = "4"; stepN_opt->description = _("Length of each spline step in the north-south direction"); stepN_opt->guisection = _("Settings"); type_opt = G_define_option(); type_opt->key = "method"; type_opt->description = _("Spline interpolation algorithm"); type_opt->type = TYPE_STRING; type_opt->options = "bilinear,bicubic"; type_opt->answer = "bilinear"; type_opt->guisection = _("Settings"); G_asprintf((char **) &(type_opt->descriptions), "bilinear;%s;bicubic;%s", _("Bilinear interpolation"), _("Bicubic interpolation")); lambda_f_opt = G_define_option(); lambda_f_opt->key = "lambda_i"; lambda_f_opt->type = TYPE_DOUBLE; lambda_f_opt->required = NO; lambda_f_opt->description = _("Tykhonov regularization parameter (affects smoothing)"); lambda_f_opt->answer = "0.01"; lambda_f_opt->guisection = _("Settings"); solver = N_define_standard_option(N_OPT_SOLVER_SYMM); solver->options = "cholesky,cg"; solver->answer = "cholesky"; iter = N_define_standard_option(N_OPT_MAX_ITERATIONS); error = N_define_standard_option(N_OPT_ITERATION_ERROR); memory_opt = G_define_option(); memory_opt->key = "memory"; memory_opt->type = TYPE_INTEGER; memory_opt->required = NO; memory_opt->answer = "300"; memory_opt->label = _("Maximum memory to be used (in MB)"); memory_opt->description = _("Cache size for raster rows"); /*----------------------------------------------------------------*/ /* Parsing */ G_gisinit(argv[0]); if (G_parser(argc, argv)) exit(EXIT_FAILURE); vector = out_opt->answer; map = out_map_opt->answer; if (vector && map) G_fatal_error(_("Choose either vector or raster output, not both")); if (!vector && !map && !cross_corr_flag->answer) G_fatal_error(_("No raster or vector or cross-validation output")); if (!strcmp(type_opt->answer, "linear")) bilin = P_BILINEAR; else bilin = P_BICUBIC; stepN = atof(stepN_opt->answer); stepE = atof(stepE_opt->answer); lambda = atof(lambda_f_opt->answer); flag_auxiliar = FALSE; drv = db_get_default_driver_name(); if (!drv) { if (db_set_default_connection() != DB_OK) G_fatal_error(_("Unable to set default DB connection")); drv = db_get_default_driver_name(); } db = db_get_default_database_name(); if (!db) G_fatal_error(_("No default DB defined")); /* Set auxiliary table's name */ if (vector) { if (G_name_is_fully_qualified(out_opt->answer, xname, xmapset)) { sprintf(table_name, "%s_aux", xname); } else sprintf(table_name, "%s_aux", out_opt->answer); } /* Something went wrong in a previous v.surf.bspline execution */ if (db_table_exists(drv, db, table_name)) { /* Start driver and open db */ driver = db_start_driver_open_database(drv, db); if (driver == NULL) G_fatal_error(_("No database connection for driver <%s> is defined. Run db.connect."), drv); db_set_error_handler_driver(driver); if (P_Drop_Aux_Table(driver, table_name) != DB_OK) G_fatal_error(_("Old auxiliary table could not be dropped")); db_close_database_shutdown_driver(driver); } /* Open input vector */ if ((mapset = G_find_vector2(in_opt->answer, "")) == NULL) G_fatal_error(_("Vector map <%s> not found"), in_opt->answer); Vect_set_open_level(1); /* WITHOUT TOPOLOGY */ if (1 > Vect_open_old(&In, in_opt->answer, mapset)) G_fatal_error(_("Unable to open vector map <%s> at the topological level"), in_opt->answer); bspline_field = 0; /* assume 3D input */ bspline_column = col_opt->answer; with_z = !bspline_column && Vect_is_3d(&In); if (Vect_is_3d(&In)) { if (!with_z) G_verbose_message(_("Input is 3D: using attribute values instead of z-coordinates for approximation")); else G_verbose_message(_("Input is 3D: using z-coordinates for approximation")); } else { /* 2D */ if (!bspline_column) G_fatal_error(_("Input vector map is 2D. Parameter <%s> required."), col_opt->key); } if (!with_z) { bspline_field = Vect_get_field_number(&In, dfield_opt->answer); } /* Estimate point density and mean distance for current region */ if (spline_step_flag->answer) { double dens, dist; if (P_estimate_splinestep(&In, &dens, &dist) == 0) { fprintf(stdout, _("Estimated point density: %.4g"), dens); fprintf(stdout, _("Estimated mean distance between points: %.4g"), dist); } else { fprintf(stdout, _("No points in current region")); } Vect_close(&In); exit(EXIT_SUCCESS); } /*----------------------------------------------------------------*/ /* Cross-correlation begins */ if (cross_corr_flag->answer) { G_debug(1, "CrossCorrelation()"); cross = cross_correlation(&In, stepE, stepN); if (cross != TRUE) G_fatal_error(_("Cross validation didn't finish correctly")); else { G_debug(1, "Cross validation finished correctly"); Vect_close(&In); G_done_msg(_("Cross validation finished for ew_step = %f and ns_step = %f"), stepE, stepN); exit(EXIT_SUCCESS); } } /* Open input ext vector */ ext = FALSE; if (in_ext_opt->answer) { ext = TRUE; G_message(_("Vector map <%s> of sparse points will be interpolated"), in_ext_opt->answer); if ((mapset = G_find_vector2(in_ext_opt->answer, "")) == NULL) G_fatal_error(_("Vector map <%s> not found"), in_ext_opt->answer); Vect_set_open_level(1); /* WITHOUT TOPOLOGY */ if (1 > Vect_open_old(&In_ext, in_ext_opt->answer, mapset)) G_fatal_error(_("Unable to open vector map <%s> at the topological level"), in_opt->answer); } /* Open output map */ /* vector output */ if (vector && !map) { if (strcmp(drv, "dbf") == 0) G_fatal_error(_("Sorry, the <%s> driver is not compatible with " "the vector output of this module. " "Try with raster output or another driver."), drv); Vect_check_input_output_name(in_opt->answer, out_opt->answer, G_FATAL_EXIT); grid = FALSE; if (0 > Vect_open_new(&Out, out_opt->answer, WITH_Z)) G_fatal_error(_("Unable to create vector map <%s>"), out_opt->answer); /* Copy vector Head File */ if (ext == FALSE) { Vect_copy_head_data(&In, &Out); Vect_hist_copy(&In, &Out); } else { Vect_copy_head_data(&In_ext, &Out); Vect_hist_copy(&In_ext, &Out); } Vect_hist_command(&Out); G_verbose_message(_("Points in input vector map <%s> will be interpolated"), vector); } /* read z values from attribute table */ if (bspline_field > 0) { G_message(_("Reading values from attribute table...")); db_CatValArray_init(&cvarr); Fi = Vect_get_field(&In, bspline_field); if (Fi == NULL) G_fatal_error(_("Cannot read layer info")); driver_cats = db_start_driver_open_database(Fi->driver, Fi->database); /*G_debug (0, _("driver=%s db=%s"), Fi->driver, Fi->database); */ if (driver_cats == NULL) G_fatal_error(_("Unable to open database <%s> by driver <%s>"), Fi->database, Fi->driver); db_set_error_handler_driver(driver_cats); nrec = db_select_CatValArray(driver_cats, Fi->table, Fi->key, col_opt->answer, NULL, &cvarr); G_debug(3, "nrec = %d", nrec); ctype = cvarr.ctype; if (ctype != DB_C_TYPE_INT && ctype != DB_C_TYPE_DOUBLE) G_fatal_error(_("Column type not supported")); if (nrec < 0) G_fatal_error(_("Unable to select data from table")); G_verbose_message(_("%d records selected from table"), nrec); db_close_database_shutdown_driver(driver_cats); } /*----------------------------------------------------------------*/ /* Interpolation begins */ G_debug(1, "Interpolation()"); /* Open driver and database */ driver = db_start_driver_open_database(drv, db); if (driver == NULL) G_fatal_error(_("No database connection for driver <%s> is defined. " "Run db.connect."), drv); db_set_error_handler_driver(driver); /* Create auxiliary table */ if (vector) { if ((flag_auxiliar = P_Create_Aux4_Table(driver, table_name)) == FALSE) { P_Drop_Aux_Table(driver, table_name); G_fatal_error(_("Interpolation: Creating table: " "It was impossible to create table <%s>."), table_name); } /* db_create_index2(driver, table_name, "ID"); */ /* sqlite likes that ??? */ db_close_database_shutdown_driver(driver); driver = db_start_driver_open_database(drv, db); } /* raster output */ raster = -1; Rast_set_fp_type(DCELL_TYPE); if (!vector && map) { grid = TRUE; raster = Rast_open_fp_new(out_map_opt->answer); G_verbose_message(_("Cells for raster map <%s> will be interpolated"), map); } /* Setting regions and boxes */ G_debug(1, "Interpolation: Setting regions and boxes"); G_get_window(&original_reg); G_get_window(&elaboration_reg); Vect_region_box(&original_reg, &original_box); Vect_region_box(&elaboration_reg, &overlap_box); Vect_region_box(&elaboration_reg, &general_box); nrows = Rast_window_rows(); ncols = Rast_window_cols(); /* Alloc raster matrix */ have_mask = 0; out_file = mask_file = NULL; out_fd = mask_fd = -1; if (grid == TRUE) { int row; DCELL *drastbuf; seg_mb = atoi(memory_opt->answer); if (seg_mb < 3) G_fatal_error(_("Memory in MB must be >= 3")); if (mask_opt->answer) seg_size = sizeof(double) + sizeof(char); else seg_size = sizeof(double); seg_size = (seg_size * SEGSIZE * SEGSIZE) / (1 << 20); segments_in_memory = seg_mb / seg_size + 0.5; G_debug(1, "%d %dx%d segments held in memory", segments_in_memory, SEGSIZE, SEGSIZE); out_file = G_tempfile(); out_fd = creat(out_file, 0666); if (Segment_format(out_fd, nrows, ncols, SEGSIZE, SEGSIZE, sizeof(double)) != 1) G_fatal_error(_("Can not create temporary file")); close(out_fd); out_fd = open(out_file, 2); if (Segment_init(&out_seg, out_fd, segments_in_memory) != 1) G_fatal_error(_("Can not initialize temporary file")); /* initialize output */ G_message(_("Initializing output...")); drastbuf = Rast_allocate_buf(DCELL_TYPE); Rast_set_d_null_value(drastbuf, ncols); for (row = 0; row < nrows; row++) { G_percent(row, nrows, 2); Segment_put_row(&out_seg, drastbuf, row); } G_percent(row, nrows, 2); if (mask_opt->answer) { int row, col, maskfd; DCELL dval, *drastbuf; char mask_val; G_message(_("Load masking map")); mask_file = G_tempfile(); mask_fd = creat(mask_file, 0666); if (Segment_format(mask_fd, nrows, ncols, SEGSIZE, SEGSIZE, sizeof(char)) != 1) G_fatal_error(_("Can not create temporary file")); close(mask_fd); mask_fd = open(mask_file, 2); if (Segment_init(&mask_seg, mask_fd, segments_in_memory) != 1) G_fatal_error(_("Can not initialize temporary file")); maskfd = Rast_open_old(mask_opt->answer, ""); drastbuf = Rast_allocate_buf(DCELL_TYPE); for (row = 0; row < nrows; row++) { G_percent(row, nrows, 2); Rast_get_d_row(maskfd, drastbuf, row); for (col = 0; col < ncols; col++) { dval = drastbuf[col]; if (Rast_is_d_null_value(&dval) || dval == 0) mask_val = 0; else mask_val = 1; Segment_put(&mask_seg, &mask_val, row, col); } } G_percent(row, nrows, 2); G_free(drastbuf); Rast_close(maskfd); have_mask = 1; } } /*------------------------------------------------------------------ | Subdividing and working with tiles: | Each original region will be divided into several subregions. | Each one will be overlaped by its neighbouring subregions. | The overlapping is calculated as a fixed OVERLAP_SIZE times | the largest spline step plus 2 * edge ----------------------------------------------------------------*/ /* Fixing parameters of the elaboration region */ P_zero_dim(&dims); /* Set dim struct to zero */ nsplx_adj = NSPLX_MAX; nsply_adj = NSPLY_MAX; if (stepN > stepE) dims.overlap = OVERLAP_SIZE * stepN; else dims.overlap = OVERLAP_SIZE * stepE; P_get_edge(bilin, &dims, stepE, stepN); P_set_dim(&dims, stepE, stepN, &nsplx_adj, &nsply_adj); G_verbose_message(_("Adjusted EW splines %d"), nsplx_adj); G_verbose_message(_("Adjusted NS splines %d"), nsply_adj); /* calculate number of subregions */ edgeE = dims.ew_size - dims.overlap - 2 * dims.edge_v; edgeN = dims.sn_size - dims.overlap - 2 * dims.edge_h; N_extension = original_reg.north - original_reg.south; E_extension = original_reg.east - original_reg.west; nsubregion_col = ceil(E_extension / edgeE) + 0.5; nsubregion_row = ceil(N_extension / edgeN) + 0.5; if (nsubregion_col < 0) nsubregion_col = 0; if (nsubregion_row < 0) nsubregion_row = 0; nsubregions = nsubregion_row * nsubregion_col; /* Creating line and categories structs */ Cats = Vect_new_cats_struct(); Vect_cat_set(Cats, 1, 0); subregion_row = 0; elaboration_reg.south = original_reg.north; last_row = FALSE; while (last_row == FALSE) { /* For each subregion row */ subregion_row++; P_set_regions(&elaboration_reg, &general_box, &overlap_box, dims, GENERAL_ROW); if (elaboration_reg.north > original_reg.north) { /* First row */ P_set_regions(&elaboration_reg, &general_box, &overlap_box, dims, FIRST_ROW); } if (elaboration_reg.south <= original_reg.south) { /* Last row */ P_set_regions(&elaboration_reg, &general_box, &overlap_box, dims, LAST_ROW); last_row = TRUE; } nsply = ceil((elaboration_reg.north - elaboration_reg.south) / stepN) + 0.5; G_debug(1, "Interpolation: nsply = %d", nsply); /* if (nsply > NSPLY_MAX) nsply = NSPLY_MAX; */ elaboration_reg.east = original_reg.west; last_column = FALSE; subregion_col = 0; /* TODO: process each subregion using its own thread (via OpenMP or pthreads) */ /* I'm not sure about pthreads, but you can tell OpenMP to start all at the same time and it will keep num_workers supplied with the next job as free cpus become available */ while (last_column == FALSE) { /* For each subregion column */ int npoints = 0; /* needed for sparse points interpolation */ int npoints_ext, *lineVect_ext = NULL; double **obsVect_ext; /*, mean_ext = .0; */ struct Point *observ_ext; subregion_col++; subregion++; if (nsubregions > 1) G_message(_("Processing subregion %d of %d..."), subregion, nsubregions); P_set_regions(&elaboration_reg, &general_box, &overlap_box, dims, GENERAL_COLUMN); if (elaboration_reg.west < original_reg.west) { /* First column */ P_set_regions(&elaboration_reg, &general_box, &overlap_box, dims, FIRST_COLUMN); } if (elaboration_reg.east >= original_reg.east) { /* Last column */ P_set_regions(&elaboration_reg, &general_box, &overlap_box, dims, LAST_COLUMN); last_column = TRUE; } nsplx = ceil((elaboration_reg.east - elaboration_reg.west) / stepE) + 0.5; G_debug(1, "Interpolation: nsplx = %d", nsplx); /* if (nsplx > NSPLX_MAX) nsplx = NSPLX_MAX; */ G_debug(1, "Interpolation: (%d,%d): subregion bounds", subregion_row, subregion_col); G_debug(1, "Interpolation: \t\tNORTH:%.2f\t", elaboration_reg.north); G_debug(1, "Interpolation: WEST:%.2f\t\tEAST:%.2f", elaboration_reg.west, elaboration_reg.east); G_debug(1, "Interpolation: \t\tSOUTH:%.2f", elaboration_reg.south); #ifdef DEBUG_SUBREGIONS fprintf(stdout, "B 5\n"); fprintf(stdout, " %.11g %.11g\n", elaboration_reg.east, elaboration_reg.north); fprintf(stdout, " %.11g %.11g\n", elaboration_reg.west, elaboration_reg.north); fprintf(stdout, " %.11g %.11g\n", elaboration_reg.west, elaboration_reg.south); fprintf(stdout, " %.11g %.11g\n", elaboration_reg.east, elaboration_reg.south); fprintf(stdout, " %.11g %.11g\n", elaboration_reg.east, elaboration_reg.north); fprintf(stdout, "C 1 1\n"); fprintf(stdout, " %.11g %.11g\n", (elaboration_reg.west + elaboration_reg.east) / 2, (elaboration_reg.south + elaboration_reg.north) / 2); fprintf(stdout, " 1 %d\n", subregion); #endif /* reading points in interpolation region */ dim_vect = nsplx * nsply; observ_ext = NULL; if (grid == FALSE && ext == TRUE) { observ_ext = P_Read_Vector_Region_Map(&In_ext, &elaboration_reg, &npoints_ext, dim_vect, 1); } else npoints_ext = 1; if (grid == TRUE && have_mask) { /* any unmasked cells in general region ? */ mean = 0; observ_ext = P_Read_Raster_Region_masked(&mask_seg, &original_reg, original_box, general_box, &npoints_ext, dim_vect, mean); } observ = NULL; if (npoints_ext > 0) { observ = P_Read_Vector_Region_Map(&In, &elaboration_reg, &npoints, dim_vect, bspline_field); } else npoints = 1; G_debug(1, "Interpolation: (%d,%d): Number of points in <elaboration_box> is %d", subregion_row, subregion_col, npoints); if (npoints > 0) G_verbose_message(_("%d points found in this subregion"), npoints); /* only interpolate if there are any points in current subregion */ if (npoints > 0 && npoints_ext > 0) { int i; nparameters = nsplx * nsply; BW = P_get_BandWidth(bilin, nsply); /* Least Squares system */ N = G_alloc_matrix(nparameters, BW); /* Normal matrix */ TN = G_alloc_vector(nparameters); /* vector */ parVect = G_alloc_vector(nparameters); /* Parameters vector */ obsVect = G_alloc_matrix(npoints, 3); /* Observation vector */ Q = G_alloc_vector(npoints); /* "a priori" var-cov matrix */ lineVect = G_alloc_ivector(npoints); /* */ for (i = 0; i < npoints; i++) { /* Setting obsVect vector & Q matrix */ double dval; Q[i] = 1; /* Q=I */ lineVect[i] = observ[i].lineID; obsVect[i][0] = observ[i].coordX; obsVect[i][1] = observ[i].coordY; /* read z coordinates from attribute table */ if (bspline_field > 0) { int cat, ival, ret; cat = observ[i].cat; if (cat < 0) continue; if (ctype == DB_C_TYPE_INT) { ret = db_CatValArray_get_value_int(&cvarr, cat, &ival); obsVect[i][2] = ival; observ[i].coordZ = ival; } else { /* DB_C_TYPE_DOUBLE */ ret = db_CatValArray_get_value_double(&cvarr, cat, &dval); obsVect[i][2] = dval; observ[i].coordZ = dval; } if (ret != DB_OK) { G_warning(_("Interpolation: (%d,%d): No record for point (cat = %d)"), subregion_row, subregion_col, cat); continue; } } /* use z coordinates of 3D vector */ else { obsVect[i][2] = observ[i].coordZ; } } /* Mean calculation for every point */ mean = P_Mean_Calc(&elaboration_reg, observ, npoints); G_debug(1, "Interpolation: (%d,%d): mean=%lf", subregion_row, subregion_col, mean); G_free(observ); for (i = 0; i < npoints; i++) obsVect[i][2] -= mean; /* Bilinear interpolation */ if (bilin) { G_debug(1, "Interpolation: (%d,%d): Bilinear interpolation...", subregion_row, subregion_col); normalDefBilin(N, TN, Q, obsVect, stepE, stepN, nsplx, nsply, elaboration_reg.west, elaboration_reg.south, npoints, nparameters, BW); nCorrectGrad(N, lambda, nsplx, nsply, stepE, stepN); } /* Bicubic interpolation */ else { G_debug(1, "Interpolation: (%d,%d): Bicubic interpolation...", subregion_row, subregion_col); normalDefBicubic(N, TN, Q, obsVect, stepE, stepN, nsplx, nsply, elaboration_reg.west, elaboration_reg.south, npoints, nparameters, BW); nCorrectGrad(N, lambda, nsplx, nsply, stepE, stepN); } if(G_strncasecmp(solver->answer, "cg", 2) == 0) G_math_solver_cg_sband(N, parVect, TN, nparameters, BW, atoi(iter->answer), atof(error->answer)); else G_math_solver_cholesky_sband(N, parVect, TN, nparameters, BW); G_free_matrix(N); G_free_vector(TN); G_free_vector(Q); if (grid == TRUE) { /* GRID INTERPOLATION ==> INTERPOLATION INTO A RASTER */ G_debug(1, "Interpolation: (%d,%d): Regular_Points...", subregion_row, subregion_col); if (!have_mask) { P_Regular_Points(&elaboration_reg, &original_reg, general_box, overlap_box, &out_seg, parVect, stepN, stepE, dims.overlap, mean, nsplx, nsply, nrows, ncols, bilin); } else { P_Sparse_Raster_Points(&out_seg, &elaboration_reg, &original_reg, general_box, overlap_box, observ_ext, parVect, stepE, stepN, dims.overlap, nsplx, nsply, npoints_ext, bilin, mean); } } else { /* OBSERVATION POINTS INTERPOLATION */ if (ext == FALSE) { G_debug(1, "Interpolation: (%d,%d): Sparse_Points...", subregion_row, subregion_col); P_Sparse_Points(&Out, &elaboration_reg, general_box, overlap_box, obsVect, parVect, lineVect, stepE, stepN, dims.overlap, nsplx, nsply, npoints, bilin, Cats, driver, mean, table_name); } else { /* FLAG_EXT == TRUE */ /* done that earlier */ /* int npoints_ext, *lineVect_ext = NULL; double **obsVect_ext; struct Point *observ_ext; observ_ext = P_Read_Vector_Region_Map(&In_ext, &elaboration_reg, &npoints_ext, dim_vect, 1); */ obsVect_ext = G_alloc_matrix(npoints_ext, 3); /* Observation vector_ext */ lineVect_ext = G_alloc_ivector(npoints_ext); for (i = 0; i < npoints_ext; i++) { /* Setting obsVect_ext vector & Q matrix */ obsVect_ext[i][0] = observ_ext[i].coordX; obsVect_ext[i][1] = observ_ext[i].coordY; obsVect_ext[i][2] = observ_ext[i].coordZ - mean; lineVect_ext[i] = observ_ext[i].lineID; } G_free(observ_ext); G_debug(1, "Interpolation: (%d,%d): Sparse_Points...", subregion_row, subregion_col); P_Sparse_Points(&Out, &elaboration_reg, general_box, overlap_box, obsVect_ext, parVect, lineVect_ext, stepE, stepN, dims.overlap, nsplx, nsply, npoints_ext, bilin, Cats, driver, mean, table_name); G_free_matrix(obsVect_ext); G_free_ivector(lineVect_ext); } /* END FLAG_EXT == TRUE */ } /* END GRID == FALSE */ G_free_vector(parVect); G_free_matrix(obsVect); G_free_ivector(lineVect); } else { if (observ) G_free(observ); if (observ_ext) G_free(observ_ext); if (npoints == 0) G_warning(_("No data within this subregion. " "Consider increasing spline step values.")); } } /*! END WHILE; last_column = TRUE */ } /*! END WHILE; last_row = TRUE */ G_verbose_message(_("Writing output...")); /* Writing the output raster map */ if (grid == TRUE) { int row, col; DCELL *drastbuf, dval; if (have_mask) { Segment_release(&mask_seg); /* release memory */ close(mask_fd); unlink(mask_file); } drastbuf = Rast_allocate_buf(DCELL_TYPE); for (row = 0; row < nrows; row++) { G_percent(row, nrows, 2); for (col = 0; col < ncols; col++) { Segment_get(&out_seg, &dval, row, col); drastbuf[col] = dval; } Rast_put_d_row(raster, drastbuf); } Rast_close(raster); Segment_release(&out_seg); /* release memory */ close(out_fd); unlink(out_file); /* set map title */ sprintf(title, "%s interpolation with Tykhonov regularization", type_opt->answer); Rast_put_cell_title(out_map_opt->answer, title); /* write map history */ Rast_short_history(out_map_opt->answer, "raster", &history); Rast_command_history(&history); Rast_write_history(out_map_opt->answer, &history); } /* Writing to the output vector map the points from the overlapping zones */ else if (flag_auxiliar == TRUE) { if (ext == FALSE) P_Aux_to_Vector(&In, &Out, driver, table_name); else P_Aux_to_Vector(&In_ext, &Out, driver, table_name); /* Drop auxiliary table */ G_debug(1, "%s: Dropping <%s>", argv[0], table_name); if (P_Drop_Aux_Table(driver, table_name) != DB_OK) G_fatal_error(_("Auxiliary table could not be dropped")); } db_close_database_shutdown_driver(driver); Vect_close(&In); if (ext != FALSE) Vect_close(&In_ext); if (vector) Vect_close(&Out); G_done_msg(" "); exit(EXIT_SUCCESS); } /*END MAIN */
int main(int argc, char *argv[]) { 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 open_files(struct globals *globals) { struct Ref Ref; /* group reference list */ int *in_fd, bounds_fd, is_null; int n, row, col, srows, scols, inlen, outlen, nseg; DCELL **inbuf; /* buffers to store lines from each of the imagery group rasters */ CELL *boundsbuf, bounds_val; int have_bounds = 0; CELL s, id; struct Range range; /* min/max values of bounds map */ struct FPRange *fp_range; /* min/max values of each input raster */ DCELL *min, *max; struct ngbr_stats Ri, Rk; /*allocate memory for flags */ globals->null_flag = flag_create(globals->nrows, globals->ncols); globals->candidate_flag = flag_create(globals->nrows, globals->ncols); flag_clear_all(globals->null_flag); flag_clear_all(globals->candidate_flag); G_debug(1, "Checking image group..."); /* ****** open the input rasters ******* */ if (!I_get_group_ref(globals->image_group, &Ref)) G_fatal_error(_("Group <%s> not found in the current mapset"), globals->image_group); if (Ref.nfiles <= 0) G_fatal_error(_("Group <%s> contains no raster maps"), globals->image_group); /* Read Imagery Group */ in_fd = G_malloc(Ref.nfiles * sizeof(int)); inbuf = (DCELL **) G_malloc(Ref.nfiles * sizeof(DCELL *)); fp_range = G_malloc(Ref.nfiles * sizeof(struct FPRange)); min = G_malloc(Ref.nfiles * sizeof(DCELL)); max = G_malloc(Ref.nfiles * sizeof(DCELL)); G_debug(1, "Opening input rasters..."); for (n = 0; n < Ref.nfiles; n++) { inbuf[n] = Rast_allocate_d_buf(); in_fd[n] = Rast_open_old(Ref.file[n].name, Ref.file[n].mapset); } /* Get min/max values of each input raster for scaling */ globals->max_diff = 0.; globals->nbands = Ref.nfiles; for (n = 0; n < Ref.nfiles; n++) { /* returns -1 on error, 2 on empty range, quitting either way. */ if (Rast_read_fp_range(Ref.file[n].name, Ref.file[n].mapset, &fp_range[n]) != 1) G_fatal_error(_("No min/max found in raster map <%s>"), Ref.file[n].name); Rast_get_fp_range_min_max(&(fp_range[n]), &min[n], &max[n]); G_debug(1, "Range for layer %d: min = %f, max = %f", n, min[n], max[n]); } if (globals->weighted == FALSE) globals->max_diff = Ref.nfiles; else { /* max difference with selected similarity method */ Ri.mean = max; Rk.mean = min; globals->max_diff = 1; globals->max_diff = (*globals->calculate_similarity) (&Ri, &Rk, globals); } /* ********** find out file segmentation size ************ */ G_debug(1, "Calculate temp file sizes..."); /* size of each element to be stored */ inlen = sizeof(DCELL) * Ref.nfiles; outlen = sizeof(CELL); G_debug(1, "data element size, in: %d , out: %d ", inlen, outlen); globals->datasize = sizeof(double) * globals->nbands; /* count non-null cells */ globals->notnullcells = (long)globals->nrows * globals->ncols; for (row = 0; row < globals->nrows; row++) { for (n = 0; n < Ref.nfiles; n++) { Rast_get_d_row(in_fd[n], inbuf[n], row); } for (col = 0; col < globals->ncols; col++) { is_null = 0; /*Assume there is data */ for (n = 0; n < Ref.nfiles; n++) { if (Rast_is_d_null_value(&inbuf[n][col])) { is_null = 1; } } if (is_null) { globals->notnullcells--; FLAG_SET(globals->null_flag, row, col); } } } G_verbose_message(_("Non-NULL cells: %ld"), globals->notnullcells); if (globals->notnullcells < 2) G_fatal_error(_("Insufficient number of non-NULL cells in current region")); /* segment lib segment size */ srows = 64; scols = 64; nseg = manage_memory(srows, scols, globals); /* create segment structures */ if (Segment_open (&globals->bands_seg, G_tempfile(), globals->nrows, globals->ncols, srows, scols, inlen, nseg) != 1) G_fatal_error("Unable to create input temporary files"); if (Segment_open (&globals->rid_seg, G_tempfile(), globals->nrows, globals->ncols, srows, scols, outlen, nseg * 2) != 1) G_fatal_error("Unable to create input temporary files"); /* load input bands to segment structure */ if (Ref.nfiles > 1) G_message(_("Loading input bands...")); else G_message(_("Loading input band...")); globals->bands_val = (double *)G_malloc(inlen); globals->second_val = (double *)G_malloc(inlen); /* initial segment ID */ s = 1; globals->row_min = globals->nrows; globals->row_max = 0; globals->col_min = globals->ncols; globals->col_max = 0; for (row = 0; row < globals->nrows; row++) { G_percent(row, globals->nrows, 4); for (n = 0; n < Ref.nfiles; n++) { Rast_get_d_row(in_fd[n], inbuf[n], row); } for (col = 0; col < globals->ncols; col++) { is_null = 0; /*Assume there is data */ for (n = 0; n < Ref.nfiles; n++) { globals->bands_val[n] = inbuf[n][col]; if (Rast_is_d_null_value(&inbuf[n][col])) { is_null = 1; } else { if (globals->weighted == FALSE) /* scaled version */ globals->bands_val[n] = (inbuf[n][col] - min[n]) / (max[n] - min[n]); } } if (Segment_put(&globals->bands_seg, (void *)globals->bands_val, row, col) != 1) G_fatal_error(_("Unable to write to temporary file")); if (!is_null) { if (!globals->seeds) { /* sequentially number all cells with a unique segment ID */ id = s; s++; } /* get min/max row/col to narrow the processing window */ if (globals->row_min > row) globals->row_min = row; if (globals->row_max < row) globals->row_max = row; if (globals->col_min > col) globals->col_min = col; if (globals->col_max < col) globals->col_max = col; } else { /* all input bands NULL */ Rast_set_c_null_value(&id, 1); FLAG_SET(globals->null_flag, row, col); } if (!globals->seeds || is_null) { if (Segment_put(&globals->rid_seg, (void *)&id, row, col) != 1) G_fatal_error(_("Unable to write to temporary file")); } } } G_percent(1, 1, 1); G_debug(1, "nrows: %d, min row: %d, max row %d", globals->nrows, globals->row_min, globals->row_max); G_debug(1, "ncols: %d, min col: %d, max col %d", globals->ncols, globals->col_min, globals->col_max); globals->row_max++; globals->col_max++; globals->ncells = (long)(globals->row_max - globals->row_min) * (globals->col_max - globals->col_min); /* bounds/constraints */ Rast_set_c_null_value(&globals->upper_bound, 1); Rast_set_c_null_value(&globals->lower_bound, 1); if (globals->bounds_map != NULL) { if (Segment_open (&globals->bounds_seg, G_tempfile(), globals->nrows, globals->ncols, srows, scols, sizeof(CELL), nseg) != TRUE) G_fatal_error("Unable to create bounds temporary files"); if (Rast_read_range(globals->bounds_map, globals->bounds_mapset, &range) != 1) G_fatal_error(_("No min/max found in raster map <%s>"), globals->bounds_map); Rast_get_range_min_max(&range, &globals->upper_bound, &globals->lower_bound); if (Rast_is_c_null_value(&globals->upper_bound) || Rast_is_c_null_value(&globals->lower_bound)) { G_fatal_error(_("No min/max found in raster map <%s>"), globals->bounds_map); } bounds_fd = Rast_open_old(globals->bounds_map, globals->bounds_mapset); boundsbuf = Rast_allocate_c_buf(); for (row = 0; row < globals->nrows; row++) { Rast_get_c_row(bounds_fd, boundsbuf, row); for (col = 0; col < globals->ncols; col++) { bounds_val = boundsbuf[col]; if (FLAG_GET(globals->null_flag, row, col)) { Rast_set_c_null_value(&bounds_val, 1); } else { if (!Rast_is_c_null_value(&bounds_val)) { have_bounds = 1; if (globals->lower_bound > bounds_val) globals->lower_bound = bounds_val; if (globals->upper_bound < bounds_val) globals->upper_bound = bounds_val; } } if (Segment_put(&globals->bounds_seg, &bounds_val, row, col) != 1) G_fatal_error(_("Unable to write to temporary file")); } } Rast_close(bounds_fd); G_free(boundsbuf); if (!have_bounds) { G_warning(_("There are no boundary constraints in '%s'"), globals->bounds_map); Rast_set_c_null_value(&globals->upper_bound, 1); Rast_set_c_null_value(&globals->lower_bound, 1); Segment_close(&globals->bounds_seg); globals->bounds_map = NULL; globals->bounds_mapset = NULL; } } else { G_debug(1, "no boundary constraint supplied."); } /* other info */ globals->candidate_count = 0; /* counter for remaining candidate pixels */ /* Free memory */ for (n = 0; n < Ref.nfiles; n++) { G_free(inbuf[n]); Rast_close(in_fd[n]); } globals->rs.sum = G_malloc(globals->datasize); globals->rs.mean = G_malloc(globals->datasize); globals->reg_tree = rgtree_create(globals->nbands, globals->datasize); globals->n_regions = s - 1; if (globals->seeds) { load_seeds(globals, srows, scols, nseg); } G_debug(1, "Number of initial regions: %d", globals->n_regions); G_free(inbuf); G_free(in_fd); G_free(fp_range); G_free(min); G_free(max); return TRUE; }
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 extract_points(int z_flag) { struct line_pnts *points = Vect_new_line_struct(); CELL *cellbuf; FCELL *fcellbuf; DCELL *dcellbuf; int row, col; double x, y; int count; switch (data_type) { case CELL_TYPE: cellbuf = Rast_allocate_c_buf(); break; case FCELL_TYPE: fcellbuf = Rast_allocate_f_buf(); break; case DCELL_TYPE: dcellbuf = Rast_allocate_d_buf(); break; } G_message(_("Extracting points...")); count = 1; for (row = 0; row < cell_head.rows; row++) { G_percent(row, n_rows, 2); y = Rast_row_to_northing((double)(row + .5), &cell_head); switch (data_type) { case CELL_TYPE: Rast_get_c_row(input_fd, cellbuf, row); break; case FCELL_TYPE: Rast_get_f_row(input_fd, fcellbuf, row); break; case DCELL_TYPE: Rast_get_d_row(input_fd, dcellbuf, row); break; } for (col = 0; col < cell_head.cols; col++) { int cat, val; double dval; x = Rast_col_to_easting((double)(col + .5), &cell_head); switch (data_type) { case CELL_TYPE: if (Rast_is_c_null_value(cellbuf + col)) continue; val = cellbuf[col]; dval = val; break; case FCELL_TYPE: if (Rast_is_f_null_value(fcellbuf + col)) continue; dval = fcellbuf[col]; break; case DCELL_TYPE: if (Rast_is_d_null_value(dcellbuf + col)) continue; dval = dcellbuf[col]; break; } /* value_flag is used only for CELL type */ cat = (value_flag) ? val : count; Vect_reset_line(points); Vect_reset_cats(Cats); Vect_cat_set(Cats, 1, cat); Vect_append_point(points, x, y, dval); Vect_write_line(&Map, GV_POINT, points, Cats); if ((driver != NULL) && !value_flag) { insert_value(cat, val, dval); } count++; } } G_percent(row, n_rows, 2); switch (data_type) { case CELL_TYPE: G_free(cellbuf); break; case FCELL_TYPE: G_free(fcellbuf); break; case DCELL_TYPE: G_free(dcellbuf); break; } Vect_destroy_line_struct(points); return (1); }
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); }
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 GModule *module; struct { struct Option *input; struct Option *output; struct Option *null; struct Option *bytes; struct Option *order; } parm; struct { struct Flag *int_out; struct Flag *float_out; struct Flag *gmt_hd; struct Flag *bil_hd; struct Flag *swap; } flag; char *name; char *outfile; double null_val; int do_stdout; int is_fp; int bytes; int order; int swap_flag; struct Cell_head region; int nrows, ncols; DCELL *in_buf; unsigned char *out_buf; int fd; FILE *fp; struct GRD_HEADER header; int row; G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("raster")); G_add_keyword(_("export")); module->description = _("Exports a GRASS raster to a binary array."); /* Define the different options */ parm.input = G_define_option(); parm.input->key = "input"; parm.input->type = TYPE_STRING; parm.input->required = YES; parm.input->gisprompt = "old,cell,raster"; parm.input->description = _("Name of input raster map"); parm.output = G_define_option(); parm.output->key = "output"; parm.output->type = TYPE_STRING; parm.output->required = NO; parm.output->description = _("Name for output binary map (use output=- for stdout)"); parm.null = G_define_option(); parm.null->key = "null"; parm.null->type = TYPE_DOUBLE; parm.null->required = NO; parm.null->answer = "0"; parm.null->description = _("Value to write out for null"); parm.bytes = G_define_option(); parm.bytes->key = "bytes"; parm.bytes->type = TYPE_INTEGER; parm.bytes->required = NO; parm.bytes->options = "1,2,4,8"; parm.bytes->description = _("Number of bytes per cell"); parm.order = G_define_option(); parm.order->key = "order"; parm.order->type = TYPE_STRING; parm.order->required = NO; parm.order->options = "big,little,native,swap"; parm.order->description = _("Output byte order"); parm.order->answer = "native"; flag.int_out = G_define_flag(); flag.int_out->key = 'i'; flag.int_out->description = _("Generate integer output"); flag.float_out = G_define_flag(); flag.float_out->key = 'f'; flag.float_out->description = _("Generate floating-point output"); flag.gmt_hd = G_define_flag(); flag.gmt_hd->key = 'h'; flag.gmt_hd->description = _("Export array with GMT compatible header"); flag.bil_hd = G_define_flag(); flag.bil_hd->key = 'b'; flag.bil_hd->description = _("Generate BIL world and header files"); flag.swap = G_define_flag(); flag.swap->key = 's'; flag.swap->description = _("Byte swap output"); if (G_parser(argc, argv)) exit(EXIT_FAILURE); if (sscanf(parm.null->answer, "%lf", &null_val) != 1) G_fatal_error(_("Invalid value for null (integers only)")); name = parm.input->answer; if (parm.output->answer) outfile = parm.output->answer; else { outfile = G_malloc(strlen(name) + 4 + 1); sprintf(outfile, "%s.bin", name); } if (G_strcasecmp(parm.order->answer, "big") == 0) order = 0; else if (G_strcasecmp(parm.order->answer, "little") == 0) order = 1; else if (G_strcasecmp(parm.order->answer, "native") == 0) order = G_is_little_endian() ? 1 : 0; else if (G_strcasecmp(parm.order->answer, "swap") == 0) order = G_is_little_endian() ? 0 : 1; if (flag.swap->answer) { if (strcmp(parm.order->answer, "native") != 0) G_fatal_error(_("order= and -s are mutually exclusive")); order = G_is_little_endian() ? 0 : 1; } swap_flag = order == (G_is_little_endian() ? 0 : 1); do_stdout = strcmp("-", outfile) == 0; if (flag.int_out->answer && flag.float_out->answer) G_fatal_error(_("-i and -f are mutually exclusive")); fd = Rast_open_old(name, ""); if (flag.int_out->answer) is_fp = 0; else if (flag.float_out->answer) is_fp = 1; else is_fp = Rast_get_map_type(fd) != CELL_TYPE; if (parm.bytes->answer) bytes = atoi(parm.bytes->answer); else if (is_fp) bytes = 4; else bytes = 2; if (is_fp && bytes < 4) G_fatal_error(_("Floating-point output requires bytes=4 or bytes=8")); #ifndef HAVE_LONG_LONG_INT if (!is_fp && bytes > 4) G_fatal_error(_("Integer output doesn't support bytes=8 in this build")); #endif G_get_window(®ion); /* open bin file for writing */ if (do_stdout) fp = stdout; else if (NULL == (fp = fopen(outfile, "w"))) G_fatal_error(_("Unable to create file <%s>"), outfile); /* Set up Parameters for GMT header */ if (flag.gmt_hd->answer) { if (!is_fp && bytes > 4) G_fatal_error(_("GMT grid doesn't support 64-bit integers")); make_gmt_header(&header, name, outfile, ®ion, null_val); } /* Write out BIL support files compatible with Arc-View */ if (flag.bil_hd->answer) { G_message(_("Creating BIL support files...")); write_bil_hdr(outfile, ®ion, bytes, order, flag.gmt_hd->answer, null_val); write_bil_wld(outfile, ®ion); } /* Write out GMT Header if required */ if (flag.gmt_hd->answer) write_gmt_header(&header, swap_flag, fp); nrows = Rast_window_rows(); ncols = Rast_window_cols(); in_buf = Rast_allocate_d_buf(); out_buf = G_malloc(ncols * bytes); if (is_fp) { G_message(_("Exporting raster as floating values (bytes=%d)"), bytes); if (flag.gmt_hd->answer) G_message(_("Writing GMT float format ID=1")); } else { G_message(_("Exporting raster as integer values (bytes=%d)"), bytes); if (flag.gmt_hd->answer) G_message(_("Writing GMT integer format ID=2")); } G_verbose_message(_("Using the current region settings...")); G_verbose_message(_("north=%f"), region.north); G_verbose_message(_("south=%f"), region.south); G_verbose_message(_("east=%f"), region.east); G_verbose_message(_("west=%f"), region.west); G_verbose_message(_("r=%d"), region.rows); G_verbose_message(_("c=%d"), region.cols); for (row = 0; row < nrows; row++) { G_percent(row, nrows, 2); Rast_get_d_row(fd, in_buf, row); convert_row(out_buf, in_buf, ncols, is_fp, bytes, swap_flag, null_val); if (fwrite(out_buf, bytes, ncols, fp) != ncols) G_fatal_error(_("Error writing data")); } G_percent(row, nrows, 2); /* finish it off */ Rast_close(fd); fclose(fp); return 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[]) { unsigned int r, c, rows, cols; /* totals */ int map1_fd, map2_fd; double sumX, sumY, sumsqX, sumsqY, sumXY; double meanX, meanY, varX, varY, sdX, sdY; double A, B, R, F; long count = 0; DCELL *map1_buf, *map2_buf, map1_val, map2_val; char *name; struct Option *input_map1, *input_map2, *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")); module->description = _("Calculates linear regression from two raster maps: y = a + b*x."); /* Define the different options */ input_map1 = G_define_standard_option(G_OPT_R_MAP); input_map1->key = "map1"; input_map1->description = (_("Map for x coefficient")); input_map2 = G_define_standard_option(G_OPT_R_MAP); input_map2->key = "map2"; input_map2->description = (_("Map for y coefficient")); 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; /* open maps */ map1_fd = Rast_open_old(input_map1->answer, ""); map2_fd = Rast_open_old(input_map2->answer, ""); map1_buf = Rast_allocate_d_buf(); map2_buf = Rast_allocate_d_buf(); sumX = sumY = sumsqX = sumsqY = sumXY = 0.0; meanX = meanY = varX = varY = sdX = sdY = 0.0; for (r = 0; r < rows; r++) { G_percent(r, rows, 2); Rast_get_d_row(map1_fd, map1_buf, r); Rast_get_d_row(map2_fd, map2_buf, r); for (c = 0; c < cols; c++) { map1_val = map1_buf[c]; map2_val = map2_buf[c]; if (Rast_is_d_null_value(&map1_val) || Rast_is_d_null_value(&map2_val)) continue; sumX += map1_val; sumY += map2_val; sumsqX += map1_val * map1_val; sumsqY += map2_val * map2_val; sumXY += map1_val * map2_val; count++; } } Rast_close(map1_fd); Rast_close(map2_fd); G_free(map1_buf); G_free(map2_buf); B = (sumXY - sumX * sumY / count) / (sumsqX - sumX * sumX / count); R = (sumXY - sumX * sumY / count) / sqrt((sumsqX - sumX * sumX / count) * (sumsqY - sumY * sumY / count)); meanX = sumX / count; sumsqX = sumsqX / count; varX = sumsqX - (meanX * meanX); sdX = sqrt(varX); meanY = sumY / count; sumsqY = sumsqY / count; varY = sumsqY - (meanY * meanY); sdY = sqrt(varY); A = meanY - B * meanX; F = R * R / (1 - R * R / count - 2); if (shell_style->answer) { fprintf(stdout, "a=%f\n", A); fprintf(stdout, "b=%f\n", B); fprintf(stdout, "R=%f\n", R); fprintf(stdout, "N=%ld\n", count); fprintf(stdout, "F=%f\n", F); fprintf(stdout, "meanX=%f\n", meanX); fprintf(stdout, "sdX=%f\n", sdX); fprintf(stdout, "meanY=%f\n", meanY); fprintf(stdout, "sdY=%f\n", sdY); } else { fprintf(stdout, "y = a + b*x\n"); fprintf(stdout, " a (Offset): %f\n", A); fprintf(stdout, " b (Gain): %f\n", B); fprintf(stdout, " R (sumXY - sumX*sumY/N): %f\n", R); fprintf(stdout, " N (Number of elements): %ld\n", count); fprintf(stdout, " F (F-test significance): %f\n", F); fprintf(stdout, " meanX (Mean of map1): %f\n", meanX); fprintf(stdout, " sdX (Standard deviation of map1): %f\n", sdX); fprintf(stdout, " meanY (Mean of map2): %f\n", meanY); fprintf(stdout, " sdY (Standard deviation of map2): %f\n", sdY); } 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[]) { 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[]) { 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[]) { 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[]) { int i, j, nlines, type, field, cat; int fd; /* struct Categories RCats; *//* TODO */ struct Cell_head window; RASTER_MAP_TYPE out_type; CELL *cell; DCELL *dcell; double drow, dcol; char buf[2000]; struct Option *vect_opt, *rast_opt, *field_opt, *col_opt, *where_opt; int Cache_size; struct order *cache; int cur_row; struct GModule *module; struct Map_info Map; struct line_pnts *Points; struct line_cats *Cats; int point; int point_cnt; /* number of points in cache */ int outside_cnt; /* points outside region */ int nocat_cnt; /* points inside region but without category */ int dupl_cnt; /* duplicate categories */ struct bound_box box; int *catexst, *cex; struct field_info *Fi; dbString stmt; dbDriver *driver; int select, norec_cnt, update_cnt, upderr_cnt, col_type; G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("vector")); G_add_keyword(_("raster")); G_add_keyword(_("position")); G_add_keyword(_("querying")); G_add_keyword(_("attribute table")); module->description = _("Uploads raster values at positions of vector points to the table."); vect_opt = G_define_standard_option(G_OPT_V_INPUT); vect_opt->key = "vector"; vect_opt->description = _("Name of input vector points map for which to edit attribute table"); rast_opt = G_define_standard_option(G_OPT_R_INPUT); rast_opt->key = "raster"; rast_opt->description = _("Name of existing raster map to be queried"); field_opt = G_define_standard_option(G_OPT_V_FIELD); col_opt = G_define_option(); col_opt->key = "column"; col_opt->type = TYPE_STRING; col_opt->required = YES; col_opt->description = _("Column name (will be updated by raster values)"); where_opt = G_define_standard_option(G_OPT_DB_WHERE); if (G_parser(argc, argv)) exit(EXIT_FAILURE); field = atoi(field_opt->answer); db_init_string(&stmt); Points = Vect_new_line_struct(); Cats = Vect_new_cats_struct(); G_get_window(&window); Vect_region_box(&window, &box); /* T and B set to +/- PORT_DOUBLE_MAX */ /* Open vector */ Vect_set_open_level(2); Vect_open_old(&Map, vect_opt->answer, ""); Fi = Vect_get_field(&Map, field); if (Fi == NULL) G_fatal_error(_("Database connection not defined for layer %d"), field); /* Open driver */ driver = db_start_driver_open_database(Fi->driver, Fi->database); if (driver == NULL) { G_fatal_error(_("Unable to open database <%s> by driver <%s>"), Fi->database, Fi->driver); } /* Open raster */ fd = Rast_open_old(rast_opt->answer, ""); out_type = Rast_get_map_type(fd); /* TODO: Later possibly category labels */ /* if ( Rast_read_cats (name, "", &RCats) < 0 ) G_fatal_error ( "Cannot read category file"); */ /* Check column type */ col_type = db_column_Ctype(driver, Fi->table, col_opt->answer); if (col_type == -1) G_fatal_error(_("Column <%s> not found"), col_opt->answer); if (col_type != DB_C_TYPE_INT && col_type != DB_C_TYPE_DOUBLE) G_fatal_error(_("Column type not supported")); if (out_type == CELL_TYPE && col_type == DB_C_TYPE_DOUBLE) G_warning(_("Raster type is integer and column type is float")); if (out_type != CELL_TYPE && col_type == DB_C_TYPE_INT) G_warning(_("Raster type is float and column type is integer, some data lost!!")); /* Read vector points to cache */ Cache_size = Vect_get_num_primitives(&Map, GV_POINT); /* Note: Some space may be wasted (outside region or no category) */ cache = (struct order *)G_calloc(Cache_size, sizeof(struct order)); point_cnt = outside_cnt = nocat_cnt = 0; nlines = Vect_get_num_lines(&Map); G_debug(1, "Reading %d vector features fom map", nlines); for (i = 1; i <= nlines; i++) { type = Vect_read_line(&Map, Points, Cats, i); G_debug(4, "line = %d type = %d", i, type); /* check type */ if (!(type & GV_POINT)) continue; /* Points only */ /* check region */ if (!Vect_point_in_box(Points->x[0], Points->y[0], 0.0, &box)) { outside_cnt++; continue; } Vect_cat_get(Cats, field, &cat); if (cat < 0) { /* no category of given field */ nocat_cnt++; continue; } G_debug(4, " cat = %d", cat); /* Add point to cache */ drow = Rast_northing_to_row(Points->y[0], &window); dcol = Rast_easting_to_col(Points->x[0], &window); /* a special case. * if north falls at southern edge, or east falls on eastern edge, * the point will appear outside the window. * So, for these edges, bring the point inside the window */ if (drow == window.rows) drow--; if (dcol == window.cols) dcol--; cache[point_cnt].row = (int)drow; cache[point_cnt].col = (int)dcol; cache[point_cnt].cat = cat; cache[point_cnt].count = 1; point_cnt++; } Vect_set_db_updated(&Map); Vect_hist_command(&Map); Vect_close(&Map); G_debug(1, "Read %d vector points", point_cnt); /* Cache may contain duplicate categories, sort by cat, find and remove duplicates * and recalc count and decrease point_cnt */ qsort(cache, point_cnt, sizeof(struct order), by_cat); G_debug(1, "Points are sorted, starting duplicate removal loop"); for (i = 0, j = 1; j < point_cnt; j++) if (cache[i].cat != cache[j].cat) cache[++i] = cache[j]; else cache[i].count++; point_cnt = i + 1; G_debug(1, "%d vector points left after removal of duplicates", point_cnt); /* Report number of points not used */ if (outside_cnt) G_warning(_("%d points outside current region were skipped"), outside_cnt); if (nocat_cnt) G_warning(_("%d points without category were skipped"), nocat_cnt); /* Sort cache by current region row */ qsort(cache, point_cnt, sizeof(struct order), by_row); /* Allocate space for raster row */ if (out_type == CELL_TYPE) cell = Rast_allocate_c_buf(); else dcell = Rast_allocate_d_buf(); /* Extract raster values from file and store in cache */ G_debug(1, "Extracting raster values"); cur_row = -1; for (point = 0; point < point_cnt; point++) { if (cache[point].count > 1) continue; /* duplicate cats */ if (cur_row != cache[point].row) { if (out_type == CELL_TYPE) Rast_get_c_row(fd, cell, cache[point].row); else Rast_get_d_row(fd, dcell, cache[point].row); } cur_row = cache[point].row; if (out_type == CELL_TYPE) { cache[point].value = cell[cache[point].col]; } else { cache[point].dvalue = dcell[cache[point].col]; } } /* point loop */ /* Update table from cache */ G_debug(1, "Updating db table"); /* select existing categories to array (array is sorted) */ select = db_select_int(driver, Fi->table, Fi->key, NULL, &catexst); db_begin_transaction(driver); norec_cnt = update_cnt = upderr_cnt = dupl_cnt = 0; for (point = 0; point < point_cnt; point++) { if (cache[point].count > 1) { G_warning(_("More points (%d) of category %d, value set to 'NULL'"), cache[point].count, cache[point].cat); dupl_cnt++; } /* category exist in DB ? */ cex = (int *)bsearch((void *)&(cache[point].cat), catexst, select, sizeof(int), srch_cat); if (cex == NULL) { /* cat does not exist in DB */ norec_cnt++; G_warning(_("No record for category %d in table <%s>"), cache[point].cat, Fi->table); continue; } sprintf(buf, "update %s set %s = ", Fi->table, col_opt->answer); db_set_string(&stmt, buf); if (out_type == CELL_TYPE) { if (cache[point].count > 1 || Rast_is_c_null_value(&cache[point].value)) { sprintf(buf, "NULL"); } else { sprintf(buf, "%d ", cache[point].value); } } else { /* FCELL or DCELL */ if (cache[point].count > 1 || Rast_is_d_null_value(&cache[point].dvalue)) { sprintf(buf, "NULL"); } else { sprintf(buf, "%.10f", cache[point].dvalue); } } db_append_string(&stmt, buf); sprintf(buf, " where %s = %d", Fi->key, cache[point].cat); db_append_string(&stmt, buf); /* user provides where condition: */ if (where_opt->answer) { sprintf(buf, " AND %s", where_opt->answer); db_append_string(&stmt, buf); } G_debug(3, db_get_string(&stmt)); /* Update table */ if (db_execute_immediate(driver, &stmt) == DB_OK) { update_cnt++; } else { upderr_cnt++; } } G_debug(1, "Committing DB transaction"); db_commit_transaction(driver); G_free(catexst); db_close_database_shutdown_driver(driver); db_free_string(&stmt); /* Report */ G_message(_("%d categories loaded from table"), select); G_message(_("%d categories loaded from vector"), point_cnt); G_message(_("%d categories from vector missing in table"), norec_cnt); G_message(_("%d duplicate categories in vector"), dupl_cnt); if (!where_opt->answer) G_message(_("%d records updated"), update_cnt); G_message(_("%d update errors"), upderr_cnt); exit(EXIT_SUCCESS); }
int main(int argc, char *argv[]) { /* 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); }