예제 #1
0
파일: grassio.c 프로젝트: RHESSys/RHESSys
void array2raster(const void* data, const char* name,
		const RASTER_MAP_TYPE type, const int maxr, const int maxc) {
	void* rast = G_allocate_raster_buf(type);
	int fd;
	if ((fd = G_open_raster_new(name, type)) < 0) {
		G_fatal_error("Unable to create raster map <%s>", name);
	}

	int row, col;
	for (row = 0; row < maxr; ++row) {
		for (col = 0; col < maxc; ++col) {
			int i = row * maxc + col;
			switch (type) {
			case CELL_TYPE:
				((int*) rast)[col] = ((int*) data)[i];
				break;
			case FCELL_TYPE:
				((float*) rast)[col] = ((float*) data)[i];
				break;
			case DCELL_TYPE:
				((double*) rast)[col] = ((double*) data)[i];
				break;
			}
		}

		if (G_put_raster_row(fd, rast, type) < 0) {
			G_fatal_error("Failed writing raster map <%s>", name);
		}
	}

	G_free(rast);
	G_close_cell(fd);

	return;
}
예제 #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;
}
예제 #3
0
파일: hata_cl.c 프로젝트: lichinka/cai
/*
 * Saves raster data pointed by 'rastdata', using the received file
 * descriptor. It returns the sum of all elements in 'rastdata'.
 *
 * FCELL *rastdata ........ raster data to be saved.
 * int nrows .............. the number of rows in the raster data.
 * int ncols .............. the number of columns in the raster data.
 * int outfd .............. file descriptor used for writing.
 *
 */
FCELL save_raster (FCELL *rastdata,
                   const int nrows, const int ncols, 
                   const int outfd)
{
    int row, col;
    FCELL ret_value = (FCELL) 0.0f;

    FCELL *rastbuf = malloc (ncols * G_raster_size (FCELL_TYPE));

    G_message ("Creating output raster from host memory ...");

    /* Save raster data row by row */
    for (row = 0; row < nrows; row++)
    {
        /* display completion percentage */
        G_percent (row, nrows, 2);
       
        for (col = 0; col<ncols; col++)
        {
            ((FCELL *) rastbuf)[col] = rastdata[row * ncols + col];

            if (! isnan(rastbuf[col]))
                ret_value += rastbuf[col];
        }

        if (G_put_raster_row (outfd, rastbuf, FCELL_TYPE) < 0)
            G_fatal_error ("Failed writing output raster map");
    }

    /* free buffers */
    free (rastbuf);

    return ret_value;
}
예제 #4
0
파일: raster.c 프로젝트: imincik/pkg-grass
int output_raster(int fd)
{
    int i, j;

    for (i = 0; i < page.rows; i++, at_row++) {
	switch (format) {

	case USE_CHAR:
	    for (j = 0; j < page.cols; j++) {
		cell[j] = (CELL) raster.c[i][j];
		if (cell[j] == 0)
		    G_set_null_value(&cell[j], 1, CELL_TYPE);
	    }
	    break;

	case USE_UCHAR:
	    for (j = 0; j < page.cols; j++) {
		cell[j] = (CELL) raster.u[i][j];
		if (cell[j] == 0)
		    G_set_null_value(&cell[j], 1, CELL_TYPE);
	    }
	    break;

	case USE_SHORT:
	    for (j = 0; j < page.cols; j++) {
		cell[j] = (CELL) raster.s[i][j];
		if (cell[j] == 0)
		    G_set_null_value(&cell[j], 1, CELL_TYPE);
	    }
	    break;

	case USE_CELL:
	    cell = raster.cell[i];
	    if (cell == 0)
		G_set_null_value(&cell, 1, CELL_TYPE);
	    break;
	}

	G_percent(i, page.rows, 2);
	if (G_put_raster_row(fd, cell, CELL_TYPE) < 0)
	    return ERROR;
    }
    G_percent(i, page.rows, 2);
    return configure_plot();
}
예제 #5
0
파일: r2hmain.c 프로젝트: imincik/pkg-grass
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);
}
예제 #6
0
파일: main.c 프로젝트: imincik/pkg-grass
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);
}
예제 #7
0
static int close_new(int fd, int ok)
{
    struct fileinfo *fcb = &G__.fileinfo[fd];
    int stat;
    struct Categories cats;
    struct History hist;
    char path[GPATH_MAX];
    CELL cell_min, cell_max;
    int row, i, open_mode;

    if (ok) {
	switch (fcb->open_mode) {
	case OPEN_NEW_COMPRESSED:
	    G_debug(1, "close %s compressed", fcb->name);
	    break;
	case OPEN_NEW_UNCOMPRESSED:
	    G_debug(1, "close %s uncompressed", fcb->name);
	    break;
	case OPEN_NEW_RANDOM:
	    G_debug(1, "close %s random", fcb->name);
	    break;
	}

	if (fcb->open_mode != OPEN_NEW_RANDOM &&
	    fcb->cur_row < fcb->cellhd.rows) {
	    G_zero_raster_buf(fcb->data, fcb->map_type);
	    for (row = fcb->cur_row; row < fcb->cellhd.rows; row++)
		G_put_raster_row(fd, fcb->data, fcb->map_type);
	    G_free(fcb->data);
	    fcb->data = NULL;
	}

	/* create path : full null file name */
	G__make_mapset_element_misc("cell_misc", fcb->name);
	G__file_name_misc(path, "cell_misc", NULL_FILE, fcb->name,
			  G_mapset());
	remove(path);

	if (fcb->null_cur_row > 0) {
	    /* if temporary NULL file exists, write it into cell_misc/name/null */
	    int null_fd;

	    null_fd = G__open_null_write(fd);
	    if (null_fd <= 0)
		return -1;
	    if (null_fd < 1)
		return -1;

	    /* first finish writing null file */
	    /* write out the rows stored in memory */
	    for (row = fcb->min_null_row; row < fcb->null_cur_row; row++)
		G__write_null_bits(null_fd,
				   fcb->NULL_ROWS[row - fcb->min_null_row],
				   row, fcb->cellhd.cols, fd);

	    /* write missing rows */
	    if (fcb->open_mode != OPEN_NEW_RANDOM
		&& fcb->null_cur_row < fcb->cellhd.rows) {
		G__init_null_bits(fcb->null_work_buf, fcb->cellhd.cols);
		for (row = fcb->null_cur_row; row < fcb->cellhd.rows; row++)
		    G__write_null_bits(null_fd, fcb->null_work_buf, row,
				       fcb->cellhd.cols, fd);
	    }
	    close(null_fd);

	    if (rename(fcb->null_temp_name, path)) {
		G_warning(_("closecell: can't move %s\nto null file %s"),
			  fcb->null_temp_name, path);
		stat = -1;
	    }
	    else {
		remove(fcb->null_temp_name);
	    }
	}
	else {
	    remove(fcb->null_temp_name);
	    remove(path);
	}			/* null_cur_row > 0 */

	if (fcb->open_mode == OPEN_NEW_COMPRESSED) {	/* auto compression */
	    fcb->row_ptr[fcb->cellhd.rows] = lseek(fd, 0L, SEEK_CUR);
	    G__write_row_ptrs(fd);
	}

	if (fcb->map_type != CELL_TYPE) {	/* floating point map */
	    int cell_fd;

	    if (G__write_fp_format(fd) != 0) {
		G_warning(_("Error writing floating point format file for map %s"),
			  fcb->name);
		stat = -1;
	    }

	    /* now write 0-length cell file */
	    G__make_mapset_element("cell");
	    cell_fd =
		creat(G__file_name(path, "cell", fcb->name, fcb->mapset),
		      0666);
	    close(cell_fd);
	    strcpy(CELL_DIR, "fcell");
	}
	else {
	    /* remove fcell/name file */
	    G__file_name(path, "fcell", fcb->name, fcb->mapset);
	    remove(path);
	    /* remove cell_misc/name/f_format */
	    G__file_name_misc(path, "cell_misc", FORMAT_FILE, fcb->name,
			      fcb->mapset);
	    remove(path);
	    strcpy(CELL_DIR, "cell");
	    close(fd);
	}
    }				/* ok */
    /* NOW CLOSE THE FILE DESCRIPTOR */

    close(fd);
    /* remember open_mode */
    open_mode = fcb->open_mode;
    fcb->open_mode = -1;

    if (fcb->data != NULL)
	G_free(fcb->data);

    if (fcb->null_temp_name != NULL) {
	G_free(fcb->null_temp_name);
	fcb->null_temp_name = NULL;
    }

    /* if the cell file was written to a temporary file
     * move this temporary file into the cell file
     * if the move fails, tell the user, but go ahead and create
     * the support files
     */
    stat = 1;
    if (ok && (fcb->temp_name != NULL)) {
	G__file_name(path, CELL_DIR, fcb->name, fcb->mapset);
	remove(path);
	if (rename(fcb->temp_name, path)) {
	    G_warning(_("closecell: can't move %s\nto cell file %s"),
		      fcb->temp_name, path);
	    stat = -1;
	}
	else {
	    remove(fcb->temp_name);
	}
    }

    if (fcb->temp_name != NULL) {
	G_free(fcb->temp_name);
    }

    if (ok) {
	/* remove color table */
	G_remove_colors(fcb->name, "");

	/* create a history file */
	G_short_history(fcb->name, "raster", &hist);
	G_write_history(fcb->name, &hist);

	/* write the range */
	if (fcb->map_type == CELL_TYPE) {
	    G_write_range(fcb->name, &fcb->range);
	    G__remove_fp_range(fcb->name);
	}
	/*NOTE: int range for floating point maps is not written out */
	else {			/* if(fcb->map_type != CELL_TYPE) */

	    G_write_fp_range(fcb->name, &fcb->fp_range);
	    G_construct_default_range(&fcb->range);
	    /* this range will be used to add default rule to quant structure */
	}

	if (fcb->map_type != CELL_TYPE)
	    fcb->cellhd.format = -1;
	else			/* CELL map */
	    fcb->cellhd.format = fcb->nbytes - 1;

	/* write header file */
	G_put_cellhd(fcb->name, &fcb->cellhd);

	/* if map is floating point write the quant rules, otherwise remove f_quant */
	if (fcb->map_type != CELL_TYPE) {
	    /* DEFAULT RANGE QUANT
	       G_get_fp_range_min_max(&fcb->fp_range, &dcell_min, &dcell_max);
	       if(!G_is_d_null_value(&dcell_min) && !G_is_d_null_value(&dcell_max))
	       {
	       G_get_range_min_max(&fcb->range, &cell_min, &cell_max);
	       G_quant_add_rule(&fcb->quant, dcell_min, dcell_max, 
	       cell_min, cell_max);
	       }
	     */
	    G_quant_round(&fcb->quant);
	    if (G_write_quant(fcb->name, fcb->mapset, &fcb->quant) < 0)
		G_warning(_("unable to write quant file!"));
	}
	else {
	    /* remove cell_misc/name/f_quant */
	    G__file_name_misc(path, "cell_misc", QUANT_FILE, fcb->name,
			      fcb->mapset);
	    remove(path);
	}

	/* create empty cats file */
	G_get_range_min_max(&fcb->range, &cell_min, &cell_max);
	if (G_is_c_null_value(&cell_max))
	    cell_max = 0;
	G_init_cats(cell_max, (char *)NULL, &cats);
	G_write_cats(fcb->name, &cats);
	G_free_cats(&cats);

	/* write the histogram */
	/* only works for integer maps */
	if ((fcb->map_type == CELL_TYPE)
	    && (fcb->want_histogram)) {
	    G_write_histogram_cs(fcb->name, &fcb->statf);
	    G_free_cell_stats(&fcb->statf);
	}
	else {
	    G_remove_histogram(fcb->name);
	}
    }				/* OK */

    G_free(fcb->name);
    G_free(fcb->mapset);

    for (i = 0; i < NULL_ROWS_INMEM; i++)
	G_free(fcb->NULL_ROWS[i]);
    G_free(fcb->null_work_buf);

    if (fcb->map_type != CELL_TYPE)
	G_quant_free(&fcb->quant);

    return stat;
}
예제 #8
0
파일: main.c 프로젝트: 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);
}
예제 #9
0
파일: main.c 프로젝트: imincik/pkg-grass
int main(int argc, char *argv[])
{

    FILE *in_fp;
    int out_fd;
    char *infile, *outmap;
    int xcol, ycol, zcol, max_col, percent;
    int do_zfilter;
    int method = -1;
    int bin_n, bin_min, bin_max, bin_sum, bin_sumsq, bin_index;
    double zrange_min, zrange_max, d_tmp;
    char *fs;			/* field delim */
    off_t filesize;
    int linesize;
    long estimated_lines;
    int from_stdin;
    int can_seek;

    RASTER_MAP_TYPE rtype;
    struct History history;
    char title[64];
    void *n_array, *min_array, *max_array, *sum_array, *sumsq_array,
	*index_array;
    void *raster_row, *ptr;
    struct Cell_head region;
    int rows, cols;		/* scan box size */
    int row, col;		/* counters */

    int pass, npasses;
    unsigned long line;
    char buff[BUFFSIZE];
    double x, y, z;
    char **tokens;
    int ntokens;		/* number of tokens */
    double pass_north, pass_south;
    int arr_row, arr_col;
    unsigned long count, count_total;

    double min = 0.0 / 0.0;	/* init as nan */
    double max = 0.0 / 0.0;	/* init as nan */
    double zscale = 1.0;
    size_t offset, n_offset;
    int n = 0;
    double sum = 0.;
    double sumsq = 0.;
    double variance, mean, skew, sumdev;
    int pth = 0;
    double trim = 0.0;

    int j, k;
    int head_id, node_id;
    int r_low, r_up;

    struct GModule *module;
    struct Option *input_opt, *output_opt, *delim_opt, *percent_opt,
	*type_opt;
    struct Option *method_opt, *xcol_opt, *ycol_opt, *zcol_opt, *zrange_opt,
	*zscale_opt;
    struct Option *trim_opt, *pth_opt;
    struct Flag *scan_flag, *shell_style, *skipline;


    G_gisinit(argv[0]);

    module = G_define_module();
    module->keywords = _("raster, import, LIDAR");
    module->description =
	_("Create a raster map from an assemblage of many coordinates using univariate statistics.");

    input_opt = G_define_standard_option(G_OPT_F_INPUT);
    input_opt->description =
	_("ASCII file containing input data (or \"-\" to read from stdin)");

    output_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 = NO;
    method_opt->description = _("Statistic to use for raster values");
    method_opt->options =
	"n,min,max,range,sum,mean,stddev,variance,coeff_var,median,percentile,skewness,trimmean";
    method_opt->answer = "mean";
    method_opt->guisection = _("Statistic");

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

    delim_opt = G_define_standard_option(G_OPT_F_SEP);
    delim_opt->guisection = _("Input");

    xcol_opt = G_define_option();
    xcol_opt->key = "x";
    xcol_opt->type = TYPE_INTEGER;
    xcol_opt->required = NO;
    xcol_opt->answer = "1";
    xcol_opt->description =
	_("Column number of x coordinates in input file (first column is 1)");
    xcol_opt->guisection = _("Input");

    ycol_opt = G_define_option();
    ycol_opt->key = "y";
    ycol_opt->type = TYPE_INTEGER;
    ycol_opt->required = NO;
    ycol_opt->answer = "2";
    ycol_opt->description = _("Column number of y coordinates in input file");
    ycol_opt->guisection = _("Input");

    zcol_opt = G_define_option();
    zcol_opt->key = "z";
    zcol_opt->type = TYPE_INTEGER;
    zcol_opt->required = NO;
    zcol_opt->answer = "3";
    zcol_opt->description = _("Column number of data values in input file");
    zcol_opt->guisection = _("Input");

    zrange_opt = G_define_option();
    zrange_opt->key = "zrange";
    zrange_opt->type = TYPE_DOUBLE;
    zrange_opt->required = NO;
    zrange_opt->key_desc = "min,max";
    zrange_opt->description = _("Filter range for z data (min,max)");

    zscale_opt = G_define_option();
    zscale_opt->key = "zscale";
    zscale_opt->type = TYPE_DOUBLE;
    zscale_opt->required = NO;
    zscale_opt->answer = "1.0";
    zscale_opt->description = _("Scale to apply to z data");

    percent_opt = G_define_option();
    percent_opt->key = "percent";
    percent_opt->type = TYPE_INTEGER;
    percent_opt->required = NO;
    percent_opt->answer = "100";
    percent_opt->options = "1-100";
    percent_opt->description = _("Percent of map to keep in memory");

    pth_opt = G_define_option();
    pth_opt->key = "pth";
    pth_opt->type = TYPE_INTEGER;
    pth_opt->required = NO;
    pth_opt->options = "1-100";
    pth_opt->description = _("pth percentile of the values");
    pth_opt->guisection = _("Statistic");

    trim_opt = G_define_option();
    trim_opt->key = "trim";
    trim_opt->type = TYPE_DOUBLE;
    trim_opt->required = NO;
    trim_opt->options = "0-50";
    trim_opt->description =
	_("Discard <trim> percent of the smallest and <trim> percent of the largest observations");
    trim_opt->guisection = _("Statistic");

    scan_flag = G_define_flag();
    scan_flag->key = 's';
    scan_flag->description = _("Scan data file for extent then exit");

    shell_style = G_define_flag();
    shell_style->key = 'g';
    shell_style->description =
	_("In scan mode, print using shell script style");

    skipline = G_define_flag();
    skipline->key = 'i';
    skipline->description = _("Ignore broken lines");

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


    /* parse input values */
    infile = input_opt->answer;
    outmap = output_opt->answer;

    if (shell_style->answer && !scan_flag->answer) {
	scan_flag->answer = 1;
    }

    fs = delim_opt->answer;
    if (strcmp(fs, "\\t") == 0)
	fs = "\t";
    if (strcmp(fs, "tab") == 0)
	fs = "\t";
    if (strcmp(fs, "space") == 0)
	fs = " ";

    xcol = atoi(xcol_opt->answer);
    ycol = atoi(ycol_opt->answer);
    zcol = atoi(zcol_opt->answer);
    if ((xcol < 0) || (ycol < 0) || (zcol < 0))
	G_fatal_error(_("Please specify a reasonable column number."));
    max_col = (xcol > ycol) ? xcol : ycol;
    max_col = (zcol > max_col) ? zcol : max_col;

    percent = atoi(percent_opt->answer);
    zscale = atof(zscale_opt->answer);

    /* parse zrange */
    do_zfilter = FALSE;
    if (zrange_opt->answer != NULL) {
	if (zrange_opt->answers[0] == NULL)
	    G_fatal_error(_("Invalid zrange"));

	sscanf(zrange_opt->answers[0], "%lf", &zrange_min);
	sscanf(zrange_opt->answers[1], "%lf", &zrange_max);
	do_zfilter = TRUE;

	if (zrange_min > zrange_max) {
	    d_tmp = zrange_max;
	    zrange_max = zrange_min;
	    zrange_min = d_tmp;
	}
    }

    /* figure out what maps we need in memory */
    /*  n               n
       min              min
       max              max
       range            min max         max - min
       sum              sum
       mean             sum n           sum/n
       stddev           sum sumsq n     sqrt((sumsq - sum*sum/n)/n)
       variance         sum sumsq n     (sumsq - sum*sum/n)/n
       coeff_var        sum sumsq n     sqrt((sumsq - sum*sum/n)/n) / (sum/n)
       median           n               array index to linked list
       percentile       n               array index to linked list
       skewness         n               array index to linked list
       trimmean         n               array index to linked list
     */
    bin_n = FALSE;
    bin_min = FALSE;
    bin_max = FALSE;
    bin_sum = FALSE;
    bin_sumsq = FALSE;
    bin_index = FALSE;

    if (strcmp(method_opt->answer, "n") == 0) {
	method = METHOD_N;
	bin_n = TRUE;
    }
    if (strcmp(method_opt->answer, "min") == 0) {
	method = METHOD_MIN;
	bin_min = TRUE;
    }
    if (strcmp(method_opt->answer, "max") == 0) {
	method = METHOD_MAX;
	bin_max = TRUE;
    }
    if (strcmp(method_opt->answer, "range") == 0) {
	method = METHOD_RANGE;
	bin_min = TRUE;
	bin_max = TRUE;
    }
    if (strcmp(method_opt->answer, "sum") == 0) {
	method = METHOD_SUM;
	bin_sum = TRUE;
    }
    if (strcmp(method_opt->answer, "mean") == 0) {
	method = METHOD_MEAN;
	bin_sum = TRUE;
	bin_n = TRUE;
    }
    if (strcmp(method_opt->answer, "stddev") == 0) {
	method = METHOD_STDDEV;
	bin_sum = TRUE;
	bin_sumsq = TRUE;
	bin_n = TRUE;
    }
    if (strcmp(method_opt->answer, "variance") == 0) {
	method = METHOD_VARIANCE;
	bin_sum = TRUE;
	bin_sumsq = TRUE;
	bin_n = TRUE;
    }
    if (strcmp(method_opt->answer, "coeff_var") == 0) {
	method = METHOD_COEFF_VAR;
	bin_sum = TRUE;
	bin_sumsq = TRUE;
	bin_n = TRUE;
    }
    if (strcmp(method_opt->answer, "median") == 0) {
	method = METHOD_MEDIAN;
	bin_index = TRUE;
    }
    if (strcmp(method_opt->answer, "percentile") == 0) {
	if (pth_opt->answer != NULL)
	    pth = atoi(pth_opt->answer);
	else
	    G_fatal_error(_("Unable to calculate percentile without the pth option specified!"));
	method = METHOD_PERCENTILE;
	bin_index = TRUE;
    }
    if (strcmp(method_opt->answer, "skewness") == 0) {
	method = METHOD_SKEWNESS;
	bin_index = TRUE;
    }
    if (strcmp(method_opt->answer, "trimmean") == 0) {
	if (trim_opt->answer != NULL)
	    trim = atof(trim_opt->answer) / 100.0;
	else
	    G_fatal_error(_("Unable to calculate trimmed mean without the trim option specified!"));
	method = METHOD_TRIMMEAN;
	bin_index = TRUE;
    }

    if (strcmp("CELL", type_opt->answer) == 0)
	rtype = CELL_TYPE;
    else if (strcmp("DCELL", type_opt->answer) == 0)
	rtype = DCELL_TYPE;
    else
	rtype = FCELL_TYPE;

    if (method == METHOD_N)
	rtype = CELL_TYPE;


    G_get_window(&region);
    rows = (int)(region.rows * (percent / 100.0));
    cols = region.cols;

    G_debug(2, "region.n=%f  region.s=%f  region.ns_res=%f", region.north,
	    region.south, region.ns_res);
    G_debug(2, "region.rows=%d  [box_rows=%d]  region.cols=%d", region.rows,
	    rows, region.cols);

    npasses = (int)ceil(1.0 * region.rows / rows);

    if (!scan_flag->answer) {
	/* allocate memory (test for enough before we start) */
	if (bin_n)
	    n_array = G_calloc(rows * (cols + 1), G_raster_size(CELL_TYPE));
	if (bin_min)
	    min_array = G_calloc(rows * (cols + 1), G_raster_size(rtype));
	if (bin_max)
	    max_array = G_calloc(rows * (cols + 1), G_raster_size(rtype));
	if (bin_sum)
	    sum_array = G_calloc(rows * (cols + 1), G_raster_size(rtype));
	if (bin_sumsq)
	    sumsq_array = G_calloc(rows * (cols + 1), G_raster_size(rtype));
	if (bin_index)
	    index_array =
		G_calloc(rows * (cols + 1), G_raster_size(CELL_TYPE));

	/* and then free it again */
	if (bin_n)
	    G_free(n_array);
	if (bin_min)
	    G_free(min_array);
	if (bin_max)
	    G_free(max_array);
	if (bin_sum)
	    G_free(sum_array);
	if (bin_sumsq)
	    G_free(sumsq_array);
	if (bin_index)
	    G_free(index_array);

	/** end memory test **/
    }


    /* open input file */
    if (strcmp("-", infile) == 0) {
	from_stdin = TRUE;
	in_fp = stdin;
	infile = G_store("stdin");	/* filename for history metadata */
    }
    else {
	if ((in_fp = fopen(infile, "r")) == NULL)
	    G_fatal_error(_("Unable to open input file <%s>"), infile);
    }

    can_seek = fseek(in_fp, 0, SEEK_SET) == 0;

    /* can't rewind() non-files */
    if (!can_seek && npasses != 1) {
	G_warning(_("If input is not from a file it is only possible to perform a single pass."));
	npasses = 1;
    }

    if (scan_flag->answer) {
	if (zrange_opt->answer)
	    G_warning(_("zrange will not be taken into account during scan"));

	scan_bounds(in_fp, xcol, ycol, zcol, fs, shell_style->answer,
		    skipline->answer, zscale);

	if (!from_stdin)
	    fclose(in_fp);

	exit(EXIT_SUCCESS);
    }


    /* open output map */
    out_fd = G_open_raster_new(outmap, rtype);
    if (out_fd < 0)
	G_fatal_error(_("Unable to create raster map <%s>"), outmap);

    if (can_seek) {
	/* guess at number of lines in the file without actually reading it all in */
	for (line = 0; line < 10; line++) {	/* arbitrarily use 10th line for guess */
	    if (0 == G_getl2(buff, BUFFSIZE - 1, in_fp))
		break;
	    linesize = strlen(buff) + 1;
	}
	fseek(in_fp, 0L, SEEK_END);
	filesize = ftell(in_fp);
	rewind(in_fp);
	if (linesize < 6)	/* min possible: "0,0,0\n" */
	    linesize = 6;
	estimated_lines = filesize / linesize;
	G_debug(2, "estimated number of lines in file: %ld", estimated_lines);
    }
    else
	estimated_lines = -1;

    /* allocate memory for a single row of output data */
    raster_row = G_allocate_raster_buf(rtype);

    G_message(_("Reading data ..."));

    count_total = 0;

    /* main binning loop(s) */
    for (pass = 1; pass <= npasses; pass++) {
	if (npasses > 1)
	    G_message(_("Pass #%d (of %d) ..."), pass, npasses);

	if (can_seek)
	    rewind(in_fp);

	/* figure out segmentation */
	pass_north = region.north - (pass - 1) * rows * region.ns_res;
	if (pass == npasses)
	    rows = region.rows - (pass - 1) * rows;
	pass_south = pass_north - rows * region.ns_res;

	G_debug(2, "pass=%d/%d  pass_n=%f  pass_s=%f  rows=%d",
		pass, npasses, pass_north, pass_south, rows);


	if (bin_n) {
	    G_debug(2, "allocating n_array");
	    n_array = G_calloc(rows * (cols + 1), G_raster_size(CELL_TYPE));
	    blank_array(n_array, rows, cols, CELL_TYPE, 0);
	}
	if (bin_min) {
	    G_debug(2, "allocating min_array");
	    min_array = G_calloc(rows * (cols + 1), G_raster_size(rtype));
	    blank_array(min_array, rows, cols, rtype, -1);	/* fill with NULLs */
	}
	if (bin_max) {
	    G_debug(2, "allocating max_array");
	    max_array = G_calloc(rows * (cols + 1), G_raster_size(rtype));
	    blank_array(max_array, rows, cols, rtype, -1);	/* fill with NULLs */
	}
	if (bin_sum) {
	    G_debug(2, "allocating sum_array");
	    sum_array = G_calloc(rows * (cols + 1), G_raster_size(rtype));
	    blank_array(sum_array, rows, cols, rtype, 0);
	}
	if (bin_sumsq) {
	    G_debug(2, "allocating sumsq_array");
	    sumsq_array = G_calloc(rows * (cols + 1), G_raster_size(rtype));
	    blank_array(sumsq_array, rows, cols, rtype, 0);
	}
	if (bin_index) {
	    G_debug(2, "allocating index_array");
	    index_array =
		G_calloc(rows * (cols + 1), G_raster_size(CELL_TYPE));
	    blank_array(index_array, rows, cols, CELL_TYPE, -1);	/* fill with NULLs */
	}

	line = 0;
	count = 0;
	G_percent_reset();

	while (0 != G_getl2(buff, BUFFSIZE - 1, in_fp)) {
	    line++;

	    if (line % 10000 == 0) {	/* mod for speed */
		if (!can_seek)
		    G_clicker();
		else if (line < estimated_lines)
		    G_percent(line, estimated_lines, 3);
	    }

	    if ((buff[0] == '#') || (buff[0] == '\0')) {
		continue;	/* line is a comment or blank */
	    }

	    G_chop(buff);	/* remove leading and trailing whitespace from the string.  unneded?? */
	    tokens = G_tokenize(buff, fs);
	    ntokens = G_number_of_tokens(tokens);

	    if ((ntokens < 3) || (max_col > ntokens)) {
		if (skipline->answer) {
		    G_warning(_("Not enough data columns. "
				"Incorrect delimiter or column number? "
				"Found the following character(s) in row %lu:\n[%s]"),
			      line, buff);
		    G_warning(_("Line ignored as requested"));
		    continue;	/* line is garbage */
		}
		else {
		    G_fatal_error(_("Not enough data columns. "
				    "Incorrect delimiter or column number? "
				    "Found the following character(s) in row %lu:\n[%s]"),
				  line, buff);
		}
	    }

	    /* too slow?
	       if ( G_projection() == PROJECTION_LL ) {
	       G_scan_easting( tokens[xcol-1], &x, region.proj);
	       G_scan_northing( tokens[ycol-1], &y, region.proj);
	       }
	       else {
	     */
	    if (1 != sscanf(tokens[ycol - 1], "%lf", &y))
		G_fatal_error(_("Bad y-coordinate line %lu column %d. <%s>"),
			      line, ycol, tokens[ycol - 1]);
	    if (y <= pass_south || y > pass_north) {
		G_free_tokens(tokens);
		continue;
	    }
	    if (1 != sscanf(tokens[xcol - 1], "%lf", &x))
		G_fatal_error(_("Bad x-coordinate line %lu column %d. <%s>"),
			      line, xcol, tokens[xcol - 1]);
	    if (x < region.west || x > region.east) {
		G_free_tokens(tokens);
		continue;
	    }
	    if (1 != sscanf(tokens[zcol - 1], "%lf", &z))
		G_fatal_error(_("Bad z-coordinate line %lu column %d. <%s>"),
			      line, zcol, tokens[zcol - 1]);

	    z = z * zscale;

	    if (zrange_opt->answer) {
		if (z < zrange_min || z > zrange_max) {
		    G_free_tokens(tokens);
		    continue;
		}
	    }

	    count++;
	    /*          G_debug(5, "x: %f, y: %f, z: %f", x, y, z); */
	    G_free_tokens(tokens);

	    /* find the bin in the current array box */
	    arr_row = (int)((pass_north - y) / region.ns_res);
	    arr_col = (int)((x - region.west) / region.ew_res);

	    /*          G_debug(5, "arr_row: %d   arr_col: %d", arr_row, arr_col); */

	    /* The range should be [0,cols-1]. We use (int) to round down,
	       but if the point exactly on eastern edge arr_col will be /just/
	       on the max edge .0000000 and end up on the next row.
	       We could make above bounds check "if(x>=region.east) continue;"
	       But instead we go to all sorts of trouble so that not one single
	       data point is lost. GE is too small to catch them all.
	       We don't try to make y happy as percent segmenting will make some
	       points happen twice that way; so instead we use the y<= test above.
	     */
	    if (arr_col >= cols) {
		if (((x - region.west) / region.ew_res) - cols <
		    10 * GRASS_EPSILON)
		    arr_col--;
		else {		/* oh well, we tried. */
		    G_debug(3,
			    "skipping extraneous data point [%.3f], column %d of %d",
			    x, arr_col, cols);
		    continue;
		}
	    }

	    if (bin_n)
		update_n(n_array, cols, arr_row, arr_col);
	    if (bin_min)
		update_min(min_array, cols, arr_row, arr_col, rtype, z);
	    if (bin_max)
		update_max(max_array, cols, arr_row, arr_col, rtype, z);
	    if (bin_sum)
		update_sum(sum_array, cols, arr_row, arr_col, rtype, z);
	    if (bin_sumsq)
		update_sumsq(sumsq_array, cols, arr_row, arr_col, rtype, z);
	    if (bin_index) {
		ptr = index_array;
		ptr =
		    G_incr_void_ptr(ptr,
				    ((arr_row * cols) +
				     arr_col) * G_raster_size(CELL_TYPE));

		if (G_is_null_value(ptr, CELL_TYPE)) {	/* first node */
		    head_id = new_node();
		    nodes[head_id].next = -1;
		    nodes[head_id].z = z;
		    G_set_raster_value_c(ptr, head_id, CELL_TYPE);	/* store index to head */
		}
		else {		/* head is already there */

		    head_id = G_get_raster_value_c(ptr, CELL_TYPE);	/* get index to head */
		    head_id = add_node(head_id, z);
		    if (head_id != -1)
			G_set_raster_value_c(ptr, head_id, CELL_TYPE);	/* store index to head */
		}
	    }
	}			/* while !EOF */

	G_percent(1, 1, 1);	/* flush */
	G_debug(2, "pass %d finished, %lu coordinates in box", pass, count);
	count_total += count;


	/* calc stats and output */
	G_message(_("Writing to map ..."));
	for (row = 0; row < rows; row++) {

	    switch (method) {
	    case METHOD_N:	/* n is a straight copy */
		G_raster_cpy(raster_row,
			     n_array +
			     (row * cols * G_raster_size(CELL_TYPE)), cols,
			     CELL_TYPE);
		break;

	    case METHOD_MIN:
		G_raster_cpy(raster_row,
			     min_array + (row * cols * G_raster_size(rtype)),
			     cols, rtype);
		break;

	    case METHOD_MAX:
		G_raster_cpy(raster_row,
			     max_array + (row * cols * G_raster_size(rtype)),
			     cols, rtype);
		break;

	    case METHOD_SUM:
		G_raster_cpy(raster_row,
			     sum_array + (row * cols * G_raster_size(rtype)),
			     cols, rtype);
		break;

	    case METHOD_RANGE:	/* (max-min) */
		ptr = raster_row;
		for (col = 0; col < cols; col++) {
		    offset = (row * cols + col) * G_raster_size(rtype);
		    min = G_get_raster_value_d(min_array + offset, rtype);
		    max = G_get_raster_value_d(max_array + offset, rtype);
		    G_set_raster_value_d(ptr, max - min, rtype);
		    ptr = G_incr_void_ptr(ptr, G_raster_size(rtype));
		}
		break;

	    case METHOD_MEAN:	/* (sum / n) */
		ptr = raster_row;
		for (col = 0; col < cols; col++) {
		    offset = (row * cols + col) * G_raster_size(rtype);
		    n_offset = (row * cols + col) * G_raster_size(CELL_TYPE);
		    n = G_get_raster_value_c(n_array + n_offset, CELL_TYPE);
		    sum = G_get_raster_value_d(sum_array + offset, rtype);

		    if (n == 0)
			G_set_null_value(ptr, 1, rtype);
		    else
			G_set_raster_value_d(ptr, (sum / n), rtype);

		    ptr = G_incr_void_ptr(ptr, G_raster_size(rtype));
		}
		break;

	    case METHOD_STDDEV:	/*  sqrt(variance)        */
	    case METHOD_VARIANCE:	/*  (sumsq - sum*sum/n)/n */
	    case METHOD_COEFF_VAR:	/*  100 * stdev / mean    */
		ptr = raster_row;
		for (col = 0; col < cols; col++) {
		    offset = (row * cols + col) * G_raster_size(rtype);
		    n_offset = (row * cols + col) * G_raster_size(CELL_TYPE);
		    n = G_get_raster_value_c(n_array + n_offset, CELL_TYPE);
		    sum = G_get_raster_value_d(sum_array + offset, rtype);
		    sumsq = G_get_raster_value_d(sumsq_array + offset, rtype);

		    if (n == 0)
			G_set_null_value(ptr, 1, rtype);
		    else {
			variance = (sumsq - sum * sum / n) / n;
			if (variance < GRASS_EPSILON)
			    variance = 0.0;

			if (method == METHOD_STDDEV)
			    G_set_raster_value_d(ptr, sqrt(variance), rtype);

			else if (method == METHOD_VARIANCE)
			    G_set_raster_value_d(ptr, variance, rtype);

			else if (method == METHOD_COEFF_VAR)
			    G_set_raster_value_d(ptr,
						 100 * sqrt(variance) / (sum /
									 n),
						 rtype);

		    }
		    ptr = G_incr_void_ptr(ptr, G_raster_size(rtype));
		}
		break;
	    case METHOD_MEDIAN:	/* median, if only one point in cell we will use that */
		ptr = raster_row;
		for (col = 0; col < cols; col++) {
		    n_offset = (row * cols + col) * G_raster_size(CELL_TYPE);
		    if (G_is_null_value(index_array + n_offset, CELL_TYPE))	/* no points in cell */
			G_set_null_value(ptr, 1, rtype);
		    else {	/* one or more points in cell */

			head_id =
			    G_get_raster_value_c(index_array + n_offset,
						 CELL_TYPE);
			node_id = head_id;

			n = 0;

			while (node_id != -1) {	/* count number of points in cell */
			    n++;
			    node_id = nodes[node_id].next;
			}

			if (n == 1)	/* only one point, use that */
			    G_set_raster_value_d(ptr, nodes[head_id].z,
						 rtype);
			else if (n % 2 != 0) {	/* odd number of points: median_i = (n + 1) / 2 */
			    n = (n + 1) / 2;
			    node_id = head_id;
			    for (j = 1; j < n; j++)	/* get "median element" */
				node_id = nodes[node_id].next;

			    G_set_raster_value_d(ptr, nodes[node_id].z,
						 rtype);
			}
			else {	/* even number of points: median = (val_below + val_above) / 2 */

			    z = (n + 1) / 2.0;
			    n = floor(z);
			    node_id = head_id;
			    for (j = 1; j < n; j++)	/* get element "below" */
				node_id = nodes[node_id].next;

			    z = (nodes[node_id].z +
				 nodes[nodes[node_id].next].z) / 2;
			    G_set_raster_value_d(ptr, z, rtype);
			}
		    }
		    ptr = G_incr_void_ptr(ptr, G_raster_size(rtype));
		}
		break;
	    case METHOD_PERCENTILE:	/* rank = (pth*(n+1))/100; interpolate linearly */
		ptr = raster_row;
		for (col = 0; col < cols; col++) {
		    n_offset = (row * cols + col) * G_raster_size(CELL_TYPE);
		    if (G_is_null_value(index_array + n_offset, CELL_TYPE))	/* no points in cell */
			G_set_null_value(ptr, 1, rtype);
		    else {
			head_id =
			    G_get_raster_value_c(index_array + n_offset,
						 CELL_TYPE);
			node_id = head_id;
			n = 0;

			while (node_id != -1) {	/* count number of points in cell */
			    n++;
			    node_id = nodes[node_id].next;
			}

			z = (pth * (n + 1)) / 100.0;
			r_low = floor(z);	/* lower rank */
			if (r_low < 1)
			    r_low = 1;
			else if (r_low > n)
			    r_low = n;

			r_up = ceil(z);	/* upper rank */
			if (r_up > n)
			    r_up = n;

			node_id = head_id;
			for (j = 1; j < r_low; j++)	/* search lower value */
			    node_id = nodes[node_id].next;

			z = nodes[node_id].z;	/* save lower value */
			node_id = head_id;
			for (j = 1; j < r_up; j++)	/* search upper value */
			    node_id = nodes[node_id].next;

			z = (z + nodes[node_id].z) / 2;
			G_set_raster_value_d(ptr, z, rtype);
		    }
		    ptr = G_incr_void_ptr(ptr, G_raster_size(rtype));
		}
		break;
	    case METHOD_SKEWNESS:	/* skewness = sum(xi-mean)^3/(N-1)*s^3 */
		ptr = raster_row;
		for (col = 0; col < cols; col++) {
		    n_offset = (row * cols + col) * G_raster_size(CELL_TYPE);
		    if (G_is_null_value(index_array + n_offset, CELL_TYPE))	/* no points in cell */
			G_set_null_value(ptr, 1, rtype);
		    else {
			head_id =
			    G_get_raster_value_c(index_array + n_offset,
						 CELL_TYPE);
			node_id = head_id;

			n = 0;	/* count */
			sum = 0.0;	/* sum */
			sumsq = 0.0;	/* sum of squares */
			sumdev = 0.0;	/* sum of (xi - mean)^3 */
			skew = 0.0;	/* skewness */

			while (node_id != -1) {
			    z = nodes[node_id].z;
			    n++;
			    sum += z;
			    sumsq += (z * z);
			    node_id = nodes[node_id].next;
			}

			if (n > 1) {	/* if n == 1, skew is "0.0" */
			    mean = sum / n;
			    node_id = head_id;
			    while (node_id != -1) {
				z = nodes[node_id].z;
				sumdev += pow((z - mean), 3);
				node_id = nodes[node_id].next;
			    }

			    variance = (sumsq - sum * sum / n) / n;
			    if (variance < GRASS_EPSILON)
				skew = 0.0;
			    else
				skew =
				    sumdev / ((n - 1) *
					      pow(sqrt(variance), 3));
			}
			G_set_raster_value_d(ptr, skew, rtype);
		    }
		    ptr = G_incr_void_ptr(ptr, G_raster_size(rtype));
		}
		break;
	    case METHOD_TRIMMEAN:
		ptr = raster_row;
		for (col = 0; col < cols; col++) {
		    n_offset = (row * cols + col) * G_raster_size(CELL_TYPE);
		    if (G_is_null_value(index_array + n_offset, CELL_TYPE))	/* no points in cell */
			G_set_null_value(ptr, 1, rtype);
		    else {
			head_id =
			    G_get_raster_value_c(index_array + n_offset,
						 CELL_TYPE);

			node_id = head_id;
			n = 0;
			while (node_id != -1) {	/* count number of points in cell */
			    n++;
			    node_id = nodes[node_id].next;
			}

			if (1 == n)
			    mean = nodes[head_id].z;
			else {
			    k = floor(trim * n + 0.5);	/* number of ranks to discard on each tail */

			    if (k > 0 && (n - 2 * k) > 0) {	/* enough elements to discard */
				node_id = head_id;
				for (j = 0; j < k; j++)	/* move to first rank to consider */
				    node_id = nodes[node_id].next;

				j = k + 1;
				k = n - k;
				n = 0;
				sum = 0.0;

				while (j <= k) {	/* get values in interval */
				    n++;
				    sum += nodes[node_id].z;
				    node_id = nodes[node_id].next;
				    j++;
				}
			    }
			    else {
				node_id = head_id;
				n = 0;
				sum = 0.0;
				while (node_id != -1) {
				    n++;
				    sum += nodes[node_id].z;
				    node_id = nodes[node_id].next;
				}
			    }
			    mean = sum / n;
			}
			G_set_raster_value_d(ptr, mean, rtype);
		    }
		    ptr = G_incr_void_ptr(ptr, G_raster_size(rtype));
		}
		break;

	    default:
		G_fatal_error("?");
	    }

	    /* write out line of raster data */
	    if (1 != G_put_raster_row(out_fd, raster_row, rtype)) {
		G_close_cell(out_fd);
		G_fatal_error(_("Writing map, row %d"),
			      ((pass - 1) * rows) + row);
	    }
	}

	/* free memory */
	if (bin_n)
	    G_free(n_array);
	if (bin_min)
	    G_free(min_array);
	if (bin_max)
	    G_free(max_array);
	if (bin_sum)
	    G_free(sum_array);
	if (bin_sumsq)
	    G_free(sumsq_array);
	if (bin_index) {
	    G_free(index_array);
	    G_free(nodes);
	    num_nodes = 0;
	    max_nodes = 0;
	    nodes = NULL;
	}

    }				/* passes loop */

    G_percent(1, 1, 1);		/* flush */
    G_free(raster_row);

    /* close input file */
    if (!from_stdin)
	fclose(in_fp);

    /* close raster file & write history */
    G_close_cell(out_fd);

    sprintf(title, "Raw x,y,z data binned into a raster grid by cell %s",
	    method_opt->answer);
    G_put_cell_title(outmap, title);

    G_short_history(outmap, "raster", &history);
    G_command_history(&history);
    strncpy(history.datsrc_1, infile, RECORD_LEN);
    history.datsrc_1[RECORD_LEN - 1] = '\0';	/* strncpy() doesn't null terminate if maxfill */
    G_write_history(outmap, &history);


    sprintf(buff, _("%lu points found in region."), count_total);
    G_done_msg(buff);
    G_debug(1, "Processed %lu lines.", line);

    exit(EXIT_SUCCESS);

}
예제 #10
0
int make_new_cell_layer(void)
{
    struct History hist;
    void *rast;
    int cellfd;

    int tmpfd;
    int row;

    /* open the new raster map to contain the edited version of
       the original cell layer. open our temporary file for read
       and copy its contents to the layer */

    G_set_window(&real_window);

    cellfd = G_open_raster_new(new_name, map_type);
    tmpfd = open(tempfile, 0);
    lseek(tmpfd, 0L, 0);

    rast = G_allocate_raster_buf(map_type);

    fprintf(stderr, "\n     +-------------------------------------------+\n");
    fprintf(stderr, "     |         Saving new cell layer             |\n");
    fprintf(stderr, "     +---------------------------------------");


    for (row = 0; row < real_nrows; row++) {
	if (read(tmpfd, rast, real_ncols * cellsize) !=
	    (real_ncols * cellsize))
	    error(1, "error writing raster map during copy");
	G_put_raster_row(cellfd, rast, map_type);
	G_percent(row, real_nrows, 5);
    }
    G_percent(100, 100, 5);
    fprintf(stderr, "\n");

    close(tmpfd);
    G_close_cell(cellfd);
    unlink(tempfile);

    /* create and write cat, colr, quant, and hist support files
       for the newly created layer */

    if (colr_ok) {
	G_write_colors(new_name, user_mapset, &colr);
	G_free_colors(&colr);
	colr_ok = 0;
    }
    if (cats_ok) {
	cats.num = G_number_of_cats(new_name, user_mapset);
	G_write_cats(new_name, &cats);
	G_free_cats(&cats);
	cats_ok = 0;
    }
    if (quant_ok) {
	G_write_quant(new_name, G_mapset(), &quant);
	G_quant_free(&quant);
	cats_ok = 0;
    }

    /* construct some history information */
    sprintf(hist.mapid, "%s", G_date());
    sprintf(hist.title, "%s", new_name);
    sprintf(hist.mapset, "%s", user_mapset);
    sprintf(hist.creator, "%s", G_whoami());
    sprintf(hist.maptype, "cell");
    sprintf(hist.edhist[0],
	    "Generated by d.rast.edit from original raster map");
    sprintf(hist.edhist[1], "  %s in mapset %s ", orig_name, orig_mapset);
    hist.edlinecnt = 2;

    /* write history */
    if (G_write_history(new_name, &hist) == -1)
	error(0, "could not write history");

    return 0;
}
예제 #11
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);
}
예제 #12
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);
}