int get_stats(const char *name, struct Cell_stats *statf) { int fd; CELL *cell; int row, nrows, ncols; fd = Rast_open_old(name, ""); nrows = Rast_window_rows(); ncols = Rast_window_cols(); cell = Rast_allocate_c_buf(); Rast_init_cell_stats(statf); G_message(_("Reading %s ..."), name); for (row = 0; row < nrows; row++) { G_percent(row, nrows, 2); Rast_get_c_row(fd, cell, row); Rast_update_cell_stats(cell, ncols, statf); } if (row < nrows) exit(1); Rast_close(fd); G_free(cell); G_percent(row, nrows, 2); return 0; }
int get_range(const char *name, long *min, long *max) { struct Range range; int nrows, ncols, row, col; CELL *cell; int fd; CELL cmin, cmax; struct Cell_head cellhd; if (Rast_read_range(name, "", &range) < 0) { Rast_init_range(&range); /* read the file to get the range */ Rast_get_cellhd(name, "", &cellhd); Rast_set_window(&cellhd); cell = Rast_allocate_c_buf(); fd = Rast_open_old(name, ""); nrows = Rast_window_rows(); ncols = Rast_window_cols(); G_message(_("Reading %s ..."), name); for (row = 0; row < nrows; row++) { G_percent(row, nrows, 2); Rast_get_c_row_nomask(fd, cell, row); for (col = 0; col < ncols; col++) Rast_update_range(cell[col], &range); } G_percent(row, nrows, 2); Rast_close(fd); G_free(cell); } Rast_get_range_min_max(&range, &cmin, &cmax); *min = cmin; *max = cmax; return 0; }
int close_file(char *name) { int cell_file, row, k; int row_count, col_count; CELL *buf; cell_file = Rast_open_c_new(name); row_count = n_rows - (PAD << 1); col_count = n_cols - (PAD << 1); G_message(_("Output file %d rows X %d columns"), row_count, col_count); G_message(_("Window %d rows X %d columns"), Rast_window_rows(), Rast_window_cols()); for (row = 0, k = PAD; row < row_count; row++, k++) { buf = get_a_row(k); Rast_put_row(cell_file, buf + PAD, CELL_TYPE); } Rast_close(cell_file); Rowio_flush(&row_io); close(Rowio_fileno(&row_io)); Rowio_release(&row_io); unlink(work_file_name); return 0; }
int randsurf(char *out, /* Name of raster maps to be opened. */ int min, int max, /* Minimum and maximum cell values. */ int int_map) { /* if map is to be written as a CELL map */ int nrows, ncols; /* Number of cell rows and columns */ DCELL *row_out_D; /* Buffer just large enough to hold one */ CELL *row_out_C; /* row of the raster map layer. */ int fd_out; /* File descriptor - used to identify */ /* open raster maps. */ int row_count, col_count; /****** INITIALISE RANDOM NUMBER GENERATOR ******/ G_math_rand(-1 * getpid()); /****** OPEN CELL FILES AND GET CELL DETAILS ******/ fd_out = Rast_open_new(out, int_map ? CELL_TYPE : DCELL_TYPE); nrows = Rast_window_rows(); ncols = Rast_window_cols(); if (int_map) row_out_C = Rast_allocate_c_buf(); else row_out_D = Rast_allocate_d_buf(); /****** PASS THROUGH EACH CELL ASSIGNING RANDOM VALUE ******/ for (row_count = 0; row_count < nrows; row_count++) { G_percent(row_count, nrows, 2); for (col_count = 0; col_count < ncols; col_count++) { if (int_map) *(row_out_C + col_count) = (CELL) (G_math_rand(2742) * (max + 1 - min) + min); /* under represents first and last bin */ /* *(row_out_C + col_count) = (CELL) floor(rand1(2742)*(max-min)+min +0.5); */ else *(row_out_D + col_count) = (DCELL) (G_math_rand(2742) * (max - min) + min); } /* Write contents row by row */ if (int_map) Rast_put_c_row(fd_out, (CELL *) row_out_C); else Rast_put_d_row(fd_out, (DCELL *) row_out_D); } G_percent(1, 1, 1); Rast_close(fd_out); return 0; }
/* Converts the buffer to cell and write it to disk */ static void write_fp_to_cell(int ofd, FCELL *buf) { CELL *cbuf; int col; cbuf = (CELL *) Rast_allocate_buf(CELL_TYPE); for (col = 0; col < Rast_window_cols(); col++) cbuf[col] = round_c(buf[col]); Rast_put_row(ofd, cbuf, CELL_TYPE); }
int dseg_open(DSEG * dseg, int srows, int scols, int nsegs_in_memory) { char *filename; int errflag; int fd; dseg->filename = NULL; dseg->fd = -1; dseg->name = NULL; dseg->mapset = NULL; filename = G_tempfile(); if (-1 == (fd = creat(filename, 0666))) { G_warning("dseg_open(): unable to create segment file"); return -2; } if (0 > (errflag = Segment_format(fd, Rast_window_rows(), Rast_window_cols(), srows, scols, sizeof(double)))) { close(fd); unlink(filename); if (errflag == -1) { G_warning("dseg_open(): could not write segment file"); return -1; } else { G_warning("dseg_open(): illegal configuration parameter(s)"); return -3; } } close(fd); if (-1 == (fd = open(filename, 2))) { unlink(filename); G_warning("dseg_open(): unable to re-open segment file"); return -4; } if (0 > (errflag = Segment_init(&(dseg->seg), fd, nsegs_in_memory))) { close(fd); unlink(filename); if (errflag == -1) { G_warning("dseg_open(): could not read segment file"); return -5; } else { G_warning("dseg_open(): out of memory"); return -6; } } dseg->filename = filename; dseg->fd = fd; return 0; }
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; }
int process(void) { /*-------------------------------------------------------------------*/ /* INITIALISE */ /*-------------------------------------------------------------------*/ int nrows, /* Will store the current number of */ ncols, /* rows and columns in the raster. */ nn; /* Size of raster to nearest power of 2. */ double *data[2]; /* Array holding complex data. */ /*------------------------------------------------------------------*/ /* GET DETAILS OF INPUT RASTER */ /*------------------------------------------------------------------*/ nrows = Rast_window_rows(); /* Find out the number of rows and */ ncols = Rast_window_cols(); /* columns of the raster view. */ nn = G_math_max_pow2(MAX(nrows, ncols)); /* Find smallest power of 2 that */ /* largest side of raster will fit. */ /*------------------------------------------------------------------*/ /* CREATE SQUARE ARRAY OF SIDE 2^n */ /*------------------------------------------------------------------*/ if (nn * nn * sizeof(double) < 1) G_fatal_error(_("Unable to allocate data buffer. " "Check current region with g.region.")); data[0] = (double *)G_malloc(nn * nn * sizeof(double)); data[1] = (double *)G_malloc(nn * nn * sizeof(double)); /*------------------------------------------------------------------*/ /* Apply spectral synthesis algorithm. */ /*------------------------------------------------------------------*/ specsyn(data, nn); G_free(data[0]); G_free(data[1]); return 0; }
static int calc_mu(int *fds, double *mu, int bands) { int i; int rows = Rast_window_rows(); int cols = Rast_window_cols(); void *rowbuf = NULL; for (i = 0; i < bands; i++) { RASTER_MAP_TYPE maptype; int row, col; double sum = 0.; maptype = Rast_get_map_type(fds[i]); /* don't assume each image is of the same type */ if (rowbuf) G_free(rowbuf); if ((rowbuf = Rast_allocate_buf(maptype)) == NULL) G_fatal_error(_("Unable allocate memory for row buffer")); G_message(_("Computing means for band %d..."), i + 1); for (row = 0; row < rows; row++) { void *ptr = rowbuf; G_percent(row, rows - 1, 2); Rast_get_row(fds[i], rowbuf, row, maptype); for (col = 0; col < cols; col++) { /* skip null cells */ if (Rast_is_null_value(ptr, maptype)) { ptr = G_incr_void_ptr(ptr, Rast_cell_size(maptype)); continue; } sum += Rast_get_d_value(ptr, maptype); ptr = G_incr_void_ptr(ptr, Rast_cell_size(maptype)); } } mu[i] = sum / (double)(rows * cols); } if (rowbuf) G_free(rowbuf); return 0; }
void *read_raster(void *buf, const int fd, const RASTER_MAP_TYPE rtype) { void *tmpbuf = buf; int rows = Rast_window_rows(); int i; G_message(_("Reading raster map...")); for (i = 0; i < rows; i++) { G_percent(i + 1, rows, 10); Rast_get_row(fd, tmpbuf, i, rtype); tmpbuf = G_incr_void_ptr(tmpbuf, Rast_cell_size(rtype) * Rast_window_cols()); } return tmpbuf; }
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; }
int openfiles(struct parms *parms, struct files *files) { struct Ref Ref; /* subgroup reference list */ int n; if (!I_get_subgroup_ref(parms->group, parms->subgroup, &Ref)) G_fatal_error(_("Unable to read REF file for subgroup <%s> in group <%s>"), parms->subgroup, parms->group); if (Ref.nfiles <= 0) G_fatal_error(_("Subgroup <%s> in group <%s> contains no raster maps"), parms->subgroup, parms->group); /* allocate file descriptors, and io buffer */ files->cellbuf = Rast_allocate_d_buf(); files->outbuf = Rast_allocate_c_buf(); files->isdata = G_malloc(Rast_window_cols()); files->nbands = Ref.nfiles; files->band_fd = (int *)G_calloc(Ref.nfiles, sizeof(int)); /* open all group maps for reading */ for (n = 0; n < Ref.nfiles; n++) files->band_fd[n] = open_cell_old(Ref.file[n].name, Ref.file[n].mapset); /* open output map */ files->output_fd = open_cell_new(parms->output_map); if (parms->goodness_map) files->goodness_fd = Rast_open_new(parms->goodness_map, FCELL_TYPE); else files->goodness_fd = -1; return 0; }
/*---------------------------------------------------------------------------------------*/ void P_Aux_to_Raster(double **matrix, int fd) { int ncols, col, nrows, row; void *ptr, *raster; nrows = Rast_window_rows(); ncols = Rast_window_cols(); raster = Rast_allocate_buf(DCELL_TYPE); for (row = 0; row < nrows; row++) { G_percent(row, nrows, 2); Rast_set_d_null_value(raster, ncols); for (col = 0, ptr = raster; col < ncols; col++, ptr = G_incr_void_ptr(ptr, Rast_cell_size(DCELL_TYPE))) { Rast_set_d_value(ptr, (DCELL) (matrix[row][col]), DCELL_TYPE); } Rast_put_d_row(fd, raster); } G_percent(row, nrows, 2); }
int get_cats(const char *name, const char *mapset) { int fd; int row, nrows, ncols; CELL *cell; struct Cell_head cellhd; /* set the window to the cell header */ Rast_get_cellhd(name, mapset, &cellhd); Rast_set_window(&cellhd); /* open the raster map */ fd = Rast_open_old(name, mapset); nrows = Rast_window_rows(); ncols = Rast_window_cols(); cell = Rast_allocate_c_buf(); Rast_init_cell_stats(&statf); /* read the raster map */ G_verbose_message(_("Reading <%s> in <%s>"), name, mapset); for (row = 0; row < nrows; row++) { if (G_verbose() > G_verbose_std()) G_percent(row, nrows, 2); Rast_get_c_row_nomask(fd, cell, row); Rast_update_cell_stats(cell, ncols, &statf); } /* done */ if (G_verbose() > G_verbose_std()) G_percent(row, nrows, 2); Rast_close(fd); G_free(cell); Rast_rewind_cell_stats(&statf); return 0; }
/* * do_histogram() - Creates histogram for CELL * * RETURN: EXIT_SUCCESS / EXIT_FAILURE */ int do_histogram(const char *name) { CELL *cell; struct Cell_head cellhd; struct Cell_stats statf; int nrows, ncols; int row; int fd; Rast_get_cellhd(name, "", &cellhd); Rast_set_window(&cellhd); fd = Rast_open_old(name, ""); nrows = Rast_window_rows(); ncols = Rast_window_cols(); cell = Rast_allocate_c_buf(); Rast_init_cell_stats(&statf); for (row = 0; row < nrows; row++) { Rast_get_c_row_nomask(fd, cell, row); Rast_update_cell_stats(cell, ncols, &statf); } if (row == nrows) Rast_write_histogram_cs(name, &statf); Rast_free_cell_stats(&statf); Rast_close(fd); G_free(cell); if (row < nrows) return -1; return 0; }
int main(int argc, char **argv) { struct GModule *module; struct Option *viewopts[MAXVIEWS], *out, *qual; struct Flag *conv; int i; int *sdimp, longdim, r_out; G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("raster")); G_add_keyword(_("export")); G_add_keyword(_("animation")); module->description = _("Converts raster map series to MPEG movie."); for (i = 0; i < MAXVIEWS; i++) { char *buf = NULL; viewopts[i] = G_define_standard_option(G_OPT_R_INPUTS); G_asprintf(&buf, "view%d", i + 1); viewopts[i]->key = G_store(buf); viewopts[i]->required = (i ? NO : YES); G_asprintf(&buf, _("Name of input raster map(s) for view no.%d"), i + 1); viewopts[i]->description = G_store(buf); viewopts[i]->guisection = _("Views"); G_free(buf); } out = G_define_standard_option(G_OPT_R_OUTPUT); out->description = _("Name for output file"); qual = G_define_option(); qual->key = "qual"; qual->type = TYPE_INTEGER; qual->required = NO; qual->multiple = NO; qual->answer = "3"; qual->options = "1-5"; qual->description = _("Quality factor (1 = highest quality, lowest compression)"); qual->guisection = _("Settings"); conv = G_define_flag(); conv->key = 'c'; conv->label = _("Convert on the fly, uses less disk space"); conv->description = _("Requires r.out.ppm with stdout option"); if (G_parser(argc, argv)) exit(EXIT_FAILURE); parse_command(viewopts, vfiles, &numviews, &frames); r_out = 0; if (conv->answer) r_out = 1; quality = 3; if (qual->answer != NULL) sscanf(qual->answer, "%d", &quality); if (quality > 5 || quality < 1) quality = 3; /* find a working encoder */ if (check_encoder("ppmtompeg")) encoder = "ppmtompeg"; else if (check_encoder("mpeg_encode")) encoder = "mpeg_encode"; else G_fatal_error(_("Either mpeg_encode or ppmtompeg must be installed")); G_debug(1, "encoder = [%s]", encoder); vrows = Rast_window_rows(); vcols = Rast_window_cols(); nrows = vrows; ncols = vcols; /* short dimension */ sdimp = nrows > ncols ? &ncols : &nrows; /* these proportions should work fine for 1 or 4 views, but for 2 views, want to double the narrow dim & for 3 views triple it */ if (numviews == 2) *sdimp *= 2; else if (numviews == 3) *sdimp *= 3; longdim = nrows > ncols ? nrows : ncols; scale = 1.0; { /* find animation image size */ int max, min; char *p; max = DEF_MAX; min = DEF_MIN; if ((p = getenv("GMPEG_SIZE"))) max = min = atoi(p); if (longdim > max) /* scale down */ scale = (float)max / longdim; else if (longdim < min) /* scale up */ scale = (float)min / longdim; } /* TODO: align image size to 16 pixel width & height */ vscale = scale; if (numviews == 4) vscale = scale / 2.; nrows *= scale; ncols *= scale; /* now nrows & ncols are the size of the combined - views image */ vrows *= vscale; vcols *= vscale; /* now vrows & vcols are the size for each sub-image */ /* add to nrows & ncols for borders */ /* irows, icols used for vert/horizontal determination in loop below */ irows = nrows; icols = ncols; nrows += (1 + (nrows / vrows)) * BORDER_W; ncols += (1 + (ncols / vcols)) * BORDER_W; if (numviews == 1 && r_out) use_r_out(); else load_files(); return (EXIT_SUCCESS); }
static int load_files(void) { void *voidc; int rtype; register int i, rowoff, row, col, vxoff, vyoff, offset; int cnt, fd, size, tsiz, coff; int vnum; int y_rows, y_cols; char *pr, *pg, *pb; unsigned char *tr, *tg, *tb, *tset; char *mpfilename, *name; char *yfiles[MAXIMAGES]; struct Colors colors; int ret; size = nrows * ncols; pr = G_malloc(size); pg = G_malloc(size); pb = G_malloc(size); tsiz = Rast_window_cols(); tr = (unsigned char *)G_malloc(tsiz); tg = (unsigned char *)G_malloc(tsiz); tb = (unsigned char *)G_malloc(tsiz); tset = (unsigned char *)G_malloc(tsiz); for (cnt = 0; cnt < frames; cnt++) { if (cnt > MAXIMAGES) { cnt--; break; } for (i = 0; i < size; i++) pr[i] = pg[i] = pb[i] = 0; 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; } name = vfiles[vnum][cnt]; G_message(_("Reading raster map <%s>..."), name); fd = Rast_open_old(name, ""); if (Rast_read_colors(name, "", &colors) < 0) G_fatal_error(_("Unable to read color table for <%s>"), name); rtype = Rast_get_map_type(fd); voidc = Rast_allocate_buf(rtype); for (row = 0; row < vrows; row++) { Rast_get_row(fd, voidc, (int)(row / vscale), rtype); rowoff = (vyoff + row) * ncols; Rast_lookup_colors(voidc, tr, tg, tb, tset, tsiz, &colors, rtype); for (col = 0; col < vcols; col++) { coff = (int)(col / vscale); offset = rowoff + col + vxoff; if (!tset[coff]) pr[offset] = pg[offset] = pb[offset] = (char)255; else { pr[offset] = (char)tr[coff]; pg[offset] = (char)tg[coff]; pb[offset] = (char)tb[coff]; } } } Rast_close(fd); } yfiles[cnt] = G_tempfile(); #ifdef USE_PPM write_ppm(pr, pg, pb, nrows, ncols, &y_rows, &y_cols, yfiles[cnt]); #else write_ycc(pr, pg, pb, nrows, ncols, &y_rows, &y_cols, yfiles[cnt]); #endif } mpfilename = G_tempfile(); write_params(mpfilename, yfiles, outfile, cnt, quality, y_rows, y_cols, 0); if (G_verbose() <= G_verbose_min()) ret = G_spawn(encoder, encoder, mpfilename, SF_REDIRECT_FILE, SF_STDOUT, SF_MODE_OUT, G_DEV_NULL, SF_REDIRECT_FILE, SF_STDERR, SF_MODE_OUT, G_DEV_NULL, NULL); else ret = G_spawn(encoder, encoder, mpfilename, NULL); if (ret != 0) G_warning(_("mpeg_encode ERROR")); clean_files(mpfilename, yfiles, cnt); G_free(voidc); G_free(tset); G_free(tr); G_free(tg); G_free(tb); G_free(pr); G_free(pg); G_free(pb); return (cnt); }
int main(int argc, char *argv[]) { int i, row, col; /* counters */ unsigned long filesize; int endianness; /* 0=little, 1=big */ int data_format; /* 0=double 1=float 2=32bit signed int 5=8bit unsigned int (ie text) */ int data_type; /* 0=numbers 1=text */ int format_block; /* combo of endianness, 0, data_format, and type */ int realflag = 0; /* 0=only real values used */ /* should type be specifically uint32 ??? */ char array_name[32]; /* variable names must start with a letter (case sensitive) followed by letters, numbers, or underscores. 31 chars max. */ int name_len; int mrows, ncols; /* text/data/map array dimensions */ int val_i; /* for misc use */ float val_f; /* for misc use */ double val_d; /* for misc use */ char *infile, *outfile, *maptitle, *basename; struct Cell_head region; void *raster, *ptr; RASTER_MAP_TYPE map_type; struct Option *inputfile, *outputfile; struct GModule *module; int fd; FILE *fp1; 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 MAT-File."); /* Define the different options */ inputfile = G_define_standard_option(G_OPT_R_INPUT); outputfile = G_define_option(); outputfile->key = "output"; outputfile->type = TYPE_STRING; outputfile->required = YES; outputfile->gisprompt = "new_file,file,output"; outputfile->description = _("Name for the output binary MAT-File"); if (G_parser(argc, argv)) exit(EXIT_FAILURE); infile = inputfile->answer; basename = G_store(outputfile->answer); G_basename(basename, "mat"); outfile = G_malloc(strlen(basename) + 5); sprintf(outfile, "%s.mat", basename); fd = Rast_open_old(infile, ""); map_type = Rast_get_map_type(fd); /* open bin file for writing */ fp1 = fopen(outfile, "wb"); if (NULL == fp1) G_fatal_error(_("Unable to open output file <%s>"), outfile); /* Check Endian State of Host Computer */ if (G_is_little_endian()) endianness = 0; /* ie little endian */ else endianness = 1; /* ie big endian */ G_debug(1, "Machine is %s endian.\n", endianness ? "big" : "little"); G_get_window(®ion); /********** Write map **********/ /** write text element (map name) **/ strncpy(array_name, "map_name", 31); mrows = 1; ncols = strlen(infile); data_format = 5; /* 0=double 1=float 2=32bit signed int 5=8bit unsigned int(text) */ data_type = 1; /* 0=numbers 1=text */ G_verbose_message(_("Exporting <%s>"), infile); /* 4 byte data format */ format_block = endianness * 1000 + data_format * 10 + data_type; fwrite(&format_block, sizeof(int), 1, fp1); /* fprintf(stderr, "name data format is [%04ld]\n", format_block); */ /* 4 byte number of rows & columns */ fwrite(&mrows, sizeof(int), 1, fp1); fwrite(&ncols, sizeof(int), 1, fp1); /* 4 byte real/imag flag 0=real vals only */ fwrite(&realflag, sizeof(int), 1, fp1); /* length of array_name+1 */ name_len = strlen(array_name) + 1; fwrite(&name_len, sizeof(int), 1, fp1); /* array name */ fprintf(fp1, "%s%c", array_name, '\0'); /* array data */ fprintf(fp1, "%s", infile); /********** Write title (if there is one) **********/ maptitle = Rast_get_cell_title(infile, ""); if (strlen(maptitle) >= 1) { /** write text element (map title) **/ strncpy(array_name, "map_title", 31); mrows = 1; ncols = strlen(maptitle); data_format = 5; /* 0=double 1=float 2=32bit signed int 5=8bit unsigned int(text) */ data_type = 1; /* 0=numbers 1=text */ /* 4 byte data format */ format_block = endianness * 1000 + data_format * 10 + data_type; fwrite(&format_block, sizeof(int), 1, fp1); /* 4 byte number of rows & columns */ fwrite(&mrows, sizeof(int), 1, fp1); fwrite(&ncols, sizeof(int), 1, fp1); /* 4 byte real/imag flag 0=real vals only */ fwrite(&realflag, sizeof(int), 1, fp1); /* length of array_name+1 */ name_len = strlen(array_name) + 1; fwrite(&name_len, sizeof(int), 1, fp1); /* array name */ fprintf(fp1, "%s%c", array_name, '\0'); /* array data */ fprintf(fp1, "%s", maptitle); } /***** Write bounds *****/ G_verbose_message(""); G_verbose_message(_("Using the Current Region settings:")); G_verbose_message(_("northern edge=%f"), region.north); G_verbose_message(_("southern edge=%f"), region.south); G_verbose_message(_("eastern edge=%f"), region.east); G_verbose_message(_("western edge=%f"), region.west); G_verbose_message(_("nsres=%f"), region.ns_res); G_verbose_message(_("ewres=%f"), region.ew_res); G_verbose_message(_("rows=%d"), region.rows); G_verbose_message(_("cols=%d"), region.cols); G_verbose_message(""); for (i = 0; i < 4; i++) { switch (i) { case 0: strncpy(array_name, "map_northern_edge", 31); val_d = region.north; break; case 1: strncpy(array_name, "map_southern_edge", 31); val_d = region.south; break; case 2: strncpy(array_name, "map_eastern_edge", 31); val_d = region.east; break; case 3: strncpy(array_name, "map_western_edge", 31); val_d = region.west; break; default: fclose(fp1); G_fatal_error("please contact development team"); break; } /** write data element **/ data_format = 0; /* 0=double 1=float 2=32bit signed int 5=8bit unsigned int(text) */ data_type = 0; /* 0=numbers 1=text */ mrows = 1; ncols = 1; /* 4 byte data format */ format_block = endianness * 1000 + data_format * 10 + data_type; fwrite(&format_block, sizeof(int), 1, fp1); /* fprintf(stderr, "bounds data format is [%04ld]\n", format_block); */ /* 4 byte number of rows , 4 byte number of colums */ fwrite(&mrows, sizeof(int), 1, fp1); fwrite(&ncols, sizeof(int), 1, fp1); /* 4 byte real/imag flag 0=only real */ fwrite(&realflag, sizeof(int), 1, fp1); /* length of array_name+1 */ name_len = strlen(array_name) + 1; fwrite(&name_len, sizeof(int), 1, fp1); /* array name */ fprintf(fp1, "%s%c", array_name, '\0'); /* write array data, by increasing column */ fwrite(&val_d, sizeof(double), 1, fp1); /** end of data element **/ } /***** Write map data *****/ strncpy(array_name, "map_data", 31); switch (map_type) { /* data_format: 0=double 1=float 2=32bit signed int 5=8bit unsigned int (ie text) */ case CELL_TYPE: data_format = 2; G_verbose_message(_("Exporting raster as integer values")); break; case FCELL_TYPE: data_format = 1; G_verbose_message(_("Exporting raster as floating point values")); break; case DCELL_TYPE: data_format = 0; G_verbose_message(_("Exporting raster as double FP values")); break; default: fclose(fp1); G_fatal_error("Please contact development team"); break; } data_type = 0; /* 0=numbers 1=text */ mrows = region.rows; ncols = region.cols; /* 4 byte data format */ format_block = (endianness * 1000) + (data_format * 10) + data_type; fwrite(&format_block, sizeof(int), 1, fp1); G_debug(3, "map data format is [%04d]\n", format_block); /* 4 byte number of rows & columns */ fwrite(&mrows, sizeof(int), 1, fp1); fwrite(&ncols, sizeof(int), 1, fp1); /* 4 byte real/imag flag 0=only real */ fwrite(&realflag, sizeof(int), 1, fp1); /* length of array_name+1 */ name_len = strlen(array_name) + 1; fwrite(&name_len, sizeof(int), 1, fp1); /* array name */ fprintf(fp1, "%s%c", array_name, '\0'); /* data array, by increasing column */ raster = G_calloc((Rast_window_rows() + 1) * (Rast_window_cols() + 1), Rast_cell_size(map_type)); G_debug(1, "mem alloc is %d bytes\n", /* I think _cols()+1 is unneeded? */ Rast_cell_size(map_type) * (Rast_window_rows() + 1) * (Rast_window_cols() + 1)); G_verbose_message(_("Reading in map ... ")); /* load entire map into memory */ for (row = 0, ptr = raster; row < mrows; row++, ptr = G_incr_void_ptr(ptr, (Rast_window_cols() + 1) * Rast_cell_size(map_type))) { Rast_get_row(fd, ptr, row, map_type); G_percent(row, mrows, 2); } G_percent(row, mrows, 2); /* finish it off */ G_verbose_message(_("Writing out map...")); /* then write it to disk */ /* NoGood: fwrite(raster, Rast_cell_size(map_type), mrows*ncols, fp1); */ for (col = 0; col < ncols; col++) { for (row = 0; row < mrows; row++) { ptr = raster; ptr = G_incr_void_ptr(ptr, (col + row * (ncols + 1)) * Rast_cell_size(map_type)); if (!Rast_is_null_value(ptr, map_type)) { if (map_type == CELL_TYPE) { val_i = *((CELL *) ptr); fwrite(&val_i, sizeof(int), 1, fp1); } else if (map_type == FCELL_TYPE) { val_f = *((FCELL *) ptr); fwrite(&val_f, sizeof(float), 1, fp1); } else if (map_type == DCELL_TYPE) { val_d = *((DCELL *) ptr); fwrite(&val_d, sizeof(double), 1, fp1); } } else { /* ie if NULL cell -> write IEEE NaN value */ if (map_type == CELL_TYPE) { val_i = *((CELL *) ptr); /* int has no NaN value, so use whatever GRASS uses */ fwrite(&val_i, sizeof(int), 1, fp1); } else if (map_type == FCELL_TYPE) { if (endianness) /* ie big */ fprintf(fp1, "%c%c%c%c", 0xff, 0xf8, 0, 0); else /* ie little */ fprintf(fp1, "%c%c%c%c", 0, 0, 0xf8, 0xff); } else if (map_type == DCELL_TYPE) { if (endianness) fprintf(fp1, "%c%c%c%c%c%c%c%c", 0xff, 0xf8, 0, 0, 0, 0, 0, 0); else fprintf(fp1, "%c%c%c%c%c%c%c%c", 0, 0, 0, 0, 0, 0, 0xf8, 0xff); } } } G_percent(col, ncols, 2); } G_percent(col, ncols, 2); /* finish it off */ /*** end of data element ***/ /* done! */ filesize = G_ftell(fp1); fclose(fp1); G_verbose_message(_("%ld bytes written to '%s'"), filesize, outfile); G_done_msg(""); G_free(basename); G_free(outfile); exit(EXIT_SUCCESS); }
int main(int argc, char **argv) { FILTER *filter; int nfilters; int repeat; char *in_name; char *filt_name; char *out_name; char title[1024]; char temp[300]; int i; struct GModule *module; struct Flag *flag2; struct Option *opt1; struct Option *opt2; struct Option *opt3; struct Option *opt4; struct Option *opt5; G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("raster")); G_add_keyword(_("algebra")); G_add_keyword(_("statistics")); module->description = _("Performs raster map matrix filter."); /* Define the different options */ opt1 = G_define_standard_option(G_OPT_R_INPUT); opt2 = G_define_standard_option(G_OPT_R_OUTPUT); opt3 = G_define_standard_option(G_OPT_F_INPUT); opt3->key = "filter"; opt3->required = YES; opt3->description = _("Path to filter file"); opt4 = G_define_option(); opt4->key = "repeat"; opt4->type = TYPE_INTEGER; opt4->multiple = NO; opt4->required = NO; opt4->answer = "1"; opt4->description = _("Number of times to repeat the filter"); opt4->guisection = _("Filter"); opt5 = G_define_option(); opt5->key = "title"; opt5->type = TYPE_STRING; opt5->required = NO; opt5->description = _("Output raster map title"); /* Define the different flags */ /* this isn't implemented at all flag3 = G_define_flag() ; flag3->key = 'p' ; flag3->description = _("Preserved edge") ; */ flag2 = G_define_flag(); flag2->key = 'z'; flag2->description = _("Apply filter only to null data values"); flag2->guisection = _("Filter"); if (G_parser(argc, argv)) exit(EXIT_FAILURE); /* preserve_edges = flag3->answer; */ null_only = flag2->answer; sscanf(opt4->answer, "%d", &repeat); out_name = opt2->answer; filt_name = opt3->answer; in_name = opt1->answer; nrows = Rast_window_rows(); ncols = Rast_window_cols(); buflen = ncols * sizeof(DCELL); /* get the filter */ filter = get_filter(filt_name, &nfilters, temp); /* make sure filter matrix won't extend outside the raster map */ for (i = 0; i < nfilters; i++) { if (filter[i].size > ncols || filter[i].size > nrows) G_fatal_error(_("Raster map too small for the size of the filter")); } /* make a title for result */ if (opt5->answer) strcpy(title, opt5->answer); else { if (*temp == 0) strcpy(temp, "unknown filter"); sprintf(title, "%s filtered using %s", in_name, temp); } perform_filter(in_name, out_name, filter, nfilters, repeat); Rast_put_cell_title(out_name, title); exit(EXIT_SUCCESS); }
/*! * \brief Allocates memory for a raster map of type FCELL. * * Allocate an array of FCELL based on the number of columns in the * current region. * * \return pointer to allocated buffer */ FCELL *Rast_allocate_f_buf(void) { return (FCELL *) G_calloc(Rast_window_cols() + 1, sizeof(FCELL)); }
/*! * \brief Allocate memory for a raster map of given type * * Allocate an array of CELL, FCELL, or DCELL (depending on * <i>data_type</i>) based on the number of columns in the current * region. * * \param data_type raster type (CELL, FCELL, DCELL) * * \return pointer to allocated buffer */ void *Rast_allocate_buf(RASTER_MAP_TYPE data_type) { return (void *)G_calloc(Rast_window_cols() + 1, Rast_cell_size(data_type)); }
/*! * \brief Allocates memory for a null buffer. * * Allocate an array of char based on the number of columns in the * current region. * * \return pointer to allocated buffer */ char *Rast_allocate_null_buf(void) { return (char *)G_calloc(Rast_window_cols() + 1, sizeof(char)); }
void filter_holes(Gfile * out) { int row, col, nrows, ncols; void *arast, *brast, *crast; int i, pixel[9], cold, warm, shadow, nulo, lim; Gfile tmp; nrows = Rast_window_rows(); ncols = Rast_window_cols(); if (nrows < 3 || ncols < 3) return; /* Open to read */ if ((out->fd = Rast_open_old(out->name, "")) < 0) G_fatal_error(_("Unable to open raster map <%s>"), out->name); arast = Rast_allocate_buf(CELL_TYPE); brast = Rast_allocate_buf(CELL_TYPE); crast = Rast_allocate_buf(CELL_TYPE); /* Open to write */ sprintf(tmp.name, "_%d.BBB", getpid()); tmp.rast = Rast_allocate_buf(CELL_TYPE); if ((tmp.fd = Rast_open_new(tmp.name, CELL_TYPE)) < 0) G_fatal_error(_("Unable to create raster map <%s>"), tmp.name); G_important_message(_("Filling small holes in clouds...")); /* Se puede acelerar creandolos nulos y luego arast = brast brast = crast y cargando crast solamente G_set_f_null_value(cell[2], ncols); */ for (row = 0; row < nrows; row++) { G_percent(row, nrows, 2); /* Read row values */ if (row != 0) { Rast_get_c_row(out->fd, arast, row - 1); } Rast_get_c_row(out->fd, brast, row); if (row != (nrows - 1)) { Rast_get_c_row(out->fd, crast, row + 1); } /* Analysis of all pixels */ for (col = 0; col < ncols; col++) { pixel[0] = pval(brast, col); if (pixel[0] == 0) { if (row == 0) { pixel[1] = -1; pixel[2] = -1; pixel[3] = -1; if (col == 0) { pixel[4] = -1; pixel[5] = pval(brast, col + 1); pixel[6] = -1; pixel[7] = pval(crast, col); pixel[8] = pval(crast, col + 1); } else if (col != (ncols - 1)) { pixel[4] = pval(brast, col - 1); pixel[5] = pval(brast, col + 1); pixel[6] = pval(crast, col - 1); pixel[7] = pval(crast, col); pixel[8] = pval(crast, col + 1); } else { pixel[4] = pval(brast, col - 1); pixel[5] = -1; pixel[6] = pval(crast, col - 1); pixel[7] = pval(crast, col); pixel[8] = -1; } } else if (row != (nrows - 1)) { if (col == 0) { pixel[1] = -1; pixel[2] = pval(arast, col); pixel[3] = pval(arast, col + 1); pixel[4] = -1; pixel[5] = pval(brast, col + 1); pixel[6] = -1; pixel[7] = pval(crast, col); pixel[8] = pval(crast, col + 1); } else if (col != (ncols - 1)) { pixel[1] = pval(arast, col - 1); pixel[2] = pval(arast, col); pixel[3] = pval(arast, col + 1); pixel[4] = pval(brast, col - 1); pixel[5] = pval(brast, col + 1); pixel[6] = pval(crast, col - 1); pixel[7] = pval(crast, col); pixel[8] = pval(crast, col + 1); } else { pixel[1] = pval(arast, col - 1); pixel[2] = pval(arast, col); pixel[3] = -1; pixel[4] = pval(brast, col - 1); pixel[5] = -1; pixel[6] = pval(crast, col - 1); pixel[7] = pval(crast, col); pixel[8] = -1; } } else { pixel[6] = -1; pixel[7] = -1; pixel[8] = -1; if (col == 0) { pixel[1] = -1; pixel[2] = pval(arast, col); pixel[3] = pval(arast, col + 1); pixel[4] = -1; pixel[5] = pval(brast, col + 1); } else if (col != (ncols - 1)) { pixel[1] = pval(arast, col - 1); pixel[2] = pval(arast, col); pixel[3] = pval(arast, col + 1); pixel[4] = pval(brast, col - 1); pixel[5] = pval(brast, col + 1); } else { pixel[1] = pval(arast, col - 1); pixel[2] = pval(arast, col); pixel[3] = -1; pixel[4] = pval(brast, col - 1); pixel[5] = -1; } } cold = warm = shadow = nulo = 0; for (i = 1; i < 9; i++) { switch (pixel[i]) { case IS_COLD_CLOUD: cold++; break; case IS_WARM_CLOUD: warm++; break; case IS_SHADOW: shadow++; break; default: nulo++; break; } } lim = (int)(cold + warm + shadow + nulo) / 2; /* Entra pixel[0] = 0 */ if (nulo < lim) { if (shadow >= (cold + warm)) pixel[0] = IS_SHADOW; else pixel[0] = (warm > cold) ? IS_WARM_CLOUD : IS_COLD_CLOUD; } } if (pixel[0] != 0) { ((CELL *) tmp.rast)[col] = pixel[0]; } else { Rast_set_c_null_value((CELL *) tmp.rast + col, 1); } } Rast_put_row(tmp.fd, tmp.rast, CELL_TYPE); } G_percent(1, 1, 1); G_free(arast); G_free(brast); G_free(crast); Rast_close(out->fd); G_free(tmp.rast); Rast_close(tmp.fd); G_remove("cats", out->name); G_remove("cell", out->name); G_remove("cellhd", out->name); G_remove("cell_misc", out->name); G_remove("hist", out->name); G_rename("cats", tmp.name, out->name); G_rename("cell", tmp.name, out->name); G_rename("cellhd", tmp.name, out->name); G_rename("cell_misc", tmp.name, out->name); G_rename("hist", tmp.name, out->name); return; }
int main(int argc, char *argv[]) { struct GModule *module; struct { struct Option *quant, *perc, *slots, *basemap, *covermap, *output; } opt; struct { struct Flag *r, *p; } flag; const char *basemap, *covermap; char **outputs; int reclass, print; int cover_fd, base_fd; struct Range range; struct FPRange fprange; int i; G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("raster")); G_add_keyword(_("statistics")); module->description = _("Compute category quantiles using two passes."); opt.basemap = G_define_standard_option(G_OPT_R_BASE); opt.covermap = G_define_standard_option(G_OPT_R_COVER); opt.quant = G_define_option(); opt.quant->key = "quantiles"; opt.quant->type = TYPE_INTEGER; opt.quant->required = NO; opt.quant->description = _("Number of quantiles"); opt.perc = G_define_option(); opt.perc->key = "percentiles"; opt.perc->type = TYPE_DOUBLE; opt.perc->multiple = YES; opt.perc->description = _("List of percentiles"); opt.perc->answer = "50"; opt.slots = G_define_option(); opt.slots->key = "bins"; opt.slots->type = TYPE_INTEGER; opt.slots->required = NO; opt.slots->description = _("Number of bins to use"); opt.slots->answer = "1000"; opt.output = G_define_standard_option(G_OPT_R_OUTPUT); opt.output->description = _("Resultant raster map(s)"); opt.output->required = NO; opt.output->multiple = YES; flag.r = G_define_flag(); flag.r->key = 'r'; flag.r->description = _("Create reclass map with statistics as category labels"); flag.p = G_define_flag(); flag.p->key = 'p'; flag.p->description = _("Do not create output maps; just print statistics"); if (G_parser(argc, argv)) exit(EXIT_FAILURE); basemap = opt.basemap->answer; covermap = opt.covermap->answer; outputs = opt.output->answers; reclass = flag.r->answer; print = flag.p->answer; if (!print && !opt.output->answers) G_fatal_error(_("Either -%c or %s= must be given"), flag.p->key, opt.output->key); if (print && opt.output->answers) G_fatal_error(_("-%c and %s= are mutually exclusive"), flag.p->key, opt.output->key); num_slots = atoi(opt.slots->answer); if (opt.quant->answer) { num_quants = atoi(opt.quant->answer) - 1; quants = G_calloc(num_quants, sizeof(DCELL)); for (i = 0; i < num_quants; i++) quants[i] = 1.0 * (i + 1) / (num_quants + 1); } else { for (i = 0; opt.perc->answers[i]; i++) ; num_quants = i; quants = G_calloc(num_quants, sizeof(DCELL)); for (i = 0; i < num_quants; i++) quants[i] = atof(opt.perc->answers[i]) / 100; qsort(quants, num_quants, sizeof(DCELL), compare_dcell); } if (opt.output->answer) { for (i = 0; opt.output->answers[i]; i++) ; if (i != num_quants) G_fatal_error(_("Number of quantiles (%d) does not match number of output maps (%d)"), num_quants, i); } base_fd = Rast_open_old(basemap, ""); cover_fd = Rast_open_old(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); Rast_get_range_min_max(&range, &min, &max); num_cats = max - min + 1; if (num_cats > MAX_CATS) G_fatal_error(_("Base map <%s> has too many categories (max: %d)"), basemap, MAX_CATS); Rast_read_fp_range(covermap, "", &fprange); Rast_get_fp_range_min_max(&fprange, &f_min, &f_max); slot_size = (f_max - f_min) / num_slots; basecats = G_calloc(num_cats, sizeof(struct basecat)); for (i = 0; i < num_cats; i++) basecats[i].slots = G_calloc(num_slots, sizeof(unsigned int)); rows = Rast_window_rows(); cols = Rast_window_cols(); get_slot_counts(base_fd, cover_fd); initialize_bins(); fill_bins(base_fd, cover_fd); sort_bins(); compute_quantiles(); if (print) print_quantiles(); else if (reclass) do_reclass(basemap, outputs); else do_output(base_fd, outputs, covermap); Rast_close(cover_fd); Rast_close(base_fd); return (EXIT_SUCCESS); }
/* ************************************************************************* */ int main(int argc, char *argv[]) { RASTER3D_Region region, inputmap_bounds; struct Cell_head region2d; struct GModule *module; struct History history; void *map = NULL; /*The 3D Rastermap */ int i = 0, changemask = 0; int *fd = NULL, output_type, cols, rows; char *RasterFileName; int overwrite = 0; /* Initialize GRASS */ G_gisinit(argv[0]); module = G_define_module(); G_add_keyword(_("raster3d")); G_add_keyword(_("conversion")); G_add_keyword(_("raster")); G_add_keyword(_("voxel")); module->description = _("Converts 3D raster maps to 2D raster maps"); /* Get parameters from user */ set_params(); /* Have GRASS get inputs */ if (G_parser(argc, argv)) exit(EXIT_FAILURE); G_debug(3, "Open 3D raster map <%s>", param.input->answer); if (NULL == G_find_raster3d(param.input->answer, "")) Rast3d_fatal_error(_("3D raster map <%s> not found"), param.input->answer); /*Set the defaults */ Rast3d_init_defaults(); /*Set the resolution of the output maps */ if (param.res->answer) { /*Open the map with current region */ map = Rast3d_open_cell_old(param.input->answer, G_find_raster3d(param.input->answer, ""), RASTER3D_DEFAULT_WINDOW, RASTER3D_TILE_SAME_AS_FILE, RASTER3D_USE_CACHE_DEFAULT); if (map == NULL) Rast3d_fatal_error(_("Unable to open 3D raster map <%s>"), param.input->answer); /*Get the region of the map */ Rast3d_get_region_struct_map(map, ®ion); /*set this region as current 3D window for map */ Rast3d_set_window_map(map, ®ion); /*Set the 2d region appropriate */ Rast3d_extract2d_region(®ion, ®ion2d); /*Make the new 2d region the default */ Rast_set_window(®ion2d); } else { /* Figure out the region from the map */ Rast3d_get_window(®ion); /*Open the 3d raster map */ map = Rast3d_open_cell_old(param.input->answer, G_find_raster3d(param.input->answer, ""), ®ion, RASTER3D_TILE_SAME_AS_FILE, RASTER3D_USE_CACHE_DEFAULT); if (map == NULL) Rast3d_fatal_error(_("Unable to open 3D raster map <%s>"), param.input->answer); } /*Check if the g3d-region is equal to the 2D rows and cols */ rows = Rast_window_rows(); cols = Rast_window_cols(); /*If not equal, set the 3D window correct */ if (rows != region.rows || cols != region.cols) { G_message(_("The 2D and 3D region settings are different. " "Using the 2D window settings to adjust the 2D part of the 3D region.")); G_get_set_window(®ion2d); region.ns_res = region2d.ns_res; region.ew_res = region2d.ew_res; region.rows = region2d.rows; region.cols = region2d.cols; Rast3d_adjust_region(®ion); Rast3d_set_window_map(map, ®ion); } /* save the input map region for later use (history meta-data) */ Rast3d_get_region_struct_map(map, &inputmap_bounds); /*Get the output type */ output_type = Rast3d_file_type_map(map); /*prepare the filehandler */ fd = (int *) G_malloc(region.depths * sizeof (int)); if (fd == NULL) fatal_error(map, NULL, 0, _("Out of memory")); G_message(_("Creating %i raster maps"), region.depths); /*Loop over all output maps! open */ for (i = 0; i < region.depths; i++) { /*Create the outputmaps */ G_asprintf(&RasterFileName, "%s_%05d", param.output->answer, i + 1); G_message(_("Raster map %i Filename: %s"), i + 1, RasterFileName); overwrite = G_check_overwrite(argc, argv); if (G_find_raster2(RasterFileName, "") && !overwrite) G_fatal_error(_("Raster map %d Filename: %s already exists. Use the flag --o to overwrite."), i + 1, RasterFileName); if (output_type == FCELL_TYPE) fd[i] = open_output_map(RasterFileName, FCELL_TYPE); else if (output_type == DCELL_TYPE) fd[i] = open_output_map(RasterFileName, DCELL_TYPE); } /*if requested set the Mask on */ if (param.mask->answer) { if (Rast3d_mask_file_exists()) { changemask = 0; if (Rast3d_mask_is_off(map)) { Rast3d_mask_on(map); changemask = 1; } } } /*Create the Rastermaps */ g3d_to_raster(map, region, fd); /*Loop over all output maps! close */ for (i = 0; i < region.depths; i++) { close_output_map(fd[i]); /* write history */ G_asprintf(&RasterFileName, "%s_%i", param.output->answer, i + 1); G_debug(4, "Raster map %d Filename: %s", i + 1, RasterFileName); Rast_short_history(RasterFileName, "raster", &history); Rast_set_history(&history, HIST_DATSRC_1, "3D Raster map:"); Rast_set_history(&history, HIST_DATSRC_2, param.input->answer); Rast_append_format_history(&history, "Level %d of %d", i + 1, region.depths); Rast_append_format_history(&history, "Level z-range: %f to %f", region.bottom + (i * region.tb_res), region.bottom + (i + 1 * region.tb_res)); Rast_append_format_history(&history, "Input map full z-range: %f to %f", inputmap_bounds.bottom, inputmap_bounds.top); Rast_append_format_history(&history, "Input map z-resolution: %f", inputmap_bounds.tb_res); if (!param.res->answer) { Rast_append_format_history(&history, "GIS region full z-range: %f to %f", region.bottom, region.top); Rast_append_format_history(&history, "GIS region z-resolution: %f", region.tb_res); } Rast_command_history(&history); Rast_write_history(RasterFileName, &history); } /*We set the Mask off, if it was off before */ if (param.mask->answer) { if (Rast3d_mask_file_exists()) if (Rast3d_mask_is_on(map) && changemask) Rast3d_mask_off(map); } /*Cleaning */ if (RasterFileName) G_free(RasterFileName); if (fd) G_free(fd); /* Close files and exit */ if (!Rast3d_close(map)) fatal_error(map, NULL, 0, _("Unable to close 3D raster map")); map = NULL; return (EXIT_SUCCESS); }
int main(int argc, char **argv) { 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 open_file(char *name) { int cell_file, buf_len; int i, row; CELL *buf; /* open raster map */ cell_file = Rast_open_old(name, ""); if (Rast_get_map_type(cell_file) != CELL_TYPE) { Rast_close(cell_file); G_fatal_error(_("Input raster must be of type CELL.")); } n_rows = Rast_window_rows(); n_cols = Rast_window_cols(); G_message(_("File %s -- %d rows X %d columns"), name, n_rows, n_cols); n_cols += (PAD << 1); /* copy raster map into our read/write file */ work_file_name = G_tempfile(); /* create the file and then open it for read and write */ close(creat(work_file_name, 0666)); if ((work_file = open(work_file_name, 2)) < 0) { unlink(work_file_name); G_fatal_error(_("%s: Unable to create temporary file <%s> -- errno = %d"), error_prefix, work_file_name, errno); } buf_len = n_cols * sizeof(CELL); buf = (CELL *) G_malloc(buf_len); Rast_set_c_null_value(buf, n_cols); for (i = 0; i < PAD; i++) { if (write(work_file, buf, buf_len) != buf_len) { unlink(work_file_name); G_fatal_error(_("%s: Error writing temporary file"), error_prefix); } } for (row = 0; row < n_rows; row++) { Rast_get_c_row(cell_file, buf + PAD, row); if (write(work_file, buf, buf_len) != buf_len) { unlink(work_file_name); G_fatal_error(_("%s: Error writing temporary file"), error_prefix); } } Rast_set_c_null_value(buf, n_cols); for (i = 0; i < PAD; i++) { if (write(work_file, buf, buf_len) != buf_len) { unlink(work_file_name); G_fatal_error(_("%s: Error writing temporary file"), error_prefix); } } n_rows += (PAD << 1); G_free(buf); Rast_close(cell_file); Rowio_setup(&row_io, work_file, MAX_ROW, n_cols * sizeof(CELL), read_row, write_row); return 0; }
int execute_random(struct rr_state *theState) { long nt; long nc; struct Cell_head window; int nrows, ncols, row, col; int infd, cinfd, outfd; struct Map_info Out; struct field_info *fi; dbTable *table; dbColumn *column; dbString sql; dbDriver *driver; struct line_pnts *Points; struct line_cats *Cats; int cat; RASTER_MAP_TYPE type; int do_check; G_get_window(&window); nrows = Rast_window_rows(); ncols = Rast_window_cols(); /* open the data files, input raster should be set-up already */ if ((infd = theState->fd_old) < 0) G_fatal_error(_("Unable to open raster map <%s>"), theState->inraster); if (theState->docover == TRUE) { if ((cinfd = theState->fd_cold) < 0) G_fatal_error(_("Unable to open raster map <%s>"), theState->inrcover); } if (theState->outraster != NULL) { if (theState->docover == TRUE) type = theState->cover.type; else type = theState->buf.type; outfd = Rast_open_new(theState->outraster, type); theState->fd_new = outfd; } if (theState->outvector) { if (Vect_open_new(&Out, theState->outvector, theState->z_geometry) < 0) G_fatal_error(_("Unable to create vector map <%s>"), theState->outvector); Vect_hist_command(&Out); fi = Vect_default_field_info(&Out, 1, NULL, GV_1TABLE); driver = db_start_driver_open_database(fi->driver, Vect_subst_var(fi->database, &Out)); if (!driver) G_fatal_error(_("Unable to open database <%s> by driver <%s>"), Vect_subst_var(fi->database, &Out), fi->driver); db_set_error_handler_driver(driver); Vect_map_add_dblink(&Out, 1, NULL, fi->table, GV_KEY_COLUMN, fi->database, fi->driver); if (theState->docover == TRUE) table = db_alloc_table(3); else table = db_alloc_table(2); db_set_table_name(table, fi->table); column = db_get_table_column(table, 0); db_set_column_name(column, GV_KEY_COLUMN); db_set_column_sqltype(column, DB_SQL_TYPE_INTEGER); column = db_get_table_column(table, 1); db_set_column_name(column, "value"); db_set_column_sqltype(column, DB_SQL_TYPE_DOUBLE_PRECISION); if (theState->docover == TRUE) { column = db_get_table_column(table, 2); db_set_column_name(column, "covervalue"); db_set_column_sqltype(column, DB_SQL_TYPE_DOUBLE_PRECISION); } if (db_create_table(driver, table) != DB_OK) G_warning(_("Cannot create new table")); db_begin_transaction(driver); Points = Vect_new_line_struct(); Cats = Vect_new_cats_struct(); db_init_string(&sql); } if (theState->outvector && theState->outraster) G_message(_("Writing raster map <%s> and vector map <%s> ..."), theState->outraster, theState->outvector); else if (theState->outraster) G_message(_("Writing raster map <%s> ..."), theState->outraster); else if (theState->outvector) G_message(_("Writing vector map <%s> ..."), theState->outvector); G_percent(0, theState->nRand, 2); init_rand(); nc = (theState->use_nulls) ? theState->nCells : theState->nCells - theState->nNulls; nt = theState->nRand; /* Number of points to generate */ cat = 1; /* Execute for loop for every row if nt>1 */ for (row = 0; row < nrows && nt; row++) { Rast_get_row(infd, theState->buf.data.v, row, theState->buf.type); if (theState->docover == TRUE) { Rast_get_row(cinfd, theState->cover.data.v, row, theState->cover.type); } for (col = 0; col < ncols && nt; col++) { do_check = 0; if (theState->use_nulls || !is_null_value(theState->buf, col)) do_check = 1; if (do_check && theState->docover == TRUE) { /* skip no data cover points */ if (!theState->use_nulls && is_null_value(theState->cover, col)) do_check = 0; } if (do_check && make_rand() % nc < nt) { nt--; if (is_null_value(theState->buf, col)) cpvalue(&theState->nulls, 0, &theState->buf, col); if (theState->docover == TRUE) { if (is_null_value(theState->cover, col)) cpvalue(&theState->cnulls, 0, &theState->cover, col); } if (theState->outvector) { double x, y, val, coverval; char buf[500]; Vect_reset_line(Points); Vect_reset_cats(Cats); x = window.west + (col + .5) * window.ew_res; y = window.north - (row + .5) * window.ns_res; val = cell_as_dbl(&theState->buf, col); if (theState->docover == 1) coverval = cell_as_dbl(&theState->cover, col); if (theState->z_geometry) Vect_append_point(Points, x, y, val); else Vect_append_point(Points, x, y, 0.0); Vect_cat_set(Cats, 1, cat); Vect_write_line(&Out, GV_POINT, Points, Cats); if (theState->docover == 1) if (is_null_value(theState->cover, col)) sprintf(buf, "insert into %s values ( %d, %f, NULL )", fi->table, cat, val); else sprintf(buf, "insert into %s values ( %d, %f, %f )", fi->table, cat, val, coverval); else sprintf(buf, "insert into %s values ( %d, %f )", fi->table, cat, val); db_set_string(&sql, buf); if (db_execute_immediate(driver, &sql) != DB_OK) G_fatal_error(_("Cannot insert new record: %s"), db_get_string(&sql)); cat++; } G_percent((theState->nRand - nt), theState->nRand, 2); } else { set_to_null(&theState->buf, col); if (theState->docover == 1) set_to_null(&theState->cover, col); } if (do_check) nc--; } while (col < ncols) { set_to_null(&theState->buf, col); if (theState->docover == 1) set_to_null(&theState->cover, col); col++; } if (theState->outraster) { if (theState->docover == 1) Rast_put_row(outfd, theState->cover.data.v, theState->cover.type); else Rast_put_row(outfd, theState->buf.data.v, theState->buf.type); } } /* Catch any remaining rows in the window */ if (theState->outraster && row < nrows) { for (col = 0; col < ncols; col++) { if (theState->docover == 1) set_to_null(&theState->cover, col); else set_to_null(&theState->buf, col); } for (; row < nrows; row++) { if (theState->docover == 1) Rast_put_row(outfd, theState->cover.data.v, theState->cover.type); else Rast_put_row(outfd, theState->buf.data.v, theState->buf.type); } } if (nt > 0) G_warning(_("Only [%ld] random points created"), theState->nRand - nt); /* close files */ Rast_close(infd); if (theState->docover == TRUE) Rast_close(cinfd); if (theState->outvector) { db_commit_transaction(driver); if (db_create_index2(driver, fi->table, GV_KEY_COLUMN) != DB_OK) G_warning(_("Unable to create index")); if (db_grant_on_table (driver, fi->table, DB_PRIV_SELECT, DB_GROUP | DB_PUBLIC) != DB_OK) { G_fatal_error(_("Unable to grant privileges on table <%s>"), fi->table); } db_close_database_shutdown_driver(driver); if (theState->notopol != 1) Vect_build(&Out); Vect_close(&Out); } if (theState->outraster) Rast_close(outfd); return 0; } /* execute_random() */