/* store a raster map in a mem segment on disk */ void Segment_infile (char* map_name, char* mapset, char* search_mapset, int* map_fd, char* seg_name, int* seg_fd, SEGMENT* seg, void *cell_buf, int fract, RASTER_MAP_TYPE data_type) { int nrows, row; strcpy (mapset, G_find_cell (map_name, search_mapset)); if (mapset == NULL) G_fatal_error ("Can't find displayed data layer "); if ((*map_fd = G_open_cell_old (map_name, mapset)) < 0) G_fatal_error ("Can't open displayed data layer "); nrows = G_window_rows (); /* next line creates the actual segment, returns name of disk file */ strcpy (seg_name, Create_segment_file (nrows, fract, data_type)); *seg_fd = open (seg_name, O_RDWR); if (*seg_fd < 0) G_fatal_error ("Cannot open segment disk file "); segment_init (seg, *seg_fd, 4); /* store map data in segment file IGNORE MASK */ /* cell_buf must be pre-allocated by caller! */ for (row = 0; row < nrows; row++) { if (G_get_raster_row_nomask (*map_fd, cell_buf, row, data_type) < 0) { G_fatal_error ("Unable to read data layer into segment file "); } segment_put_row (seg, cell_buf, row); /* store raster map in segment file */ } }
CELL *open_cell(char *name, char *mapset, int *fd) { if (mapset == NULL) mapset = G_find_cell(name, ""); *fd = G_open_cell_old(name, mapset); if (*fd < 0) G_fatal_error(_("Unable to open raster map <%s>"), name); return G_allocate_cell_buf(); }
/*! \brief Load raster map as integer map Calling function must have already allocated space in buff for struct BM of wind->rows & wind->cols. This routine simply loads the map into the bitmap by repetitve calls to get_map_row. Any value other than 0 in the map will set the bitmap. (may want to change later to allow specific value to set) Changed to use null. \param wind current window \param map_name raster map name \param[out] buff data buffer \returns 1 on success \return -1 on failure */ int Gs_loadmap_as_bitmap(struct Cell_head *wind, const char *map_name, struct BM *buff) { FILEDESC cellfile; const char *map_set; char *nullflags; int *tmp_buf; int row, col; G_debug(3, "Gs_loadmap_as_bitmap"); map_set = G_find_cell2(map_name, ""); if (!map_set) { G_warning(_("Raster map <%s> not found"), map_name); return -1; } if ((cellfile = G_open_cell_old(map_name, map_set)) == -1) { G_fatal_error(_("Unable to open raster map <%s>"), map_name); } tmp_buf = (int *)G_malloc(wind->cols * sizeof(int)); /* G_fatal_error */ if (!tmp_buf) { return -1; } nullflags = G_allocate_null_buf(); if (!nullflags) { G_fatal_error(_("Unable to allocate memory for a null buffer")); } G_message(_("Loading raster map <%s>..."), G_fully_qualified_name(map_name, map_set)); for (row = 0; row < wind->rows; row++) { G_get_null_value_row(cellfile, nullflags, row); for (col = 0; col < wind->cols; col++) { if (nullflags[col]) { /* no data */ BM_set(buff, col, row, 1); } else { BM_set(buff, col, row, 0); } } } G_close_cell(cellfile); G_free(tmp_buf); G_free(nullflags); return (1); }
CPLErr GRASSRasterBand::ResetReading ( struct Cell_head *sNewWindow ) { /* Check if the window has changed */ if ( sNewWindow->north != sOpenWindow.north || sNewWindow->south != sOpenWindow.south || sNewWindow->east != sOpenWindow.east || sNewWindow->west != sOpenWindow.west || sNewWindow->ew_res != sOpenWindow.ew_res || sNewWindow->ns_res != sOpenWindow.ns_res || sNewWindow->rows != sOpenWindow.rows || sNewWindow->cols != sOpenWindow.cols ) { if( hCell >= 0 ) { G_close_cell( hCell ); hCell = -1; } /* Set window */ G_set_window( sNewWindow ); /* Open raster */ G__setenv( "GISDBASE", ((GRASSDataset *)poDS)->pszGisdbase ); G__setenv( "LOCATION_NAME", ((GRASSDataset *)poDS)->pszLocation ); G__setenv( "MAPSET", pszMapset); G_reset_mapsets(); G_add_mapset_to_search_path ( pszMapset ); if ( (hCell = G_open_cell_old( pszCellName, pszMapset)) < 0 ) { CPLError( CE_Warning, CPLE_AppDefined, "GRASS: Cannot open raster '%s'", pszCellName ); this->valid = false; return CE_Failure; } G_copy((void *) &sOpenWindow, (void *) sNewWindow, sizeof(struct Cell_head)); } else { /* The windows are identical, check current window */ struct Cell_head sCurrentWindow; G_get_window ( &sCurrentWindow ); if ( sNewWindow->north != sCurrentWindow.north || sNewWindow->south != sCurrentWindow.south || sNewWindow->east != sCurrentWindow.east || sNewWindow->west != sCurrentWindow.west || sNewWindow->ew_res != sCurrentWindow.ew_res || sNewWindow->ns_res != sCurrentWindow.ns_res || sNewWindow->rows != sCurrentWindow.rows || sNewWindow->cols != sCurrentWindow.cols ) { /* Reset window */ G_set_window( sNewWindow ); } } return CE_None; }
/*! \brief Load raster map as floating point map Calling function must have already allocated space in buff for wind->rows * wind->cols floats. This routine simply loads the map into a 2d array by repetitve calls to get_f_raster_row. \param wind current window \param map_name raster map name \param[out] buff data buffer \param[out] nullmap null map buffer \param[out] has_null indicates if raster map contains null-data \return 1 on success \return 0 on failure */ int Gs_loadmap_as_float(struct Cell_head *wind, const char *map_name, float *buff, struct BM *nullmap, int *has_null) { FILEDESC cellfile; const char *map_set; char *nullflags; int offset, row, col; G_debug(3, "Gs_loadmap_as_float(): name=%s", map_name); map_set = G_find_cell2(map_name, ""); if (!map_set) { G_warning(_("Raster map <%s> not found"), map_name); return 0; } *has_null = 0; nullflags = G_allocate_null_buf(); /* G_fatal_error */ if (!nullflags) { G_fatal_error(_("Unable to allocate memory for a null buffer")); } if ((cellfile = G_open_cell_old(map_name, map_set)) == -1) { G_fatal_error(_("Unable to open raster map <%s>"), map_name); } G_message(_("Loading raster map <%s>..."), G_fully_qualified_name(map_name, map_set)); for (row = 0; row < wind->rows; row++) { offset = row * wind->cols; G_get_f_raster_row(cellfile, &(buff[offset]), row); G_get_null_value_row(cellfile, nullflags, row); G_percent(row, wind->rows, 2); for (col = 0; col < wind->cols; col++) { if (nullflags[col] || G_is_f_null_value(buff + offset + col)) { *has_null = 1; BM_set(nullmap, col, row, 1); } /* set nm */ } } G_percent(1, 1, 1); G_debug(4, " has_null=%d", *has_null); G_close_cell(cellfile); G_free(nullflags); return (1); }
/* * do_histogram() - Creates histogram for CELL * * RETURN: 0 on success / 1 on failure */ int do_histogram(char *name, char *mapset) { CELL *cell; struct Cell_head cellhd; struct Cell_stats statf; int nrows, ncols; int row; int fd; if (G_get_cellhd(name, mapset, &cellhd) < 0) return 1; G_set_window(&cellhd); if ((fd = G_open_cell_old(name, mapset)) < 0) return 1; nrows = G_window_rows(); ncols = G_window_cols(); cell = G_allocate_cell_buf(); G_init_cell_stats(&statf); /* Update statistics for each row */ for (row = 0; row < nrows; row++) { G_percent(row, nrows, 2); if (G_get_map_row_nomask(fd, cell, row) < 0) break; G_update_cell_stats(cell, ncols, &statf); } /* Write histogram if it made it through the loop */ if (row == nrows) G_write_histogram_cs(name, &statf); G_free_cell_stats(&statf); G_close_cell(fd); G_free(cell); if (row == nrows) return 0; return 1; }
int get_cats(char *name, char *mapset) { int fd; int row, nrows, ncols; CELL *cell; struct Cell_head cellhd; /* set the window to the cell header */ if (G_get_cellhd(name, mapset, &cellhd) < 0) G_fatal_error(_("Cannot read header of raster map <%s> in <%s>"), name, mapset); G_set_window(&cellhd); /* open the raster map */ fd = G_open_cell_old(name, mapset); if (fd < 0) G_fatal_error(_("Cannot open cell file of raster map <%s> in <%s>"), name, mapset); nrows = G_window_rows(); ncols = G_window_cols(); cell = G_allocate_cell_buf(); G_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); if (G_get_c_raster_row_nomask(fd, cell, row) < 0) exit(EXIT_SUCCESS); G_update_cell_stats(cell, ncols, &statf); } /* done */ if (G_verbose() > G_verbose_std()) G_percent(row, nrows, 2); G_close_cell(fd); G_free(cell); G_rewind_cell_stats(&statf); return 0; }
static int cell_draw( char *name, char *mapset, struct Colors *colors, RASTER_MAP_TYPE data_type, char *format ) { int cellfile; void *xarray; int row; int ncols, nrows; static unsigned char *red, *grn, *blu, *set; int i; void *ptr; int big_endian; long one = 1; FILE *fo; int raster_size; big_endian = !( *(( char * )( &one ) ) ); ncols = G_window_cols(); nrows = G_window_rows(); /* Make sure map is available */ if (( cellfile = G_open_cell_old( name, mapset ) ) == -1 ) G_fatal_error(( "Unable to open raster map <%s>" ), name ); /* Allocate space for cell buffer */ xarray = G_allocate_raster_buf( data_type ); red = G_malloc( ncols ); grn = G_malloc( ncols ); blu = G_malloc( ncols ); set = G_malloc( ncols ); /* some buggy C libraries require BOTH setmode() and fdopen(bin) */ #ifdef WIN32 if ( _setmode( _fileno( stdout ), _O_BINARY ) == -1 ) G_fatal_error( "Cannot set stdout mode" ); #endif // Unfortunately this is not sufficient on Windows to switch stdout to binary mode fo = fdopen( fileno( stdout ), "wb" ); raster_size = G_raster_size( data_type ); //fprintf( fo, "%d %d", data_type, raster_size ); //exit(0); /* loop for array rows */ for ( row = 0; row < nrows; row++ ) { G_get_raster_row( cellfile, xarray, row, data_type ); ptr = xarray; G_lookup_raster_colors( xarray, red, grn, blu, set, ncols, colors, data_type ); for ( i = 0; i < ncols; i++ ) { unsigned char alpha = 255; //G_debug ( 0, "row = %d col = %d", row, i ); if ( G_is_null_value( ptr, data_type ) ) { alpha = 0; } if ( strcmp( format, "color" ) == 0 ) { // We need data suitable for QImage 32-bpp // the data are stored in QImage as QRgb which is unsigned int. // Because it depends on byte order of the platform we have to // consider byte order (well, middle endian ignored) if ( big_endian ) { // I have never tested this fprintf( fo, "%c%c%c%c", alpha, red[i], grn[i], blu[i] ); } else { fprintf( fo, "%c%c%c%c", blu[i], grn[i], red[i], alpha ); } } else { if ( data_type == CELL_TYPE ) { //G_debug ( 0, "valx = %d", *((CELL *) ptr)); } if ( G_is_null_value( ptr, data_type ) ) { if ( data_type == CELL_TYPE ) { int nul = -2147483647; fwrite( &nul , 4, 1, fo ); } else if ( data_type == DCELL_TYPE ) { double nul = 2.2250738585072014e-308; fwrite( &nul , 8, 1, fo ); } else if ( data_type == FCELL_TYPE ) { double nul = 1.17549435e-38F; fwrite( &nul , 4, 1, fo ); } } else { fwrite( ptr, raster_size, 1, fo ); } } ptr = G_incr_void_ptr( ptr, raster_size ); } } G_close_cell( cellfile ); return ( 0 ); }
int main(int argc, char *argv[]) { char *terrainmap, *seedmap, *lakemap, *mapset; int rows, cols, in_terran_fd, out_fd, lake_fd, row, col, pases, pass; int lastcount, curcount, start_col = 0, start_row = 0; double east, north, area = 0, volume = 0; FCELL **in_terran, **out_water, water_level, max_depth = 0, min_depth = 0; FCELL water_window[3][3]; struct Option *tmap_opt, *smap_opt, *wlvl_opt, *lake_opt, *sdxy_opt; struct Flag *negative_flag, *overwrite_flag; struct GModule *module; struct Colors colr; struct Cell_head window; struct History history; G_gisinit(argv[0]); module = G_define_module(); module->keywords = _("raster, hydrology"); module->description = _("Fills lake at given point to given level."); tmap_opt = G_define_option(); tmap_opt->key = "dem"; tmap_opt->key_desc = "name"; tmap_opt->description = _("Name of terrain raster map (DEM)"); tmap_opt->type = TYPE_STRING; tmap_opt->gisprompt = "old,cell,raster"; tmap_opt->required = YES; wlvl_opt = G_define_option(); wlvl_opt->key = "wl"; wlvl_opt->description = _("Water level"); wlvl_opt->type = TYPE_DOUBLE; wlvl_opt->required = YES; lake_opt = G_define_option(); lake_opt->key = "lake"; lake_opt->key_desc = "name"; lake_opt->description = _("Name for output raster map with lake"); lake_opt->type = TYPE_STRING; lake_opt->gisprompt = "new,cell,raster"; lake_opt->required = NO; sdxy_opt = G_define_option(); sdxy_opt->key = "xy"; sdxy_opt->description = _("Seed point coordinates"); sdxy_opt->type = TYPE_DOUBLE; sdxy_opt->key_desc = "east,north"; sdxy_opt->required = NO; sdxy_opt->multiple = NO; smap_opt = G_define_option(); smap_opt->key = "seed"; smap_opt->key_desc = "name"; smap_opt->description = _("Name of raster map with given starting point(s) (at least 1 cell > 0)"); smap_opt->type = TYPE_STRING; smap_opt->gisprompt = "old,cell,raster"; smap_opt->required = NO; negative_flag = G_define_flag(); negative_flag->key = 'n'; negative_flag->description = _("Use negative depth values for lake raster map"); overwrite_flag = G_define_flag(); overwrite_flag->key = 'o'; overwrite_flag->description = _("Overwrite seed map with result (lake) map"); if (G_parser(argc, argv)) /* Returns 0 if successful, non-zero otherwise */ exit(EXIT_FAILURE); if (smap_opt->answer && sdxy_opt->answer) G_fatal_error(_("Both seed map and coordinates cannot be specified")); if (!smap_opt->answer && !sdxy_opt->answer) G_fatal_error(_("Seed map or seed coordinates must be set!")); if (sdxy_opt->answer && !lake_opt->answer) G_fatal_error(_("Seed coordinates and output map lake= must be set!")); if (lake_opt->answer && overwrite_flag->answer) G_fatal_error(_("Both lake and overwrite cannot be specified")); if (!lake_opt->answer && !overwrite_flag->answer) G_fatal_error(_("Output lake map or overwrite flag must be set!")); terrainmap = tmap_opt->answer; seedmap = smap_opt->answer; sscanf(wlvl_opt->answer, "%f", &water_level); lakemap = lake_opt->answer; /* If lakemap is set, write to it, else is set overwrite flag and we should write to seedmap. */ if (lakemap) { lake_fd = G_open_raster_new(lakemap, 1); if (lake_fd < 0) G_fatal_error(_("Unable to create raster map <%s>"), lakemap); } rows = G_window_rows(); cols = G_window_cols(); /* If we use x,y as seed... */ if (sdxy_opt->answer) { G_get_window(&window); east = window.east; north = window.north; G_scan_easting(sdxy_opt->answers[0], &east, G_projection()); G_scan_northing(sdxy_opt->answers[1], &north, G_projection()); start_col = (int)G_easting_to_col(east, &window); start_row = (int)G_northing_to_row(north, &window); if (start_row < 0 || start_row > rows || start_col < 0 || start_col > cols) G_fatal_error(_("Seed point outside the current region")); } /* Open terran map */ mapset = G_find_cell2(terrainmap, ""); if (mapset == NULL) G_fatal_error(_("Raster map <%s> not found"), terrainmap); in_terran_fd = G_open_cell_old(terrainmap, mapset); if (in_terran_fd < 0) G_fatal_error(_("Unable to open raster map <%s>"), G_fully_qualified_name(terrainmap, mapset)); /* Open seed map */ if (smap_opt->answer) { mapset = G_find_cell2(seedmap, ""); if (mapset == NULL) G_fatal_error(_("Raster map <%s> not found"), seedmap); out_fd = G_open_cell_old(seedmap, mapset); if (out_fd < 0) G_fatal_error(_("Unable to open raster map <%s>"), G_fully_qualified_name(seedmap, mapset)); } /* Pointers to rows. Row = ptr to 'col' size array. */ in_terran = (FCELL **) G_malloc(rows * sizeof(FCELL *)); out_water = (FCELL **) G_malloc(rows * sizeof(FCELL *)); if (in_terran == NULL || out_water == NULL) G_fatal_error(_("G_malloc: out of memory")); G_debug(1, "Loading maps..."); /* foo_rows[row] == array with data (2d array). */ for (row = 0; row < rows; row++) { in_terran[row] = (FCELL *) G_malloc(cols * sizeof(FCELL)); out_water[row] = (FCELL *) G_calloc(cols, sizeof(FCELL)); /* In newly created space load data from file. */ if (G_get_f_raster_row(in_terran_fd, in_terran[row], row) != 1) G_fatal_error(_("Unable to read raster map <%s> row %d"), terrainmap, row); if (smap_opt->answer) if (G_get_f_raster_row(out_fd, out_water[row], row) != 1) G_fatal_error(_("Unable to read raster map <%s> row %d"), seedmap, row); G_percent(row + 1, rows, 5); } /* Set seed point */ if (sdxy_opt->answer) /* Check is water level higher than seed point */ if (in_terran[start_row][start_col] >= water_level) G_fatal_error(_("Given water level at seed point is below earth surface. " "Increase water level or move seed point.")); out_water[start_row][start_col] = 1; /* Close seed map for reading. */ if (smap_opt->answer) G_close_cell(out_fd); /* Open output map for writing. */ if (lakemap) { out_fd = lake_fd; } else { out_fd = G_open_raster_new(seedmap, 1); if (out_fd < 0) G_fatal_error(_("Unable to create raster map <%s>"), seedmap); } /* More pases are renudant. Real pases count is controled by altered cell count. */ pases = (int)(rows * cols) / 2; G_debug(1, "Starting lake filling at level of %8.4f in %d passes. Percent done:", water_level, pases); lastcount = 0; for (pass = 0; pass < pases; pass++) { G_debug(3, "Pass: %d", pass); curcount = 0; /* Move from left upper corner to right lower corner. */ for (row = 0; row < rows; row++) { for (col = 0; col < cols; col++) { /* Loading water data into window. */ load_window_values(out_water, water_window, rows, cols, row, col); /* Cheking presence of water. */ if (is_near_water(water_window) == 1) { if (in_terran[row][col] < water_level) { out_water[row][col] = water_level - in_terran[row][col]; curcount++; } else { out_water[row][col] = 0; /* Cell is higher than water level -> NULL. */ } } } } if (curcount == lastcount) break; /* We done. */ lastcount = curcount; curcount = 0; /* Move backwards - from lower right corner to upper left corner. */ for (row = rows - 1; row >= 0; row--) { for (col = cols - 1; col >= 0; col--) { load_window_values(out_water, water_window, rows, cols, row, col); if (is_near_water(water_window) == 1) { if (in_terran[row][col] < water_level) { out_water[row][col] = water_level - in_terran[row][col]; curcount++; } else { out_water[row][col] = 0; } } } } G_percent(pass + 1, pases, 10); if (curcount == lastcount) break; /* We done. */ lastcount = curcount; } /*pases */ G_percent(pases, pases, 10); /* Show 100%. */ save_map(out_water, out_fd, rows, cols, negative_flag->answer, &min_depth, &max_depth, &area, &volume); G_message(_("Lake depth from %f to %f"), min_depth, max_depth); G_message(_("Lake area %f square meters"), area); G_message(_("Lake volume %f cubic meters"), volume); G_warning(_("Volume is correct only if lake depth (terrain raster map) is in meters")); /* Close all files. Lake map gets written only now. */ G_close_cell(in_terran_fd); G_close_cell(out_fd); /* Add blue color gradient from light bank to dark depth */ G_init_colors(&colr); if (negative_flag->answer == 1) { G_add_f_raster_color_rule(&max_depth, 0, 240, 255, &min_depth, 0, 50, 170, &colr); } else { G_add_f_raster_color_rule(&min_depth, 0, 240, 255, &max_depth, 0, 50, 170, &colr); } if (G_write_colors(lakemap, G_mapset(), &colr) != 1) G_fatal_error(_("Unable to read color file of raster map <%s>"), lakemap); G_short_history(lakemap, "raster", &history); G_command_history(&history); G_write_history(lakemap, &history); return EXIT_SUCCESS; }
int describe(char *name, char *mapset, int compact, char *no_data_str, int range, int windowed, int nsteps, int as_int, int skip_nulls) { int fd; struct Cell_stats statf; CELL *buf, *b; int nrows, ncols; int row, col; struct Cell_head window; CELL negmin = 0, negmax = 0, zero = 0, posmin = 0, posmax = 0; CELL null = 0; RASTER_MAP_TYPE map_type; struct Quant q; struct FPRange r; DCELL dmin, dmax; int (*get_row) (); if (windowed) { get_row = G_get_c_raster_row; } else { char msg[100]; if (G_get_cellhd(name, mapset, &window) < 0) { sprintf(msg, "can't get cell header for [%s] in [%s]", name, mapset); G_fatal_error(msg); } G_set_window(&window); get_row = G_get_c_raster_row_nomask; } fd = G_open_cell_old(name, mapset); if (fd < 0) return 0; map_type = G_get_raster_map_type(fd); if (as_int) map_type = CELL_TYPE; /* read as int */ /* allocate the cell buffer */ buf = G_allocate_cell_buf(); if (map_type != CELL_TYPE && range) /* this will make it report fp range */ { range = 0; nsteps = 1; } /* start the cell stats */ if (!range) { G_init_cell_stats(&statf); } else { zero = 0; negmin = 0; negmax = 0; posmin = 0; posmax = 0; null = 0; dmin = 0.0; dmax = 0.0; } /* set up quantization rules */ if (map_type != CELL_TYPE) { G_quant_init(&q); G_read_fp_range(name, mapset, &r); G_get_fp_range_min_max(&r, &dmin, &dmax); G_quant_add_rule(&q, dmin, dmax, 1, nsteps); G_set_quant_rules(fd, &q); } nrows = G_window_rows(); ncols = G_window_cols(); G_verbose_message("Reading [%s in %s] ...", name, mapset); for (row = 0; row < nrows; row++) { G_percent(row, nrows, 2); if ((*get_row) (fd, b = buf, row) < 0) break; if (range) { for (col = ncols; col-- > 0; b++) { if (G_is_c_null_value(b)) null = 1; else if (*b == 0) zero = 1; else if (*b < 0) { if (!negmin) negmin = negmax = *b; else if (*b > negmax) negmax = *b; else if (*b < negmin) negmin = *b; } else { if (!posmin) posmin = posmax = *b; else if (*b > posmax) posmax = *b; else if (*b < posmin) posmin = *b; } } } else G_update_cell_stats(buf, ncols, &statf); } G_percent(nrows, nrows, 2); G_close_cell(fd); G_free(buf); if (range) { if (compact) compact_range_list(negmin, negmax, zero, posmin, posmax, null, no_data_str, skip_nulls); else range_list(negmin, negmax, zero, posmin, posmax, null, no_data_str, skip_nulls); } else { G_rewind_cell_stats(&statf); if (compact) compact_list(&statf, dmin, dmax, no_data_str, skip_nulls, map_type, nsteps); else long_list(&statf, dmin, dmax, no_data_str, skip_nulls, map_type, nsteps); G_free_cell_stats(&statf); } return 1; }
void* raster2array(const char* name, struct Cell_head* header, int* rows, int* cols, RASTER_MAP_TYPE out_type) { // Open the raster map and load the dem // for simplicity sake, the dem will be an array of // doubles, converted from any possible GRASS CELL type. char* mapset = G_find_cell2(name, ""); if (mapset == NULL) G_fatal_error("Raster map <%s> not found", name); // Find out the cell type of the DEM RASTER_MAP_TYPE type = G_raster_map_type(name, mapset); // Get a file descriptor for the DEM raster map int infd; if ((infd = G_open_cell_old(name, mapset)) < 0) G_fatal_error("Unable to open raster map <%s>", name); // Get header info for the DEM raster map struct Cell_head cellhd; if (G_get_cellhd(name, mapset, &cellhd) < 0) G_fatal_error("Unable to open raster map <%s>", name); // Create a GRASS buffer for the DEM raster void* inrast = G_allocate_raster_buf(type); // Get the max rows and max cols from the window information, since the // header gives the values for the full raster const int maxr = G_window_rows(); const int maxc = G_window_cols(); // Read in the raster line by line, copying it into the double array // rast for return. void* rast; switch (out_type) { case CELL_TYPE: rast = (int*) calloc(maxr * maxc, sizeof(int)); break; case FCELL_TYPE: rast = (float*) calloc(maxr * maxc, sizeof(float)); break; case DCELL_TYPE: rast = (double*) calloc(maxr * maxc, sizeof(double)); break; } if (rast == NULL) { G_fatal_error("Unable to allocate memory for raster map <%s>", name); } int row, col; for (row = 0; row < maxr; ++row) { if (G_get_raster_row(infd, inrast, row, type) < 0) G_fatal_error("Unable to read raster map <%s> row %d", name, row); for (col = 0; col < maxc; ++col) { int index = col + row * maxc; if (out_type == CELL_TYPE) { switch (type) { case CELL_TYPE: ((int*) rast)[index] = ((int *) inrast)[col]; break; case FCELL_TYPE: ((int*) rast)[index] = (int) ((float *) inrast)[col]; break; case DCELL_TYPE: ((int*) rast)[index] = (int) ((double *) inrast)[col]; break; default: G_fatal_error("Unknown cell type"); break; } } if (out_type == FCELL_TYPE) { switch (type) { case CELL_TYPE: ((float*) rast)[index] = (float) ((int *) inrast)[col]; break; case FCELL_TYPE: ((float*) rast)[index] = ((float *) inrast)[col]; break; case DCELL_TYPE: ((float*) rast)[index] = (float) ((double *) inrast)[col]; break; default: G_fatal_error("Unknown cell type"); break; } } if (out_type == DCELL_TYPE) { switch (type) { case CELL_TYPE: ((double*) rast)[index] = (double) ((int *) inrast)[col]; break; case FCELL_TYPE: ((double*) rast)[index] = (double) ((float *) inrast)[col]; break; case DCELL_TYPE: ((double*) rast)[index] = ((double *) inrast)[col]; break; default: G_fatal_error("Unknown cell type"); break; } } } } // Return cellhd, maxr, and maxc by pointer if (header != NULL) *header = cellhd; if (rows != NULL) *rows = maxr; if (cols != NULL) *cols = maxc; return rast; }
/* * main function */ int main(int argc, char *argv[]) { /* struct Cell_head window; database window */ struct Cell_head cellhd; /* it stores region information, and header information of rasters */ char *name, *name2; /* input raster name */ char *result; /* output raster name */ char *mapset; /* mapset name */ void *inrast; /* input buffer */ unsigned char *outrast; /* output buffer */ int nrows, ncols; int row, col; int infd, outfd; /* file descriptor */ int verbose; struct History history; /* holds meta-data (title, comments,..) */ struct GModule *module; /* GRASS module for parsing arguments */ struct Option *input, *output, *input2; /* options */ FILE *in; /*file for Path loss factors*/ struct Flag *flag1; /* flags */ char buffer_out[1000]; strcpy(buffer_out,getenv("GISBASE")); strcat(buffer_out,"/etc/radio_coverage/lossfactors_new.txt"); /*G_message(_("1!! Pot1: %s, Pot2: %s"), buffer_path, buffer_path1); buffer_out=strcat(buffer_path,buffer_path1); G_message(_("Pot1: %s, Pot2: %s"), buffer_path, buffer_path1);*/ /* initialize GIS environment */ G_gisinit(argv[0]); /* reads grass env, stores program name to G_program_name() */ /* initialize module */ module = G_define_module(); module->keywords = _("raster, clutter"); module->description = _("Clutter convert module"); /* Define the different options as defined in gis.h */ input = G_define_standard_option(G_OPT_R_INPUT); input2 = G_define_standard_option(G_OPT_F_INPUT); input2->key = "Path_loss_values"; input2->type = TYPE_STRING; input2->required = YES; input2->answer = buffer_out;//getenv("GISBASE"); //strcat(buffer_path1,(char *)getenv("GISBASE"));//,"/etc/radio_coverage"); input2->gisprompt = "old_file,file,input"; input2->description = _("Path loss factors for land usage"); /* Define the different flags */ flag1 = G_define_flag(); flag1->key = 'o'; flag1->description = _("Old_Cipher"); output = G_define_standard_option(G_OPT_R_OUTPUT); /* options and flags parser */ if (G_parser(argc, argv)) { exit(EXIT_FAILURE); } /*G_message(_("1!! Pot1: %s, Pot2: %s"), buffer_path, buffer_path1); strcat(buffer_path,buffer_path1); G_message(_("Pot1: %s, Pot2: %s"), buffer_path, buffer_path1); input2->answer = buffer_path;//getenv("GISBASE"); //strcat(buffer_path1,(char *)getenv("GISBASE"));//,"/etc/radio_coverage");*/ /* stores options and flags to variables */ name = input->answer; name2 = input2->answer; result = output->answer; verbose = (flag1->answer); G_message(_("Verbose: %d"),verbose); /* returns NULL if the map was not found in any mapset, * mapset name otherwise */ //G_message(_("3_START")); mapset = G_find_cell2(name, ""); if (mapset == NULL) G_fatal_error(_("Raster map <%s> not found"), name); if (G_legal_filename(result) < 0) G_fatal_error(_("<%s> is an illegal file name"), result); /* G_open_cell_old - returns file destriptor (>0) */ if ((infd = G_open_cell_old(name, mapset)) < 0) G_fatal_error(_("Unable to open raster map <%s>"), name); /* controlling, if we can open input raster */ if (G_get_cellhd(name, mapset, &cellhd) < 0) G_fatal_error(_("Unable to read file header of <%s>"), name); G_debug(3, "number of rows %d", cellhd.rows); G_set_window(&cellhd); G_get_set_window(&cellhd); /* Allocate input buffer */ inrast = G_allocate_raster_buf(FCELL_TYPE); /* Allocate output buffer, use input map data_type */ nrows = G_window_rows(); ncols = G_window_cols(); outrast = G_allocate_raster_buf(FCELL_TYPE); G_message(_("nrows %d and ncols %d"),nrows,ncols); /* controlling, if we can write the raster */ if ((outfd = G_open_raster_new(result, FCELL_TYPE)) < 0) G_fatal_error(_("Unable to create raster map <%s>"), result); /* do Clutter Convert */ /* open file for model tuning parameters*/ char fileName[150]; strcpy (fileName, name2); //G_message(_("Path: %s"),name2); if( (in = fopen(fileName,"r")) == NULL ) G_fatal_error(_("Unable to open file <%s>"), fileName); char buffer[256]; double terr_path_loss[100]; int counter=0; fgets (buffer, 250, in); while(fgets(buffer,250,in)!=NULL){ sscanf(buffer,"%lf %lf", &terr_path_loss[counter]); counter++; } int cipher_cont=0; /* old or new clutter */ if (verbose == 1) { cipher_cont=1; G_message(_("Parameter UR: %f, GP: %f, RP: %f, GI: %f, GL: %f, GM: %f, GR: %f, VO: %f, KM: %f, OD: %f"), terr_path_loss[0], terr_path_loss[1], terr_path_loss[2], terr_path_loss[3], terr_path_loss[4], terr_path_loss[5], terr_path_loss[6], terr_path_loss[7], terr_path_loss[8], terr_path_loss[9]); } else if (verbose == 0) { cipher_cont=11; G_message(_("Parameter UR1: %f, UR2: %f, UR3: %f, UR4: %f, UR5: %f, GI: %f, GL: %f, GM: %f, GR: %f, VO: %f, KM: %f, OD: %f"), terr_path_loss[0], terr_path_loss[1], terr_path_loss[2], terr_path_loss[3], terr_path_loss[4], terr_path_loss[5], terr_path_loss[6], terr_path_loss[7], terr_path_loss[8], terr_path_loss[9], terr_path_loss[10], terr_path_loss[11]); } G_message(_("Counter: %d"),counter); G_message(_("cipher_cont: %d"),cipher_cont); G_message(_("START")); /* for each row */ for (row = 0; row < nrows; row++) { FCELL f_in, f_out; /* read input map */ if (G_get_raster_row(infd, inrast, row, FCELL_TYPE) < 0) G_fatal_error(_("Unable to read raster map <%s> row %d"), name, row); /* process the data */ for (col = 0; col < ncols; col++) { f_in = ((FCELL *) inrast)[col]; //G_message(_("Input data: %d"),(int)f_in); f_out = terr_path_loss[(int)f_in-cipher_cont]; //G_message(_("Output data: %f"),(double)f_out); ((FCELL *) outrast)[col] = f_out; } /* write raster row to output raster map */ if (G_put_raster_row(outfd, outrast, FCELL_TYPE) < 0) G_fatal_error(_("Failed writing raster map <%s>"), result); } //G_message(_("END_clutconvert_test")); G_message(_("END")); /* memory cleanup */ G_free(inrast); G_free(outrast); /* closing raster maps */ G_close_cell(infd); G_close_cell(outfd); /* add command line incantation to history file */ G_short_history(result, "raster", &history); G_command_history(&history); G_write_history(result, &history); exit(EXIT_SUCCESS); }
void do_calculations_rast (Shypothesis **samples, char **groups, int norm, char* basename, char **outvals, char *hypspec, int quiet_flag, char *logfile, xmlDocPtr doc, Sfp_struct* file_pointers) { long y,x; int i, j, k, l, m; long ymax,xmax; double woc; struct Categories cats, icats; DCELL cmin, cmax; Sresult_struct *result_row; /* one result_struct for each DST value */ BOOL **garbage; int no_hyps; char* val_names[NUMVALS]={"bel","pl","doubt","common","bint","woc","maxbpa","minbpa", "maxsrc","minsrc"}; int error; char **outhyps; int no_sets; /* for keeping min and max statistics */ Uint nsets; double *min_backup, *max_backup; int *minev_backup, *maxev_backup; woc = 0; /* check for output options */ if ( G_legal_filename(basename) != 1 ) { G_fatal_error ("Please provide a legal filename as basename for output maps(s).\n"); } if ( hypspec != NULL ) { /* user specified hyps, let's see if they're valid */ /* create an outhyps array that has as each of its elements the name of one of the hypotheses specified on the command line */ outhyps = parse_hyps (hypspec, &no_hyps); check_hyps ( outhyps, no_hyps, doc ); } else { /* just process all hypotheses */ outhyps = get_hyp_names_XML ( &no_hyps, doc ); } if ( logfile != NULL ) { fprintf (lp,"Writing output RASTER maps for: \n"); } /* create raster rows to store results */ result_row = G_malloc ( NUMVALS * sizeof (Sresult_struct) ); for (i=0; i<NUMVALS; i++) { result_row[i].use = NO; strcpy (result_row[i].valname,val_names[i]); /* individual raster rows will be alloc'd later */ result_row[i].row = (DCELL **) G_malloc ( no_hyps * sizeof (DCELL*) ); result_row[i].crow = (CELL **) G_malloc ( no_hyps * sizeof (CELL*) ); result_row[i].filename = NULL; } j = 0; while ( outvals[j] != NULL ) { if ( !strcmp (outvals[j],"bel") ) { if ( logfile != NULL ) fprintf (lp,"\t'bel' (Believe) values\n"); make_result_row ( BEL, basename, outhyps, no_hyps, &result_row[BEL], doc ); } if ( !strcmp (outvals[j],"pl") ) { if ( logfile != NULL ) fprintf (lp,"\t'pl' (Plausibility) values\n"); make_result_row ( PL, basename, outhyps, no_hyps, &result_row[PL], doc ); } if ( !strcmp (outvals[j],"doubt") ) { if ( logfile != NULL ) fprintf (lp,"\t'doubt' (Doubt) values\n"); make_result_row ( DOUBT, basename, outhyps, no_hyps, &result_row[DOUBT], doc ); } if ( !strcmp (outvals[j],"common") ) { if ( logfile != NULL ) fprintf (lp,"\t'common' (Commonality) values\n"); make_result_row ( COMMON, basename, outhyps, no_hyps, &result_row[COMMON], doc ); } if ( !strcmp (outvals[j],"bint") ) { if ( logfile != NULL ) fprintf (lp,"\t'bint' (Believe interval) values\n"); make_result_row ( BINT, basename, outhyps, no_hyps, &result_row[BINT], doc ); } if ( !strcmp (outvals[j],"woc") ) { if ( logfile != NULL ) fprintf (lp,"\t'woc' (Weight of conflict) values\n"); make_result_row ( WOC, basename, outhyps, no_hyps,&result_row[WOC], doc ); } if ( !strcmp (outvals[j],"maxbpa") ) { if ( logfile != NULL ) fprintf (lp,"\t'maxbpa' (Maximum BPA) values\n"); make_result_row ( MAXBPA, basename, outhyps, no_hyps,&result_row[MAXBPA], doc ); } if ( !strcmp (outvals[j],"minbpa") ) { if ( logfile != NULL ) fprintf (lp,"\t'minbpa' (Minimum BPA) values\n"); make_result_row ( MINBPA, basename, outhyps, no_hyps,&result_row[MINBPA], doc ); } if ( !strcmp (outvals[j],"maxsrc") ) { if ( logfile != NULL ) fprintf (lp,"\t'maxsrc' (source of highest BPA) values\n"); make_result_row ( MAXSRC, basename, outhyps, no_hyps,&result_row[MAXSRC], doc ); } if ( !strcmp (outvals[j],"minsrc") ) { if ( logfile != NULL ) fprintf (lp,"\t'minsrc' (source of lowest BPA) values\n"); make_result_row ( MINSRC, basename, outhyps, no_hyps,&result_row[MINSRC], doc ); } j ++; } /* open output maps to store results */ if ( logfile != NULL ) fprintf (lp,"Opening output maps:\n"); for (i=0; i<NUMVALS;i++) { if (result_row[i].use == YES) { if ( i == WOC ) { if ( logfile != NULL ) fprintf (lp,"\t%s\n",result_row[i].filename[0]); result_row[i].fd[0] = G_open_raster_new (result_row[i].filename[0],DCELL_TYPE); } else { for (j=0; j < no_hyps; j++) { if ( logfile != NULL ) fprintf (lp,"\t%s\n",result_row[i].filename[j]); if ((i == MAXSRC) || (i == MINSRC)) { result_row[i].fd[j] = G_open_raster_new (result_row[i].filename[j],CELL_TYPE); } else { result_row[i].fd[j] = G_open_raster_new (result_row[i].filename[j],DCELL_TYPE); } /* check fd for errors */ if ( result_row[i].fd[j] < 0 ) { G_fatal_error ("Could not create output map for %s\n", result_row[i].filename[j]); } } } } } if ( logfile != NULL ) { fprintf (lp, "Evidence will be combined for these groups:\n"); for ( i=0; i < N; i++) { fprintf (lp,"\t%s\n",groups[i]); } fprintf (lp, "Output will be stored in mapset '%s'.\n", G_mapset()); fprintf (lp,"\nRead output below carefully to detect potential problems:\n"); } /* set start coordinates for reading from raster maps */ ReadX = 0; ReadY = 0; ymax = G_window_rows (); xmax = G_window_cols (); if ( !quiet_flag ) { fprintf (stdout,"Combining RAST evidence: \n"); fflush (stdout); } /* allocate all file pointers */ /* open raster maps for this group */ /* 0 is the NULL hypothesis, so we start at 1 */ no_sets = (Uint) pow((float) 2, (float) NO_SINGLETONS); for (l=0; l<N; l++) { for ( m = 1; m < no_sets; m ++ ) { file_pointers[l].fp[m] = G_open_cell_old ( file_pointers[l].filename[m], G_find_cell ( file_pointers[l].filename[m],"") ); if ( file_pointers[l].fp[m] < 0 ) { G_fatal_error ("Could not open raster map '%s' for reading.\n", file_pointers[l].filename[m] ); } } } for (y=0; y<ymax; y++) { for (x=0; x<xmax; x++) { garbage = garbage_init (); NULL_SIGNAL = 0; for (i=0; i<N; i++) { samples[i] = get_rast_samples_XML (groups[i],i, norm, &nsets, garbage, doc, file_pointers ); } /* get min and max values */ for (i=0; i<N; i++) { if (NULL_SIGNAL == 0) { for (k=0; k < nsets; k++) { samples[i][k].minbpn = samples[i][k].bpa; samples[i][k].maxbpn = samples[i][k].bpa; samples[i][k].minbpnev = i + 1; samples[i][k].maxbpnev = i + 1; } } } for (i=0; i<N; i++) { if (NULL_SIGNAL == 0) { for (j=0; j < N; j++) { for (k=0; k < nsets; k++) { if (samples[i][k].bpa < samples[j][k].minbpn) { samples[j][k].minbpn = samples[i][k].bpa; samples[j][k].minbpnev = i + 1; } if (samples[i][k].bpa > samples[j][k].maxbpn) { samples[j][k].maxbpn = samples[i][k].bpa; samples[j][k].maxbpnev = i + 1; } } } } } /* initialise: */ /* set belief and plausibility before first combination of evidence */ for(i=0;i<N;i++) { if ( NULL_SIGNAL == 0 ) { set_beliefs(samples[i]); set_plausibilities(samples[i]); } } /* combine evidence and set bel and pl again */ /* AFTER COMBINE_BPN(), VALUES IN SAMPLES[0] WILL ALL BE ALTERED */ /* so we must save min and max values for later use */ min_backup = G_malloc ((unsigned)(nsets * sizeof(double))); max_backup = G_malloc ((unsigned)(nsets * sizeof(double))); minev_backup = G_malloc ((unsigned)(nsets * sizeof(int))); maxev_backup = G_malloc ((unsigned)(nsets * sizeof(int))); for (k=0; k < nsets; k++) { min_backup[k] = samples[0][k].minbpn; max_backup[k] = samples[0][k].maxbpn; minev_backup[k] = samples[0][k].minbpnev; maxev_backup[k] = samples[0][k].maxbpnev; } /* now, do the combination! */ for(i=0;i<N-1;i++) { if ( NULL_SIGNAL == 0 ) { woc = combine_bpn(samples[0], samples[i+1], garbage, RAST_MODE ); set_beliefs(samples[0]); set_plausibilities(samples[0]); } } /* restore min and max values */ for (k=0; k < nsets; k++) { samples[0][k].minbpn = min_backup[k]; samples[0][k].maxbpn = max_backup[k]; samples[0][k].minbpnev = minev_backup[k]; samples[0][k].maxbpnev = maxev_backup[k]; } G_free (min_backup); G_free (max_backup); G_free (minev_backup); G_free (maxev_backup); /* all other metrics can be derived from bel and pl, no need */ /* to combine evidence again! */ if ( NULL_SIGNAL == 0 ) { set_commonalities(samples[0]); set_doubts(samples[0]); set_bint(samples[0]); } if ( NULL_SIGNAL == 1 ) { for (i=0; i<NUMVALS;i++) { if (result_row[i].use == YES) { if ( i == WOC) { write_row_null (result_row[i].row[0], ReadX); } else { if ((i == MAXSRC)||(i == MINSRC)) { for (j=0; j < no_hyps; j++) { write_crow_null (result_row[i].crow[j], ReadX); } } else { for (j=0; j < no_hyps; j++) { write_row_null (result_row[i].row[j], ReadX); } } } } } } else { for (i=0; i<NUMVALS;i++) { if (result_row[i].use == YES) { if ( i == WOC ) { write_row_val (result_row[i].row[0], ReadX, samples[0], result_row[i].hyp_idx[0], i, woc); } else { if (( i == MAXSRC ) || ( i == MINSRC )) { for (j=0; j < no_hyps; j++) { write_crow_val (result_row[i].crow[j], ReadX, samples[0], result_row[i].hyp_idx[j], i); } } else { for (j=0; j < no_hyps; j++) { write_row_val (result_row[i].row[j], ReadX, samples[0], result_row[i].hyp_idx[j], i, woc); } } } } } } ReadX ++; garbage_free ( garbage ); for (i=0; i<N; i++) { free_sample (samples[i]); } } ReadY ++; /* go to next row */ ReadX = 0; /* save this row to the result file */ for (i=0; i<NUMVALS;i++) { if (result_row[i].use == YES) { if ( i == WOC ) { write_row_file ( result_row[i].row[0],result_row[i].fd[0]); } else { if ( ( i == MAXSRC ) || ( i == MINSRC ) ) { for (j=0; j<no_hyps; j++) { write_crow_file ( result_row[i].crow[j],result_row[i].fd[j]); } } else { for (j=0; j<no_hyps; j++) { write_row_file ( result_row[i].row[j],result_row[i].fd[j]); } } } } } if ( !quiet_flag ) { G_percent (ReadY,ymax,1); fflush (stdout); } } if ( !quiet_flag ) { fprintf (stdout,"\n"); fflush (stdout); } for (i=0; i<NUMVALS;i++) { if (result_row[i].use == YES) { if ( i == WOC ) { G_close_cell (result_row[i].fd[0]); } else { for (j=0; j<no_hyps; j++) { G_close_cell (result_row[i].fd[j]); } } } } /* close raster maps */ /* 0 is the NULL hypothesis, so we start at 1 */ for (l=0; l<N; l++) { for ( m = 1; m < no_sets; m ++ ) { G_close_cell (file_pointers[l].fp[m]); } } /* create a categories structure for output maps */ /* DCELL maps */ G_init_cats (3, "Value ranges", &cats); cmin = 0; cmax = 0.333333; G_set_d_raster_cat (&cmin, &cmax, "low", &cats); cmin = 0.333334; cmax = 0.666666; G_set_d_raster_cat (&cmin, &cmax, "medium", &cats); cmin = 0.666667; cmax = 1; G_set_d_raster_cat (&cmin, &cmax, "high", &cats); /* CELL maps */ G_init_cats (N+1, "Source of evidence", &icats); G_set_cat (0,"no data",&icats); for (i=1; i<=N; i++) { G_set_cat (i,groups[i-1],&icats); } /* write all color tables, categories information and history metadata */ for (i=0; i<NUMVALS;i++) { if (result_row[i].use == YES) { if ( i == WOC ) { error = G_write_colors (result_row[i].filename[0], G_mapset(), result_row[i].colors[0]); if (error == -1) { G_warning ("Could not create color table for map '%s'.\n",result_row[i].filename[j]); } } else { if (( i == MAXSRC ) || ( i == MINSRC )) { for (j=0; j<no_hyps; j++) { G_write_cats (result_row[i].filename[j], &icats); } } else { for (j=0; j<no_hyps; j++) { error = G_write_colors (result_row[i].filename[j], G_mapset(), result_row[i].colors[j]); if (error == -1) { G_warning ("Could not create color table for map '%s'.\n",result_row[i].filename[j]); } G_write_raster_cats (result_row[i].filename[j], &cats); } } } } } G_free (samples); for ( i=0; i < no_hyps; i ++ ) { G_free ( outhyps[i]); } G_free (outhyps); }
/*! \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; if ((mapset = G_find_cell2(filename, "")) == NULL) { G_warning(_("Raster map <%s> not found"), filename); return 0; } if (-1 != G_read_cats(filename, mapset, &cats)) { fd = G_open_cell_old(filename, mapset); map_type = G_get_raster_map_type(fd); if (map_type == CELL_TYPE) { buf = G_allocate_c_raster_buf(); if (G_get_c_raster_row(fd, buf, drow) < 0) { sprintf(catstr, "error"); } else if (G_is_c_null_value(&buf[dcol])) { sprintf(catstr, "(NULL) %s", G_get_c_raster_cat(&buf[dcol], &cats)); } else { sprintf(catstr, "(%d) %s", buf[dcol], G_get_c_raster_cat(&buf[dcol], &cats)); } G_free(buf); } else { /* fp map */ dbuf = G_allocate_d_raster_buf(); if (G_get_d_raster_row(fd, dbuf, drow) < 0) { sprintf(catstr, "error"); } else if (G_is_d_null_value(&dbuf[dcol])) { sprintf(catstr, "(NULL) %s", G_get_d_raster_cat(&dbuf[dcol], &cats)); } else { sprintf(catstr, "(%g) %s", dbuf[dcol], G_get_d_raster_cat(&dbuf[dcol], &cats)); } G_free(dbuf); } } else { strcpy(catstr, "no category label"); } /* TODO: may want to keep these around for multiple queries */ G_free_cats(&cats); G_close_cell(fd); return (1); }
int main(int argc, char *argv[]) { struct Cell_head cellhd; struct Range range; char *name; /* input raster name */ char *result; /* output raster name */ char *mapset; /* mapset name */ DCELL *inrast; /* input buffer */ DCELL *outrast; /* output buffer */ int row,col; int infd, outfd; /* file descriptor */ int verbose; double *weights; /* array of weights */ DCELL **D_rows; DCELL *tmp; int nrows; int ncols; double min, max; /* raster map range */ RASTER_MAP_TYPE data_type; /* type of the map */ void *values; /* neighborhood values */ int n,i; /* number of neighborhood cells */ int size; /* matrix size */ double ssigma; /* sigma of the spatial part */ double csigma; /* sigma of the color part */ char title[1024]; /* map title */ struct GModule *module; /* GRASS module for parsing arguments */ struct { struct Option *input, *output; struct Option *sigma_s, *sigma_c, *size; struct Option *title; } parm; struct { struct Flag *quiet; struct Flag *print_sigmas; } flag; /* initialize GIS environment */ G_gisinit(argv[0]); /* reads grass env, stores program name to G_program_name */ /* initialize module */ module = G_define_module(); module->description = ("Gaussian filter for raster maps."); /* Define the different options */ parm.input = G_define_option() ; parm.input->key = "input"; parm.input->type = TYPE_STRING; parm.input->required = YES; parm.input->description= ("Name of an input layer" ); parm.output = G_define_option() ; parm.output->key = "output"; parm.output->type = TYPE_STRING; parm.output->required = YES; parm.output->description= ("Name of an output layer"); parm.sigma_s = G_define_option() ; parm.sigma_s->key = "ssigma"; parm.sigma_s->type = TYPE_DOUBLE; parm.sigma_s->required = NO; parm.sigma_s->description= ("Sigma for space part of the filter\n\t(default: 0.465*((size-1)/2)"); parm.sigma_c = G_define_option() ; parm.sigma_c->key = "csigma"; parm.sigma_c->type = TYPE_DOUBLE; parm.sigma_c->required = NO; parm.sigma_c->description= ("Sigma for color part of the filter\n(default: 0.465*((color_range)/2)"); parm.size = G_define_option() ; parm.size->key = "size"; parm.size->type = TYPE_INTEGER; parm.size->required = YES; parm.size->description= ("Size of the matrix (odd number)"); flag.print_sigmas = G_define_flag() ; flag.print_sigmas->key = 's' ; flag.print_sigmas->description = "Print calculated values for sigmas" ; flag.quiet = G_define_flag() ; flag.quiet->key = 'q' ; flag.quiet->description = "Quiet" ; /* options and flags pareser */ if (G_parser(argc, argv)) exit (-1); /* stores options and flags to variables */ name = parm.input->answer; result = parm.output->answer; verbose = (! flag.quiet->answer); sscanf(parm.size->answer, "%d", &size); if (!parm.sigma_s->answer) ssigma = 0.465*((size-1)/2); else sscanf(parm.sigma_s->answer, "%lf", &ssigma); /* controlling the input values */ if (size%2 == 0) G_fatal_error("Size <%d> is not odd number", size); /* returs NULL if the map was not found in any mapset, * mapset name otherwise*/ mapset = G_find_cell2 (name, ""); if (mapset == NULL) G_fatal_error ("cell file [%s] not found", name); /* color sigma next */ if (!parm.sigma_c->answer) { if (G_read_range(name, mapset, &range) < 0) G_fatal_error("Could not read the raster map range"); /* for raster maps with range from 0-255 the result * should be around 60 */ min = (double)range.min; max = (double)range.max; csigma = 0.456*(max - min)/2; } else sscanf(parm.sigma_c->answer, "%lf", &csigma); /* print if appropriate */ if (flag.print_sigmas->answer) printf("Space sigma: %f\nColor sigma: %f\n", ssigma, csigma); if (G_legal_filename (result) < 0) G_fatal_error ("[%s] is an illegal name", result); /* count weights */ weights = (double *)malloc(size * size * sizeof(double)); /* stores values of gauss. bell into 'weigts'*/ count_weights(weights, size, ssigma); /* determine the inputmap type (CELL/FCELL/DCELL) */ data_type = G_raster_map_type(name, mapset); /* G_open_cell_old - returns file destriptor (>0) */ if ( (infd = G_open_cell_old (name, mapset)) < 0) G_fatal_error ("Cannot open cell file [%s]", name); /* controlling, if we can open input raster */ if (G_get_cellhd (name, mapset, &cellhd) < 0) G_fatal_error ("Cannot read file header of [%s]", name); /* Allocate input buffer */ inrast = G_allocate_raster_buf(data_type); /* Allocate output buffer, use input map data_type */ nrows = G_window_rows(); ncols = G_window_cols(); outrast = G_allocate_d_raster_buf(); /* Allocate values buffers */ values = (DCELL *) malloc(size * size * sizeof(DCELL)); /* allocating memory for rows */ D_rows = (DCELL **)malloc(size * sizeof(DCELL)); for (i = 0; i < size; i++) { D_rows[i] = G_allocate_raster_buf(DCELL_TYPE); } if (values == NULL) G_fatal_error("Cannot allocate memory"); /* controlling, if we can write the raster */ if ( (outfd = G_open_raster_new (result, data_type)) < 0) G_fatal_error ("Could not open <%s>",result); /* write first rows as NULL values */ for (row = 0; row < size/2; row++) { G_set_d_null_value(outrast, ncols); if (G_put_d_raster_row (outfd, outrast) < 0) G_fatal_error ("Cannot write to <%s>",result); } /* allocate first size/2 rows */ for (row = 0; row < size; row++) if (G_get_d_raster_row(infd, D_rows[row], row) < 0) G_fatal_error ("Could not open <%s>",result); /****************************************************************/ /* for each row inside the region */ for ( row = size/2; row < nrows - size/2; row++) { if (verbose) G_percent (row, nrows, 2); /* allocate new last row */ G_get_d_raster_row(infd, D_rows[size-1], row+(size/2)); /*process the data */ for (col=0; col < ncols; col++){ /* skip the outside columns */ if ( (col - size/2) < 0 || ncols <= (col + size/2)) { G_set_d_null_value(outrast, 1); } /* work only with columns, which are inside */ else { /* store values of the matrix into arry 'values', 'n' is * number of elements of the matrix */ n = D_gather(infd, values, D_rows, col, row,size); ((DCELL *)outrast)[col] = D_bilateral(values, ssigma, csigma, size, weights); } } /* for each column */ /* write raster row to output raster file */ G_put_d_raster_row (outfd, outrast); /* switch rows */ tmp = D_rows[0]; for (i = 0; i < size; i++){ D_rows[i] = D_rows[i + 1]; } D_rows[size-1] = tmp; } /* for each row */ /* write last rows as NULL values */ for (i = 0; i < size/2; i++) { G_set_d_null_value(outrast, ncols); G_put_d_raster_row (outfd, outrast); } /* memory cleaning */ G_free(outrast); G_free(inrast); G_free(values); for (i = 0; i < size; i++) { G_free(D_rows[i]); } free((void *) D_rows); /* closing rastr files */ G_close_cell (infd); G_close_cell (outfd); /* set the map title */ sprintf(title, "Bilateral filter of %s with %dx%d matrix: ssigma %.3f, csigma %.3f", name, size, size, ssigma, csigma ); G_put_cell_title (result, title ); return 0; }
void cell_clip(DCELL ** buf, DCELL ** null_buf, int row0, int col0, int nrows, int ncols, int index, float radius) { CELL *tmp, *tmp1; FCELL *ftmp; DCELL *dtmp; char *tmpname, *nulltmp; int fr; register int i, j; double center_row = 0.0, center_col = 0.0; double dist; RASTER_MAP_TYPE data_type; /* Variables: IN: buf = pointer to array containing only the pixels inside the area that was specified to be clipped, so a smaller array than the original raster map null_buf = pointer to array containing the corresponding null values row0 = starting row for the area to be clipped out of the raster map col0 = starting col for the area to be clipped out of the raster map nrows = total number of rows in the area to be clipped ncols = total number of cols in the area to be clipped index = number of the region to be clipped, if there's a region map INTERNAL: tmp = pointer to a temporary array to store a row of the raster map tmp1 = pointer to a temporary array to store a row of the region map fr = return value from attempting to open the region map i, j = indices to rows and cols of the arrays */ data_type = G_raster_map_type(choice->fn, G_mapset()); /* if sampling by region was chosen, check for the region map and make sure it is an integer (CELL_TYPE) map */ if (choice->wrum == 'r') { if (0 > (fr = G_open_cell_old(choice->reg, G_mapset()))) { fprintf(stderr, "\n"); fprintf(stderr, " *******************************************************\n"); fprintf(stderr, " You specified sam=r to request sampling by region, \n"); fprintf(stderr, " but the region map specified with the 'reg=' parameter\n"); fprintf(stderr, " cannot be found in the current mapset. \n"); fprintf(stderr, " *******************************************************\n"); exit(1); } if (G_raster_map_type(choice->reg, G_mapset()) > 0) { fprintf(stderr, "\n"); fprintf(stderr, " *******************************************************\n"); fprintf(stderr, " You specified sam=r to request sampling by region, \n"); fprintf(stderr, " but the region map specified with the 'reg=' parameter\n"); fprintf(stderr, " must be an integer map, and it is floating point or \n"); fprintf(stderr, " double instead. \n"); fprintf(stderr, " *******************************************************\n"); exit(1); } tmp1 = G_allocate_raster_buf(CELL_TYPE); G_zero_raster_buf(tmp1, CELL_TYPE); fprintf(stderr, "Analyzing region number %d...\n", index); } /* allocate memory to store a row of the raster map, depending on the type of input raster map; keep track of the name of the buffer for each raster type */ switch (data_type) { case CELL_TYPE: tmp = G_allocate_raster_buf(CELL_TYPE); tmpname = "tmp"; break; case FCELL_TYPE: ftmp = G_allocate_raster_buf(FCELL_TYPE); tmpname = "ftmp"; break; case DCELL_TYPE: dtmp = G_allocate_raster_buf(DCELL_TYPE); tmpname = "dtmp"; break; } /* allocate memory to store a row of the null values corresponding to the raster map */ nulltmp = G_allocate_null_buf(); /* if circles are used for sampling, then calculate the center of the area to be clipped, in pixels */ if ((int)radius) { center_row = ((double)row0 + ((double)nrows - 1) / 2); center_col = ((double)col0 + ((double)ncols - 1) / 2); } /* for each row of the area to be clipped */ for (i = row0; i < row0 + nrows; i++) { /* if region, read in the corresponding map row in the region file */ if (choice->wrum == 'r') G_get_raster_row_nomask(fr, tmp1, i, CELL_TYPE); /* initialize each element of the row buffer to 0; this row buffer will hold one row of the clipped raster map. Then read row i of the map and the corresponding null values into tmp and nulltmp buffers */ switch (data_type) { case CELL_TYPE: G_zero_raster_buf(tmp, data_type); G_get_raster_row(finput, tmp, i, CELL_TYPE); break; case FCELL_TYPE: G_zero_raster_buf(ftmp, data_type); G_get_raster_row(finput, ftmp, i, FCELL_TYPE); break; case DCELL_TYPE: G_zero_raster_buf(dtmp, data_type); G_get_raster_row(finput, dtmp, i, DCELL_TYPE); break; } G_get_null_value_row(finput, nulltmp, i); /* for all the columns one by one */ for (j = col0; j < col0 + ncols; j++) { /* if circles are used for sampling */ if ((int)radius) { dist = sqrt(((double)i - center_row) * ((double)i - center_row) + ((double)j - center_col) * ((double)j - center_col)); /* copy the contents of tmp into the appropriate cell in buf */ if (dist < radius) { switch (data_type) { case CELL_TYPE: *(*(buf + i + 1 - row0) + j + 1 - col0) = *(tmp + j); break; case FCELL_TYPE: *(*(buf + i + 1 - row0) + j + 1 - col0) = *(ftmp + j); break; case DCELL_TYPE: *(*(buf + i + 1 - row0) + j + 1 - col0) = *(dtmp + j); break; } *(*(null_buf + i + 1 - row0) + j + 1 - col0) = *(nulltmp + j); } } /* if circles are not used and if the choice is not "by region" or if this column is in region "index" */ else if (choice->wrum != 'r' || *(tmp1 + j) == index) { /* copy the contents of the correct tmp into the appropriate cell in the buf and the corresponding null values into the appropriate cell in null_buf */ switch (data_type) { case CELL_TYPE: *(*(buf + i + 1 - row0) + j + 1 - col0) = *(tmp + j); break; case FCELL_TYPE: *(*(buf + i + 1 - row0) + j + 1 - col0) = *(ftmp + j); break; case DCELL_TYPE: *(*(buf + i + 1 - row0) + j + 1 - col0) = *(dtmp + j); break; } *(*(null_buf + i + 1 - row0) + j + 1 - col0) = *(nulltmp + j); } } } switch (data_type) { case CELL_TYPE: G_free(tmp); break; case FCELL_TYPE: G_free(ftmp); break; case DCELL_TYPE: G_free(dtmp); break; } if (choice->wrum == 'r') { G_free(tmp1); G_close_cell(fr); } G_free(nulltmp); return; }
G_free_cats(&cats); } if (map_type != CELL_TYPE && quant_ok) G_write_quant(name, mapset, &quant); return 0; } int doit(char *name, char *mapset, int change_null, RASTER_MAP_TYPE map_type) { int new, old, row; void *rast; G_set_window(&cellhd); old = G_open_cell_old(name, mapset); if (old < 0) G_fatal_error(_("Unable to open raster map <%s>"), name); new = G_open_raster_new(name, map_type); if (new < 0) G_fatal_error(_("Unable to create raster map <%s>"), name); rast = G_allocate_raster_buf(map_type); G_verbose_message(_("Writing new data for raster map <%s>..."), name); /* the null file is written automatically */ for (row = 0; row < cellhd.rows; row++) { G_percent(row, cellhd.rows, 1);
/*! \brief Load raster map as integer map Calling function must have already allocated space in buff for wind->rows * wind->cols shorts. This routine simply loads the map into a 2d array by repetitve calls to get_map_row. \param wind current window \param map_name raster map name \param[out] buff data buffer \param[out] nullmap null map buffer \param[out] has_null indicates if raster map contains null-data \return 1 on success \return -1 on failure, \return -2 if read ok, but 1 or more values were too large (small) to fit into a short (in which case the max (min) short is used) */ int Gs_loadmap_as_short(struct Cell_head *wind, const char *map_name, short *buff, struct BM *nullmap, int *has_null) { FILEDESC cellfile; const char *map_set; char *nullflags; int *ti, *tmp_buf; int offset, row, col, val, max_short, overflow, shortsize, bitplace; short *ts; G_debug(3, "Gs_loadmap_as_short"); overflow = 0; shortsize = 8 * sizeof(short); /* 1 bit for sign */ /* same as 2 << (shortsize-1) */ for (max_short = bitplace = 1; bitplace < shortsize; ++bitplace) { max_short *= 2; } max_short -= 1; map_set = G_find_cell2(map_name, ""); if (!map_set) { G_warning(_("Raster map <%s> not found"), map_name); return -1; } *has_null = 0; nullflags = G_allocate_null_buf(); if (!nullflags) { G_fatal_error(_("Unable to allocate memory for a null buffer")); } if ((cellfile = G_open_cell_old(map_name, map_set)) == -1) { G_fatal_error(_("Unable to open raster map <%s>"), map_name); } tmp_buf = (int *)G_malloc(wind->cols * sizeof(int)); /* G_fatal_error */ if (!tmp_buf) { return -1; } G_message(_("Loading raster map <%s>..."), G_fully_qualified_name(map_name, map_set)); for (row = 0; row < wind->rows; row++) { offset = row * wind->cols; G_get_c_raster_row(cellfile, tmp_buf, row); G_get_null_value_row(cellfile, nullflags, row); G_percent(row, wind->rows, 2); ts = &(buff[offset]); ti = tmp_buf; for (col = 0; col < wind->cols; col++) { if (nullflags[col]) { *has_null = 1; BM_set(nullmap, col, row, 1); } else { val = *ti; if (abs(val) > max_short) { overflow = 1; /* assign floor/ceiling value? */ *ts = (short)(max_short * val / abs(val)); } else { *ts = (short)val; } } ti++; ts++; } } G_percent(1, 1, 1); G_close_cell(cellfile); G_free(tmp_buf); G_free(nullflags); return (overflow ? -2 : 1); }
int main(int argc, char *argv[]) { RASTER_MAP_TYPE out_type, map_type; char *name; char *mapset; char *null_str; char surfer_null_str[13] = { "1.70141e+038" }; int fd; int nrows, ncols, dp, width; int rc; FILE *fp; struct GModule *module; struct { struct Option *map; struct Option *output; struct Option *dp; struct Option *width; struct Option *null; } parm; struct { struct Flag *noheader; struct Flag *surfer; struct Flag *modflow; struct Flag *int_out; } flag; G_gisinit(argv[0]); module = G_define_module(); module->keywords = _("raster, export"); module->description = _("Converts a raster map layer into an ASCII text file."); /* Define the different options */ parm.map = G_define_option(); parm.map->key = "input"; parm.map->type = TYPE_STRING; parm.map->required = YES; parm.map->gisprompt = "old,cell,raster"; parm.map->description = _("Name of an existing raster map"); parm.output = G_define_option(); parm.output->key = "output"; parm.output->type = TYPE_STRING; parm.output->required = NO; parm.output->gisprompt = "new_file,file,output"; parm.output->description = _("Name for output ASCII grid map (use out=- for stdout)"); parm.dp = G_define_option(); parm.dp->key = "dp"; parm.dp->type = TYPE_INTEGER; parm.dp->required = NO; parm.dp->description = _("Number of significant digits (floating point only)"); parm.width = G_define_option(); parm.width->key = "width"; parm.width->type = TYPE_INTEGER; parm.width->required = NO; parm.width->description = _("Number of values printed before wrapping a line (only SURFER or MODFLOW format)"); parm.null = G_define_option(); parm.null->key = "null"; parm.null->type = TYPE_STRING; parm.null->required = NO; parm.null->answer = "*"; parm.null->description = _("String to represent null cell (GRASS grid only)"); flag.noheader = G_define_flag(); flag.noheader->key = 'h'; flag.noheader->description = _("Suppress printing of header information"); flag.surfer = G_define_flag(); flag.surfer->key = 's'; flag.surfer->description = _("Write SURFER (Golden Software) ASCII grid"); flag.modflow = G_define_flag(); flag.modflow->key = 'm'; flag.modflow->description = _("Write MODFLOW (USGS) ASCII array"); flag.int_out = G_define_flag(); flag.int_out->key = 'i'; flag.int_out->description = _("Force output of integer values"); if (G_parser(argc, argv)) exit(EXIT_FAILURE); if (parm.dp->answer) { if (sscanf(parm.dp->answer, "%d", &dp) != 1) G_fatal_error(_("Failed to interpret dp as an integer")); if (dp > 20 || dp < 0) G_fatal_error(_("dp has to be from 0 to 20")); } width = 10; if (parm.width->answer) { if (sscanf(parm.width->answer, "%d", &width) != 1) G_fatal_error(_("Failed to interpret width as an integer")); } null_str = parm.null->answer; if (flag.surfer->answer && flag.noheader->answer) G_fatal_error(_("Both -s and -h doesn't make sense")); if (flag.surfer->answer && flag.modflow->answer) G_fatal_error(_("Use -M or -s, not both")); name = parm.map->answer; mapset = G_find_cell2(name, ""); if (!mapset) G_fatal_error(_("Raster map <%s> not found"), name); /* open raster map */ fd = G_open_cell_old(name, mapset); if (fd < 0) G_fatal_error(_("Unable to open raster map <%s>"), name); map_type = G_get_raster_map_type(fd); if (!flag.int_out->answer) out_type = map_type; else out_type = CELL_TYPE; if (!parm.dp->answer) { dp = 6; if (out_type == DCELL_TYPE) dp = 16; } nrows = G_window_rows(); ncols = G_window_cols(); /* open ascii file for writing or use stdout */ if (parm.output->answer && strcmp("-", parm.output->answer) != 0) { if (NULL == (fp = fopen(parm.output->answer, "w"))) G_fatal_error(_("Unable to open file <%s>"), parm.output->answer); } else fp = stdout; /* process the requested output format */ if (flag.surfer->answer) { if (!flag.noheader->answer) { if (writeGSheader(fp, name, mapset)) G_fatal_error(_("Unable to read fp range for <%s>"), name); } rc = write_GSGRID(fd, fp, nrows, ncols, out_type, dp, surfer_null_str, width); } else if (flag.modflow->answer) { if (!flag.noheader->answer) writeMFheader(fp, dp, width, out_type); rc = write_MODFLOW(fd, fp, nrows, ncols, out_type, dp, width); } else { if (!flag.noheader->answer) writeGRASSheader(fp); rc = write_GRASS(fd, fp, nrows, ncols, out_type, dp, null_str); } if (rc) { G_fatal_error(_("Read failed at row %d"), rc); } /* tidy up and go away */ G_close_cell(fd); fclose(fp); exit(EXIT_SUCCESS); }
int main(int argc, char *argv[]) { struct GModule *module; struct Option *rastin, *rastout, *method; struct History history; char title[64]; char buf_nsres[100], buf_ewres[100]; struct Colors colors; char *inmap; int infile, outfile; DCELL *outbuf; int row, col; struct Cell_head dst_w, src_w; G_gisinit(argv[0]); module = G_define_module(); module->keywords = _("raster, resample"); module->description = _("Resamples raster map layers to a finer grid using interpolation."); rastin = G_define_standard_option(G_OPT_R_INPUT); rastout = G_define_standard_option(G_OPT_R_OUTPUT); method = G_define_option(); method->key = "method"; method->type = TYPE_STRING; method->required = NO; method->description = _("Interpolation method"); method->options = "nearest,bilinear,bicubic"; method->answer = "bilinear"; if (G_parser(argc, argv)) exit(EXIT_FAILURE); if (G_strcasecmp(method->answer, "nearest") == 0) neighbors = 1; else if (G_strcasecmp(method->answer, "bilinear") == 0) neighbors = 2; else if (G_strcasecmp(method->answer, "bicubic") == 0) neighbors = 4; else G_fatal_error(_("Invalid method: %s"), method->answer); G_get_set_window(&dst_w); inmap = G_find_cell2(rastin->answer, ""); if (!inmap) G_fatal_error(_("Raster map <%s> not found"), rastin->answer); /* set window to old map */ G_get_cellhd(rastin->answer, inmap, &src_w); /* enlarge source window */ { double north = G_row_to_northing(0.5, &dst_w); double south = G_row_to_northing(dst_w.rows - 0.5, &dst_w); int r0 = (int)floor(G_northing_to_row(north, &src_w) - 0.5) - 1; int r1 = (int)floor(G_northing_to_row(south, &src_w) - 0.5) + 3; double west = G_col_to_easting(0.5, &dst_w); double east = G_col_to_easting(dst_w.cols - 0.5, &dst_w); int c0 = (int)floor(G_easting_to_col(west, &src_w) - 0.5) - 1; int c1 = (int)floor(G_easting_to_col(east, &src_w) - 0.5) + 3; src_w.south -= src_w.ns_res * (r1 - src_w.rows); src_w.north += src_w.ns_res * (-r0); src_w.west -= src_w.ew_res * (-c0); src_w.east += src_w.ew_res * (c1 - src_w.cols); src_w.rows = r1 - r0; src_w.cols = c1 - c0; } G_set_window(&src_w); /* allocate buffers for input rows */ for (row = 0; row < neighbors; row++) bufs[row] = G_allocate_d_raster_buf(); cur_row = -100; /* open old map */ infile = G_open_cell_old(rastin->answer, inmap); if (infile < 0) G_fatal_error(_("Unable to open raster map <%s>"), rastin->answer); /* reset window to current region */ G_set_window(&dst_w); outbuf = G_allocate_d_raster_buf(); /* open new map */ outfile = G_open_raster_new(rastout->answer, DCELL_TYPE); if (outfile < 0) G_fatal_error(_("Unable to create raster map <%s>"), rastout->answer); G_suppress_warnings(1); /* otherwise get complaints about window changes */ switch (neighbors) { case 1: /* nearest */ for (row = 0; row < dst_w.rows; row++) { double north = G_row_to_northing(row + 0.5, &dst_w); double maprow_f = G_northing_to_row(north, &src_w) - 0.5; int maprow0 = (int)floor(maprow_f + 0.5); G_percent(row, dst_w.rows, 2); G_set_window(&src_w); read_rows(infile, maprow0); for (col = 0; col < dst_w.cols; col++) { double east = G_col_to_easting(col + 0.5, &dst_w); double mapcol_f = G_easting_to_col(east, &src_w) - 0.5; int mapcol0 = (int)floor(mapcol_f + 0.5); double c = bufs[0][mapcol0]; if (G_is_d_null_value(&c)) { G_set_d_null_value(&outbuf[col], 1); } else { outbuf[col] = c; } } G_set_window(&dst_w); G_put_d_raster_row(outfile, outbuf); } break; case 2: /* bilinear */ for (row = 0; row < dst_w.rows; row++) { double north = G_row_to_northing(row + 0.5, &dst_w); double maprow_f = G_northing_to_row(north, &src_w) - 0.5; int maprow0 = (int)floor(maprow_f); double v = maprow_f - maprow0; G_percent(row, dst_w.rows, 2); G_set_window(&src_w); read_rows(infile, maprow0); for (col = 0; col < dst_w.cols; col++) { double east = G_col_to_easting(col + 0.5, &dst_w); double mapcol_f = G_easting_to_col(east, &src_w) - 0.5; int mapcol0 = (int)floor(mapcol_f); int mapcol1 = mapcol0 + 1; double u = mapcol_f - mapcol0; double c00 = bufs[0][mapcol0]; double c01 = bufs[0][mapcol1]; double c10 = bufs[1][mapcol0]; double c11 = bufs[1][mapcol1]; if (G_is_d_null_value(&c00) || G_is_d_null_value(&c01) || G_is_d_null_value(&c10) || G_is_d_null_value(&c11)) { G_set_d_null_value(&outbuf[col], 1); } else { outbuf[col] = G_interp_bilinear(u, v, c00, c01, c10, c11); } } G_set_window(&dst_w); G_put_d_raster_row(outfile, outbuf); } break; case 4: /* bicubic */ for (row = 0; row < dst_w.rows; row++) { double north = G_row_to_northing(row + 0.5, &dst_w); double maprow_f = G_northing_to_row(north, &src_w) - 0.5; int maprow1 = (int)floor(maprow_f); int maprow0 = maprow1 - 1; double v = maprow_f - maprow1; G_percent(row, dst_w.rows, 2); G_set_window(&src_w); read_rows(infile, maprow0); for (col = 0; col < dst_w.cols; col++) { double east = G_col_to_easting(col + 0.5, &dst_w); double mapcol_f = G_easting_to_col(east, &src_w) - 0.5; int mapcol1 = (int)floor(mapcol_f); int mapcol0 = mapcol1 - 1; int mapcol2 = mapcol1 + 1; int mapcol3 = mapcol1 + 2; double u = mapcol_f - mapcol1; double c00 = bufs[0][mapcol0]; double c01 = bufs[0][mapcol1]; double c02 = bufs[0][mapcol2]; double c03 = bufs[0][mapcol3]; double c10 = bufs[1][mapcol0]; double c11 = bufs[1][mapcol1]; double c12 = bufs[1][mapcol2]; double c13 = bufs[1][mapcol3]; double c20 = bufs[2][mapcol0]; double c21 = bufs[2][mapcol1]; double c22 = bufs[2][mapcol2]; double c23 = bufs[2][mapcol3]; double c30 = bufs[3][mapcol0]; double c31 = bufs[3][mapcol1]; double c32 = bufs[3][mapcol2]; double c33 = bufs[3][mapcol3]; if (G_is_d_null_value(&c00) || G_is_d_null_value(&c01) || G_is_d_null_value(&c02) || G_is_d_null_value(&c03) || G_is_d_null_value(&c10) || G_is_d_null_value(&c11) || G_is_d_null_value(&c12) || G_is_d_null_value(&c13) || G_is_d_null_value(&c20) || G_is_d_null_value(&c21) || G_is_d_null_value(&c22) || G_is_d_null_value(&c23) || G_is_d_null_value(&c30) || G_is_d_null_value(&c31) || G_is_d_null_value(&c32) || G_is_d_null_value(&c33)) { G_set_d_null_value(&outbuf[col], 1); } else { outbuf[col] = G_interp_bicubic(u, v, c00, c01, c02, c03, c10, c11, c12, c13, c20, c21, c22, c23, c30, c31, c32, c33); } } G_set_window(&dst_w); G_put_d_raster_row(outfile, outbuf); } break; } G_percent(dst_w.rows, dst_w.rows, 2); G_close_cell(infile); G_close_cell(outfile); /* record map metadata/history info */ sprintf(title, "Resample by %s interpolation", method->answer); G_put_cell_title(rastout->answer, title); G_short_history(rastout->answer, "raster", &history); strncpy(history.datsrc_1, rastin->answer, RECORD_LEN); history.datsrc_1[RECORD_LEN - 1] = '\0'; /* strncpy() doesn't null terminate if maxfill */ G_format_resolution(src_w.ns_res, buf_nsres, src_w.proj); G_format_resolution(src_w.ew_res, buf_ewres, src_w.proj); sprintf(history.datsrc_2, "Source map NS res: %s EW res: %s", buf_nsres, buf_ewres); G_command_history(&history); G_write_history(rastout->answer, &history); /* copy color table from source map */ if (G_read_colors(rastin->answer, inmap, &colors) < 0) G_fatal_error(_("Unable to read color table for %s"), rastin->answer); G_mark_colors_as_fp(&colors); if (G_write_colors(rastout->answer, G_mapset(), &colors) < 0) G_fatal_error(_("Unable to write color table for %s"), rastout->answer); return (EXIT_SUCCESS); }
GRASSRasterBand::GRASSRasterBand( GRASSDataset *poDS, int nBand, const char * pszMapset, const char * pszCellName ) { struct Cell_head sCellInfo; this->poDS = poDS; this->nBand = nBand; G_get_cellhd( (char *) pszCellName, (char *) pszMapset, &sCellInfo ); nGRSType = G_raster_map_type( (char *) pszCellName, (char *) pszMapset ); /* -------------------------------------------------------------------- */ /* Get min/max values. */ /* -------------------------------------------------------------------- */ struct FPRange sRange; if( G_read_fp_range( (char *) pszCellName, (char *) pszMapset, &sRange ) == -1 ) { bHaveMinMax = FALSE; } else { bHaveMinMax = TRUE; G_get_fp_range_min_max( &sRange, &dfCellMin, &dfCellMax ); } /* -------------------------------------------------------------------- */ /* Setup band type, and preferred nodata value. */ /* -------------------------------------------------------------------- */ dfNoData = 0.0; if( nGRSType == CELL_TYPE && sCellInfo.format == 0 ) { if( bHaveMinMax && dfCellMin < 1.0 && dfCellMax > 254.0 ) { this->eDataType = GDT_UInt16; dfNoData = 256.0; } else { this->eDataType = GDT_Byte; if( dfCellMax < 255.0 ) dfNoData = 255.0; else dfNoData = 0.0; } } else if( nGRSType == CELL_TYPE && sCellInfo.format == 1 ) { this->eDataType = GDT_UInt16; dfNoData = 65535.0; } else if( nGRSType == CELL_TYPE ) { this->eDataType = GDT_UInt32; dfNoData = 65535.0; } else if( nGRSType == FCELL_TYPE ) { this->eDataType = GDT_Float32; dfNoData = -12345.0; } else if( nGRSType == DCELL_TYPE ) { this->eDataType = GDT_Float64; dfNoData = -12345.0; } nBlockXSize = poDS->nRasterXSize;; nBlockYSize = 1; hCell = G_open_cell_old((char *) pszCellName, (char *) pszMapset); /* -------------------------------------------------------------------- */ /* Do we have a color table? */ /* -------------------------------------------------------------------- */ struct Colors sGrassColors; poCT = NULL; if( G_read_colors( (char *) pszCellName, (char *) pszMapset, &sGrassColors ) == 1 ) { poCT = new GDALColorTable(); for( int iColor = 0; iColor < 256; iColor++ ) { int nRed, nGreen, nBlue; GDALColorEntry sColor; if( G_get_color( iColor, &nRed, &nGreen, &nBlue, &sGrassColors ) ) { sColor.c1 = nRed; sColor.c2 = nGreen; sColor.c3 = nBlue; sColor.c4 = 255; poCT->SetColorEntry( iColor, &sColor ); } else { sColor.c1 = 0; sColor.c2 = 0; sColor.c3 = 0; sColor.c4 = 0; poCT->SetColorEntry( iColor, &sColor ); } } G_free_colors( &sGrassColors ); } }
/* useful to create randomised samples for statistical tests */ void do_split_sample ( char *input, char *output, int in_types, double percentage, char *map, int all, int processing_mode, int quiet) { CELL *cellbuf; DCELL *dcellbuf; GT_Row_cache_t *cache; int fd; int i,j,k,l; int no_sites; int sites_tried = 0; struct Cell_head region; int error; char *mapset, errmsg [200]; unsigned int *taken; /* this is an array of 0/1 which signals, if a certain site has already been 'drawn' */ long row_idx, col_idx; struct Map_info in_vect_map; struct Map_info out_vect_map; struct line_pnts *vect_points; struct line_cats *vect_cats; double x,y,z; int n_points = 1; int cur_type; cellbuf = NULL; dcellbuf = NULL; cache = NULL; /* get current region */ G_get_window (®ion); /* attempt to create new file for output */ Vect_set_open_level (2); if (0 > Vect_open_new (&out_vect_map, output, 0) ) { G_fatal_error ("Could not open output vector map.\n"); } /* open input vector map */ if ((mapset = G_find_vector2 (input, "")) == NULL) { sprintf (errmsg, "Could not find input %s\n", input); G_fatal_error ("%s",errmsg); } if (1 > Vect_open_old (&in_vect_map, input, "")) { sprintf (errmsg, "Could not open input map %s.\n", input); G_fatal_error ("%s",errmsg); } vect_points = Vect_new_line_struct (); vect_cats = Vect_new_cats_struct (); /* set constraints specified */ if (in_types != 0) { Vect_set_constraint_type (&in_vect_map, in_types); } if (all != 1) { Vect_set_constraint_region (&in_vect_map, region.north, region.south, region.east, region.west, 0.0, 0.0); } /* get total number of objects with constraints */ i = 0; while ((cur_type = Vect_read_next_line (&in_vect_map, vect_points, vect_cats) > 0)) { i ++; } k = ( ((float) i/100)) * percentage; /* k now has the number of objects wanted */ if ( quiet != 1 ) { fprintf (stderr,"Creating randomised sample of size n = %i.\n",k); } /* now, we need to acquire exactly 'k' random objects that fall in NON-NULL */ /* coverage raster cells. */ taken = G_calloc (i, sizeof (unsigned int)); for ( l = 0; l < k; l ++ ) { taken[l] = 0; } no_sites = i; /* store this for later use */ /* does user want to filter objects through a raster map? */ if ( map != NULL) { /* open raster map */ fd = G_open_cell_old (map, G_find_cell (map, "")); if (fd < 0) { G_fatal_error ("Could not open raster map for reading!\n"); } /* allocate cache and buffer, according to type of coverage */ if ( processing_mode == CELL_TYPE) { /* INT coverage */ cache = (GT_Row_cache_t *) G_malloc (sizeof (GT_Row_cache_t)); /* TODO: check error value */ error = GT_RC_open (cache, cachesize, fd, CELL_TYPE); cellbuf = G_allocate_raster_buf (CELL_TYPE); } if ( (processing_mode == FCELL_TYPE) || (processing_mode == DCELL_TYPE) ) { /* FP coverage */ cache = (GT_Row_cache_t *) G_malloc (sizeof (GT_Row_cache_t)); /* TODO: check error value */ error = GT_RC_open (cache, cachesize, fd, DCELL_TYPE); dcellbuf = G_allocate_raster_buf (DCELL_TYPE); } } srand ( ((unsigned int) time (NULL)) + getpid()); /* set seed for random number generator from system time and process ID*/ i = 0; /* MAIN LOOP */ while ( i < k ) { /* get a random index, but one that was not taken already */ l = 0; while ( l == 0 ) { j = rand () % ( no_sites - 1 + 1) + 1; /* j now has the random position to try */ if ( taken[j-1] == 0 ) { l = 1; /* exit loop */ } } taken [j-1] = 1; /* mark this index as 'taken' */ sites_tried ++; /* keep track of this so we do not enter an infinite loop */ if ( sites_tried > no_sites ) { /* could not create a large enough sample */ G_fatal_error ("Could not find enough objects for split sampling.\nDecrease split sample size.\n"); } /* get next vector object */ cur_type = Vect_read_line (&in_vect_map, vect_points, vect_cats, j); if (cur_type < 0 ) { G_fatal_error ("Error reading vector map: premature EOF.\n"); } /* now, check if coverage under site is NON-NULL and within region */ /* convert site northing to row! */ /* for this check, we use only the first pair of coordinates! */ Vect_copy_pnts_to_xyz (vect_points, &x, &y, &z, &n_points); row_idx = (long) G_northing_to_row (y, ®ion); col_idx = (long) G_easting_to_col (x, ®ion); /* do region check, first... OBSOLETE */ /* read row from cache and check for NULL */ /* if required */ if ( map != NULL ) { if ( processing_mode == CELL_TYPE ) { cellbuf = GT_RC_get (cache, row_idx); if (!G_is_c_null_value(&cellbuf[col_idx])) { i ++; Vect_write_line (&out_vect_map, cur_type, vect_points, vect_cats ); fflush (stdout); } } if ( (processing_mode == FCELL_TYPE) || (processing_mode == DCELL_TYPE) ) { dcellbuf = GT_RC_get (cache, row_idx); if (!G_is_d_null_value(&dcellbuf[col_idx])) { i ++; Vect_write_line (&out_vect_map, cur_type, vect_points, vect_cats ); fflush (stdout); } } } else { i ++; Vect_write_line (&out_vect_map, GV_POINT, vect_points, vect_cats ); fflush (stdout); } /* disregard region setting and map, if -a flag is given */ if ( all == 1 ) { i ++; Vect_write_line (&out_vect_map, cur_type, vect_points, vect_cats ); fflush (stdout); } if ( quiet != 1 ) { G_percent(i,k,1); } } /* END OF MAIN LOOP */ Vect_copy_head_data (&in_vect_map, &out_vect_map); fprintf (stdout, "Building topology information for output map.\n"); Vect_build (&out_vect_map); Vect_close (&in_vect_map); Vect_close (&out_vect_map); if ( map != NULL ) { /* close cache, free buffers! */ GT_RC_close (cache); if ( processing_mode == CELL_TYPE ) { G_free (cellbuf); } if ( (processing_mode == FCELL_TYPE) || (processing_mode == DCELL_TYPE) ) { G_free (dcellbuf); } G_free (cache); } }
int read_rgb(char *key, char *data) { char names[3][100]; char fullname[100]; int i; if (sscanf(data, "%s %s %s", names[0], names[1], names[2]) != 3) { error(key, data, "illegal request (rgb)"); return 0; } PS.do_raster = 0; PS.do_colortable = 0; if (PS.cell_fd >= 0) { G_close_cell(PS.cell_fd); G_free(PS.cell_name); G_free(PS.cell_mapset); G_free_colors(&PS.colors); PS.cell_fd = -1; } /* initialize group structure (for compatibility with PS_raster_plot()) */ I_init_group_ref(&grp.ref); /* * not relevant here * if (I_get_group_ref(grp.group_name, &grp.ref) == 0) G_fatal_error(_("Can't get group information")); */ grp.group_name = "RGB Group"; /* get file names for R, G, & B */ for (i = 0; i < 3; i++) { char *mapset, *name, *p; name = names[i]; p = strchr(name, '@'); if (p) { *p = '\0'; mapset = p + 1; } else { mapset = G_find_file2("cell", name, ""); if (!mapset) { error(name, "", "not found"); return 0; } } grp.name[i] = G_store(name); grp.mapset[i] = G_store(mapset); /* read in colors */ if (G_read_colors(grp.name[i], grp.mapset[i], &(grp.colors[i])) == -1) { sprintf(fullname, "%s in %s", grp.name[i], grp.mapset[i]); error(fullname, "", "can't read color table"); return 0; } /* open raster maps for reading */ if ((grp.fd[i] = G_open_cell_old(grp.name[i], grp.mapset[i])) < 0) { sprintf(fullname, "%s in %s", grp.name[i], grp.mapset[i]); error(fullname, "", "can't open raster map"); G_free_colors(&(grp.colors[i])); return 0; } } strcpy(PS.celltitle, grp.group_name); G_strip(PS.celltitle); return 1; }
int main( int argc, char **argv ) { struct GModule *module; struct Option *info_opt, *rast_opt, *vect_opt, *coor_opt, *north_opt, *south_opt, *east_opt, *west_opt, *rows_opt, *cols_opt; struct Cell_head window; /* Initialize the GIS calls */ G_gisinit( argv[0] ); module = G_define_module(); module->description = ( "Get info about locations,mapsets,maps" ); info_opt = G_define_option(); info_opt->key = "info"; info_opt->type = TYPE_STRING; info_opt->description = "info key"; info_opt->options = "proj,window,size,query,info,colors,stats"; rast_opt = G_define_standard_option( G_OPT_R_INPUT ); rast_opt->key = "rast"; rast_opt->required = NO; vect_opt = G_define_standard_option( G_OPT_V_INPUT ); vect_opt->key = "vect"; vect_opt->required = NO; coor_opt = G_define_option(); coor_opt->key = "coor"; coor_opt->type = TYPE_DOUBLE; coor_opt->multiple = YES; north_opt = G_define_option(); north_opt->key = "north"; north_opt->type = TYPE_STRING; south_opt = G_define_option(); south_opt->key = "south"; south_opt->type = TYPE_STRING; east_opt = G_define_option(); east_opt->key = "east"; east_opt->type = TYPE_STRING; west_opt = G_define_option(); west_opt->key = "west"; west_opt->type = TYPE_STRING; rows_opt = G_define_option(); rows_opt->key = "rows"; rows_opt->type = TYPE_INTEGER; cols_opt = G_define_option(); cols_opt->key = "cols"; cols_opt->type = TYPE_INTEGER; if ( G_parser( argc, argv ) ) exit( EXIT_FAILURE ); if ( strcmp( "proj", info_opt->answer ) == 0 ) { G_get_window( &window ); /* code from g.proj */ if ( window.proj != PROJECTION_XY ) { struct Key_Value *projinfo, *projunits; char *wkt; projinfo = G_get_projinfo(); projunits = G_get_projunits(); wkt = GPJ_grass_to_wkt( projinfo, projunits, 0, 0 ); fprintf( stdout, "%s", wkt ); } } else if ( strcmp( "window", info_opt->answer ) == 0 ) { if ( rast_opt->answer ) { G_get_cellhd( rast_opt->answer, "", &window ); fprintf( stdout, "%f,%f,%f,%f", window.west, window.south, window.east, window.north ); } else if ( vect_opt->answer ) { G_fatal_error( "Not yet supported" ); } } // raster width and height else if ( strcmp( "size", info_opt->answer ) == 0 ) { if ( rast_opt->answer ) { G_get_cellhd( rast_opt->answer, "", &window ); fprintf( stdout, "%d,%d", window.cols, window.rows ); } else if ( vect_opt->answer ) { G_fatal_error( "Not yet supported" ); } } // raster informations else if ( strcmp( "info", info_opt->answer ) == 0 ) { struct FPRange range; double zmin, zmax; // Data type RASTER_MAP_TYPE raster_type = G_raster_map_type( rast_opt->answer, "" ); fprintf( stdout, "TYPE:%d\n", raster_type ); // Statistics if ( G_read_fp_range( rast_opt->answer, "", &range ) < 0 ) { G_fatal_error(( "Unable to read range file" ) ); } G_get_fp_range_min_max( &range, &zmin, &zmax ); fprintf( stdout, "MIN_VALUE:%.17e\n", zmin ); fprintf( stdout, "MAX_VALUE:%.17e\n", zmax ); } else if ( strcmp( "colors", info_opt->answer ) == 0 ) { // Color table struct Colors colors; int i, ccount; if ( G_read_colors( rast_opt->answer, "", &colors ) == 1 ) { //int maxcolor; //CELL min, max; //G_get_color_range ( &min, &max, &colors); ccount = G_colors_count( &colors ); for ( i = ccount - 1; i >= 0; i-- ) { DCELL val1, val2; unsigned char r1, g1, b1, r2, g2, b2; G_get_f_color_rule( &val1, &r1, &g1, &b1, &val2, &r2, &g2, &b2, &colors, i ); fprintf( stdout, "%.17e %.17e %d %d %d %d %d %d\n", val1, val2, r1, g1, b1, r2, g2, b2 ); } } } else if ( strcmp( "query", info_opt->answer ) == 0 ) { double x, y; int row, col; //x = atof( coor_opt->answers[0] ); //y = atof( coor_opt->answers[1] ); if ( rast_opt->answer ) { int fd; RASTER_MAP_TYPE rast_type; DCELL *dcell; CELL *cell; char buff[101]; G_get_cellhd( rast_opt->answer, "", &window ); G_set_window( &window ); fd = G_open_cell_old( rast_opt->answer, "" ); // wait for coors from stdin while ( fgets( buff, 100, stdin ) != 0 ) { if ( sscanf( buff, "%lf%lf", &x, &y ) != 2 ) { fprintf( stdout, "value:error\n" ); } else { col = ( int ) G_easting_to_col( x, &window ); row = ( int ) G_northing_to_row( y, &window ); if ( col == window.cols ) col--; if ( row == window.rows ) row--; if ( col < 0 || col > window.cols || row < 0 || row > window.rows ) { fprintf( stdout, "value:out\n" ); } else { void *ptr; double val; #if defined(GRASS_VERSION_MAJOR) && defined(GRASS_VERSION_MINOR) && \ ( ( GRASS_VERSION_MAJOR == 6 && GRASS_VERSION_MINOR > 2 ) || GRASS_VERSION_MAJOR > 6 ) rast_type = G_get_raster_map_type( fd ); #else rast_type = G_raster_map_type( rast_opt->answer, "" ); #endif cell = G_allocate_c_raster_buf(); dcell = G_allocate_d_raster_buf(); if ( rast_type == CELL_TYPE ) { if ( G_get_c_raster_row( fd, cell, row ) < 0 ) { G_fatal_error(( "Unable to read raster map <%s> row %d" ), rast_opt->answer, row ); } val = cell[col]; ptr = &( cell[col] ); } else { if ( G_get_d_raster_row( fd, dcell, row ) < 0 ) { G_fatal_error(( "Unable to read raster map <%s> row %d" ), rast_opt->answer, row ); } val = dcell[col]; ptr = &( dcell[col] ); } if ( G_is_null_value( ptr, rast_type ) ) { fprintf( stdout, "value:null\n" ); } else { fprintf( stdout, "value:%f\n", val ); } } } fflush( stdout ); } G_close_cell( fd ); } else if ( vect_opt->answer ) { G_fatal_error( "Not yet supported" ); } } else if ( strcmp( "stats", info_opt->answer ) == 0 ) { if ( rast_opt->answer ) { int fd; RASTER_MAP_TYPE rast_type; DCELL *dcell; CELL *cell; int ncols, nrows; int row, col; void *ptr; double val; double min = DBL_MAX; double max = -DBL_MAX; double sum = 0; // sum of values int count = 0; // count of non null values double mean = 0; double squares_sum = 0; // sum of squares double stdev = 0; // standard deviation G_get_cellhd( rast_opt->answer, "", &window ); window.north = atof( north_opt->answer ); window.south = atof( south_opt->answer ); window.east = atof( east_opt->answer ); window.west = atof( west_opt->answer ); window.rows = ( int ) atoi( rows_opt->answer ); window.cols = ( int ) atoi( cols_opt->answer ); G_set_window( &window ); fd = G_open_cell_old( rast_opt->answer, "" ); ncols = G_window_cols(); nrows = G_window_rows(); #if defined(GRASS_VERSION_MAJOR) && defined(GRASS_VERSION_MINOR) && \ ( ( GRASS_VERSION_MAJOR == 6 && GRASS_VERSION_MINOR > 2 ) || GRASS_VERSION_MAJOR > 6 ) rast_type = G_get_raster_map_type( fd ); #else rast_type = G_raster_map_type( rast_opt->answer, "" ); #endif cell = G_allocate_c_raster_buf(); dcell = G_allocate_d_raster_buf(); // Calc stats is very slow for large rasters -> prefer optimization for speed over // code length and readability (which is not currently true) for ( row = 0; row < nrows; row++ ) { if ( rast_type == CELL_TYPE ) { if ( G_get_c_raster_row( fd, cell, row ) < 0 ) { G_fatal_error(( "Unable to read raster map <%s> row %d" ), rast_opt->answer, row ); } } else { if ( G_get_d_raster_row( fd, dcell, row ) < 0 ) { G_fatal_error(( "Unable to read raster map <%s> row %d" ), rast_opt->answer, row ); } } for ( col = 0; col < ncols; col++ ) { if ( rast_type == CELL_TYPE ) { val = cell[col]; ptr = &( cell[col] ); } else { val = dcell[col]; ptr = &( dcell[col] ); } if ( ! G_is_null_value( ptr, rast_type ) ) { if ( val < min ) min = val; if ( val > max ) max = val; sum += val; count++; squares_sum += pow( val, 2 ); } } } mean = sum / count; squares_sum -= count * pow( mean, 2 ); stdev = sqrt( squares_sum / ( count - 1 ) ); fprintf( stdout, "MIN:%.17e\n", min ); fprintf( stdout, "MAX:%.17e\n", max ); fprintf( stdout, "SUM:%.17e\n", sum ); fprintf( stdout, "MEAN:%.17e\n", mean ); fprintf( stdout, "COUNT:%d\n", count ); fprintf( stdout, "STDEV:%.17e\n", stdev ); fprintf( stdout, "SQSUM:%.17e\n", squares_sum ); G_close_cell( fd ); } else if ( vect_opt->answer ) { G_fatal_error( "Not yet supported" ); } } exit( EXIT_SUCCESS ); }
static int cell_draw( char *name, char *mapset, struct Colors *colors, RASTER_MAP_TYPE data_type, char *format ) { int cellfile; void *xarray = 0; int row; int ncols, nrows; static unsigned char *red, *grn, *blu, *set; int i; void *ptr = 0; int big_endian; long one = 1; FILE *fo = 0; size_t raster_size; #ifdef NAN double dnul = NAN; float fnul = ( float )( NAN ); #else double dnul = strtod( "NAN", 0 ); float fnul = strtof( "NAN", 0 ); // another possibility would be nan()/nanf() - C99 // and 0./0. if all fails #endif assert( dnul != dnul ); assert( fnul != fnul ); big_endian = !( *( ( char * )( &one ) ) ); ncols = G_window_cols(); nrows = G_window_rows(); /* Make sure map is available */ if ( ( cellfile = G_open_cell_old( name, mapset ) ) == -1 ) G_fatal_error( ( "Unable to open raster map <%s>" ), name ); /* Allocate space for cell buffer */ xarray = G_allocate_raster_buf( data_type ); red = G_malloc( ncols ); grn = G_malloc( ncols ); blu = G_malloc( ncols ); set = G_malloc( ncols ); /* some buggy C libraries require BOTH setmode() and fdopen(bin) */ // Do not use Q_OS_WIN, we are in C file, no Qt headers #ifdef WIN32 if ( _setmode( _fileno( stdout ), _O_BINARY ) == -1 ) G_fatal_error( "Cannot set stdout mode" ); #endif // Unfortunately this is not sufficient on Windows to switch stdout to binary mode fo = fdopen( fileno( stdout ), "wb" ); raster_size = G_raster_size( data_type ); //fprintf( fo, "%d %d", data_type, raster_size ); //exit(0); /* loop for array rows */ for ( row = 0; row < nrows; row++ ) { G_get_raster_row( cellfile, xarray, row, data_type ); ptr = xarray; G_lookup_raster_colors( xarray, red, grn, blu, set, ncols, colors, data_type ); for ( i = 0; i < ncols; i++ ) { unsigned char alpha = 255; //G_debug ( 0, "row = %d col = %d", row, i ); if ( G_is_null_value( ptr, data_type ) ) { alpha = 0; } if ( strcmp( format, "color" ) == 0 ) { // We need data suitable for QImage 32-bpp // the data are stored in QImage as QRgb which is unsigned int. // Because it depends on byte order of the platform we have to // consider byte order (well, middle endian ignored) if ( big_endian ) { // I have never tested this fprintf( fo, "%c%c%c%c", alpha, red[i], grn[i], blu[i] ); } else { fprintf( fo, "%c%c%c%c", blu[i], grn[i], red[i], alpha ); } } else { if ( data_type == CELL_TYPE ) { //G_debug ( 0, "valx = %d", *((CELL *) ptr)); } if ( G_is_null_value( ptr, data_type ) ) { // see comments in QgsGrassRasterProvider::noDataValue() if ( data_type == CELL_TYPE ) { //int nul = -2000000000; int nul = INT_MIN; fwrite( &nul, 4, 1, fo ); } else if ( data_type == DCELL_TYPE ) { //double nul = -1e+300; fwrite( &dnul, 8, 1, fo ); } else if ( data_type == FCELL_TYPE ) { //double nul = -1e+30; fwrite( &fnul, 4, 1, fo ); } } else { fwrite( ptr, raster_size, 1, fo ); } } ptr = G_incr_void_ptr( ptr, raster_size ); } } G_close_cell( cellfile ); fclose( fo ); return ( 0 ); }
GRASSRasterBand::GRASSRasterBand( GRASSDataset *poDS, int nBand, const char * pszMapset, const char * pszCellName ) { struct Cell_head sCellInfo; // Note: GISDBASE, LOCATION_NAME ans MAPSET was set in GRASSDataset::Open this->poDS = poDS; this->nBand = nBand; this->valid = false; this->pszCellName = G_store ( (char *) pszCellName ); this->pszMapset = G_store ( (char *) pszMapset ); G_get_cellhd( (char *) pszCellName, (char *) pszMapset, &sCellInfo ); nGRSType = G_raster_map_type( (char *) pszCellName, (char *) pszMapset ); /* -------------------------------------------------------------------- */ /* Get min/max values. */ /* -------------------------------------------------------------------- */ struct FPRange sRange; if( G_read_fp_range( (char *) pszCellName, (char *) pszMapset, &sRange ) == -1 ) { bHaveMinMax = FALSE; } else { bHaveMinMax = TRUE; G_get_fp_range_min_max( &sRange, &dfCellMin, &dfCellMax ); } /* -------------------------------------------------------------------- */ /* Setup band type, and preferred nodata value. */ /* -------------------------------------------------------------------- */ // Negative values are also (?) stored as 4 bytes (format = 3) // => raster with format < 3 has only positive values // GRASS modules usually do not waste space and only the format necessary to keep // full raster values range is used -> no checks if shorter type could be used if( nGRSType == CELL_TYPE ) { if ( sCellInfo.format == 0 ) { // 1 byte / cell -> possible range 0,255 if ( bHaveMinMax && dfCellMin > 0 ) { this->eDataType = GDT_Byte; dfNoData = 0.0; } else if ( bHaveMinMax && dfCellMax < 255 ) { this->eDataType = GDT_Byte; dfNoData = 255.0; } else { // maximum is not known or full range is used this->eDataType = GDT_UInt16; dfNoData = 256.0; } nativeNulls = false; } else if ( sCellInfo.format == 1 ) { // 2 bytes / cell -> possible range 0,65535 if ( bHaveMinMax && dfCellMin > 0 ) { this->eDataType = GDT_UInt16; dfNoData = 0.0; } else if ( bHaveMinMax && dfCellMax < 65535 ) { this->eDataType = GDT_UInt16; dfNoData = 65535; } else { // maximum is not known or full range is used CELL cval; this->eDataType = GDT_Int32; G_set_c_null_value ( &cval, 1); dfNoData = (double) cval; nativeNulls = true; } nativeNulls = false; } else { // 3-4 bytes CELL cval; this->eDataType = GDT_Int32; G_set_c_null_value ( &cval, 1); dfNoData = (double) cval; nativeNulls = true; } } else if( nGRSType == FCELL_TYPE ) { FCELL fval; this->eDataType = GDT_Float32; G_set_f_null_value ( &fval, 1); dfNoData = (double) fval; nativeNulls = true; } else if( nGRSType == DCELL_TYPE ) { DCELL dval; this->eDataType = GDT_Float64; G_set_d_null_value ( &dval, 1); dfNoData = (double) dval; nativeNulls = true; } nBlockXSize = poDS->nRasterXSize;; nBlockYSize = 1; G_set_window( &(((GRASSDataset *)poDS)->sCellInfo) ); if ( (hCell = G_open_cell_old((char *) pszCellName, (char *) pszMapset)) < 0 ) { CPLError( CE_Warning, CPLE_AppDefined, "GRASS: Cannot open raster '%s'", pszCellName ); return; } G_copy((void *) &sOpenWindow, (void *) &(((GRASSDataset *)poDS)->sCellInfo), sizeof(struct Cell_head)); /* -------------------------------------------------------------------- */ /* Do we have a color table? */ /* -------------------------------------------------------------------- */ poCT = NULL; if( G_read_colors( (char *) pszCellName, (char *) pszMapset, &sGrassColors ) == 1 ) { int maxcolor; CELL min, max; G_get_color_range ( &min, &max, &sGrassColors); if ( bHaveMinMax ) { if ( max < dfCellMax ) { maxcolor = max; } else { maxcolor = (int) ceil ( dfCellMax ); } if ( maxcolor > GRASS_MAX_COLORS ) { maxcolor = GRASS_MAX_COLORS; CPLDebug( "GRASS", "Too many values, color table cut to %d entries.", maxcolor ); } } else { if ( max < GRASS_MAX_COLORS ) { maxcolor = max; } else { maxcolor = GRASS_MAX_COLORS; CPLDebug( "GRASS", "Too many values, color table set to %d entries.", maxcolor ); } } poCT = new GDALColorTable(); for( int iColor = 0; iColor <= maxcolor; iColor++ ) { int nRed, nGreen, nBlue; GDALColorEntry sColor; #if GRASS_VERSION_MAJOR >= 7 if( Rast_get_c_color( &iColor, &nRed, &nGreen, &nBlue, &sGrassColors ) ) #else if( G_get_color( iColor, &nRed, &nGreen, &nBlue, &sGrassColors ) ) #endif { sColor.c1 = nRed; sColor.c2 = nGreen; sColor.c3 = nBlue; sColor.c4 = 255; poCT->SetColorEntry( iColor, &sColor ); } else { sColor.c1 = 0; sColor.c2 = 0; sColor.c3 = 0; sColor.c4 = 0; poCT->SetColorEntry( iColor, &sColor ); } } /* Create metadata enries for color table rules */ char key[200], value[200]; int rcount = G_colors_count ( &sGrassColors ); sprintf ( value, "%d", rcount ); this->SetMetadataItem( "COLOR_TABLE_RULES_COUNT", value ); /* Add the rules in reverse order */ for ( int i = rcount-1; i >= 0; i-- ) { DCELL val1, val2; unsigned char r1, g1, b1, r2, g2, b2; G_get_f_color_rule ( &val1, &r1, &g1, &b1, &val2, &r2, &g2, &b2, &sGrassColors, i ); sprintf ( key, "COLOR_TABLE_RULE_RGB_%d", rcount-i-1 ); sprintf ( value, "%e %e %d %d %d %d %d %d", val1, val2, r1, g1, b1, r2, g2, b2 ); this->SetMetadataItem( key, value ); } } else { this->SetMetadataItem( "COLOR_TABLE_RULES_COUNT", "0" ); } this->valid = true; }
/*! \brief Load raster map as integer map Calling function must have already allocated space in buff for wind->rows * wind->cols unsigned chars. This routine simply loads the map into a 2d array by repetitve calls to get_map_row. Since signs of chars can be tricky, we only load positive chars between 0-255. \todo fn body Gs_loadmap_as_float() \param wind current window \param map_name raster map name \param[out] buff data buffer \param[out] nullmap null map buffer \param[out] has_null indicates if raster map contains null-data \return 1 on success \return -1 on failure \return -2 if read ok, but 1 or more values were too large (small) to fit into an unsigned char. (in which case the max (min) char is used) */ int Gs_loadmap_as_char(struct Cell_head *wind, const char *map_name, unsigned char *buff, struct BM *nullmap, int *has_null) { FILEDESC cellfile; const char *map_set; char *nullflags; int *ti, *tmp_buf; int offset, row, col, val, max_char, overflow, charsize, bitplace; unsigned char *tc; G_debug(3, "Gs_loadmap_as_char"); overflow = 0; charsize = 8 * sizeof(unsigned char); /* 0 bits for sign! */ max_char = 1; for (bitplace = 0; bitplace < charsize; ++bitplace) { max_char *= 2; } max_char -= 1; map_set = G_find_cell2(map_name, ""); if (!map_set) { G_warning(_("Raster map <%s> not found"), map_name); return -1; } *has_null = 0; nullflags = G_allocate_null_buf(); /* G_fatal_error */ if (!nullflags) { G_fatal_error(_("Unable to allocate memory for a null buffer")); } if ((cellfile = G_open_cell_old(map_name, map_set)) == -1) { G_fatal_error(_("Unable to open raster map <%s>"), map_name); } tmp_buf = (int *)G_malloc(wind->cols * sizeof(int)); /* G_fatal_error */ if (!tmp_buf) { return -1; } G_message(_("Loading raster map <%s>..."), G_fully_qualified_name(map_name, map_set)); for (row = 0; row < wind->rows; row++) { offset = row * wind->cols; G_get_c_raster_row(cellfile, tmp_buf, row); G_get_null_value_row(cellfile, nullflags, row); tc = (unsigned char *)&(buff[offset]); ti = tmp_buf; G_percent(row, wind->rows, 2); for (col = 0; col < wind->cols; col++) { if (nullflags[col]) { *has_null = 1; BM_set(nullmap, col, row, 1); } else { val = *ti; if (val > max_char) { overflow = 1; *tc = (unsigned char)max_char; } else if (val < 0) { overflow = 1; *tc = 0; } else { *tc = (unsigned char)val; } } ti++; tc++; } } G_percent(1, 1, 1); G_close_cell(cellfile); G_free(tmp_buf); G_free(nullflags); return (overflow ? -2 : 1); }
int main( int argc, char **argv ) { struct GModule *module; struct Option *info_opt, *rast_opt, *vect_opt, *coor_opt; struct Cell_head window; /* Initialize the GIS calls */ G_gisinit( argv[0] ); module = G_define_module(); module->description = ( "Get info about locations,mapsets,maps" ); info_opt = G_define_option(); info_opt->key = "info"; info_opt->type = TYPE_STRING; info_opt->description = "info key"; info_opt->options = "proj,window,query"; rast_opt = G_define_standard_option( G_OPT_R_INPUT ); rast_opt->key = "rast"; rast_opt->required = NO; vect_opt = G_define_standard_option( G_OPT_V_INPUT ); vect_opt->key = "vect"; vect_opt->required = NO; coor_opt = G_define_option(); coor_opt->key = "coor"; coor_opt->type = TYPE_DOUBLE; coor_opt->multiple = YES; if ( G_parser( argc, argv ) ) exit( EXIT_FAILURE ); if ( strcmp( "proj", info_opt->answer ) == 0 ) { G_get_window( &window ); /* code from g.proj */ if ( window.proj != PROJECTION_XY ) { struct Key_Value *projinfo, *projunits; char *wkt; projinfo = G_get_projinfo(); projunits = G_get_projunits(); wkt = GPJ_grass_to_wkt( projinfo, projunits, 0, 0 ); fprintf( stdout, "%s", wkt ); } } else if ( strcmp( "window", info_opt->answer ) == 0 ) { if ( rast_opt->answer ) { G_get_cellhd( rast_opt->answer, "", &window ); fprintf( stdout, "%f,%f,%f,%f", window.west, window.south, window.east, window.north ); } else if ( vect_opt->answer ) { G_fatal_error( "Not yet supported" ); } } else if ( strcmp( "query", info_opt->answer ) == 0 ) { double x, y; int row, col; x = atof( coor_opt->answers[0] ); y = atof( coor_opt->answers[1] ); if ( rast_opt->answer ) { int fd; RASTER_MAP_TYPE rast_type; DCELL *dcell; CELL *cell; G_get_cellhd( rast_opt->answer, "", &window ); G_set_window( &window ); fd = G_open_cell_old( rast_opt->answer, "" ); col = ( int ) G_easting_to_col( x, &window ); row = ( int ) G_northing_to_row( y, &window ); if ( col == window.cols ) col--; if ( row == window.rows ) row--; if ( col < 0 || col > window.cols || row < 0 || row > window.rows ) { fprintf( stdout, "value:null\n" ); } else { void *ptr; double val; #if defined(GRASS_VERSION_MAJOR) && defined(GRASS_VERSION_MINOR) && \ ( ( GRASS_VERSION_MAJOR == 6 && GRASS_VERSION_MINOR > 2 ) || GRASS_VERSION_MAJOR > 6 ) rast_type = G_get_raster_map_type( fd ); #else rast_type = G_raster_map_type( rast_opt->answer, "" ); #endif cell = G_allocate_c_raster_buf(); dcell = G_allocate_d_raster_buf(); if ( rast_type == CELL_TYPE ) { if ( G_get_c_raster_row( fd, cell, row ) < 0 ) { G_fatal_error(( "Unable to read raster map <%s> row %d" ), rast_opt->answer, row ); } val = cell[col]; ptr = &( cell[col] ); } else { if ( G_get_d_raster_row( fd, dcell, row ) < 0 ) { G_fatal_error(( "Unable to read raster map <%s> row %d" ), rast_opt->answer, row ); } val = dcell[col]; ptr = &( dcell[col] ); } if ( G_is_null_value( ptr, rast_type ) ) { fprintf( stdout, "value:null\n" ); } else { fprintf( stdout, "value:%f\n", val ); } } G_close_cell( fd ); } else if ( vect_opt->answer ) { G_fatal_error( "Not yet supported" ); } } exit( EXIT_SUCCESS ); }
/* create the actual report */ void do_report_CELL ( char *map, char *mapset, char *sites, int precision, int null_flag, int uncat_flag, int all_flag, int quiet_flag, int skip_flag, char *logfile, int background, int gain, int show_progress) { CELL *cellbuf; struct Cell_head region; GT_Row_cache_t *cache; unsigned long row_idx, col_idx; int fd; unsigned long i,j,k; unsigned long no_sites; FILE *lp; unsigned long nrows, ncols; unsigned long *share_smp = NULL; /* array that keeps percentage of sites */ double total = 0; double map_total = 0; double kvamme_gain; long null_count = 0; /* keeps count of sites on NULL cells */ long nocat_count = 0; /* category counts and descriptions */ int cats; char **cats_description; /* category labels */ long *cat_count; /* category counts */ long null_count_map; /* number of NULL cells in input map */ long nocat_count_map; /* number of cells that do not fall into the category range [0 .. n] */ int debug_mode = 0; /* 1 to enable writing additional output to logfile */ time_t systime; char errmsg [200]; struct Map_info in_vect_map; struct line_pnts *vect_points; double x,y,z; int n_points = 1; int cur_type; /* get current region */ G_get_window (®ion); nrows = G_window_rows (); ncols = G_window_cols (); /* check logfile */ if (logfile != NULL) { debug_mode = 1; if ( !G_legal_filename (logfile) ) { delete_tmpfile (map); G_fatal_error ("Please specify a legal filename for the logfile.\n"); } /* attempt to write to logfile */ if ( (lp = fopen ( logfile, "w+" ) ) == NULL ) { delete_tmpfile (map); G_fatal_error ("Could not create logfile.\n"); } /* we want unbuffered output for the logfile */ setvbuf (lp,NULL,_IONBF,0); fprintf (lp,"This is %s, version %.2f\n",PROGNAME, PROGVERSION); systime = time (NULL); fprintf (lp,"Started on %s",ctime(&systime)); fprintf (lp,"\tlocation = %s\n",G_location()); fprintf (lp,"\tmapset = %s\n",G_mapset()); fprintf (lp,"\tinput map = %s\n",map); fprintf (lp,"\tsample file = %s\n",sites); } else { /* log output to stderr by default */ lp = stderr; } if (1 > Vect_open_old (&in_vect_map, sites, "")) { delete_tmpfile (map); sprintf (errmsg, "Could not open input map %s.\n", sites); G_fatal_error (errmsg); } vect_points = Vect_new_line_struct (); if (all_flag != 1) { Vect_set_constraint_region (&in_vect_map, region.north, region.south, region.east, region.west, 0.0, 0.0); } /* get total number of sampling points */ i = 0; while ((cur_type = Vect_read_next_line (&in_vect_map, vect_points, NULL) > 0)) { i ++; } no_sites = i; /* store this for later use */ /* open raster map */ fd = G_open_cell_old (map, G_find_cell (map, "")); if (fd < 0) { delete_tmpfile (map); G_fatal_error ("Could not open raster map for reading!\n"); } /* allocate a cache and a raster buffer */ cache = (GT_Row_cache_t *) G_malloc (sizeof (GT_Row_cache_t)); GT_RC_open (cache, CACHESIZE, fd, CELL_TYPE); cellbuf = G_allocate_raster_buf (CELL_TYPE); cats = GT_get_stats (map,mapset,&null_count_map, &nocat_count_map, show_progress); if ( cats < 2 ) { delete_tmpfile (map); G_fatal_error ("Input map must have at least two categories."); } /* get category labels and counts */ cats_description = GT_get_labels (map,mapset); if (cats_description == NULL) { delete_tmpfile (map); G_fatal_error ("Could not read category labels from input map."); } cat_count = GT_get_c_counts (map,mapset, show_progress); if (cat_count == NULL) { delete_tmpfile (map); G_fatal_error ("Could not count categories in input map."); } /* allocate a double array to hold statistics */ share_smp = (unsigned long *) G_malloc ((signed)(cats * sizeof (unsigned long))); for (i = 0; i < cats; i++) { share_smp[i] = 0; } /* count raster values under sampling points */ i = 0; k = 0; /* progress counter for status display */ Vect_rewind (&in_vect_map); if ( !quiet_flag ) { fprintf (stdout, "Counting sample: \n"); fflush (stdout); } /* we MUST not set constraints so that no raster values outside the current region are accessed, which would give an "illegal cache request" error */ Vect_set_constraint_region (&in_vect_map, region.north, region.south, region.east, region.west, 0.0, 0.0); while ((cur_type = Vect_read_next_line (&in_vect_map, vect_points, NULL) > 0)) { Vect_copy_pnts_to_xyz (vect_points, &x, &y, &z, &n_points); k ++; if ( !quiet_flag ) { G_percent ((signed) k, (signed) no_sites, 1); } /* get raster row with same northing as sample and perform quantification */ row_idx = (long) G_northing_to_row (y, ®ion); col_idx = (long) G_easting_to_col (x, ®ion); cellbuf = GT_RC_get (cache, (signed) row_idx); /* now read the raster value under the current site */ if (G_is_c_null_value (&cellbuf[col_idx]) == 0) { /* site on cell within category range [0..cats] ? */ if ( (cellbuf[col_idx] > -1) && (cellbuf[col_idx] <= cats) ) { share_smp [cellbuf[col_idx] ] ++; /* i keeps track of samples on non-null coverage only */ /* inside the current region */ i ++; } else { if ( uncat_flag ) { /* also keep count of sites on uncategorised cells? */ i ++; nocat_count++; } } } if (G_is_c_null_value (&cellbuf[col_idx]) == 1) { /* got a NULL value under this site */ if (null_flag) { /* only count this, if null flag is set */ null_count ++; i ++; } } } Vect_close (&in_vect_map); fprintf (lp,"\n"); if ( background ) { fprintf (lp,"Distribution of categories under %lu points (%lu in region) and in input map:\n",i,no_sites); } else { fprintf (lp,"Distribution of categories under %lu points (%lu in region):\n",i,no_sites); } /* determine starting value for total of sites analysed */ total = 0; for ( j=0; j < cats; j ++) { total = total + share_smp[j]; map_total = map_total + cat_count[j]; } if (null_flag) { /* add NULL values to total */ total = total + null_count; map_total = map_total + null_count_map; } if (uncat_flag) { /* add uncategorised cells to total */ total = total + nocat_count; map_total = map_total + nocat_count_map; } /* Now display those values which the user has chosen */ if ( (background) && (gain) ) { fprintf (lp,"Cat.\tPts.\t(%%)\tMap\t(%%)\tGain\tDescription\n"); } if ( (background) && (!gain) ) { fprintf (lp,"Cat.\tPts.\t(%%)\tMap\t(%%)\tDescription\n"); } if ( (!background) && (gain) ) { fprintf (lp,"Cat.\tPts.\t(%%)\tGain\tDescription\n"); } if ( (!background) && (!gain) ) { fprintf (lp,"Cat.\tPts.\t(%%)\tDescription\n"); } for ( j = 0; j < cats; j ++) { /* if skip_flag is not set: only show categories that have count > 0 */ if ((skip_flag == 1) || ((skip_flag == 0) && (share_smp[j] > 0))) { if ( (background) && (gain) ) { /* Kvamme's Gain = 1 - (%area/%sites) */ kvamme_gain = gstats_gain_K(((double) share_smp[j]*(100/total)), ((double) cat_count[j]*(100/map_total))); fprintf (lp, "%lu\t%6lu\t%6.2f\t%8lu %6.2f\t%6.2f\t%s\n", j, share_smp[j], (float) share_smp[j]*(100/total), cat_count[j], (float) cat_count[j]*(100/map_total), kvamme_gain, cats_description[j]); } if ( (background) && (!gain) ) { fprintf (lp, "%lu\t%6lu\t%6.2f\t%8lu %6.2f\t%s\n", j, share_smp[j], (float) share_smp[j]*(100/total), cat_count[j], (float) cat_count[j]*(100/map_total), cats_description[j]); } if ( (!background) && (gain) ) { kvamme_gain = 1-( (float) cat_count[j]*(100/map_total) / (float) share_smp[j]*(100/total) ); fprintf (lp, "%lu\t%6lu\t%6.2f\t%6.2f\t%s\n", j, share_smp[j], (float) share_smp[j]*(100/total), kvamme_gain, cats_description[j]); } if ( (!background) && (!gain) ) { fprintf (lp, "%lu\t%6lu\t%6.2f\t%s\n", j, share_smp[j], (float) share_smp[j]*(100/total), cats_description[j]); } } } if (null_flag) { if ( background ) { fprintf (lp,"NULL\t%6lu\t%6.2f\t%8lu %6.2f\n",null_count, (float) null_count * 100 / total ,null_count_map, (float) null_count_map * 100 / map_total); } else { fprintf (lp,"NULL\t%6lu\t%6.2f\n",null_count, (float) null_count * 100 / total); } } if (uncat_flag) { if ( background ) { fprintf (lp,"NOCAT\t%6lu\t%6.2f\t%8lu %6.2f\n",nocat_count, (float) nocat_count * 100 / total ,nocat_count_map, (float) nocat_count_map * 100 / map_total); } else { fprintf (lp,"NOCAT\t%6lu\t%6.2f\n",nocat_count, (float) nocat_count * 100 / total); } } if ( background) { fprintf (lp,"TOTAL\t%6lu\t%6.2f\t%8lu %6.2f\n",(long) total, (float) 100, (long) map_total, (float) 100); } else { fprintf (lp,"TOTAL\t%6lu\t%6.2f\n",(long) total, (float) 100); } /* close cache and sites file; free buffers. */ GT_RC_close (cache); G_free (cellbuf); G_free (cache); }