Ejemplo n.º 1
0
int get_range(const char *name, long *min, long *max)
{
    struct Range range;
    int nrows, ncols, row, col;
    CELL *cell;
    int fd;
    CELL cmin, cmax;
    struct Cell_head cellhd;

    if (Rast_read_range(name, "", &range) < 0) {
	Rast_init_range(&range);	/* read the file to get the range */
	Rast_get_cellhd(name, "", &cellhd);
	Rast_set_window(&cellhd);
	cell = Rast_allocate_c_buf();
	fd = Rast_open_old(name, "");
	nrows = Rast_window_rows();
	ncols = Rast_window_cols();
	G_message(_("Reading %s ..."), name);
	for (row = 0; row < nrows; row++) {
	    G_percent(row, nrows, 2);
	    Rast_get_c_row_nomask(fd, cell, row);
	    for (col = 0; col < ncols; col++)
		Rast_update_range(cell[col], &range);
	}
	G_percent(row, nrows, 2);
	Rast_close(fd);
	G_free(cell);
    }

    Rast_get_range_min_max(&range, &cmin, &cmax);
    *min = cmin;
    *max = cmax;

    return 0;
}
Ejemplo n.º 2
0
int get_stats(const char *name, struct Cell_stats *statf)
{
    int fd;
    CELL *cell;
    int row, nrows, ncols;

    fd = Rast_open_old(name, "");
    nrows = Rast_window_rows();
    ncols = Rast_window_cols();
    cell = Rast_allocate_c_buf();

    Rast_init_cell_stats(statf);
    G_message(_("Reading %s ..."), name);
    for (row = 0; row < nrows; row++) {
	G_percent(row, nrows, 2);
	Rast_get_c_row(fd, cell, row);
	Rast_update_cell_stats(cell, ncols, statf);
    }
    if (row < nrows)
	exit(1);
    Rast_close(fd);
    G_free(cell);
    G_percent(row, nrows, 2);

    return 0;
}
Ejemplo n.º 3
0
int cseg_read_cell(CSEG * cseg, char *map_name, char *mapset)
{
    GW_LARGE_INT row, nrows;
    int map_fd;
    CELL *buffer;

    cseg->name = NULL;
    cseg->mapset = NULL;

    map_fd = Rast_open_old(map_name, mapset);
    nrows = Rast_window_rows();
    buffer = Rast_allocate_c_buf();
    for (row = 0; row < nrows; row++) {
	Rast_get_c_row(map_fd, buffer, row);
	if (Segment_put_row(&(cseg->seg), buffer, row) < 0) {
	    G_free(buffer);
	    Rast_close(map_fd);
	    G_warning("%s(): unable to segment put row for [%s] in [%s]",
		    me, map_name, mapset);
	    return (-1);
	}
    }

    Rast_close(map_fd);
    G_free(buffer);

    cseg->name = G_store(map_name);
    cseg->mapset = G_store(mapset);

    return 0;
}
Ejemplo n.º 4
0
void openfiles(char *r_name, char *g_name, char *b_name,
	       char *h_name, char *i_name, char *s_name,
	       int fd_input[3], int fd_output[3], CELL * rowbuf[3])
{
    fd_input[0] = Rast_open_old(r_name, "");
    fd_input[1] = Rast_open_old(g_name, "");
    fd_input[2] = Rast_open_old(b_name, "");

    /* open output files */
    fd_output[0] = Rast_open_c_new(h_name);
    fd_output[1] = Rast_open_c_new(i_name);
    fd_output[2] = Rast_open_c_new(s_name);

    /* allocate the cell row buffer */
    rowbuf[0] = Rast_allocate_c_buf();
    rowbuf[1] = Rast_allocate_c_buf();
    rowbuf[2] = Rast_allocate_c_buf();
}
Ejemplo n.º 5
0
void openfiles(char *h_name, char *i_name, char *s_name,
	       char *r_name, char *g_name, char *b_name,
	       int fd_input[3], int fd_output[3], CELL * rowbuf[3])
{
    /* open output files */
    fd_output[0] = Rast_open_c_new(r_name);
    fd_output[1] = Rast_open_c_new(g_name);
    fd_output[2] = Rast_open_c_new(b_name);

    /* allocate the cell row buffer */
    rowbuf[0] = Rast_allocate_c_buf();
    rowbuf[1] = Rast_allocate_c_buf();
    rowbuf[2] = Rast_allocate_c_buf();

    /* open input files (maps can be in different mapsets) */
    fd_input[0] = Rast_open_old(h_name, "");
    fd_input[1] = Rast_open_old(i_name, "");
    fd_input[2] = Rast_open_old(s_name, "");
}
Ejemplo n.º 6
0
int randsurf(char *out,		/* Name of raster maps to be opened.    */
	     int min, int max,	/* Minimum and maximum cell values.     */
	     int int_map)
{				/* if map is to be written as a CELL map */
    int nrows, ncols;		/* Number of cell rows and columns      */

    DCELL *row_out_D;		/* Buffer just large enough to hold one */
    CELL *row_out_C;		/* row of the raster map layer.         */

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

    /* open raster maps.                    */
    int row_count, col_count;

	/****** INITIALISE RANDOM NUMBER GENERATOR ******/
    G_math_rand(-1 * getpid());

	/****** OPEN CELL FILES AND GET CELL DETAILS ******/
    fd_out = Rast_open_new(out, int_map ? CELL_TYPE : DCELL_TYPE);

    nrows = Rast_window_rows();
    ncols = Rast_window_cols();

    if (int_map)
	row_out_C = Rast_allocate_c_buf();
    else
	row_out_D = Rast_allocate_d_buf();

	/****** PASS THROUGH EACH CELL ASSIGNING RANDOM VALUE ******/
    for (row_count = 0; row_count < nrows; row_count++) {
	G_percent(row_count, nrows, 2);
	for (col_count = 0; col_count < ncols; col_count++) {
	    if (int_map)
		*(row_out_C + col_count) =
		    (CELL) (G_math_rand(2742) * (max + 1 - min) + min);
	    /* under represents first and last bin */
	    /*                  *(row_out_C + col_count) = (CELL) floor(rand1(2742)*(max-min)+min +0.5); */
	    else
		*(row_out_D + col_count) =
		    (DCELL) (G_math_rand(2742) * (max - min) + min);
	}

	/* Write contents row by row */
	if (int_map)
	    Rast_put_c_row(fd_out, (CELL *) row_out_C);
	else
	    Rast_put_d_row(fd_out, (DCELL *) row_out_D);
    }
    G_percent(1, 1, 1);
    
    Rast_close(fd_out);

    return 0;
}
Ejemplo n.º 7
0
int
transform(int *datafds, int *outfds, int rows, int cols,
	  double **eigmat, int bands, CELL *mins, CELL *maxs)
{
    int i, j, k, l;
    double *sum;
    CELL **rowbufs;

    sum = G_alloc_vector(bands);
    rowbufs = (CELL**)G_calloc(bands, sizeof(CELL*));


    /* allocate row buffers for each band */
    for (i = 0; i < bands; i++)
	if ((rowbufs[i] = Rast_allocate_c_buf()) == NULL)
	    G_fatal_error(_("Unable to allocate cell buffers."));

    for (i = 0; i < rows; i++) {
	/* get one row of data */
	for (j = 0; j < bands; j++)
	    Rast_get_c_row(datafds[j], rowbufs[j], i);

	/* transform each cell in the row */
	for (l = 0; l < cols; l++) {
	    for (j = 0; j < bands; j++) {
		sum[j] = 0.0;
		for (k = 0; k < bands; k++) {
		    sum[j] += eigmat[j][k] * (double)rowbufs[k][l];
		}
	    }
	    for (j = 0; j < bands; j++) {
		rowbufs[j][l] = (CELL) (sum[j] + 0.5);
		if (rowbufs[j][l] > maxs[j])
		    maxs[j] = rowbufs[j][l];
		if (rowbufs[j][l] < mins[j])
		    mins[j] = rowbufs[j][l];
	    }
	}

	/* output the row of data */
	for (j = 0; j < bands; j++)
	    Rast_put_row(outfds[j], rowbufs[j], CELL_TYPE);
    }
    for (i = 0; i < bands; i++)
	G_free(rowbufs[i]);

    G_free(rowbufs);
    G_free_vector(sum);

    G_message(_("Transform completed.\n"));

    return 0;
}
Ejemplo n.º 8
0
int sg_factor(void)
{
    int r, c;
    CELL low_elev, hih_elev;
    double height, length, S, sin_theta;

    G_message(_("SECTION 4: RUSLE LS and/or S factor determination."));

    if (ril_flag)
	ril_buf = Rast_allocate_c_buf();

    for (r = 0; r < nrows; r++) {
	G_percent(r, nrows, 3);
	if (ril_flag) {
	    Rast_get_c_row(ril_fd, ril_buf, r);
	}
	for (c = 0; c < ncols; c++) {
	    low_elev = alt[SEG_INDEX(alt_seg, r, c)];
	    hih_elev = r_h[SEG_INDEX(r_h_seg, r, c)];
	    length = s_l[SEG_INDEX(s_l_seg, r, c)];
	    height = 1.0 * (hih_elev - low_elev) / ele_scale;
	    if (length > max_length) {
		height *= max_length / length;
		length = max_length;
	    }
	    sin_theta = height / sqrt(height * height + length * length);
	    if (height / length < .09)
		S = 10.8 * sin_theta + .03;
	    else
		S = 16.8 * sin_theta - .50;
	    if (sg_flag)
		s_g[SEG_INDEX(s_g_seg, r, c)] = S;
	    if (ls_flag) {
		length *= METER_TO_FOOT;
		len_slp_equ(length, sin_theta, S, r, c);
	    }
	}
    }
    G_percent(nrows, nrows, 1);	/* finish it */

    if (ril_flag) {
	G_free(ril_buf);
	Rast_close(ril_fd);
    }

    return 0;
}
Ejemplo n.º 9
0
Archivo: main.c Proyecto: caomw/grass
static void init_channel(channel *c)
{
    sprintf(c->name, "%s%s", output, c->suffix);

    if (Float)
    {
	c->fd = Rast_open_fp_new(c->name);
	c->fbuf = Rast_allocate_f_buf();
    }
    else
    {
	c->fd = Rast_open_c_new(c->name);
	c->buf = Rast_allocate_c_buf();
    }

    c->active = 1;
}
Ejemplo n.º 10
0
static void do_output(int base_fd, char **outputs, const char *covermap)
{
    int *out_fd = G_malloc(num_quants * sizeof(int));
    CELL *base_buf = Rast_allocate_c_buf();
    DCELL *out_buf = Rast_allocate_d_buf();
    const char *mapset = G_mapset();
    struct Colors colors;
    int have_colors;
    int quant;
    int row, col;

    G_message(_("Writing output maps"));

    for (quant = 0; quant < num_quants; quant++) {
	const char *output = outputs[quant];

	out_fd[quant] = Rast_open_fp_new(output);
    }

    have_colors = Rast_read_colors(covermap, "", &colors) > 0;

    for (row = 0; row < rows; row++) {
	Rast_get_c_row(base_fd, base_buf, row);

	for (quant = 0; quant < num_quants; quant++) {
	    for (col = 0; col < cols; col++)
		if (Rast_is_c_null_value(&base_buf[col]))
		    Rast_set_d_null_value(&out_buf[col], 1);
		else
		    out_buf[col] = basecats[base_buf[col] - min].quants[quant];

	    Rast_put_d_row(out_fd[quant], out_buf);
	}

	G_percent(row, rows, 2);
    }

    G_percent(row, rows, 2);

    for (quant = 0; quant < num_quants; quant++) {
	Rast_close(out_fd[quant]);
	if (have_colors)
	    Rast_write_colors(outputs[quant], mapset, &colors);
    }
}
Ejemplo n.º 11
0
int cseg_write_cellfile(CSEG * cseg, char *map_name)
{
    int map_fd;
    GW_LARGE_INT row, nrows;
    CELL *buffer;

    map_fd = Rast_open_c_new(map_name);
    nrows = Rast_window_rows();
    buffer = Rast_allocate_c_buf();
    Segment_flush(&(cseg->seg));
    for (row = 0; row < nrows; row++) {
	G_percent(row, nrows, 1);
	Segment_get_row(&(cseg->seg), buffer, row);
	Rast_put_row(map_fd, buffer, CELL_TYPE);
    }
    G_percent(row, nrows, 1);    /* finish it */
    G_free(buffer);
    Rast_close(map_fd);
    return 0;
}
Ejemplo n.º 12
0
/*!
   \brief Open and allocate space for the group band files.

   \param refer pointer to band files structure
   \param[out] band_buffer buffer to read one row of each band
   \param[out] band_fd band files descriptors
 */
void open_band_files(struct Ref *refer, CELL *** band_buffer, int **band_fd)
{
    int n, nbands;

    char *name, *mapset;

    G_debug(3, "open_band_files()");

    /* allocate row buffers and open raster maps */
    nbands = refer->nfiles;
    *band_buffer = (CELL **) G_malloc(nbands * sizeof(CELL *));
    *band_fd = (int *)G_malloc(nbands * sizeof(int));

    for (n = 0; n < nbands; n++) {
	(*band_buffer)[n] = Rast_allocate_c_buf();
	name = refer->file[n].name;
	mapset = refer->file[n].mapset;
	(*band_fd)[n] = Rast_open_old(name, mapset);
    }
}
Ejemplo n.º 13
0
static void fill_bins(int basefile, int coverfile)
{
    CELL *basebuf = Rast_allocate_c_buf();
    DCELL *coverbuf = Rast_allocate_d_buf();
    int row, col;

    G_message(_("Binning data"));

    for (row = 0; row < rows; row++) {
	Rast_get_c_row(basefile, basebuf, row);
	Rast_get_d_row(coverfile, coverbuf, row);

	for (col = 0; col < cols; col++) {
	    struct basecat *bc;
	    int i, bin;
	    struct bin *b;

	    if (Rast_is_c_null_value(&basebuf[col]))
		continue;

	    if (Rast_is_d_null_value(&coverbuf[col]))
		continue;

	    i = get_slot(coverbuf[col]);
	    bc = &basecats[basebuf[col] - min];
	    if (!bc->slot_bins[i])
		continue;

	    bin = bc->slot_bins[i] - 1;
	    b = &bc->bins[bin];

	    bc->values[b->base + b->count++] = coverbuf[col];
	}

	G_percent(row, rows, 2);
    }

    G_percent(rows, rows, 2);
    G_free(basebuf);
    G_free(coverbuf);
}
Ejemplo n.º 14
0
int openfiles(struct parms *parms, struct files *files)
{
    struct Ref Ref;		/* subgroup reference list */
    int n;


    if (!I_get_subgroup_ref(parms->group, parms->subgroup, &Ref))
	G_fatal_error(_("Unable to read REF file for subgroup <%s> in group <%s>"),
		      parms->subgroup, parms->group);

    if (Ref.nfiles <= 0)
	G_fatal_error(_("Subgroup <%s> in group <%s> contains no raster maps"),
		      parms->subgroup, parms->group);

    /* allocate file descriptors, and io buffer */
    files->cellbuf = Rast_allocate_d_buf();
    files->outbuf = Rast_allocate_c_buf();

    files->isdata = G_malloc(Rast_window_cols());

    files->nbands = Ref.nfiles;
    files->band_fd = (int *)G_calloc(Ref.nfiles, sizeof(int));

    /* open all group maps for reading */
    for (n = 0; n < Ref.nfiles; n++)
	files->band_fd[n] =
	    open_cell_old(Ref.file[n].name, Ref.file[n].mapset);

    /* open output map */
    files->output_fd = open_cell_new(parms->output_map);

    if (parms->goodness_map)
	files->goodness_fd = Rast_open_new(parms->goodness_map, FCELL_TYPE);
    else
	files->goodness_fd = -1;

    return 0;
}
Ejemplo n.º 15
0
int renumber(int in, int out)
{
    CELL *cell, *c;
    int row, col;

    cell = Rast_allocate_c_buf();

    G_message(_("%s: STEP 3 ... "), G_program_name());
    for (row = 0; row < nrows; row++) {
	G_percent(row, nrows, 5);
	Rast_get_c_row(in, c = cell, row);
	col = ncols;
	while (col-- > 0) {
	    if (!Rast_is_c_null_value(c))
		*c = table[*c];
	    c++;
	}
	Rast_put_row(out, cell, CELL_TYPE);
    }
    G_percent(row, nrows, 10);
    G_free(cell);

    return 0;
}
Ejemplo n.º 16
0
int get_cats(const char *name, const char *mapset)
{
    int fd;
    int row, nrows, ncols;
    CELL *cell;
    struct Cell_head cellhd;

    /* set the window to the cell header */
    Rast_get_cellhd(name, mapset, &cellhd);

    Rast_set_window(&cellhd);

    /* open the raster map */
    fd = Rast_open_old(name, mapset);
    nrows = Rast_window_rows();
    ncols = Rast_window_cols();
    cell = Rast_allocate_c_buf();
    Rast_init_cell_stats(&statf);

    /* read the raster map */
    G_verbose_message(_("Reading <%s> in <%s>"), name, mapset);
    for (row = 0; row < nrows; row++) {
	if (G_verbose() > G_verbose_std())
	    G_percent(row, nrows, 2);
	Rast_get_c_row_nomask(fd, cell, row);
	Rast_update_cell_stats(cell, ncols, &statf);
    }
    /* done */
    if (G_verbose() > G_verbose_std())
	G_percent(row, nrows, 2);
    Rast_close(fd);
    G_free(cell);
    Rast_rewind_cell_stats(&statf);

    return 0;
}
Ejemplo n.º 17
0
static void get_slot_counts(int basefile, int coverfile)
{
    CELL *basebuf = Rast_allocate_c_buf();
    DCELL *coverbuf = Rast_allocate_d_buf();
    int row, col;

    G_message(_("Computing histograms"));

    for (row = 0; row < rows; row++) {
	Rast_get_c_row(basefile, basebuf, row);
	Rast_get_d_row(coverfile, coverbuf, row);

	for (col = 0; col < cols; col++) {
	    struct basecat *bc;
	    int i;

	    if (Rast_is_c_null_value(&basebuf[col]))
		continue;

	    if (Rast_is_d_null_value(&coverbuf[col]))
		continue;

	    i = get_slot(coverbuf[col]);
	    bc = &basecats[basebuf[col] - min];

	    bc->slots[i]++;
	    bc->total++;
	}

	G_percent(row, rows, 2);
    }

    G_percent(rows, rows, 2);
    G_free(basebuf);
    G_free(coverbuf);
}
Ejemplo n.º 18
0
/* 
 * do_histogram() - Creates histogram for CELL
 *
 * RETURN: EXIT_SUCCESS / EXIT_FAILURE
 */
int do_histogram(const char *name)
{
    CELL *cell;
    struct Cell_head cellhd;
    struct Cell_stats statf;
    int nrows, ncols;
    int row;
    int fd;

    Rast_get_cellhd(name, "", &cellhd);

    Rast_set_window(&cellhd);
    fd = Rast_open_old(name, "");

    nrows = Rast_window_rows();
    ncols = Rast_window_cols();
    cell = Rast_allocate_c_buf();

    Rast_init_cell_stats(&statf);
    for (row = 0; row < nrows; row++) {
	Rast_get_c_row_nomask(fd, cell, row);
	Rast_update_cell_stats(cell, ncols, &statf);
    }

    if (row == nrows)
	Rast_write_histogram_cs(name, &statf);

    Rast_free_cell_stats(&statf);
    Rast_close(fd);
    G_free(cell);

    if (row < nrows)
	return -1;

    return 0;
}
Ejemplo n.º 19
0
int close_maps(char *stream_rast, char *stream_vect, char *dir_rast)
{
    int stream_fd, dir_fd, r, c, i;
    CELL *cell_buf1, *cell_buf2;
    struct History history;
    CELL stream_id;
    ASP_FLAG af;

    /* cheating... */
    stream_fd = dir_fd = -1;
    cell_buf1 = cell_buf2 = NULL;

    G_message(_("Writing output raster maps..."));
    
    /* write requested output rasters */
    if (stream_rast) {
	stream_fd = Rast_open_new(stream_rast, CELL_TYPE);
	cell_buf1 = Rast_allocate_c_buf();
    }
    if (dir_rast) {
	dir_fd = Rast_open_new(dir_rast, CELL_TYPE);
	cell_buf2 = Rast_allocate_c_buf();
    }

    for (r = 0; r < nrows; r++) {
	G_percent(r, nrows, 2);
	if (stream_rast)
	    Rast_set_c_null_value(cell_buf1, ncols);	/* reset row to all NULL */
	if (dir_rast)
	    Rast_set_c_null_value(cell_buf2, ncols);	/* reset row to all NULL */

	for (c = 0; c < ncols; c++) {
	    if (stream_rast) {
		cseg_get(&stream, &stream_id, r, c);
		if (stream_id)
		    cell_buf1[c] = stream_id;
	    }
	    if (dir_rast) {
		seg_get(&aspflag, (char *)&af, r, c);
		if (!FLAG_GET(af.flag, NULLFLAG)) {
		    cell_buf2[c] = af.asp;
		}
	    }
	    
	}
	if (stream_rast)
	    Rast_put_row(stream_fd, cell_buf1, CELL_TYPE);
	if (dir_rast)
	    Rast_put_row(dir_fd, cell_buf2, CELL_TYPE);
    }
    G_percent(nrows, nrows, 2);	/* finish it */

    if (stream_rast) {
	Rast_close(stream_fd);
	G_free(cell_buf1);
	Rast_short_history(stream_rast, "raster", &history);
	Rast_command_history(&history);
	Rast_write_history(stream_rast, &history);
    }
    if (dir_rast) {
	struct Colors colors;

	Rast_close(dir_fd);
	G_free(cell_buf2);

	Rast_short_history(dir_rast, "raster", &history);
	Rast_command_history(&history);
	Rast_write_history(dir_rast, &history);

	Rast_init_colors(&colors);
	Rast_make_aspect_colors(&colors, -8, 8);
	Rast_write_colors(dir_rast, G_mapset(), &colors);
    }

    /* close stream vector */
    if (stream_vect) {
	if (close_streamvect(stream_vect) < 0)
	    G_fatal_error(_("Unable to write vector map <%s>"), stream_vect);
    }

    /* rearranging desk chairs on the Titanic... */
    G_free(outlets);

    /* free stream nodes */
    for (i = 1; i <= n_stream_nodes; i++) {
	if (stream_node[i].n_alloc > 0) {
	    G_free(stream_node[i].trib);
	}
    }
    G_free(stream_node);

    return 1;
}
Ejemplo n.º 20
0
int main(int argc, char *argv[])
{
    int i, j, nlines, type, field, cat;
    int fd;

    /* struct Categories RCats; *//* TODO */
    struct Cell_head window;
    RASTER_MAP_TYPE out_type;
    CELL *cell;
    DCELL *dcell;
    double drow, dcol;
    char buf[2000];
    struct Option *vect_opt, *rast_opt, *field_opt, *col_opt, *where_opt;
    int Cache_size;
    struct order *cache;
    int cur_row;
    struct GModule *module;

    struct Map_info Map;
    struct line_pnts *Points;
    struct line_cats *Cats;
    int point;
    int point_cnt;		/* number of points in cache */
    int outside_cnt;		/* points outside region */
    int nocat_cnt;		/* points inside region but without category */
    int dupl_cnt;		/* duplicate categories */
    struct bound_box box;

    int *catexst, *cex;
    struct field_info *Fi;
    dbString stmt;
    dbDriver *driver;
    int select, norec_cnt, update_cnt, upderr_cnt, col_type;

    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("vector"));
    G_add_keyword(_("raster"));
    G_add_keyword(_("position"));
    G_add_keyword(_("querying"));
    G_add_keyword(_("attribute table"));
    module->description =
	_("Uploads raster values at positions of vector points to the table.");

    vect_opt = G_define_standard_option(G_OPT_V_INPUT);
    vect_opt->key = "vector";
    vect_opt->description =
	_("Name of input vector points map for which to edit attribute table");

    rast_opt = G_define_standard_option(G_OPT_R_INPUT);
    rast_opt->key = "raster";
    rast_opt->description = _("Name of existing raster map to be queried");

    field_opt = G_define_standard_option(G_OPT_V_FIELD);

    col_opt = G_define_option();
    col_opt->key = "column";
    col_opt->type = TYPE_STRING;
    col_opt->required = YES;
    col_opt->description =
	_("Column name (will be updated by raster values)");

    where_opt = G_define_standard_option(G_OPT_DB_WHERE);

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


    field = atoi(field_opt->answer);

    db_init_string(&stmt);
    Points = Vect_new_line_struct();
    Cats = Vect_new_cats_struct();

    G_get_window(&window);
    Vect_region_box(&window, &box);	/* T and B set to +/- PORT_DOUBLE_MAX */

    /* Open vector */
    Vect_set_open_level(2);
    Vect_open_old(&Map, vect_opt->answer, "");

    Fi = Vect_get_field(&Map, field);
    if (Fi == NULL)
	G_fatal_error(_("Database connection not defined for layer %d"),
		      field);

    /* Open driver */
    driver = db_start_driver_open_database(Fi->driver, Fi->database);
    if (driver == NULL) {
	G_fatal_error(_("Unable to open database <%s> by driver <%s>"),
		      Fi->database, Fi->driver);
    }

    /* Open raster */
    fd = Rast_open_old(rast_opt->answer, "");

    out_type = Rast_get_map_type(fd);

    /* TODO: Later possibly category labels */
    /* 
       if ( Rast_read_cats (name, "", &RCats) < 0 )
       G_fatal_error ( "Cannot read category file");
     */

    /* Check column type */
    col_type = db_column_Ctype(driver, Fi->table, col_opt->answer);

    if (col_type == -1)
	G_fatal_error(_("Column <%s> not found"), col_opt->answer);

    if (col_type != DB_C_TYPE_INT && col_type != DB_C_TYPE_DOUBLE)
	G_fatal_error(_("Column type not supported"));

    if (out_type == CELL_TYPE && col_type == DB_C_TYPE_DOUBLE)
	G_warning(_("Raster type is integer and column type is float"));

    if (out_type != CELL_TYPE && col_type == DB_C_TYPE_INT)
	G_warning(_("Raster type is float and column type is integer, some data lost!!"));

    /* Read vector points to cache */
    Cache_size = Vect_get_num_primitives(&Map, GV_POINT);
    /* Note: Some space may be wasted (outside region or no category) */

    cache = (struct order *)G_calloc(Cache_size, sizeof(struct order));

    point_cnt = outside_cnt = nocat_cnt = 0;

    nlines = Vect_get_num_lines(&Map);

    G_debug(1, "Reading %d vector features fom map", nlines);

    for (i = 1; i <= nlines; i++) {
	type = Vect_read_line(&Map, Points, Cats, i);
	G_debug(4, "line = %d type = %d", i, type);

	/* check type */
	if (!(type & GV_POINT))
	    continue;		/* Points only */

	/* check region */
	if (!Vect_point_in_box(Points->x[0], Points->y[0], 0.0, &box)) {
	    outside_cnt++;
	    continue;
	}

	Vect_cat_get(Cats, field, &cat);
	if (cat < 0) {		/* no category of given field */
	    nocat_cnt++;
	    continue;
	}

	G_debug(4, "    cat = %d", cat);

	/* Add point to cache */
	drow = Rast_northing_to_row(Points->y[0], &window);
	dcol = Rast_easting_to_col(Points->x[0], &window);

	/* a special case.
	 *   if north falls at southern edge, or east falls on eastern edge,
	 *   the point will appear outside the window.
	 *   So, for these edges, bring the point inside the window
	 */
	if (drow == window.rows)
	    drow--;
	if (dcol == window.cols)
	    dcol--;

	cache[point_cnt].row = (int)drow;
	cache[point_cnt].col = (int)dcol;
	cache[point_cnt].cat = cat;
	cache[point_cnt].count = 1;
	point_cnt++;
    }

    Vect_set_db_updated(&Map);
    Vect_hist_command(&Map);
    Vect_close(&Map);

    G_debug(1, "Read %d vector points", point_cnt);
    /* Cache may contain duplicate categories, sort by cat, find and remove duplicates 
     * and recalc count and decrease point_cnt  */
    qsort(cache, point_cnt, sizeof(struct order), by_cat);

    G_debug(1, "Points are sorted, starting duplicate removal loop");

    for (i = 0, j = 1; j < point_cnt; j++)
	if (cache[i].cat != cache[j].cat)
	    cache[++i] = cache[j];
	else
	    cache[i].count++;
    point_cnt = i + 1;

    G_debug(1, "%d vector points left after removal of duplicates",
	    point_cnt);

    /* Report number of points not used */
    if (outside_cnt)
	G_warning(_("%d points outside current region were skipped"),
		  outside_cnt);

    if (nocat_cnt)
	G_warning(_("%d points without category were skipped"), nocat_cnt);

    /* Sort cache by current region row */
    qsort(cache, point_cnt, sizeof(struct order), by_row);

    /* Allocate space for raster row */
    if (out_type == CELL_TYPE)
	cell = Rast_allocate_c_buf();
    else
	dcell = Rast_allocate_d_buf();

    /* Extract raster values from file and store in cache */
    G_debug(1, "Extracting raster values");

    cur_row = -1;

    for (point = 0; point < point_cnt; point++) {
	if (cache[point].count > 1)
	    continue;		/* duplicate cats */

	if (cur_row != cache[point].row) {
	    if (out_type == CELL_TYPE)
		Rast_get_c_row(fd, cell, cache[point].row);
	    else
		Rast_get_d_row(fd, dcell, cache[point].row);
	}
	cur_row = cache[point].row;

	if (out_type == CELL_TYPE) {
	    cache[point].value = cell[cache[point].col];
	}
	else {
	    cache[point].dvalue = dcell[cache[point].col];
	}
    }				/* point loop */

    /* Update table from cache */
    G_debug(1, "Updating db table");

    /* select existing categories to array (array is sorted) */
    select = db_select_int(driver, Fi->table, Fi->key, NULL, &catexst);

    db_begin_transaction(driver);

    norec_cnt = update_cnt = upderr_cnt = dupl_cnt = 0;

    for (point = 0; point < point_cnt; point++) {
	if (cache[point].count > 1) {
	    G_warning(_("More points (%d) of category %d, value set to 'NULL'"),
		      cache[point].count, cache[point].cat);
	    dupl_cnt++;
	}

	/* category exist in DB ? */
	cex =
	    (int *)bsearch((void *)&(cache[point].cat), catexst, select,
			   sizeof(int), srch_cat);
	if (cex == NULL) {	/* cat does not exist in DB */
	    norec_cnt++;
	    G_warning(_("No record for category %d in table <%s>"),
		      cache[point].cat, Fi->table);
	    continue;
	}

	sprintf(buf, "update %s set %s = ", Fi->table, col_opt->answer);

	db_set_string(&stmt, buf);

	if (out_type == CELL_TYPE) {
	    if (cache[point].count > 1 ||
		Rast_is_c_null_value(&cache[point].value)) {
		sprintf(buf, "NULL");
	    }
	    else {
		sprintf(buf, "%d ", cache[point].value);
	    }
	}
	else {			/* FCELL or DCELL */
	    if (cache[point].count > 1 ||
		Rast_is_d_null_value(&cache[point].dvalue)) {
		sprintf(buf, "NULL");
	    }
	    else {
		sprintf(buf, "%.10f", cache[point].dvalue);
	    }
	}
	db_append_string(&stmt, buf);

	sprintf(buf, " where %s = %d", Fi->key, cache[point].cat);
	db_append_string(&stmt, buf);
	/* user provides where condition: */
	if (where_opt->answer) {
	    sprintf(buf, " AND %s", where_opt->answer);
	    db_append_string(&stmt, buf);
	}
	G_debug(3, db_get_string(&stmt));

	/* Update table */
	if (db_execute_immediate(driver, &stmt) == DB_OK) {
	    update_cnt++;
	}
	else {
	    upderr_cnt++;
	}
    }

    G_debug(1, "Committing DB transaction");
    db_commit_transaction(driver);
    G_free(catexst);
    db_close_database_shutdown_driver(driver);
    db_free_string(&stmt);

    /* Report */
    G_message(_("%d categories loaded from table"), select);
    G_message(_("%d categories loaded from vector"), point_cnt);
    G_message(_("%d categories from vector missing in table"), norec_cnt);
    G_message(_("%d duplicate categories in vector"), dupl_cnt);
    if (!where_opt->answer)
	G_message(_("%d records updated"), update_cnt);
    G_message(_("%d update errors"), upderr_cnt);

    exit(EXIT_SUCCESS);
}
Ejemplo n.º 21
0
Archivo: sample.c Proyecto: caomw/grass
/* CALCULATE THE COORDINATES OF THE TOP LEFT CORNER OF THE SAMPLING UNITS */
static int calc_unit_loc(double radius, int top, int bot, int left, int right,
			 double ratio, int u_w, int u_l, int method,
			 double intv, int num, int h_d, int v_d, double *ux,
			 double *uy, int *sites, double startx, int starty,
			 int fmask, double nx, double x, double y)
{
    char *sites_mapset, sites_file_name[GNAME_MAX], *cmd;
    struct Map_info Map;
    struct Cell_head region;
    double D_u_to_a_col(), D_u_to_a_row();
    int i, j, k, cnt = 0, w_w = right - left, w_l = bot - top, exp1, exp2,
	dx = w_w, dy = w_l, l, t, left1 = left, top1 = top, n, tmp,
	ulrow, ulcol, *row_buf, lap = 0;
    static struct line_pnts *Points;
    struct line_cats *Cats;
    int ltype;

    /*   VARIABLES:
       UNITS FOR ALL DIMENSION VARIABLES IN THIS ROUTINE ARE IN PIXELS

       top  =       sampling frame top row in pixels
       bot  =       sampling frame bottom row in pixels
       left =       sampling frame left in pixels
       right        =       sampling frame right in pixels
       left1        =       col of left side of sampling frame or each stratum
       top1 =       row of top side of sampling frame or each stratum
       l    =       random # cols to be added to left1
       r    =       random # rows to be added to top1
       ratio        =
       u_w  =       sampling unit width in pixels
       u_l  =       sampling unit length in pixels
       method       =       method of sampling unit distribution (1-5)
       intv =       interval between sampling units when method=3
       num  =       number of sampling units
       h_d  =       number of horizontal strata
       v_d  =       number of vertical strata
       ux   =
       uy   =
       sites        =
       startx       =       col of UL corner starting pt for strata
       starty       =       row of UL corner starting pt for strata
       dx   =       number of cols per stratum
       dy   =       number of rows per stratum
       w_w  =       width of sampling frame in cols
       w_l  =       length of sampling frame in rows
     */


    /* if user hits Ctrl+C, abort this
       calculation */

    setjmp(jmp);
    if (tag) {
	tag = 0;
	return 0;
    }

    /* for syst. noncontig. distribution */

    if (method == 3) {
	u_w += intv;
	u_l += intv;
    }

    /* for stratified random distribution */

    if (method == 4) {
	dx = (int)((double)(w_w - startx) / (double)(h_d));
	dy = (int)((double)(w_l - starty) / (double)(v_d));
    }

    /* for syst. contig. and noncontig.
       distribution */

    else if (method == 2 || method == 3) {
	if (nx >= num)
	    dx = (w_w - startx) - (num - 1) * u_w;
	else {
	    dx = (w_w - startx) - (nx - 1) * u_w;
	    dy = (w_l - starty) - (num / nx - 1) * u_l;
	}
    }

    if (10 > (exp1 = (int)pow(10.0, ceil(log10((double)(dx - u_w + 10))))))
	exp1 = 10;
    if (10 > (exp2 = (int)pow(10.0, ceil(log10((double)(dy - u_l + 10))))))
	exp2 = 10;

    /* for random nonoverlapping and stratified
       random */

    if (method == 1 || method == 4) {

	fprintf(stderr,
		"\n   'Ctrl+C' and choose fewer units if the requested number");
	fprintf(stderr, " is not reached\n");


	for (i = 0; i < num; i++) {

	    /* if Cntl+C */

	    if (signal(SIGINT, SIG_IGN) != SIG_IGN)
		signal(SIGINT, f);

	    /* for stratified random distribution */

	    if (method == 4) {
		j = 0;
		if (n = i % h_d)
		    left1 += dx;
		else {
		    left1 = left + startx;
		    if (i < h_d)
			top1 = top + starty;
		    else
			top1 += dy;
		}
		get_rd(exp1, exp2, dx, dy, u_w, u_l, &l, &t);

	    }

	    /* for random nonoverlapping distribution */

	    if (method == 1) {

		/* get random numbers */
	      back:
		get_rd(exp1, exp2, dx, dy, u_w, u_l, &l, &t);

		if (left1 + l + u_w > right || top1 + t + u_l > bot ||
		    left1 + l < left || top1 + t < top)
		    goto back;

		/* if there is a mask, check to see that
		   the unit will be within the mask area */

		if (fmask > 0) {
		    row_buf = Rast_allocate_c_buf();
		    Rast_get_c_row_nomask(fmask, row_buf, t + top1);
		    if (!
			(*(row_buf + l + left1) &&
			 *(row_buf + l + left1 + u_w - 1)))
			goto back;
		    Rast_zero_c_buf(row_buf);
		    Rast_get_c_row_nomask(fmask, row_buf, t + top1 + u_l - 1);
		    if (!
			(*(row_buf + l + left1) &&
			 *(row_buf + l + left1 + u_w - 1)))
			goto back;
		    G_free(row_buf);
		}

		/* check for sampling unit overlap */

		lap = 0;
		for (j = 0; j < cnt; j++) {
		    if (overlap
			(l + left1, t + top1, (int)ux[j], (int)uy[j], u_w,
			 u_l))
			lap = 1;
		}
		if (lap)
		    goto back;

		cnt++;
	    }
	    /* fill the array of upper left coordinates
	       for the sampling units */

	    *(ux + i) = l + left1;
	    *(uy + i) = t + top1;

	    /* draw the sampling units on the
	       screen */

	    R_open_driver();
	    R_standard_color(D_translate_color("red"));
	    if (radius)
		draw_circle((int)((double)(ux[i]) / x),
			    (int)((double)(uy[i]) / y),
			    (int)((double)(ux[i] + u_w) / x),
			    (int)((double)(uy[i] + u_l) / y), 3);
	    else
		draw_box((int)((double)(ux[i]) / x),
			 (int)((double)(uy[i]) / y),
			 (int)((double)(ux[i] + u_w) / x),
			 (int)((double)(uy[i] + u_l) / y), 1);
	    R_close_driver();
	    fprintf(stderr, "    Distributed unit %4d of %4d requested\r",
		    i + 1, num);

	}
    }

    /* for syst. contig. & syst. noncontig. */

    else if (method == 2 || method == 3) {
	for (i = 0; i < num; i++) {
	    *(ux + i) =
		left + startx + u_w * (i - nx * floor((double)i / nx));
	    *(uy + i) = top + starty + u_l * floor((double)i / nx);
	}
    }

    /* for centered over sites */

    else if (method == 5) {
	sites_mapset =
	    G_ask_vector_old("    Enter name of vector points map",
			     sites_file_name);
	if (sites_mapset == NULL) {
	    G_system("d.frame -e");
	    exit(0);
	}

	if (Vect_open_old(&Map, sites_file_name, sites_mapset) < 0)
	    G_fatal_error(_("Unable to open vector map <%s>"), sites_file_name);
	/*    fprintf(stderr, "\n    Can't open vector points file %s\n", sites_file_name); */

	*sites = 0;
	i = 0;
	n = 0;

	Points = Vect_new_line_struct();	/* init line_pnts struct */
	Cats = Vect_new_cats_struct();

	while (1) {
	    ltype = Vect_read_next_line(&Map, Points, Cats);
	    if (ltype == -1)
		G_fatal_error(_("Cannot read vector"));
	    if (ltype == -2)
		break;		/* EOF */
	    /* point features only. (GV_POINTS is pts AND centroids, GV_POINT is just pts) */
	    if (!(ltype & GV_POINT))
		continue;

	    ulcol = ((int)(D_u_to_a_col(Points->x[0]))) + 1 - u_w / 2;
	    ulrow = ((int)(D_u_to_a_row(Points->y[0]))) + 1 - u_l / 2;
	    if (ulcol <= left || ulrow <= top || ulcol + u_w - 1 > right ||
		ulrow + u_l - 1 > bot) {
		fprintf(stderr,
			"    No sampling unit over site %d at east=%8.1f north=%8.1f\n",
			n + 1, Points->x[0], Points->y[0]);
		fprintf(stderr,
			"       as it would extend outside the map\n");

	    }
	    else {
		*(ux + i) = ulcol - 1;
		*(uy + i) = ulrow - 1;
		i++;
	    }
	    n++;
	    if (n > 250)
		G_fatal_error
		    ("There are more than the maximum of 250 sites\n");
	}
	fprintf(stderr, "    Total sites with sampling units = %d\n", i);

	*sites = i;
	cmd = G_malloc(100);
	sprintf(cmd, "d.vect %s color=black", sites_file_name);
	G_system(cmd);
	G_free(cmd);

	Vect_close(&Map);
	G_free(Points);
	G_free(Cats);

    }

    return 1;

}
Ejemplo n.º 22
0
Archivo: sample.c Proyecto: caomw/grass
static void graph_unit(int t, int b, int l, int r, char *n1, char *n2,
		       char *n3, double *mx, int fmask)
{
    int x0 = 0, y0 = 0, xp, yp, ux[250], uy[250], u_w, u_l, btn = 0, k = 0,
	w_w = 0, w_l = 0, *row_buf, at, ab, al, ar, circle = 0,
	tmpw, tmpl, au_w, au_l, lap = 0, l0 = 0, r0 = 0, t0 = 0, b0 = 0;
    FILE *fp;
    double tmp, radius = 0.0;
    register int i, j;

    /*  VARIABLES:
       COORDINATES IN THIS ROUTINE ARE IN CELLS

       t    =       top row of sampling frame
       b    =       bottom row of sampling frame
       l    =       left col of sampling frame
       r    =       right col of sampling frame
       n1   =
       n2   =
       n3   =
       mx[0]        =       cols of region/width of screen
       mx[1]        =       rows of region/height of screen
       xp   =       mouse x location in screen coordinates (col)
       yp   =       mouse y location in screen coordinates (row)
       ar   =       mouse x location in map coordinates (col)
       al   =       mouse y location in map coordinates (row)

     */


    l0 = l;
    r0 = r;
    t0 = t;
    b0 = b;

    l = (int)((double)(l * mx[0]) + 0.5);
    r = (int)((double)(r * mx[0]) + 0.5);
    t = (int)((double)(t * mx[1]) + 0.5);
    b = (int)((double)(b * mx[1]) + 0.5);
    w_w = r - l;
    w_l = b - t;

    /* draw the sampling frame */

    R_open_driver();
    R_standard_color(D_translate_color("grey"));
    draw_box((int)(l / mx[0]), (int)(t / mx[1]), (int)(r / mx[0]),
	     (int)(b / mx[1]), 1);
    R_close_driver();

    fp = fopen0("r.le.para/units", "w");
    G_sleep_on_error(0);

    /* get the number of scales */

    do {
	fprintf(stderr,
		"\n    How many different SCALES do you want? (1-15)  ");

	numtrap(1, &tmp);
	if (tmp < 1 || tmp > 15)
	    fprintf(stderr,
		    "    Too many (>15) or too few scales, try again.\n");
    }
    while (tmp < 1 || tmp > 15);
    fprintf(fp, "%10d    # of scales\n", (int)(tmp));

    /* for each scale */

    for (i = 0; i < tmp; i++) {
	G_system("clear");

	radius = 0.0;
	circle = 0;

	/* if sampling using circles */

	fprintf(stderr, "\n    SCALE %d\n", i + 1);
	fprintf(stderr, "\n    Do you want to sample using rectangles");

	if (!G_yes("\n       (including squares) (y) or circles (n)?   ", 1)) {
	    circle = 1;
	    fprintf(stderr,
		    "\n    Draw a rectangular area to contain a standard circular");
	    fprintf(stderr,
		    "\n    sampling unit of scale %d.  First select upper left",
		    i + 1);
	    fprintf(stderr, "\n    corner, then lower right:\n");
	    fprintf(stderr, "       Left button:     Check unit size\n");
	    fprintf(stderr,
		    "       Middle button:   Upper left corner of area here\n");
	    fprintf(stderr,
		    "       Right button:    Lower right corner of area here\n");

	}

	else {
	    fprintf(stderr,
		    "\n    Draw a standard rectangular unit of scale %d.",
		    i + 1);
	    fprintf(stderr,
		    "\n    First select upper left corner, then lower right:\n");
	    fprintf(stderr, "       Left button:     Check unit size\n");
	    fprintf(stderr,
		    "       Middle button:   Upper left corner of unit here\n");
	    fprintf(stderr,
		    "       Right button:    Lower right corner of unit here\n");

	}

	R_open_driver();

	do {
	  back1:
	    R_get_location_with_box(x0, y0, &xp, &yp, &btn);

	    /* convert the upper left screen coordinate
	       (x0, y0) and the mouse position (xp, yp)
	       on the screen to the nearest row and
	       column; do the same for the sampling
	       unit width (u_w) and height (u_l);
	       then convert back */

	    ar = (int)((double)(xp) * mx[0] + 0.5);
	    xp = (int)((double)(ar) / mx[0] + 0.5);
	    al = (int)((double)(x0) * mx[0] + 0.5);
	    x0 = (int)((double)(al) / mx[0] + 0.5);
	    au_w = ar - al;
	    u_w = (int)((double)(au_w) / mx[0] + 0.5);
	    ab = (int)((double)(yp) * mx[1] + 0.5);
	    yp = (int)((double)(ab) / mx[1] + 0.5);
	    at = (int)((double)(y0) * mx[1] + 0.5);
	    y0 = (int)((double)(at) / mx[1] + 0.5);
	    au_l = ab - at;
	    u_l = (int)((double)(au_l) / mx[1] + 0.5);


	    /* left button, check the size of the rubber
	       box in array system */

	    if (btn == 1) {
		if (ar > r || ab > b || ar < l || ab < t) {
		    fprintf(stderr,
			    "\n    This point is not in the sampling frame; try again\n");

		    goto back1;
		}
		if (x0 < l || y0 < t) {
		    fprintf(stderr,
			    "\n    Use the middle button to first put the upper left");
		    fprintf(stderr,
			    "\n    corner inside the sampling frame\n");

		    goto back1;
		}
		if (ar <= al || ab <= at) {
		    fprintf(stderr,
			    "\n    Please put the lower right corner down and to");
		    fprintf(stderr,
			    "\n    the right of the upper left corner\n");

		    goto back1;
		}
		else {
		    fprintf(stderr,
			    "\n    Unit would be %d columns wide by %d rows long\n",
			    abs(au_w), abs(au_l));
		    fprintf(stderr,
			    "    Width/length would be %5.2f and size %d pixels\n",
			    (double)abs((au_w)) / (double)abs((au_l)),
			    abs(au_w) * abs(au_l));

		}
	    }

	    /* mid button, move the start point of the
	       rubber box */

	    else if (btn == 2) {
		if (ar > r || ab > b || ar < l || ab < t) {
		    fprintf(stderr,
			    "\n    Point is not in the sampling frame; try again\n");

		    goto back1;
		}
		else {
		    R_move_abs(xp, yp);
		    x0 = xp;
		    y0 = yp;
		}
	    }

	    /* right button, outline the unit */

	    else if (btn == 3) {

		if (circle) {
		    if (u_w > u_l) {
			al = al + ((ar - al) - (ab - at)) / 2;
			ar = al + (ab - at);
			x0 = (int)((double)(al) / mx[0] + 0.5);
			xp = (int)((double)(ar) / mx[0] + 0.5);
			au_w = ar - al;
			u_w = u_l = (int)((double)(au_w) / mx[0] + 0.5);
		    }
		    if (u_l > u_w) {
			at = at + ((ab - at) - (ar - al)) / 2;
			ab = at + (ar - al);
			y0 = (int)((double)(at) / mx[1] + 0.5);
			yp = (int)((double)(ab) / mx[1] + 0.5);
			au_l = ab - at;
			u_w = u_l = (int)((double)(au_l) / mx[1] + 0.5);
		    }
		}

		if (ar > r || ab > b || al < l || at < t) {
		    fprintf(stderr,
			    "\n    The unit extends outside the sampling frame or map;");
		    fprintf(stderr, "\n       try again\n");

		    goto back1;
		}

		if (au_w > w_w || au_l > w_l) {
		    fprintf(stderr,
			    "\n    The unit is too big for the sampling frame; ");
		    fprintf(stderr, "try again\n");

		    goto back1;
		}

		/* if there is a mask, check to see that
		   the unit will be within the mask area,
		   by checking to see whether the four
		   corners of the unit are in the mask */

		if (fmask > 0) {
		    row_buf = Rast_allocate_c_buf();
		    Rast_get_c_row_nomask(fmask, row_buf, at);
		    if (!(*(row_buf + al) && *(row_buf + ar - 1))) {
			fprintf(stderr,
				"\n    The unit would be outside the mask; ");
			fprintf(stderr, "try again\n");

			G_free(row_buf);
			goto back1;
		    }
		    Rast_zero_c_buf(row_buf);
		    Rast_get_c_row_nomask(fmask, row_buf, ab - 1);
		    if (!(*(row_buf + al) && *(row_buf + ar - 1))) {
			fprintf(stderr,
				"\n    The unit would be outside the mask; ");
			fprintf(stderr, "try again\n");

			G_free(row_buf);
			goto back1;
		    }
		    G_free(row_buf);
		}

		if (xp - x0 > 0 && yp - y0 > 0) {
		    R_standard_color(D_translate_color("red"));
		    if (circle)
			draw_circle(x0, y0, xp, yp, 3);
		    else
			draw_box(x0, y0, xp, yp, 1);
		    G_system("clear");
		    if (circle) {
			fprintf(stderr,
				"\n\n    The standard circular sampling unit has:\n");
			fprintf(stderr, "       radius = %f pixels\n",
				(double)(ar - al) / 2.0);

		    }
		    else {
			fprintf(stderr,
				"\n\n    The standard sampling unit has:\n");
			fprintf(stderr, "       columns=%d    rows=%d\n",
				abs(ar - al), abs(ab - at));
			fprintf(stderr, "       width/length ratio=%5.2f\n",
				(double)abs(ar - al) / (double)abs(ab - at));
			fprintf(stderr, "       size=%d pixels\n",
				abs(ar - al) * abs(ab - at));

		    }
		    k = 0;
		    ux[0] = al;
		    uy[0] = at;
		}
		else if (xp - x0 == 0 || yp - y0 == 0) {
		    fprintf(stderr,
			    "\n    Unit has 0 rows and/or 0 columns; try again\n");

		    goto back1;
		}
		else {
		    fprintf(stderr,
			    "\n    You did not put the lower right corner below");
		    fprintf(stderr,
			    "\n       and to the right of the upper left corner. Please try again");

		    goto back1;
		}
	    }
	}
	while (btn != 3);
	R_close_driver();

	/* use the size and shape of the
	   standard unit to outline more units
	   in that scale */

	fprintf(stderr, "\n    Outline more sampling units of scale %d?\n",
		i + 1);
	fprintf(stderr, "       Left button:     Exit\n");
	fprintf(stderr, "       Middle button:   Check unit position\n");
	fprintf(stderr,
		"       Right button:    Lower right corner of next unit here\n");

	R_open_driver();

	/* if not the left button (to exit) */

      back2:
	while (btn != 1) {
	    R_get_location_with_box(xp - u_w, yp - u_l, &xp, &yp, &btn);

	    /* convert the left (x0), right (y0),
	       top (y0), bottom (yp) coordinates in
	       screen pixels to the nearest row and
	       column; do the same for the sampling
	       unit width (u_w) and height (u_l);
	       then convert back */

	    ar = (int)((double)(xp) * mx[0] + 0.5);
	    ab = (int)((double)(yp) * mx[1] + 0.5);
	    xp = (int)((double)(ar) / mx[0] + 0.5);
	    yp = (int)((double)(ab) / mx[1] + 0.5);
	    al = (int)((double)(xp - u_w) * mx[0] + 0.5);
	    at = (int)((double)(yp - u_l) * mx[0] + 0.5);
	    x0 = (int)((double)(al) / mx[0] + 0.5);
	    y0 = (int)((double)(at) / mx[1] + 0.5);


	    /* if right button, outline the unit */

	    if (btn == 3) {

		if (ar > r || ab > b || al < l || at < t) {
		    fprintf(stderr,
			    "\n    The unit would be outside the map; try again");
		    goto back2;

		}

		/* if there is a mask, check to see that
		   the unit will be within the mask area */

		if (fmask > 0) {
		    row_buf = Rast_allocate_c_buf();
		    Rast_get_c_row_nomask(fmask, row_buf, at);
		    if (!(*(row_buf + al) && *(row_buf + ar - 1))) {
			fprintf(stderr,
				"\n    The unit would be outside the mask; ");
			fprintf(stderr, "try again");

			G_free(row_buf);
			goto back2;
		    }
		    Rast_zero_c_buf(row_buf);
		    Rast_get_c_row_nomask(fmask, row_buf, ab - 1);
		    if (!(*(row_buf + al) && *(row_buf + ar - 1))) {
			fprintf(stderr,
				"\n    The unit would be outside the mask; ");
			fprintf(stderr, "try again");
			G_free(row_buf);
			goto back2;
		    }
		    G_free(row_buf);
		}

		/* check for sampling unit overlap */

		lap = 0;
		for (j = 0; j < k + 1; j++) {
		    if (overlap(al, at, ux[j], uy[j], au_w, au_l)) {
			fprintf(stderr,
				"\n    The unit would overlap a previously drawn ");
			fprintf(stderr, "unit; try again");

			lap = 1;
		    }
		}
		if (lap)
		    goto back2;

		k++;
		fprintf(stderr, "\n    %d sampling units have been placed",
			(k + 1));

		ux[k] = al;
		uy[k] = at;
		R_standard_color(D_translate_color("red"));
		if (circle)
		    draw_circle(x0, y0, xp, yp, 3);
		else
		    draw_box(x0, y0, xp, yp, 1);
	    }
	}
	R_close_driver();

	/* save the sampling units in the
	   r.le.para/units file */

	if (circle)
	    radius = (double)(ar - al) / 2.0;
	else
	    radius = 0.0;
	fprintf(fp, "%10d    # of units of scale %d\n", k + 1, i + 1);
	fprintf(fp, "%10d%10d   u_w, u_l of units in scale %d\n",
		(int)(u_w * mx[0]), (int)(u_l * mx[1]), i + 1);
	fprintf(fp, "%10.1f             radius of circles in scale %d\n",
		radius, (i + 1));
	for (j = 0; j < k + 1; j++)
	    fprintf(fp, "%10d%10d   left, top of unit[%d]\n", ux[j], uy[j],
		    j + 1);

	if (i < tmp - 1 && G_yes("\n    Refresh the screen?   ", 1)) {
	    paint_map(n1, n2, n3);
	    R_open_driver();
	    R_standard_color(D_translate_color("red"));
	    R_close_driver();
	}
    }

    fclose(fp);
    return;
}
Ejemplo n.º 23
0
int open_files(void)
{
    char *name, *mapset;
    FILE *fd;
    int n;

    I_init_group_ref(&Ref);
    if (!I_find_group(group))
	G_fatal_error(_("Group <%s> not found"), group);

    if (!I_find_subgroup(group, subgroup))
	G_fatal_error(_("Subgroup <%s> in group <%s> not found"),
		      subgroup, group);

    I_get_subgroup_ref(group, subgroup, &Ref);

    if (Ref.nfiles <= 1) {
	if (Ref.nfiles <= 0)
	    G_fatal_error(_("Subgroup <%s> of group <%s> doesn't have any raster maps. "
			    "The subgroup must have at least 2 raster maps."));
	else
	    G_fatal_error(_("Subgroup <%s> of group <%s> only has 1 raster map. "
			    "The subgroup must have at least 2 raster maps."));
    }

    cell = (DCELL **) G_malloc(Ref.nfiles * sizeof(DCELL *));
    cellfd = (int *)G_malloc(Ref.nfiles * sizeof(int));
    P = (double *)G_malloc(Ref.nfiles * sizeof(double));
    for (n = 0; n < Ref.nfiles; n++) {
	cell[n] = Rast_allocate_d_buf();
	name = Ref.file[n].name;
	mapset = Ref.file[n].mapset;
	cellfd[n] = Rast_open_old(name, mapset);
    }

    I_init_signatures(&S, Ref.nfiles);
    fd = I_fopen_signature_file_old(group, subgroup, sigfile);
    if (fd == NULL)
	G_fatal_error(_("Unable to open signature file <%s>"),
		      sigfile);

    n = I_read_signatures(fd, &S);
    fclose(fd);
    if (n < 0)
	G_fatal_error(_("Unable to read signature file <%s>"),
		      sigfile);

    if (S.nsigs > 255)
	G_fatal_error(_("<%s> has too many signatures (limit is 255)"),
		      sigfile);

    B = (double *)G_malloc(S.nsigs * sizeof(double));
    invert_signatures();

    class_fd = Rast_open_c_new(class_name);
    class_cell = Rast_allocate_c_buf();

    reject_cell = NULL;
    if (reject_name) {
	reject_fd = Rast_open_c_new(reject_name);
	reject_cell = Rast_allocate_c_buf();
    }

    return 0;
}
Ejemplo n.º 24
0
int main(int argc, char **argv)
{
    MELEMENT *rowlist;
    SHORT nrows, ncols;
    SHORT datarows;
    int npoints;
    struct GModule *module;
    struct History history;
    struct
    {
	struct Option *input, *output, *npoints;
    } parm;
    struct
    {
	struct Flag *e;
    } flag;
    int n, fd, maskfd;

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

    module = G_define_module();
    G_add_keyword(_("raster"));
    G_add_keyword(_("surface"));
    G_add_keyword(_("interpolation"));
    G_add_keyword(_("IDW"));
    module->description =
	_("Surface interpolation utility for raster map.");

    parm.input = G_define_standard_option(G_OPT_R_INPUT);

    parm.output = G_define_standard_option(G_OPT_R_OUTPUT);

    parm.npoints = G_define_option();
    parm.npoints->key = "npoints";
    parm.npoints->type = TYPE_INTEGER;
    parm.npoints->required = NO;
    parm.npoints->description = _("Number of interpolation points");
    parm.npoints->answer = "12";

    flag.e = G_define_flag();
    flag.e->key = 'e';
    flag.e->description = _("Output is the interpolation error");

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

    if (sscanf(parm.npoints->answer, "%d", &n) != 1 || n <= 0)
	G_fatal_error(_("Illegal value for '%s' (%s)"), parm.npoints->key,
		      parm.npoints->answer);

    npoints = n;
    error_flag = flag.e->answer;
    input = parm.input->answer;
    output = parm.output->answer;

    /*  Get database window parameters                              */
    G_get_window(&window);

    /*  find number of rows and columns in window                   */
    nrows = Rast_window_rows();
    ncols = Rast_window_cols();

    /* create distance squared or latitude lookup tables */
    /* initialize function pointers */
    lookup_and_function_ptrs(nrows, ncols);

    /*  allocate buffers for row i/o                                */
    cell = Rast_allocate_c_buf();
    if ((maskfd = Rast_maskfd()) >= 0 || error_flag) {	/* apply mask to output */
	if (error_flag)		/* use input as mask when -e option chosen */
	    maskfd = Rast_open_old(input, "");
	mask = Rast_allocate_c_buf();
    }
    else
	mask = NULL;

    /*  Open input cell layer for reading                           */
    fd = Rast_open_old(input, "");

    /* Store input data in array-indexed doubly-linked lists and close input file */
    rowlist = row_lists(nrows, ncols, &datarows, &n, fd, cell);
    Rast_close(fd);
    if (npoints > n)
	npoints = n;


    /* open cell layer for writing output              */
    fd = Rast_open_c_new(output);

    /* call the interpolation function                              */
    interpolate(rowlist, nrows, ncols, datarows, npoints, fd, maskfd);

    /* free allocated memory */
    free_row_lists(rowlist, nrows);
    G_free(rowlook);
    G_free(collook);
    if (ll)
	free_dist_params();
    Rast_close(fd);
    /* writing history file */
    Rast_short_history(output, "raster", &history);
    Rast_command_history(&history);
    Rast_write_history(output, &history);

    G_done_msg(" ");
    
    exit(EXIT_SUCCESS);
}
Ejemplo n.º 25
0
Archivo: main.c Proyecto: caomw/grass
int main(int argc, char **argv)
{
    static DCELL *count, *sum, *mean, *sumu, *sum2, *sum3, *sum4, *min, *max;
    DCELL *result;
    struct GModule *module;
    struct {
	struct Option *method, *basemap, *covermap, *output;
    } opt;
    struct {
	struct Flag *c, *r;
    } flag;
    char methods[2048];
    const char *basemap, *covermap, *output;
    int usecats;
    int reclass;
    int base_fd, cover_fd;
    struct Categories cats;
    CELL *base_buf;
    DCELL *cover_buf;
    struct Range range;
    CELL mincat, ncats;
    int method;
    int rows, cols;
    int row, col, i;

    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("raster"));
    G_add_keyword(_("statistics"));
    module->description =
	_("Calculates category or object oriented statistics (accumulator-based statistics).");

    opt.basemap = G_define_standard_option(G_OPT_R_BASE);

    opt.covermap = G_define_standard_option(G_OPT_R_COVER);

    opt.method = G_define_option();
    opt.method->key = "method";
    opt.method->type = TYPE_STRING;
    opt.method->required = YES;
    opt.method->description = _("Method of object-based statistic");

    for (i = 0; menu[i].name; i++) {
	if (i)
	    strcat(methods, ",");
	else
	    *(methods) = 0;
	strcat(methods, menu[i].name);
    }
    opt.method->options = G_store(methods);

    for (i = 0; menu[i].name; i++) {
	if (i)
	    strcat(methods, ";");
	else
	    *(methods) = 0;
	strcat(methods, menu[i].name);
	strcat(methods, ";");
	strcat(methods, menu[i].text);
    }
    opt.method->descriptions = G_store(methods);

    opt.output = G_define_standard_option(G_OPT_R_OUTPUT);
    opt.output->description = _("Resultant raster map");
    opt.output->required = YES;

    flag.c = G_define_flag();
    flag.c->key = 'c';
    flag.c->description =
	_("Cover values extracted from the category labels of the cover map");

    flag.r = G_define_flag();
    flag.r->key = 'r';
    flag.r->description =
	_("Create reclass map with statistics as category labels");

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

    basemap = opt.basemap->answer;
    covermap = opt.covermap->answer;
    output = opt.output->answer;
    usecats = flag.c->answer;
    reclass = flag.r->answer;

    for (i = 0; menu[i].name; i++)
	if (strcmp(menu[i].name, opt.method->answer) == 0)
	    break;

    if (!menu[i].name) {
	G_warning(_("<%s=%s> unknown %s"), opt.method->key, opt.method->answer,
		  opt.method->key);
	G_usage();
	exit(EXIT_FAILURE);
    }

    method = menu[i].val;

    base_fd = Rast_open_old(basemap, "");

    cover_fd = Rast_open_old(covermap, "");

    if (usecats && Rast_read_cats(covermap, "", &cats) < 0)
	G_fatal_error(_("Unable to read category file of cover map <%s>"), covermap);

    if (Rast_map_is_fp(basemap, "") != 0)
	G_fatal_error(_("The base map must be an integer (CELL) map"));

    if (Rast_read_range(basemap, "", &range) < 0)
	G_fatal_error(_("Unable to read range of base map <%s>"), basemap);

    mincat = range.min;
    ncats = range.max - range.min + 1;

    rows = Rast_window_rows();
    cols = Rast_window_cols();

    switch (method) {
    case COUNT:
	count = G_calloc(ncats, sizeof(DCELL));
	break;
    case SUM:
	sum = G_calloc(ncats, sizeof(DCELL));
	break;
    case MIN:
	min = G_malloc(ncats * sizeof(DCELL));
	break;
    case MAX:
	max = G_malloc(ncats * sizeof(DCELL));
	break;
    case RANGE:
	min = G_malloc(ncats * sizeof(DCELL));
	max = G_malloc(ncats * sizeof(DCELL));
	break;
    case AVERAGE:
    case ADEV:
    case VARIANCE2:
    case STDDEV2:
    case SKEWNESS2:
    case KURTOSIS2:
	count = G_calloc(ncats, sizeof(DCELL));
	sum = G_calloc(ncats, sizeof(DCELL));
	break;
    case VARIANCE1:
    case STDDEV1:
	count = G_calloc(ncats, sizeof(DCELL));
	sum = G_calloc(ncats, sizeof(DCELL));
	sum2 = G_calloc(ncats, sizeof(DCELL));
	break;
    case SKEWNESS1:
	count = G_calloc(ncats, sizeof(DCELL));
	sum = G_calloc(ncats, sizeof(DCELL));
	sum2 = G_calloc(ncats, sizeof(DCELL));
	sum3 = G_calloc(ncats, sizeof(DCELL));
	break;
    case KURTOSIS1:
	count = G_calloc(ncats, sizeof(DCELL));
	sum = G_calloc(ncats, sizeof(DCELL));
	sum2 = G_calloc(ncats, sizeof(DCELL));
	sum4 = G_calloc(ncats, sizeof(DCELL));
	break;
    }

    if (min)
	for (i = 0; i < ncats; i++)
	    min[i] = 1e300;
    if (max)
	for (i = 0; i < ncats; i++)
	    max[i] = -1e300;

    base_buf = Rast_allocate_c_buf();
    cover_buf = Rast_allocate_d_buf();

    G_message(_("First pass"));

    for (row = 0; row < rows; row++) {
	Rast_get_c_row(base_fd, base_buf, row);
	Rast_get_d_row(cover_fd, cover_buf, row);

	for (col = 0; col < cols; col++) {
	    int n;
	    DCELL v;

	    if (Rast_is_c_null_value(&base_buf[col]))
		continue;
	    if (Rast_is_d_null_value(&cover_buf[col]))
		continue;

	    n = base_buf[col] - mincat;

	    if (n < 0 || n >= ncats)
		continue;

	    v = cover_buf[col];
	    if (usecats)
		sscanf(Rast_get_c_cat((CELL *) &v, &cats), "%lf", &v);

	    if (count)
		count[n]++;
	    if (sum)
		sum[n] += v;
	    if (sum2)
		sum2[n] += v * v;
	    if (sum3)
		sum3[n] += v * v * v;
	    if (sum4)
		sum4[n] += v * v * v * v;
	    if (min && min[n] > v)
		min[n] = v;
	    if (max && max[n] < v)
		max[n] = v;
	}

	G_percent(row, rows, 2);
    }

    G_percent(row, rows, 2);

    result = G_calloc(ncats, sizeof(DCELL));

    switch (method) {
    case ADEV:
    case VARIANCE2:
    case STDDEV2:
    case SKEWNESS2:
    case KURTOSIS2:
	mean = G_calloc(ncats, sizeof(DCELL));
	for (i = 0; i < ncats; i++)
	    mean[i] = sum[i] / count[i];
	G_free(sum);
	break;
    }

    switch (method) {
    case ADEV:
	sumu = G_calloc(ncats, sizeof(DCELL));
	break;
    case VARIANCE2:
    case STDDEV2:
	sum2 = G_calloc(ncats, sizeof(DCELL));
	break;
    case SKEWNESS2:
	sum2 = G_calloc(ncats, sizeof(DCELL));
	sum3 = G_calloc(ncats, sizeof(DCELL));
	break;
    case KURTOSIS2:
	sum2 = G_calloc(ncats, sizeof(DCELL));
	sum4 = G_calloc(ncats, sizeof(DCELL));
	break;
    }

    if (mean) {
	G_message(_("Second pass"));

	for (row = 0; row < rows; row++) {
	    Rast_get_c_row(base_fd, base_buf, row);
	    Rast_get_d_row(cover_fd, cover_buf, row);

	    for (col = 0; col < cols; col++) {
		int n;
		DCELL v, d;

		if (Rast_is_c_null_value(&base_buf[col]))
		    continue;
		if (Rast_is_d_null_value(&cover_buf[col]))
		    continue;

		n = base_buf[col] - mincat;

		if (n < 0 || n >= ncats)
		    continue;

		v = cover_buf[col];
		if (usecats)
		    sscanf(Rast_get_c_cat((CELL *) &v, &cats), "%lf", &v);
		d = v - mean[n];

		if (sumu)
		    sumu[n] += fabs(d);
		if (sum2)
		    sum2[n] += d * d;
		if (sum3)
		    sum3[n] += d * d * d;
		if (sum4)
		    sum4[n] += d * d * d * d;
	    }

	    G_percent(row, rows, 2);
	}

	G_percent(row, rows, 2);
	G_free(mean);
	G_free(cover_buf);
    }

    switch (method) {
    case COUNT:
	for (i = 0; i < ncats; i++)
	    result[i] = count[i];
	break;
    case SUM:
	for (i = 0; i < ncats; i++)
	    result[i] = sum[i];
	break;
    case AVERAGE:
	for (i = 0; i < ncats; i++)
	    result[i] = sum[i] / count[i];
	break;
    case MIN:
	for (i = 0; i < ncats; i++)
	    result[i] = min[i];
	break;
    case MAX:
	for (i = 0; i < ncats; i++)
	    result[i] = max[i];
	break;
    case RANGE:
	for (i = 0; i < ncats; i++)
	    result[i] = max[i] - min[i];
	break;
    case VARIANCE1:
	for (i = 0; i < ncats; i++) {
	    double n = count[i];
	    double var = (sum2[i] - sum[i] * sum[i] / n) / (n - 1);
	    result[i] = var;
	}
	break;
    case STDDEV1:
	for (i = 0; i < ncats; i++) {
	    double n = count[i];
	    double var = (sum2[i] - sum[i] * sum[i] / n) / (n - 1);
	    result[i] = sqrt(var);
	}
	break;
    case SKEWNESS1:
	for (i = 0; i < ncats; i++) {
	    double n = count[i];
	    double var = (sum2[i] - sum[i] * sum[i] / n) / (n - 1);
	    double skew = (sum3[i] / n
			   - 3 * sum[i] * sum2[i] / (n * n)
			   + 2 * sum[i] * sum[i] * sum[i] / (n * n * n))
		/ (pow(var, 1.5));
	    result[i] = skew;
	}
	break;
    case KURTOSIS1:
	for (i = 0; i < ncats; i++) {
	    double n = count[i];
	    double var = (sum2[i] - sum[i] * sum[i] / n) / (n - 1);
	    double kurt = (sum4[i] / n
			   - 4 * sum[i] * sum3[i] / (n * n)
			   + 6 * sum[i] * sum[i] * sum2[i] / (n * n * n)
			   - 3 * sum[i] * sum[i] * sum[i] * sum[i] / (n * n * n * n))
		/ (var * var) - 3;
	    result[i] = kurt;
	}
	break;
    case ADEV:
	for (i = 0; i < ncats; i++)
	    result[i] = sumu[i] / count[i];
	break;
    case VARIANCE2:
	for (i = 0; i < ncats; i++)
	    result[i] = sum2[i] / (count[i] - 1);
	break;
    case STDDEV2:
	for (i = 0; i < ncats; i++)
	    result[i] = sqrt(sum2[i] / (count[i] - 1));
	break;
    case SKEWNESS2:
	for (i = 0; i < ncats; i++) {
	    double n = count[i];
	    double var = sum2[i] / (n - 1);
	    double sdev = sqrt(var);
	    result[i] = sum3[i] / (sdev * sdev * sdev) / n;
	}
	G_free(count);
	G_free(sum2);
	G_free(sum3);
	break;
    case KURTOSIS2:
	for (i = 0; i < ncats; i++) {
	    double n = count[i];
	    double var = sum2[i] / (n - 1);
	    result[i] = sum4[i] / (var * var) / n - 3;
	}
	G_free(count);
	G_free(sum2);
	G_free(sum4);
	break;
    }

    if (reclass) {
	const char *tempfile = G_tempfile();
	char *input_arg = G_malloc(strlen(basemap) + 7);
	char *output_arg = G_malloc(strlen(output) + 8);
	char *rules_arg = G_malloc(strlen(tempfile) + 7);
	FILE *fp;

	G_message(_("Generating reclass map"));

	sprintf(input_arg, "input=%s", basemap);
	sprintf(output_arg, "output=%s", output);
	sprintf(rules_arg, "rules=%s", tempfile);

	fp = fopen(tempfile, "w");
	if (!fp)
	    G_fatal_error(_("Unable to open temporary file"));

	for (i = 0; i < ncats; i++)
	    fprintf(fp, "%d = %d %f\n", mincat + i, mincat + i, result[i]);

	fclose(fp);

	G_spawn("r.reclass", "r.reclass", input_arg, output_arg, rules_arg, NULL);
    }
    else {
	int out_fd;
	DCELL *out_buf;
	struct Colors colors;

	G_message(_("Writing output map"));

	out_fd = Rast_open_fp_new(output);

	out_buf = Rast_allocate_d_buf();

	for (row = 0; row < rows; row++) {
	    Rast_get_c_row(base_fd, base_buf, row);

	    for (col = 0; col < cols; col++)
		if (Rast_is_c_null_value(&base_buf[col]))
		    Rast_set_d_null_value(&out_buf[col], 1);
		else
		    out_buf[col] = result[base_buf[col] - mincat];

	    Rast_put_d_row(out_fd, out_buf);

	    G_percent(row, rows, 2);
	}

	G_percent(row, rows, 2);

	Rast_close(out_fd);

	if (Rast_read_colors(covermap, "", &colors) > 0)
	    Rast_write_colors(output, G_mapset(), &colors);
    }

    return 0;
}
Ejemplo n.º 26
0
int main(int argc, char **argv)
{
    int fe, fd, fm;
    int i, j, type;
    int new_id;
    int nrows, ncols, nbasins;
    int map_id, dir_id, bas_id;
    char map_name[GNAME_MAX], new_map_name[GNAME_MAX];
    const char *tempfile1, *tempfile2, *tempfile3;
    char dir_name[GNAME_MAX];
    char bas_name[GNAME_MAX];

    struct Cell_head window;
    struct GModule *module;
    struct Option *opt1, *opt2, *opt3, *opt4, *opt5;
    struct Flag *flag1;
    int in_type, bufsz;
    void *in_buf;
    CELL *out_buf;
    struct band3 bnd, bndC;

    /*  Initialize the GRASS environment variables */
    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("raster"));
    G_add_keyword(_("hydrology"));
    module->description =
	_("Filters and generates a depressionless elevation map and a "
	  "flow direction map from a given elevation raster map.");
    
    opt1 = G_define_standard_option(G_OPT_R_ELEV);
    
    opt2 = G_define_standard_option(G_OPT_R_OUTPUT);
    opt2->key = "depressionless";
    opt2->description = _("Name for output depressionless elevation raster map");
    
    opt4 = G_define_standard_option(G_OPT_R_OUTPUT);
    opt4->key = "direction";
    opt4->description = _("Name for output flow direction map for depressionless elevation raster map");

    opt5 = G_define_standard_option(G_OPT_R_OUTPUT);
    opt5->key = "areas";
    opt5->required = NO;
    opt5->description = _("Name for output raster map of problem areas");

    opt3 = G_define_option();
    opt3->key = "type";
    opt3->type = TYPE_STRING;
    opt3->required = NO;
    opt3->description =
	_("Aspect direction format");
    opt3->options = "agnps,answers,grass";
    opt3->answer = "grass";
    
    flag1 = G_define_flag();
    flag1->key = 'f';
    flag1->description = _("Find unresolved areas only");
    
    if (G_parser(argc, argv))
	exit(EXIT_FAILURE);

    if (flag1->answer && opt5->answer == NULL) {
	G_fatal_error(_("The '%c' flag requires '%s'to be specified"),
		      flag1->key, opt5->key);
    }

    type = 0;
    strcpy(map_name, opt1->answer);
    strcpy(new_map_name, opt2->answer);
    strcpy(dir_name, opt4->answer);
    if (opt5->answer != NULL)
	strcpy(bas_name, opt5->answer);

    if (strcmp(opt3->answer, "agnps") == 0)
	type = 1;
    else if (strcmp(opt3->answer, "answers") == 0)
	type = 2;
    else if (strcmp(opt3->answer, "grass") == 0)
	type = 3;
    
    G_debug(1, "output type (1=AGNPS, 2=ANSWERS, 3=GRASS): %d", type);

    if (type == 3)
	G_verbose_message(_("Direction map is D8 resolution, i.e. 45 degrees"));
    
    /* open the maps and get their file id  */
    map_id = Rast_open_old(map_name, "");

    /* allocate cell buf for the map layer */
    in_type = Rast_get_map_type(map_id);

    /* set the pointers for multi-typed functions */
    set_func_pointers(in_type);

    /* get the window information  */
    G_get_window(&window);
    nrows = Rast_window_rows();
    ncols = Rast_window_cols();

    /* buffers for internal use */
    bndC.ns = ncols;
    bndC.sz = sizeof(CELL) * ncols;
    bndC.b[0] = G_calloc(ncols, sizeof(CELL));
    bndC.b[1] = G_calloc(ncols, sizeof(CELL));
    bndC.b[2] = G_calloc(ncols, sizeof(CELL));

    /* buffers for external use */
    bnd.ns = ncols;
    bnd.sz = ncols * bpe();
    bnd.b[0] = G_calloc(ncols, bpe());
    bnd.b[1] = G_calloc(ncols, bpe());
    bnd.b[2] = G_calloc(ncols, bpe());

    in_buf = get_buf();

    tempfile1 = G_tempfile();
    tempfile2 = G_tempfile();
    tempfile3 = G_tempfile();

    fe = open(tempfile1, O_RDWR | O_CREAT, 0666);	/* elev */
    fd = open(tempfile2, O_RDWR | O_CREAT, 0666);	/* dirn */
    fm = open(tempfile3, O_RDWR | O_CREAT, 0666);	/* problems */

    G_message(_("Reading elevation map..."));
    for (i = 0; i < nrows; i++) {
	G_percent(i, nrows, 2);
	get_row(map_id, in_buf, i);
	write(fe, in_buf, bnd.sz);
    }
    G_percent(1, 1, 1);
    Rast_close(map_id);

    /* fill single-cell holes and take a first stab at flow directions */
    G_message(_("Filling sinks..."));
    filldir(fe, fd, nrows, &bnd);

    /* determine flow directions for ambiguous cases */
    G_message(_("Determining flow directions for ambiguous cases..."));
    resolve(fd, nrows, &bndC);

    /* mark and count the sinks in each internally drained basin */
    nbasins = dopolys(fd, fm, nrows, ncols);
    if (flag1->answer) {
	/* determine the watershed for each sink */
	wtrshed(fm, fd, nrows, ncols, 4);

	/* fill all of the watersheds up to the elevation necessary for drainage */
	ppupdate(fe, fm, nrows, nbasins, &bnd, &bndC);

	/* repeat the first three steps to get the final directions */
	G_message(_("Repeat to get the final directions..."));
	filldir(fe, fd, nrows, &bnd);
	resolve(fd, nrows, &bndC);
	nbasins = dopolys(fd, fm, nrows, ncols);
    }

    G_free(bndC.b[0]);
    G_free(bndC.b[1]);
    G_free(bndC.b[2]);

    G_free(bnd.b[0]);
    G_free(bnd.b[1]);
    G_free(bnd.b[2]);

    out_buf = Rast_allocate_c_buf();
    bufsz = ncols * sizeof(CELL);

    lseek(fe, 0, SEEK_SET);
    new_id = Rast_open_new(new_map_name, in_type);

    lseek(fd, 0, SEEK_SET);
    dir_id = Rast_open_new(dir_name, CELL_TYPE);

    if (opt5->answer != NULL) {
	lseek(fm, 0, SEEK_SET);
	bas_id = Rast_open_new(bas_name, CELL_TYPE);

	for (i = 0; i < nrows; i++) {
	    read(fm, out_buf, bufsz);
	    Rast_put_row(bas_id, out_buf, CELL_TYPE);
	}

	Rast_close(bas_id);
	close(fm);
    }

    for (i = 0; i < nrows; i++) {
	read(fe, in_buf, bnd.sz);
	put_row(new_id, in_buf);

	read(fd, out_buf, bufsz);

	for (j = 0; j < ncols; j += 1)
	    out_buf[j] = dir_type(type, out_buf[j]);

	Rast_put_row(dir_id, out_buf, CELL_TYPE);

    }

    Rast_close(new_id);
    close(fe);

    Rast_close(dir_id);
    close(fd);

    G_free(in_buf);
    G_free(out_buf);

    exit(EXIT_SUCCESS);
}
Ejemplo n.º 27
0
int cell_stats(int fd[], int with_percents, int with_counts,
	       int with_areas, int do_sort, int with_labels, char *fmt)
{
    CELL **cell;
    int i;
    int row;
    double unit_area;
    int planimetric = 0;
    int compute_areas;
    double G_area_of_cell_at_row();

    /* allocate i/o buffers for each raster map */
    cell = (CELL **) G_calloc(nfiles, sizeof(CELL *));
    for (i = 0; i < nfiles; i++)
	cell[i] = Rast_allocate_c_buf();

    /* if we want area totals, set this up.
     * distinguish projections which are planimetric (all cells same size)
     * from those which are not (e.g., lat-long)
     */
    unit_area = 0.0;
    if (with_areas) {
	switch (G_begin_cell_area_calculations()) {
	case 0:		/* areas don't make sense, but ignore this for now */
	case 1:
	    planimetric = 1;
	    unit_area = G_area_of_cell_at_row(0);
	    break;
	default:
	    planimetric = 0;
	    break;
	}
    }
    compute_areas = with_areas && !planimetric;

    /* here we go */
    initialize_cell_stats(nfiles);

    for (row = 0; row < nrows; row++) {
	if (compute_areas)
	    unit_area = G_area_of_cell_at_row(row);

	G_percent(row, nrows, 2);

	for (i = 0; i < nfiles; i++) {
	    Rast_get_c_row(fd[i], cell[i], row);

	    /* include max FP value in nsteps'th bin */
	    if(is_fp[i])
		fix_max_fp_val(cell[i], ncols);

	    /* we can't compute hash on null values, so we change all
	       nulls to max+1, set NULL_CELL to max+1, and later compare
	       with NULL_CELL to chack for nulls */
	    reset_null_vals(cell[i], ncols);
	}

	update_cell_stats(cell, ncols, unit_area);
    }

    G_percent(row, nrows, 2);

    sort_cell_stats(do_sort);
    print_cell_stats(fmt, with_percents, with_counts, with_areas, with_labels,
		     fs);

    return 0;
}
Ejemplo n.º 28
0
int calculate(int fd, struct area_entry *ad, double *result)
{
    CELL *buf, *buf_sup, *buf_null;
    CELL corrCell, precCell, supCell;
    long npatch, area; 
    long pid, old_pid, new_pid, *pid_corr, *pid_sup, *ltmp;
    struct pst *pst;
    long nalloc, incr;
    int i, j, k;
    int connected;
    int mask_fd, *mask_buf, *mask_sup, *mask_tmp, masked;
    struct Cell_head hd;

    Rast_get_window(&hd);

    buf_null = Rast_allocate_c_buf();
    Rast_set_c_null_value(buf_null, Rast_window_cols());
    buf_sup = buf_null;

    /* initialize patch ids */
    pid_corr = G_malloc(Rast_window_cols() * sizeof(long));
    pid_sup = G_malloc(Rast_window_cols() * sizeof(long));

    for (j = 0; j < Rast_window_cols(); j++) {
	pid_corr[j] = 0;
	pid_sup[j] = 0;
    }

    /* open mask if needed */
    mask_fd = -1;
    mask_buf = mask_sup = NULL;
    masked = FALSE;
    if (ad->mask == 1) {
	if ((mask_fd = open(ad->mask_name, O_RDONLY, 0755)) < 0)
	    return RLI_ERRORE;
	mask_buf = G_malloc(ad->cl * sizeof(int));
	if (mask_buf == NULL) {
	    G_fatal_error("malloc mask_buf failed");
	    return RLI_ERRORE;
	}
	mask_sup = G_malloc(ad->cl * sizeof(int));
	if (mask_sup == NULL) {
	    G_fatal_error("malloc mask_buf failed");
	    return RLI_ERRORE;
	}
	for (j = 0; j < ad->cl; j++)
	    mask_buf[j] = 0;

	masked = TRUE;
    }

    /* calculate number of patches */
    npatch = 0;
    area = 0;
    pid = 0;

    /* patch size and type */
    incr = 1024;
    if (incr > ad->rl)
	incr = ad->rl;
    if (incr > ad->cl)
	incr = ad->cl;
    if (incr < 2)
	incr = 2;
    nalloc = incr;
    pst = G_malloc(nalloc * sizeof(struct pst));
    for (k = 0; k < nalloc; k++) {
	pst[k].count = 0;
    }

    for (i = 0; i < ad->rl; i++) {
	buf = RLI_get_cell_raster_row(fd, i + ad->y, ad);
	if (i > 0) {
	    buf_sup = RLI_get_cell_raster_row(fd, i - 1 + ad->y, ad);
	}

	if (masked) {
	    mask_tmp = mask_sup;
	    mask_sup = mask_buf;
	    mask_buf = mask_tmp;
	    if (read(mask_fd, mask_buf, (ad->cl * sizeof(int))) < 0)
		return 0;
	}
	
	ltmp = pid_sup;
	pid_sup = pid_corr;
	pid_corr = ltmp;

	Rast_set_c_null_value(&precCell, 1);

	connected = 0;
	for (j = 0; j < ad->cl; j++) {
	    pid_corr[j + ad->x] = 0;
	    
	    corrCell = buf[j + ad->x];
	    if (masked && (mask_buf[j] == 0)) {
		Rast_set_c_null_value(&corrCell, 1);
	    }

	    if (Rast_is_c_null_value(&corrCell)) {
		connected = 0;
		precCell = corrCell;
		continue;
	    }
	    
	    area++;
	    
	    supCell = buf_sup[j + ad->x];
	    if (masked && (mask_sup[j] == 0)) {
		Rast_set_c_null_value(&supCell, 1);
	    }

	    if (!Rast_is_c_null_value(&precCell) && corrCell == precCell) {
		pid_corr[j + ad->x] = pid_corr[j - 1 + ad->x];
		connected = 1;
		pst[pid_corr[j + ad->x]].count++;
	    }
	    else {
		connected = 0;
	    }

	    if (!Rast_is_c_null_value(&supCell) && corrCell == supCell) {

		if (pid_corr[j + ad->x] != pid_sup[j + ad->x]) {
		    /* connect or merge */
		    /* after r.clump */
		    if (connected) {
			npatch--;

			if (npatch == 0) {
			    G_fatal_error("npatch == 0 at row %d, col %d", i, j);
			}
		    }

		    old_pid = pid_corr[j + ad->x];
		    new_pid = pid_sup[j + ad->x];
		    pid_corr[j + ad->x] = new_pid;
		    if (old_pid > 0) {
			/* merge */
			/* update left side of the current row */
			for (k = 0; k < j; k++) {
			    if (pid_corr[k + ad->x] == old_pid)
				pid_corr[k + ad->x] = new_pid;
			}
			/* update right side of the previous row */
			for (k = j + 1; k < ad->cl; k++) {
			    if (pid_sup[k + ad->x] == old_pid)
				pid_sup[k + ad->x] = new_pid;
			}
			pst[new_pid].count += pst[old_pid].count;
			pst[old_pid].count = 0;
			
			if (old_pid == pid)
			    pid--;
		    }
		    else {
			pst[new_pid].count++;
		    }
		}
		connected = 1;
	    }

	    if (!connected) {
		/* start new patch */
		npatch++;
		pid++;
		pid_corr[j + ad->x] = pid;

		if (pid >= nalloc) {
		    pst = (struct pst *)G_realloc(pst, (pid + incr) * sizeof(struct pst));

		    for (k = nalloc; k < pid + incr; k++)
			pst[k].count = 0;
			
		    nalloc = pid + incr;
		}

		pst[pid].count = 1;
		pst[pid].type.t = CELL_TYPE;
		pst[pid].type.val.c = corrCell;
	    }
	    precCell = corrCell;
	}
    }

    if (npatch > 0) {
	double EW_DIST1, EW_DIST2, NS_DIST1, NS_DIST2;
	double area_p;
	double cell_size_m;
	double min, max;

	/* calculate distance */
	G_begin_distance_calculations();
	/* EW Dist at North edge */
	EW_DIST1 = G_distance(hd.east, hd.north, hd.west, hd.north);
	/* EW Dist at South Edge */
	EW_DIST2 = G_distance(hd.east, hd.south, hd.west, hd.south);
	/* NS Dist at East edge */
	NS_DIST1 = G_distance(hd.east, hd.north, hd.east, hd.south);
	/* NS Dist at West edge */
	NS_DIST2 = G_distance(hd.west, hd.north, hd.west, hd.south);

	cell_size_m = (((EW_DIST1 + EW_DIST2) / 2) / hd.cols) *
	              (((NS_DIST1 + NS_DIST2) / 2) / hd.rows);

	/* get min and max patch size */
	min = 1.0 / 0.0;	/* inf */
	max = -1.0 / 0.0;	/* -inf */
	for (old_pid = 1; old_pid <= pid; old_pid++) {
	    if (pst[old_pid].count > 0) {
		area_p = cell_size_m * pst[old_pid].count / 10000;
		if (min > area_p)
		    min = area_p;
		if (max < area_p)
		    max = area_p;
	    }
	}
	*result = max - min;
    }
    else
	Rast_set_d_null_value(result, 1);

    if (masked) {
	close(mask_fd);
	G_free(mask_buf);
	G_free(mask_sup);
    }
    G_free(buf_null);
    G_free(pid_corr);
    G_free(pid_sup);
    G_free(pst);

    return RLI_OK;
}
Ejemplo n.º 29
0
int read_input_map(char *input, char *mapset, int ZEROFLAG)
{
    int fd;
    int row;
    int hit;
    register int col;
    register CELL *cell;
    register MAPTYPE *ptr;

    map = (MAPTYPE *) G_malloc((size_t) window.rows * window.cols * sizeof(MAPTYPE));

    fd = Rast_open_old(input, mapset);

    cell = Rast_allocate_c_buf();

    ptr = map;

    minrow = -1;
    maxrow = -1;
    mincol = window.cols;
    maxcol = 0;

    G_message(_("Reading input raster map <%s>..."),
	      G_fully_qualified_name(input, mapset));

    count_rows_with_data = 0;

    for (row = 0; row < window.rows; row++) {
	hit = 0;
	G_percent(row, window.rows, 2);

	Rast_get_c_row(fd, cell, row);

	for (col = 0; col < window.cols; col++) {
	    if (ZEROFLAG) {
		if ((*ptr++ = (*cell++ != 0))) {
		    if (minrow < 0)
			minrow = row;
		    maxrow = row;
		    if (col < mincol)
			mincol = col;
		    if (col > maxcol)
			maxcol = col;
		    if (!hit) {
			count_rows_with_data++;
			hit = 1;
		    }
		}
	    }
	    else {		/* use NULL */

		if ((*ptr++ = !Rast_is_c_null_value(cell++))) {
		    if (minrow < 0)
			minrow = row;
		    maxrow = row;
		    if (col < mincol)
			mincol = col;
		    if (col > maxcol)
			maxcol = col;
		    if (!hit) {
			count_rows_with_data++;
			hit = 1;
		    }
		}
	    }
	}
	cell -= window.cols;
    }
    G_percent(row, window.rows, 2);
    Rast_close(fd);
    G_free(cell);

    return 0;
}
Ejemplo n.º 30
0
int main(int argc, char *argv[])
{
    /* Global variable & function declarations */
    struct GModule *module;
    struct {
	struct Option *orig, *real, *imag;
    } opt;
    const char *Cellmap_real, *Cellmap_imag;
    const char *Cellmap_orig;
    int realfd, imagfd,  outputfd, maskfd;	/* the input and output file descriptors */
    struct Cell_head realhead, imaghead;
    DCELL *cell_real, *cell_imag;
    CELL *maskbuf;

    int i, j;			/* Loop control variables */
    int rows, cols;		/* number of rows & columns */
    long totsize;		/* Total number of data points */
    double (*data)[2];		/* Data structure containing real & complex values of FFT */

    G_gisinit(argv[0]);

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

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

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

    opt.orig = G_define_standard_option(G_OPT_R_OUTPUT);
    opt.orig->description = _("Name for output raster map");
    
    /*call parser */
    if (G_parser(argc, argv))
	exit(EXIT_FAILURE);

    Cellmap_real = opt.real->answer;
    Cellmap_imag = opt.imag->answer;
    Cellmap_orig = opt.orig->answer;

    /* get and compare the original window data */
    Rast_get_cellhd(Cellmap_real, "", &realhead);
    Rast_get_cellhd(Cellmap_imag, "", &imaghead);

    if (realhead.proj   != imaghead.proj   ||
	realhead.zone   != imaghead.zone   ||
	realhead.north  != imaghead.north  ||
	realhead.south  != imaghead.south  ||
	realhead.east   != imaghead.east   ||
	realhead.west   != imaghead.west   ||
	realhead.ew_res != imaghead.ew_res ||
	realhead.ns_res != imaghead.ns_res)
	G_fatal_error(_("The real and imaginary original windows did not match"));

    Rast_set_window(&realhead);	/* set the window to the whole cell map */

    /* open input raster map */
    realfd = Rast_open_old(Cellmap_real, "");
    imagfd = Rast_open_old(Cellmap_imag, "");

    /* get the rows and columns in the current window */
    rows = Rast_window_rows();
    cols = Rast_window_cols();
    totsize = rows * cols;

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

    /* allocate the space for one row of cell map data */
    cell_real = Rast_allocate_d_buf();
    cell_imag = Rast_allocate_d_buf();
    
#define C(i, j) ((i) * cols + (j))

    /* Read in cell map values */
    G_message(_("Reading raster maps..."));
    for (i = 0; i < rows; i++) {
	Rast_get_d_row(realfd, cell_real, i);
	Rast_get_d_row(imagfd, cell_imag, i);
	for (j = 0; j < cols; j++) {
	    data[C(i, j)][0] = cell_real[j];
	    data[C(i, j)][1] = cell_imag[j];
	}
	G_percent(i+1, rows, 2);
    }

    /* close input cell maps */
    Rast_close(realfd);
    Rast_close(imagfd);

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

	for (i = 0; i < rows; i++) {
	    Rast_get_c_row(maskfd, maskbuf, i);
	    for (j = 0; j < cols; j++) {
		if (maskbuf[j] == 0) {
		    data[C(i, j)][0] = 0.0;
		    data[C(i, j)][1] = 0.0;
		}
	    }
	    G_percent(i+1, rows, 2);
	}

	Rast_close(maskfd);
	G_free(maskbuf);
    }

#define SWAP1(a, b)				\
    do {					\
	double temp = (a);			\
	(a) = (b);				\
	(b) = temp;				\
    } while (0)

#define SWAP2(a, b)				\
    do {					\
	SWAP1(data[(a)][0], data[(b)][0]);	\
	SWAP1(data[(a)][1], data[(b)][1]);	\
    } while (0)

    /* rotate the data array for standard display */
    G_message(_("Rotating data..."));
    for (i = 0; i < rows; i++)
	for (j = 0; j < cols / 2; j++)
	    SWAP2(C(i, j), C(i, j + cols / 2));
    for (i = 0; i < rows / 2; i++)
	for (j = 0; j < cols; j++)
	    SWAP2(C(i, j), C(i + rows / 2, j));

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

    /* open the output cell map */
    outputfd = Rast_open_fp_new(Cellmap_orig);

    /* Write out result to a new cell map */
    G_message(_("Writing raster map <%s>..."),
	      Cellmap_orig);
    for (i = 0; i < rows; i++) {
	for (j = 0; j < cols; j++)
	    cell_real[j] = data[C(i, j)][0];
	Rast_put_d_row(outputfd, cell_real);

	G_percent(i+1, rows, 2);
    }

    Rast_close(outputfd);

    G_free(cell_real);
    G_free(cell_imag);

    fft_colors(Cellmap_orig);

    /* Release memory resources */
    G_free(data);

    G_done_msg(" ");

    exit(EXIT_SUCCESS);
}