Ejemplo n.º 1
0
void Segment_outfile (char* map_name, char* mapset, int* map_fd,
		         char* seg_name, int* seg_fd, SEGMENT* seg, char* prompt, int fract,
                 RASTER_MAP_TYPE data_type)
{
    int nrows;
    char* mapset_address;

    mapset_address = G_ask_cell_new (prompt, map_name);
    
	if (mapset_address == NULL)
	  G_fatal_error ("Can't continue without filename ");
	
    strcpy (mapset, mapset_address);
    
	if ((*map_fd = G_open_cell_new (map_name)) < 0)
	  G_fatal_error ("Can't create output layer ");

    nrows = G_window_rows ();
    strcpy (seg_name, Create_segment_file (nrows, fract, data_type));
    *seg_fd = open (seg_name, 2);
    
	if (*seg_fd < 0)
	  G_fatal_error ("Can't open segment disk file ");
	
    segment_init (seg, *seg_fd, 4);
}
Ejemplo n.º 2
0
int bseg_write_cellfile(BSEG * bseg, char *map_name)
{
    int map_fd;
    int row, nrows;
    int col, ncols;
    CELL *buffer;
    CELL value;

    map_fd = G_open_cell_new(map_name);
    if (map_fd < 0) {
	G_warning("%s(): unable to open new map layer [%s]", me, map_name);
	return -1;
    }
    nrows = G_window_rows();
    ncols = G_window_cols();
    buffer = G_allocate_cell_buf();
    for (row = 0; row < nrows; row++) {
	for (col = 0; col < ncols; col++) {
	    bseg_get(bseg, &value, row, col);
	    buffer[col] = value;
	}
	if (G_put_raster_row(map_fd, buffer, CELL_TYPE) < 0) {
	    G_free(buffer);
	    G_unopen_cell(map_fd);
	    G_warning("%s(): unable to write new map layer [%s], row %d",
		      me, map_name, row);
	    return -2;
	}
    }
    G_free(buffer);
    G_close_cell(map_fd);
    return 0;
}
Ejemplo n.º 3
0
/* 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 */
    }
	
}
Ejemplo n.º 4
0
int gaussurf(char *out,		/* Name of raster maps to be opened.    */
	     double mean, double sigma	/* Distribution parameters.             */
    )
{
    int nrows, ncols;		/* Number of cell rows and columns      */

    DCELL *row_out;		/* Buffer just large enough to hold one */

    /* row of the raster map layer.         */

    int fd_out;			/* File descriptor - used to identify   */

    /* open raster maps.                    */
    struct History history;	/* cmd line history metadata            */

    int row_count, col_count;

	/****** INITIALISE RANDOM NUMBER GENERATOR ******/

    G_math_rand(-1 * getpid());

	/****** OPEN CELL FILES AND GET CELL DETAILS ******/

    fd_out = G_open_raster_new(out, DCELL_TYPE);

    nrows = G_window_rows();
    ncols = G_window_cols();

    row_out = G_allocate_d_raster_buf();


	/****** PASS THROUGH EACH CELL ASSIGNING RANDOM VALUE ******/

    for (row_count = 0; row_count < nrows; row_count++) {
	for (col_count = 0; col_count < ncols; col_count++)
	    *(row_out + col_count) =
		(DCELL) (G_math_rand_gauss(2742, sigma) + mean);

	/* Write contents row by row */
	G_put_d_raster_row(fd_out, (DCELL *) row_out);
    }


	/****** CLOSE THE CELL FILE ******/

    G_close_cell(fd_out);
    G_short_history(out, "raster", &history);
    G_command_history(&history);
    G_write_history(out, &history);

    return 0;
}
Ejemplo n.º 5
0
void Segment_tmpfile (char* seg_name, int* seg_fd, SEGMENT* seg, int fract, 
                 RASTER_MAP_TYPE data_type)
{
    int nrows;

    nrows = G_window_rows ();

    strcpy (seg_name, Create_segment_file (nrows, fract, data_type));
    *seg_fd = open (seg_name, O_RDWR);
    if (*seg_fd < 0)
	G_fatal_error ("Can't open segment disk file ");
	
	/* get a handle to read segment file data values */
	/* dimensions of segment and size of stored items are read */
	/* automatically from the file header and stored in 'seg' */
    segment_init (seg, *seg_fd, 4);
}
Ejemplo n.º 6
0
/* 
 * 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;
}
Ejemplo n.º 7
0
void Segment_named_outfile (char* map_name, char* mapset, int* map_fd,
			           char* seg_name, int* seg_fd, SEGMENT* seg, int overwrite, 
                       int terse, int fract, RASTER_MAP_TYPE data_type)
{
    int nrows;
    char* mapset_address;
    char message [64];

    mapset_address = G_find_cell (map_name, G_mapset ());
    strcpy (mapset, G_mapset ());
    if (mapset_address != NULL)
    {
      if (!overwrite)
	{
	  sprintf (message, "Raster map '%s' exists ", map_name);
	  G_fatal_error ("%s",message);
	}
      else
	{
	  if (!terse)
	    fprintf (stdout, "\nOverwriting raster map '%s' \n", map_name);
	}
    }
    else
      {
	if (!terse)
	  fprintf (stdout, "\nCreating raster map '%s' ", map_name);
      }

    if ((*map_fd = G_open_cell_new (map_name)) < 0)
	  G_fatal_error ("Can't create output layer ");

    nrows = G_window_rows ();
    
    strcpy (seg_name, Create_segment_file (nrows, fract, data_type));
    
    *seg_fd = open (seg_name, O_RDWR);
	
    if (*seg_fd < 0)
	  G_fatal_error ("Can't open segment disk file ");
	
    segment_init (seg, *seg_fd, 4);
}
Ejemplo n.º 8
0
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;
}
Ejemplo n.º 9
0
/* get maximum distance to sites in *map for all raster cells in current region */
double get_max_distance_region ( GVT_map_s *map ) {
	struct Cell_head window;
	
	int row, col;
	int nrows, ncols;
	double x, y;

	double dist, max_dist;
	
	G_get_window (&window);
    	nrows = G_window_rows ();
	ncols = G_window_cols ();	
		
	if ( PROGRESS ) {
		fprintf ( stdout, " Finding maximum distance for all centers.\n" );
		fflush ( stdout );
	}
		
	max_dist = 0.0;
	for (row=0; row < nrows; row ++) {
		y = G_row_to_northing ( (double) row, &window );
		for (col=0; col < ncols; col ++) {
			x = G_col_to_easting ( (double) col, &window );
			/* TODO: bottle neck: implement coordinate caching in gt_vector.c */
			GVT_rewind ( map );
			while ( GVT_next ( map ) ) {
				dist = GVT_get_2D_point_distance ( x, y, map );
				if ( dist > max_dist ) {
					max_dist = dist;
				}	
			}				
		}
		if ( PROGRESS ) {
			G_percent (row, (nrows-1), 2);
			fflush ( stdout );
		}				
	}
	
	return ( max_dist );
}
Ejemplo n.º 10
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 );
}
Ejemplo n.º 11
0
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;
}
Ejemplo n.º 12
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;
}
Ejemplo n.º 13
0
int main(int argc, char *argv[])
{
    char *input;
    char *output;
    char *title;
    FILE *fd;
    int cf;
    struct Cell_head cellhd;
    CELL *cell;
    FCELL *fcell;
    DCELL *dcell;
    int row, col;
    int nrows, ncols;
    static int missingval;
    int rtype;
    double mult_fact;
    double x;
    struct GModule *module;
    struct History history;
    struct
    {
	struct Option *input, *output, *type, *title, *mult;
    } parm;


    G_gisinit(argv[0]);

    module = G_define_module();
    module->keywords = _("raster, import");
    module->description =
	_("Converts an ESRI ARC/INFO ascii raster file (GRID) "
	  "into a (binary) raster map layer.");

    parm.input = G_define_option();
    parm.input->key = "input";
    parm.input->type = TYPE_STRING;
    parm.input->required = YES;
    parm.input->description =
	_("ARC/INFO ASCII raster file (GRID) to be imported");
    parm.input->gisprompt = "old_file,file,input";

    parm.output = G_define_standard_option(G_OPT_R_OUTPUT);

    parm.type = G_define_option();
    parm.type->key = "type";
    parm.type->type = TYPE_STRING;
    parm.type->required = NO;
    parm.type->options = "CELL,FCELL,DCELL";
    parm.type->answer = "FCELL";
    parm.type->description = _("Storage type for resultant raster map");

    parm.title = G_define_option();
    parm.title->key = "title";
    parm.title->key_desc = "\"phrase\"";
    parm.title->type = TYPE_STRING;
    parm.title->required = NO;
    parm.title->description = _("Title for resultant raster map");

    parm.mult = G_define_option();
    parm.mult->key = "mult";
    parm.mult->type = TYPE_DOUBLE;
    parm.mult->answer = "1.0";
    parm.mult->required = NO;
    parm.mult->description = _("Multiplier for ASCII data");

    if (G_parser(argc, argv))
	exit(EXIT_FAILURE);
    input = parm.input->answer;
    output = parm.output->answer;
    if (title = parm.title->answer)
	G_strip(title);

    sscanf(parm.mult->answer, "%lf", &mult_fact);
    if (strcmp("CELL", parm.type->answer) == 0)
	rtype = CELL_TYPE;
    else if (strcmp("DCELL", parm.type->answer) == 0)
	rtype = DCELL_TYPE;
    else
	rtype = FCELL_TYPE;

    if (strcmp("-", input) == 0) {
	Tmp_file = G_tempfile();
	if (NULL == (Tmp_fd = fopen(Tmp_file, "w+")))
	    G_fatal_error(_("Unable to open temporary file <%s>"), Tmp_file);
	unlink(Tmp_file);
	if (0 > file_cpy(stdin, Tmp_fd))
	    exit(EXIT_FAILURE);
	fd = Tmp_fd;
    }
    else
	fd = fopen(input, "r");

    if (fd == NULL)
	G_fatal_error(_("Unable to open input file <%s>"), input);

    if (!gethead(fd, &cellhd, &missingval))
	G_fatal_error(_("Can't get cell header"));

    nrows = cellhd.rows;
    ncols = cellhd.cols;
    if (G_set_window(&cellhd) < 0)
	G_fatal_error(_("Can't set window"));

    if (nrows != G_window_rows())
	G_fatal_error(_("OOPS: rows changed from %d to %d"), nrows,
		      G_window_rows());
    if (ncols != G_window_cols())
	G_fatal_error(_("OOPS: cols changed from %d to %d"), ncols,
		      G_window_cols());

    switch (rtype) {
    case CELL_TYPE:
	cell = G_allocate_c_raster_buf();
	break;
    case FCELL_TYPE:
	fcell = G_allocate_f_raster_buf();
	break;
    case DCELL_TYPE:
	dcell = G_allocate_d_raster_buf();
	break;
    }
    cf = G_open_raster_new(output, rtype);
    if (cf < 0)
	G_fatal_error(_("Unable to create raster map <%s>"), output);

    for (row = 0; row < nrows; row++) {
	G_percent(row, nrows, 5);
	for (col = 0; col < ncols; col++) {
	    if (fscanf(fd, "%lf", &x) != 1) {
		G_unopen_cell(cf);
		G_fatal_error(_("Data conversion failed at row %d, col %d"),
			      row + 1, col + 1);
	    }
	    switch (rtype) {
	    case CELL_TYPE:
		if ((int)x == missingval)
		    G_set_c_null_value(cell + col, 1);
		else
		    cell[col] = (CELL) x *mult_fact;

		break;
	    case FCELL_TYPE:
		if ((int)x == missingval)
		    G_set_f_null_value(fcell + col, 1);
		else
		    fcell[col] = (FCELL) x *mult_fact;

		break;
	    case DCELL_TYPE:
		if ((int)x == missingval)
		    G_set_d_null_value(dcell + col, 1);
		else
		    dcell[col] = (DCELL) x *mult_fact;

		break;
	    }
	}
	switch (rtype) {
	case CELL_TYPE:
	    G_put_c_raster_row(cf, cell);
	    break;
	case FCELL_TYPE:
	    G_put_f_raster_row(cf, fcell);
	    break;
	case DCELL_TYPE:
	    G_put_d_raster_row(cf, dcell);
	    break;
	}
    }
    /* G_message(_("CREATING SUPPORT FILES FOR %s"), output); */
    G_close_cell(cf);
    if (title)
	G_put_cell_title(output, title);
    G_short_history(output, "raster", &history);
    G_command_history(&history);
    G_write_history(output, &history);


    exit(EXIT_SUCCESS);
}
Ejemplo n.º 14
0
int main(int argc, char *argv[])
{
    /* Global variable & function declarations */
    char Cellmap_orig[50];
    FILE *realfp, *imagfp;	/* the input and output file descriptors */
    int outputfd, maskfd;	/* the input and output file descriptors */
    char *realmapset, *imagmapset;	/* the input mapset names */
    struct Cell_head orig_wind, realhead;
    CELL *cell_row, *maskbuf = NULL;

    int i, j;			/* Loop control variables */
    int or, oc;			/* Original dimensions of image */
    int rows, cols;		/* Smallest powers of 2 >= number of rows & columns */
    long totsize;		/* Total number of data points */
    int halfrows, halfcols;
    double *data[2];		/* Data structure containing real & complex values of FFT */
    struct Option *op1, *op2, *op3;
    struct GModule *module;

    G_gisinit(argv[0]);

    /* Set description */
    module = G_define_module();
    module->keywords = _("imagery, FFT");
    module->description =
	_("Inverse Fast Fourier Transform (IFFT) for image processing.");

    /* define options */
    op1 = G_define_standard_option(G_OPT_R_INPUT);
    op1->key = "real_image";
    op1->description = _("Name of input raster map (image fft, real part)");

    op2 = G_define_standard_option(G_OPT_R_INPUT);
    op2->key = "imaginary_image";
    op2->description = _("Name of input raster map (image fft, imaginary part");

    op3 = G_define_standard_option(G_OPT_R_OUTPUT);
    op3->key = "output_image";
    op3->description = _("Name for output raster map");

    /*call parser */
    if (G_parser(argc, argv))
	exit(EXIT_FAILURE);

    strcpy(Cellmap_real, op1->answer);
    strcpy(Cellmap_imag, op2->answer);
    strcpy(Cellmap_orig, op3->answer);

    /* open input raster map */
    if ((realmapset = G_find_cell(Cellmap_real, "")) == NULL)
	G_fatal_error(_("Raster map <%s> not found"),
		      Cellmap_real);

    if ((realfp =
	 G_fopen_old_misc("cell_misc", "fftreal", Cellmap_real,
			  realmapset)) == NULL)
	G_fatal_error(_("Unable to open real-image in the 'cell_misc' directory. "
			"Raster map probably wasn't created by i.fft"));

    if ((imagmapset = G_find_cell(Cellmap_imag, "")) == NULL)
	G_fatal_error(_("Raster map <%s> not found"),
		      Cellmap_imag);

    if ((imagfp =
	 G_fopen_old_misc("cell_misc", "fftimag", Cellmap_imag,
			  imagmapset)) == NULL)
	G_fatal_error(_("Unable to open imaginary-image in the 'cell_misc' directory. "
			"Raster map probably wasn't created by i.fft"));

    /* check command line args for validity */
    if (G_legal_filename(Cellmap_orig) < 0)
	G_fatal_error(_("<%s> is an illegal file name"),
		      Cellmap_orig);

    /* get and compare the original window data */
    get_orig_window(&orig_wind, realmapset, imagmapset);

    or = orig_wind.rows;
    oc = orig_wind.cols;
    G_get_cellhd(Cellmap_real, realmapset, &realhead);
    G_set_window(&realhead);	/* set the window to the whole cell map */

    /* get the rows and columns in the current window */
    rows = G_window_rows();
    cols = G_window_cols();
    totsize = rows * cols;
    halfrows = rows / 2;
    halfcols = cols / 2;

    G_verbose_message(_("Power 2 values: %d rows %d columns"), rows, cols);

    /* Allocate appropriate memory for the structure containing
       the real and complex components of the FFT.  DATA[0] will
       contain the real, and DATA[1] the complex component.
     */
    data[0] = (double *)G_malloc((rows * cols) * sizeof(double));
    data[1] = (double *)G_malloc((rows * cols) * sizeof(double));

    /* Initialize real & complex components to zero */
    G_message(_("Reading raster maps..."));
    {
	fread((char *)data[0], sizeof(double), totsize, realfp);
	fread((char *)data[1], sizeof(double), totsize, imagfp);
    }

    /* Read in cell map values */
    G_message(_("Masking raster maps..."));
    maskfd = G_maskfd();
    if (maskfd >= 0)
	maskbuf = G_allocate_cell_buf();

    if (maskfd >= 0) {
	for (i = 0; i < rows; i++) {
	    double *data0, *data1;

	    data0 = data[0] + i * cols;
	    data1 = data[1] + i * cols;
	    G_get_map_row(maskfd, maskbuf, i);
	    for (j = 0; j < cols; j++, data0++, data1++) {
		if (maskbuf[j] == (CELL) 0) {
		    *(data0) = 0.0;
		    *(data1) = 0.0;
		}
	    }
	}
    }

    G_message(_("Rotating data..."));
    /* rotate the data array for standard display */
    for (i = 0; i < rows; i++) {
	double temp;

	for (j = 0; j < halfcols; j++) {
	    temp = *(data[0] + i * cols + j);
	    *(data[0] + i * cols + j) = *(data[0] + i * cols + j + halfcols);
	    *(data[0] + i * cols + j + halfcols) = temp;
	    temp = *(data[1] + i * cols + j);
	    *(data[1] + i * cols + j) = *(data[1] + i * cols + j + halfcols);
	    *(data[1] + i * cols + j + halfcols) = temp;
	}
    }
    for (i = 0; i < halfrows; i++) {
	double temp;

	for (j = 0; j < cols; j++) {
	    temp = *(data[0] + i * cols + j);
	    *(data[0] + i * cols + j) =
		*(data[0] + (i + halfrows) * cols + j);
	    *(data[0] + (i + halfrows) * cols + j) = temp;
	    temp = *(data[1] + i * cols + j);
	    *(data[1] + i * cols + j) =
		*(data[1] + (i + halfrows) * cols + j);
	    *(data[1] + (i + halfrows) * cols + j) = temp;
	}
    }


    /* close input cell maps and release the row buffers */
    fclose(realfp);
    fclose(imagfp);
    if (maskfd >= 0) {
	G_close_cell(maskfd);
	G_free(maskbuf);
    }

    /* perform inverse FFT */
    G_message(_("Starting Inverse FFT..."));
    fft(1, data, totsize, cols, rows);

    /* set up a window for the transform cell map */
    G_set_window(&orig_wind);

    /* open the output cell map and allocate a cell row buffer */
    if ((outputfd = G_open_cell_new(Cellmap_orig)) < 0)
	G_fatal_error(_("Unable to create raster map <%s>"),
		      Cellmap_orig);

    cell_row = G_allocate_cell_buf();

    /* Write out result to a new cell map */
    G_message(_("Writing data..."));
    for (i = 0; i < or; i++) {
	for (j = 0; j < oc; j++) {
	    *(cell_row + j) = (CELL) (*(data[0] + i * cols + j) + 0.5);
	}
	G_put_raster_row(outputfd, cell_row, CELL_TYPE);

	G_percent(i+1, or, 2);
    }
    G_close_cell(outputfd);

    G_free(cell_row);
    {
	struct Colors colors;
	struct Range range;
	CELL min, max;

	/* make a real component color table */
	G_read_range(Cellmap_orig, G_mapset(), &range);
	G_get_range_min_max(&range, &min, &max);
	G_make_grey_scale_colors(&colors, min, max);
	G_write_colors(Cellmap_orig, G_mapset(), &colors);
    }

    /* Release memory resources */
    G_free(data[0]);
    G_free(data[1]);

    G_done_msg(" ");

    exit(EXIT_SUCCESS);
}
Ejemplo n.º 15
0
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 );
}
Ejemplo n.º 16
0
int main(int argc, char **argv)
{
    long i;
    int band, rows, cols;
    CELL *rowbuffer[3];
    struct Option *opt_hue, *opt_red;
    struct Option *opt_inten, *opt_green;
    struct Option *opt_sat, *opt_blue;
    struct GModule *module;
    int fd_input[3];
    int fd_output[3];

    /* Initialize GIS engine */
    G_gisinit(argv[0]);

    /* Set description */
    module = G_define_module();
    module->keywords = _("imagery, color transformation, RGB, HIS");
    module->description =
	_("Transforms raster maps from RGB (Red-Green-Blue) color space to "
	  "HIS (Hue-Intensity-Saturation) color space.");

    /* Define the different options */
    opt_red = G_define_standard_option(G_OPT_R_INPUT);
    opt_red->key = "red_input";
    opt_red->description = _("Name of input raster map (red)");

    opt_green = G_define_standard_option(G_OPT_R_INPUT);
    opt_green->key = "green_input";
    opt_green->description = _("Name of input raster map (green)");

    opt_blue = G_define_standard_option(G_OPT_R_INPUT);
    opt_blue->key = "blue_input";
    opt_blue->description = _("Name of input raster map (blue)");

    opt_hue = G_define_standard_option(G_OPT_R_OUTPUT);
    opt_hue->key = "hue_output";
    opt_hue->description = _("Name for output raster map (hue)");

    opt_inten = G_define_standard_option(G_OPT_R_OUTPUT);
    opt_inten->key = "intensity_output";
    opt_inten->description = _("Name for output raster map (intensity)");

    opt_sat = G_define_standard_option(G_OPT_R_OUTPUT);
    opt_sat->key = "saturation_output";
    opt_sat->description = _("Name for output raster map (saturation)");

    if (G_parser(argc, argv))
	exit(EXIT_FAILURE);


    /* get dimension of the image */
    rows = G_window_rows();
    cols = G_window_cols();

    openfiles(opt_red->answer, opt_green->answer, opt_blue->answer,
	      opt_hue->answer, opt_inten->answer, opt_sat->answer,
	      fd_input, fd_output, rowbuffer);

    for (i = 0; i < rows; i++) {
	/* read in a row from each cell map */
	G_percent(i, rows, 2);

	for (band = 0; band < 3; band++)
	    if (G_get_map_row(fd_input[band], rowbuffer[band], i) < 0)
		G_fatal_error(_("Unable to read raster map row %ld"), i);

	/* process this row of the map */
	rgb2his(rowbuffer, cols);

	/* write out the new row for each cell map */
	for (band = 0; band < 3; band++)
	    if (G_put_raster_row(fd_output[band], rowbuffer[band], CELL_TYPE)
		< 0)
		G_fatal_error(_("Failed writing raster map row %ld"), i);
    }
    G_percent(i, rows, 2);

    closefiles(opt_hue->answer, opt_inten->answer, opt_sat->answer,
	       fd_output, rowbuffer);


    exit(EXIT_SUCCESS);
}
Ejemplo n.º 17
0
/* NULL cell handling added by Benjamin Ducke, May 2004 */
void Close_segmented_outfile (char* map_name, int map_fd,
			             char* seg_name, int seg_fd, SEGMENT* seg, 
                         CELL* cell_buf, int terse,
                         SEGMENT* elevation_seg, RASTER_MAP_TYPE data_type, int make_nulls)
{
  unsigned long row, nrows, col, ncols;
  void *value = NULL;
  char *null_flags;
  /* the following are used to store different raster map types */
  CELL c_value;
  FCELL f_value;
  DCELL d_value;  	

	
  /* Find number of rows and columns in elevation map */
  nrows = G_window_rows();
  ncols = G_window_cols();
	
  /* allocate memory for a NULL data row */	
  null_flags = G_calloc ((unsigned) ncols, sizeof (char));
    
  /* Write pending updates by segment_put() to output map */
  segment_flush(seg);
  
  if (!terse) {	
    fprintf (stdout, "\nWriting raster map '%s': \n", map_name);	
  }
	
  /* Convert output submatrices to full cell overlay */
  for(row=0; row< nrows; row++) {
    segment_get_row(seg, cell_buf, (signed) row);
	/* check for NULL values in the corresponding row of the */
	/* elevation input file. If there are any, set the CELLs */
	/* in the output file to NULL, as well */
	
	/* initialize null data row */
	for (col=0; col<ncols; col++) {
		null_flags[col] = 0;
	}
	
	/* convert all -1 cells to NULL, if user wants it so */
    if ( make_nulls == 1 ) {
	    for (col=0; col<ncols; col++) {
		   if ( cell_buf[col] == -1 ) {
		     null_flags[col] = 1;
		   }
		}
	}
	
	/* update NULL flags in row */
    for (col=0; col<ncols; col++) {
		if ( data_type == CELL_TYPE ) {
		    value = (CELL*) &c_value;
		}		  
		if ( data_type == FCELL_TYPE ) {
		    value = (FCELL*) &f_value;
		}		  
		if ( data_type == DCELL_TYPE ) {
		    value = (DCELL*) &d_value;
		}
		
        segment_get (elevation_seg, value, (signed) row, (signed) col);
		
		/* check for NULL value and record in null_flags row */
		if ( data_type == CELL_TYPE ) {
		    if (G_is_c_null_value (&c_value) ) {
			  null_flags[col] = 1; /* signal NULL value in null_flags row */
			}			
		}		  
		if ( data_type == FCELL_TYPE ) {
		    if (G_is_f_null_value (&f_value) ) {
			  null_flags[col] = 1; /* signal NULL value in null_flags row */
			}
		}		  
		if ( data_type == DCELL_TYPE ) {
		    if (G_is_d_null_value (&d_value) ) {
			  null_flags[col] = 1; /* signal NULL value in null_flags row */
			}						
		}
	}
    /* set all NULL cells according to null_flags row */
	G_insert_c_null_values (cell_buf, null_flags, (signed) ncols);
	
	/* now, write this row to disk */  
    if(G_put_raster_row (map_fd, cell_buf, CELL_TYPE) < 0) {
	  G_fatal_error ("Failed to convert output submatrices ");	  
	}
	
	/* progress display */
	if (! terse) {
		G_percent ((signed) row, (signed) nrows-1,2);
	}	
  }
  
  G_free (null_flags);
  
/* Close files */
  segment_release (seg);
  close (seg_fd);
  unlink (seg_name);
  G_close_cell (map_fd);
}
Ejemplo n.º 18
0
/* 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 (&region);
	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, &region);
		col_idx = (long) G_easting_to_col (x, &region);				
				
		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);	
}
Ejemplo n.º 19
0
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);
}
Ejemplo n.º 20
0
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;
}
Ejemplo n.º 21
0
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);
}
Ejemplo n.º 22
0
int main(int argc, char *argv[])
{
    int out_fd;
    CELL *result, *rp;
    int nrows, ncols;
    int row, col;
    struct GModule *module;
    struct Option *in_opt, *out_opt;
    struct Option *method_opt, *size_opt;
    char *mapset;
    struct Map_info In;
    double radius;
    struct ilist *List;
    struct Cell_head region;
    BOUND_BOX box;
    struct line_pnts *Points;
    struct line_cats *Cats;

    G_gisinit(argv[0]);

    module = G_define_module();
    module->keywords = _("vector, raster, aggregation");
    module->description = "Makes each cell value a "
	"function of the attribute values assigned to the vector points or centroids "
	"around it, and stores new cell values in an output raster map layer.";

    in_opt = G_define_standard_option(G_OPT_V_INPUT);
    out_opt = G_define_standard_option(G_OPT_R_OUTPUT);

    method_opt = G_define_option();
    method_opt->key = "method";
    method_opt->type = TYPE_STRING;
    method_opt->required = YES;
    method_opt->options = "count";
    method_opt->answer = "count";
    method_opt->description = "Neighborhood operation";

    size_opt = G_define_option();
    size_opt->key = "size";
    size_opt->type = TYPE_DOUBLE;
    size_opt->required = YES;
    size_opt->description = "Neighborhood diameter in map units";

    if (G_parser(argc, argv))
	exit(EXIT_FAILURE);

    radius = atof(size_opt->answer) / 2;

    /* open input vector */
    if ((mapset = G_find_vector2(in_opt->answer, "")) == NULL) {
	G_fatal_error(_("Vector map <%s> not found in the current mapset"),
		      in_opt->answer);
    }

    Vect_set_open_level(2);
    Vect_open_old(&In, in_opt->answer, mapset);

    G_get_set_window(&region);
    nrows = G_window_rows();
    ncols = G_window_cols();

    result = G_allocate_raster_buf(CELL_TYPE);
    Points = Vect_new_line_struct();
    Cats = Vect_new_cats_struct();
    List = Vect_new_list();

    /*open the new cellfile */
    out_fd = G_open_raster_new(out_opt->answer, CELL_TYPE);
    if (out_fd < 0)
	G_fatal_error(_("Unable to create raster map <%s>"), out_opt->answer);

    box.T = PORT_DOUBLE_MAX;
    box.B = -PORT_DOUBLE_MAX;

    for (row = 0; row < nrows; row++) {
	double x, y;

	G_percent(row, nrows, 1);

	y = G_row_to_northing(row + 0.5, &region);
	box.N = y + radius;
	box.S = y - radius;

	G_set_null_value(result, ncols, CELL_TYPE);
	rp = result;

	for (col = 0; col < ncols; col++) {
	    int i, count;
	    CELL value;

	    x = G_col_to_easting(col + 0.5, &region);

	    box.E = x + radius;
	    box.W = x - radius;

	    Vect_select_lines_by_box(&In, &box, GV_POINTS, List);
	    G_debug(3, "  %d lines in box", List->n_values);

	    count = 0;

	    for (i = 0; i < List->n_values; i++) {
		double distance;

		Vect_read_line(&In, Points, Cats, List->value[i]);
		distance =
		    Vect_points_distance(x, y, 0.0, Points->x[0],
					 Points->y[0], 0.0, 0);

		if (distance <= radius) {
		    count++;
		}
	    }

	    if (count > 0) {
		value = count;
		G_set_raster_value_d(rp, value, CELL_TYPE);
	    }
	    rp = G_incr_void_ptr(rp, G_raster_size(CELL_TYPE));
	}

	G_put_raster_row(out_fd, result, CELL_TYPE);
    }
    G_percent(row, nrows, 1);

    Vect_close(&In);
    G_close_cell(out_fd);

    exit(EXIT_SUCCESS);
}
Ejemplo n.º 23
0
int
main (int argc, char *argv[])
{
	struct GModule *module;
	struct
	{
		struct Option *input; /* name of input site map */
		struct Option *output; /* name of output site map */
		struct Option *type;
		struct Option *where;
		struct Option *size; /* size of sample (%input) */
		struct Option *map; /* optional raster to check for NULL */
		struct Option *cachesize;
	}
	parm;
	struct
	{
		struct Flag *quiet;
		struct Flag *all; /* disregard region settings */	
	}
	flag;
	int processing_mode = 0;
	int vect_types;

	/* setup some basic GIS stuff */
	G_gisinit (argv[0]);
	module = G_define_module ();
	module->description = "Generates a random sample from a map of vector objects";
	/* do not pause after a warning message was displayed */
	G_sleep_on_error (0);

	
	/* Module Parameters: */
	
	parm.input = G_define_standard_option (G_OPT_V_INPUT);
	parm.input->key = "input";
	parm.input->type = TYPE_STRING;
	parm.input->required = YES;
	parm.input->description = "Vector map to draw sample from";
	
	/* name of output map */
	parm.output = G_define_standard_option (G_OPT_V_OUTPUT);
	parm.output->key = "output";
	parm.output->type = TYPE_STRING;
	parm.output->required = YES;
	parm.output->description = "Vector map to store random sample in";
	
	/* type of objects */
	parm.type = G_define_standard_option (G_OPT_V_TYPE);
	
	/* filter objects by sql statement */
	parm.where = G_define_standard_option (G_OPT_WHERE);

	/* percentage of input objects to include for random sample */
	parm.size = G_define_option ();
	parm.size->key = "size";
	parm.size->type = TYPE_DOUBLE;
	parm.size->required = YES;
	parm.size->description = "Size of the sample (% of input vector objects)";
	parm.size->options = "0-100";

	/* map = an optional raster map. Samples will not be generated */
	/*       in cells where this map fprintf (stderr, "HI\n");is NULL */
	parm.map = G_define_standard_option (G_OPT_R_INPUT);
	parm.map->key = "raster";
	parm.map->type = TYPE_STRING;
	parm.map->required = NO;
	parm.map->description = "Sampling cannot be done on NULL cells in this raster map";
	
	/* number of lines to store in cache */
	parm.cachesize = G_define_option ();
	parm.cachesize->key = "cachesize";
	parm.cachesize->type = TYPE_INTEGER;
	parm.cachesize->answer = "-1";
	parm.cachesize->required = NO;
	parm.cachesize->description = "Number of raster rows to store in cache (-1 for auto)";
	
	flag.all = G_define_flag ();
	flag.all->key = 'a';
	flag.all->description = "Sample outside the current region's limits";

	flag.quiet = G_define_flag ();
	flag.quiet->key = 'q';
	flag.quiet->description = "Quiet operation: no progress display";
	
	/* parse command line */
	if (G_parser (argc, argv))
	{
		exit (-1);
	}

	vect_types = Vect_option_to_types (parm.type);

	/* check if given parameters are valid */
	processing_mode =
		check_parms (parm.map->answer, parm.input->answer, parm.output->answer, flag.all->answer);				
	
	if ( parm.map->answer != NULL ) {
		/* set cachesize */
		cachesize = atoi (parm.cachesize->answer);
		if ( (cachesize<-1) || (cachesize > G_window_rows ()) ) {
			/* if cache size is invalid, just set to auto-mode (-1) */
			G_warning ("Invalid cache size requested (must be between 0 and %i or -1).\n", G_window_rows());
			cachesize = -1;
		}
	}
		
    do_split_sample ( parm.input->answer, parm.output->answer, vect_types, atof (parm.size->answer),
	                  parm.map->answer, flag.all->answer, processing_mode, flag.quiet->answer );
	
	return (EXIT_SUCCESS);
}
Ejemplo n.º 24
0
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 );
}
Ejemplo n.º 25
0
int main(int argc, char *argv[])
{

    struct GModule *module;
    struct Option *input, *vect;

    struct Cell_head window;
    int bot, right, t0, b0, l0, r0, clear = 0;
    double Rw_l, Rscr_wl;
    char *map_name = NULL, *v_name = NULL, *s_name = NULL;

    /* Initialize the GIS calls */
    G_gisinit(argv[0]);

    /* must run in a term window */
    G_putenv("GRASS_UI_TERM", "1");

    module = G_define_module();
    module->keywords = _("raster, landscape structure analysis, patch index");
    module->description =
	_("Interactive tool used to setup the sampling and analysis framework "
	 "that will be used by the other r.le programs.");

    input = G_define_standard_option(G_OPT_R_MAP);
    input->description = _("Raster map to use to setup sampling");

    vect = G_define_standard_option(G_OPT_V_INPUT);
    vect->key = "vect";
    vect->description = _("Vector map to overlay");
    vect->required = NO;

    if (G_parser(argc, argv))
	exit(EXIT_FAILURE);


    setbuf(stdout, NULL);	/* unbuffered */
    setbuf(stderr, NULL);

    G_sleep_on_error(1);	/* error messages get lost on clear screen */


    map_name = input->answer;
    v_name = vect->answer;
    s_name = NULL;		/* sites not used in GRASS 6 */

    /* setup the r.le.para directory */
    get_pwd();

    /* query for the map to be setup */
    if (R_open_driver() != 0)
	G_fatal_error("No graphics device selected");

    /* setup the current window for display & clear screen */
    D_setup(1);

    Rw_l = (double)G_window_cols() / G_window_rows();
    /*R_open_driver(); */
    /* R_font("romant"); */
    G_get_set_window(&window);
    t0 = R_screen_top();
    b0 = R_screen_bot();
    l0 = R_screen_left();
    r0 = R_screen_rite();
    Rscr_wl = (double)(r0 - l0) / (b0 - t0);

    if (Rscr_wl > Rw_l) {
	bot = b0;
	right = l0 + (b0 - t0) * Rw_l;
    }

    else {
	right = r0;
	bot = t0 + (r0 - l0) / Rw_l;
    }
    D_new_window("a", t0, bot, l0, right);
    D_set_cur_wind("a");
    D_show_window(D_translate_color("green"));
    D_setup(clear);
    R_close_driver();

    /* invoke the setup modules */
    set_map(map_name, v_name, s_name, window, t0, bot, l0, right);

    return (EXIT_SUCCESS);
}
Ejemplo n.º 26
0
Archivo: main.c Proyecto: lichinka/cai
/*
 * 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);
}
Ejemplo n.º 27
0
int
main (int argc, char *argv[]) {
	struct GModule *module;
	struct Option *map; /* raster map to work on */
	struct Option *sites; /* output map to write */
	struct Option *mode; /* Categorisation mode */
	struct Option *min; /* range of values to categorise ... */
	struct Option *max; /*   .. anything outside will be NULL in output */
	struct Option *logfile; /* log output to this file instead of stdout */
	struct Option *precision; /* decimal digits precision for log file */
	struct Option *cachesize;
	struct Flag *null; /* also count NULL values? */
	struct Flag *all; /* disregard region when reporting total percentages */			
	struct Flag *zeroskip;	/* also show categories with 0 count? */
	struct Flag *uncat; /* also show cells outside category range? */	
	struct Flag *background; /* show background distribution? */
	struct Flag *gain; /* calculate Kvamme's gain for each category? */
	struct Flag *quiet; /* no status display on screen */				
	
	char *mapset;
	int show_progress = 1; /* enable progress display by default */
	/* these vars are used to store information about the input map */
	int cats; /* number of categories in input map */
	long null_count; /* number of NULL cells */
	long nocat_count; /* number of cells that do not fall into the category range [0 .. n] */	
	/* use to create command line for r.categorize call */
	char *sysstr, *tmpfile, *input_map;	
	int error;
	
	sysstr = NULL;
	tmpfile = NULL;
	
	/* setup some basic GIS stuff */
	G_gisinit (argv[0]);
	module = G_define_module ();
	module->description = "Analyses distribution of vector sample over a raster map";
	/* do not pause after a warning message was displayed */
	G_sleep_on_error (0);
		
	/* DEFINE OPTIONS AND FLAGS */
	/* raster map to sample */
	map = G_define_standard_option (G_OPT_R_INPUT);
	map->key = "raster";
	map->type = TYPE_STRING;
	map->required = YES;
	map->description = "Raster map to sample";

	/* site map for sampling positions */
	sites = G_define_standard_option (G_OPT_V_INPUT);
	sites->key = "positions";
	sites->type = TYPE_STRING;
	sites->required = YES;
	sites->description = "Vector map with sampling positions";
		
	/* Categorisation mode */
	mode = G_define_option ();
	mode->key = "mode";
	mode->type = TYPE_STRING;
	mode->required = NO;
	mode->description = "Categorisation mode (see manual)";

	/* min raster value to categorise */
	min = G_define_option ();
	min->key = "min";
	min->type = TYPE_DOUBLE;
	min->required = NO;
	min->description = "Minimum value to include in categorisation";

	/* max raster value to categorise */
	max = G_define_option ();
	max->key = "max";
	max->type = TYPE_DOUBLE;
	max->required = NO;
	max->description = "Maximum value to include in categorisation.";

	/* optional name of logfile */
	logfile = G_define_option ();
	logfile->key = "logfile";
	logfile->type = TYPE_DOUBLE;
	logfile->required = NO;
	logfile->description = "Name of ASCII logfile, if desired.";
	
	/* optional number of decimal digitis to store in logfile/show on screen */
	precision = G_define_option ();
	precision->key = "precision";
	precision->type = TYPE_DOUBLE;
	precision->required = NO;
	precision->answer = "2";
	precision->description = "Number of decimal digits for statistics/logfile";		
	
	/* number of lines to store in cache */
	cachesize = G_define_option ();
	cachesize->key = "cachesize";
	cachesize->type = TYPE_INTEGER;
	cachesize->answer = "-1";
	cachesize->required = NO;
	cachesize->description = "Number of raster rows to store in cache (-1 for auto)";	
		
	null = G_define_flag ();
	null->key = 'n';
	null->description = "Include NULL cells in report.";
	
	uncat = G_define_flag ();
	uncat->key = 'u';
	uncat->description = "Include uncategorised cells in statistics.";
	
	all = G_define_flag ();
	all->key = 'a';
	all->description = "Disregard region setting for counts.";	
	
	zeroskip = G_define_flag ();
	zeroskip->key = 'z';
	zeroskip->description = "Also show categories with zero count/percentage.";

	background = G_define_flag ();
	background->key = 'b';
	background->description = "Show background distribution of categories in raster input map.";

	gain = G_define_flag ();
	gain->key = 'g';
	gain->description = "Calculate Kvamme's Gain Factor for each category.";

	quiet = G_define_flag ();
	quiet->key = 'q';
	quiet->description = "Quiet operation: do not show progress display.";	

	
	/* parse command line */
	if (G_parser (argc, argv))
	{
		exit (-1);
	}

	/* check for 'quiet' flag */
	if ( quiet->answer ) {
		show_progress = 0;
	}
	
	PROGNAME = argv[0];		

	/* copy the 'map' option string to another buffer and use that */
	/* from now on. We do this because we might want to manipulate */
	/* that string and that is dangerous with GRASS Option->answer strings! */
	input_map = G_calloc (255, sizeof (char));
	G_strcpy (input_map, map->answer);
	
	mapset = G_calloc (255, sizeof (char));
	/* check if input map is a fully categorised raster map */
	mapset = G_find_cell (input_map,"");
	if ( mapset == NULL) {
		G_fatal_error ("The input map does not exist in the current database.");
	}

	if ( mode->answer == NULL ) {		
		cats = GT_get_stats (input_map,mapset,&null_count, &nocat_count, show_progress);
		if ( cats < 0 ) {
			G_fatal_error ("Could not stat input map. Do you have read access?");
		}
		if ( ((cats == 0) && (mode->answer==NULL)) ) {
			G_fatal_error ("No categories defined in input map.\nPlease specify a mode to create a fully classified map.");
		}
	}

	/* a classification mode was given: call r.categorize and save output
	   in a tmp file */
	if ( mode->answer != NULL ) {
		srand ((unsigned long) time(NULL));
		tmpfile = G_calloc (255, sizeof(char));
		sysstr = G_calloc (255, sizeof(char));
		/* create tmp file name from current PID and system time */		
		sprintf (tmpfile,"tmp.%i.%i", getpid(),(rand())/10000);
		if ( getenv("GISBASE") == NULL ) {
			G_fatal_error ("GISBASE not set. Unable to call GRASS module 'r.categorise'.");
		}		
		if ( quiet->answer ) {
			sprintf (sysstr,"%s/bin/r.categorize input=%s@%s output=%s mode=%s min=%s max=%s -q", getenv("GISBASE"), map->answer, 
					mapset, tmpfile, mode->answer, min->answer, max->answer);
		} else {
			sprintf (sysstr,"%s/bin/r.categorize input=%s@%s output=%s mode=%s min=%s max=%s", getenv("GISBASE"), map->answer, 
					mapset, tmpfile, mode->answer, min->answer, max->answer);
		}
		/* now create fully classified map using r.categorize and store */
		/* it in a temporary raster map */
		error = system (sysstr);
		if ( error < 0 ) {
			G_fatal_error ("Calling r.categorize has failed. Check your installation.");
		}
				
		/* store name of temporary file as new input map */
		G_strcpy (input_map, tmpfile);
		
		/* check categories of tmpfile */
		cats = GT_get_stats (input_map,mapset,&null_count, &nocat_count, show_progress);
		if (cats < 1) {
			G_fatal_error ("Could not create a fully categorised temporary file.\nTry another categorisation mode.");
		}
	}
	
	/* initialise cache structure */
	if ( input_map != NULL ) {
		/* set cachesize */
		CACHESIZE = atoi (cachesize->answer);
		if ( (CACHESIZE<-1) || (CACHESIZE > G_window_rows ()) ) {
			/* if cache size is invalid, just set to auto-mode (-1) */
			G_warning ("Invalid cache size requested (must be between 0 and %i or -1).\n", G_window_rows());
			CACHESIZE = -1;
		}
	}			
	
	if ( G_raster_map_is_fp (input_map, mapset))  {
		do_report_DCELL (input_map, mapset, sites->answer,
				atoi (precision->answer),null->answer, uncat->answer,
	           	all->answer, quiet->answer, zeroskip->answer,
			   	logfile->answer, background->answer, gain->answer, show_progress);
	} else {
		do_report_CELL (input_map, mapset, sites->answer,
				atoi (precision->answer),null->answer, uncat->answer,
	           	all->answer, quiet->answer, zeroskip->answer,
			   	logfile->answer, background->answer, gain->answer, show_progress);		
	}

		
	/* delete temporary file, if needed */
	if ( mode->answer != NULL ) {
		delete_tmpfile (tmpfile);
		G_free (tmpfile);
	}
	
	if ( sysstr != NULL ) {
		G_free (sysstr);
	}
	G_free (input_map);

	return (EXIT_SUCCESS);
}
Ejemplo n.º 28
0
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;
}