Ejemplo n.º 1
0
Archivo: main.c Proyecto: caomw/grass
static int get_cell(DCELL *result, int fd, double x, double y)
{
    static DCELL *row1, *row2;
    static int cur_row = -1;
    static int row, col;
    DCELL *tmp;

    if (!row1) {
	row1 = Rast_allocate_d_buf();
	row2 = Rast_allocate_d_buf();
    }

    col = (int)floor(x - 0.5);
    row = (int)floor(y - 0.5);
    x -= col + 0.5;
    y -= row + 0.5;

    if (row < 0 || row + 1 >= Rast_window_rows() ||
	col < 0 || col + 1 >= Rast_window_cols()) {
	Rast_set_d_null_value(result, 1);
	return 0;
    }

    if (cur_row != row) {
	if (cur_row == row + 1) {
	    tmp = row1; row1 = row2; row2 = tmp;
	    Rast_get_d_row(fd, row1, row);
	}
	else if (cur_row == row - 1) {
	    tmp = row1; row1 = row2; row2 = tmp;
	    Rast_get_d_row(fd, row2, row + 1);
	}
	else {
	    Rast_get_d_row(fd, row1, row);
	    Rast_get_d_row(fd, row2, row + 1);
	}
	cur_row = row;
    }

    if (Rast_is_d_null_value(&row1[col]) || Rast_is_d_null_value(&row1[col+1]) ||
	Rast_is_d_null_value(&row2[col]) || Rast_is_d_null_value(&row2[col+1])) {
	Rast_set_d_null_value(result, 1);
	return 0;
    }

    *result = Rast_interp_bilinear(x, y,
				row1[col], row1[col+1],
				row2[col], row2[col+1]);

    return 1;
}
Ejemplo n.º 2
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.º 3
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.º 4
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.º 5
0
Archivo: main.c Proyecto: caomw/grass
static void get_region_range(int fd)
{
    DCELL *buf = Rast_allocate_d_buf();

    int nrows = Rast_window_rows();
    int ncols = Rast_window_cols();
    int row, col;

    min = 1e300;
    max = -1e300;

    for (row = 0; row < nrows; row++) {
	Rast_get_d_row(fd, buf, row);
	for (col = 0; col < ncols; col++) {
	    if (min > buf[col])
		min = buf[col];
	    if (max < buf[col])
		max = buf[col];
	}
    }
}
Ejemplo n.º 6
0
/*!
 *  \brief Extract a cell value from raster map (neighbor interpolation)
 *
 *  Extract a cell value from raster map at given northing and easting
 *  with a sampled 3x3 window using a neighbor interpolation.
 *
 *  \param fd file descriptor
 *  \param window region settings
 *  \param cats categories
 *  \param north northing position
 *  \param east easting position
 *  \param usedesc flag to scan category label
 *
 *  \return cell value at given position
 */
DCELL Rast_get_sample_nearest(int fd,
			      const struct Cell_head * window,
			      struct Categories * cats,
			      double north, double east, int usedesc)
{
    int row, col;
    DCELL result;
    DCELL *maprow = Rast_allocate_d_buf();

    /* convert northing and easting to row and col, resp */
    row = (int)floor(Rast_northing_to_row(north, window));
    col = (int)floor(Rast_easting_to_col(east, window));

    if (row < 0 || row >= Rast_window_rows() ||
	col < 0 || col >= Rast_window_cols()) {
	Rast_set_d_null_value(&result, 1);
	goto done;
    }

    Rast_get_d_row(fd, maprow, row);

    if (Rast_is_d_null_value(&maprow[col])) {
	Rast_set_d_null_value(&result, 1);
	goto done;
    }

    if (usedesc) {
	char *buf = Rast_get_c_cat((CELL *) & (maprow[col]), cats);

	G_squeeze(buf);
	result = scancatlabel(buf);
    }
    else
	result = maprow[col];

  done:
    G_free(maprow);

    return result;
}
Ejemplo n.º 7
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.º 8
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.º 9
0
/* ************************************************************************* */
void rast3d_cross_section(void *map,RASTER3D_Region region, int elevfd, int outfd)
{
    int col, row;
    int rows, cols, depths, typeIntern;
    FCELL *fcell = NULL;
    DCELL *dcell = NULL;
    void *elevrast;
    void *ptr;
    int intvalue;
    float fvalue;
    double dvalue;
    double elevation = 0;
    double north, east;
    struct Cell_head window;
 
    Rast_get_window(&window);
    
    rows = region.rows;
    cols = region.cols;
    depths = region.depths;
    
    /*Typ of the RASTER3D Tile */
    typeIntern = Rast3d_tile_type_map(map);

    /*Allocate mem for the output maps row */
    if (typeIntern == FCELL_TYPE)
        fcell = Rast_allocate_f_buf();
    else if (typeIntern == DCELL_TYPE)
        dcell = Rast_allocate_d_buf();

    /*Mem for the input map row */
    elevrast = Rast_allocate_buf(globalElevMapType);

    for (row = 0; row < rows; row++) {
        G_percent(row, rows - 1, 10);

        /*Read the input map row */
        Rast_get_row(elevfd, elevrast, row, globalElevMapType);

        for (col = 0, ptr = elevrast; col < cols; col++, ptr =
            G_incr_void_ptr(ptr, Rast_cell_size(globalElevMapType))) {

            if (Rast_is_null_value(ptr, globalElevMapType)) {
                if (typeIntern == FCELL_TYPE)
                    Rast_set_null_value(&fcell[col], 1, FCELL_TYPE);
                else if (typeIntern == DCELL_TYPE)
                    Rast_set_null_value(&dcell[col], 1, DCELL_TYPE);
                continue;
            }

            /*Read the elevation value */
            if (globalElevMapType == CELL_TYPE) {
                intvalue = *(CELL *) ptr;
                elevation = intvalue;
            } else if (globalElevMapType == FCELL_TYPE) {
                fvalue = *(FCELL *) ptr;
                elevation = fvalue;
            } else if (globalElevMapType == DCELL_TYPE) {
                dvalue = *(DCELL *) ptr;
                elevation = dvalue;
            }

            /* Compute the coordinates */
            north = Rast_row_to_northing((double)row + 0.5, &window);
            east = Rast_col_to_easting((double)col + 0.5, &window);

            /* Get the voxel value */
            if (typeIntern == FCELL_TYPE)
                Rast3d_get_region_value(map, north, east, elevation, &fcell[col], FCELL_TYPE);

            if (typeIntern == DCELL_TYPE)
                Rast3d_get_region_value(map, north, east, elevation, &dcell[col], DCELL_TYPE);
        }

        /*Write the data to the output map */
        if (typeIntern == FCELL_TYPE)
            Rast_put_f_row(outfd, fcell);

        if (typeIntern == DCELL_TYPE)
            Rast_put_d_row(outfd, dcell);
    }
    G_debug(3, "\nDone\n");

    /*Free the mem */
    if (elevrast)
        G_free(elevrast);
    if (dcell)
        G_free(dcell);
    if (fcell)
        G_free(fcell);
}
Ejemplo n.º 10
0
int MyApp::load_files(void)
{
    DCELL *dcell;
    unsigned char *tr, *tg, *tb, *tset;
    int tsiz, coff;
    int rowoff, row, col, vxoff, vyoff;
    int cnt, ret, fd;
    int vnum;
    const char *name;
    struct Colors colors;

    dcell = Rast_allocate_d_buf();

    tsiz = Rast_window_cols();

    /* allocate memory */
    tr   = (unsigned char *) G_malloc(tsiz * sizeof(char));
    tg   = (unsigned char *) G_malloc(tsiz * sizeof(char));
    tb   = (unsigned char *) G_malloc(tsiz * sizeof(char));
    tset = (unsigned char *) G_malloc(tsiz * sizeof(char));

    wxImage img(ncols, nrows);

    for (cnt = 0; cnt < frames; cnt++) {
	if (cnt > MAXIMAGES) {
	    cnt--;
	    break;
	}

	for (vnum = 0; vnum < numviews; vnum++) {
	    if (icols == vcols) {
		vxoff = BORDER_W;
		vyoff = (irows == vrows) ? BORDER_W :
		    BORDER_W + vnum * (BORDER_W + vrows);
	    }
	    else if (irows == vrows) {
		vxoff = (icols == vcols) ? BORDER_W :
		    BORDER_W + vnum * (BORDER_W + vcols);
		vyoff = BORDER_W;
	    }
	    else {		/* 4 views */
		/* assumes we want :
		   view1        view2

		   view3        view4   
		 */
		vxoff = vnum % 2 ? BORDER_W : vcols + 2 * BORDER_W;
		vyoff = vnum > 1 ? vrows + 2 * BORDER_W : BORDER_W;
	    }
	    if (!cnt) {
		LabelPos[vnum][0] = vxoff;
		LabelPos[vnum][1] = vyoff + vrows - 1;
	    }

	    name = vfiles[vnum][cnt];
	    G_message(_("Reading file [%s]..."), name);

	    fd = Rast_open_old(name, "");
	    if (fd < 0)
		G_fatal_error(_("Unable to open raster map <%s>"), name);
	    /*
	       strcpy(title[cnt],G_get_cell_title(name, mapset));
	     */

	    ret = Rast_read_colors(name, "", &colors);
	    if (ret < 0)
		G_fatal_error(_("Unable to read color file"));

	    for (row = 0; row < vrows; row++) {
		Rast_get_d_row(fd, dcell, (int)(row / vscale));

		rowoff = (vyoff + row) * ncols;
		Rast_lookup_d_colors(dcell, tr, tg, tb, tset, tsiz, &colors);

		for (col = 0; col < vcols; col++) {
		    coff = (int)(col / vscale);

		    if (!tset[coff])
			img.SetRGB(vxoff + col, vyoff + row, 255, 255, 255);
		    else
			img.SetRGB(vxoff + col, vyoff + row, tr[coff], tg[coff], tb[coff]);
		}
	    }

	    Rast_close(fd);
	}

	wxBitmap *bmp = new wxBitmap(img);
	pic_array[cnt] = bmp;

	mainwin->canvas->draw_image(bmp);
	mainwin->change_label(frame[cnt]);
    }

    G_free(dcell);
    G_free(tr);
    G_free(tg);
    G_free(tb);
    G_free(tset);

    return cnt;
}
Ejemplo n.º 11
0
int main(int argc, char *argv[])
{
    int fd, maskfd;
    CELL *mask;
    DCELL *dcell;
    struct GModule *module;
    struct History history;
    int row, col;
    int searchrow, searchcolumn, pointsfound;
    int *shortlistrows = NULL, *shortlistcolumns = NULL;
    long ncells = 0;
    double north, east;
    double dist;
    double sum1, sum2, interp_value;
    int n;
    double p;
    struct
    {
        struct Option *input, *npoints, *power, *output, *dfield, *col;
    } parm;
    struct
    {
        struct Flag *noindex;
    } flag;
    struct cell_list
    {
        int row, column;
        struct cell_list *next;
    };
    struct cell_list **search_list = NULL, **search_list_start = NULL;
    int max_radius, radius;
    int searchallpoints = 0;
    char *tmpstr1, *tmpstr2;

    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("vector"));
    G_add_keyword(_("surface"));
    G_add_keyword(_("interpolation"));
    G_add_keyword(_("IDW"));
    module->description =
        _("Provides surface interpolation from vector point data by Inverse "
          "Distance Squared Weighting.");

    parm.input = G_define_standard_option(G_OPT_V_INPUT);

    parm.dfield = G_define_standard_option(G_OPT_V_FIELD);

    parm.col = G_define_standard_option(G_OPT_DB_COLUMN);
    parm.col->required = NO;
    parm.col->label = _("Name of attribute column with values to interpolate");
    parm.col->description = _("If not given and input is 2D vector map then category values are used. "
                              "If input is 3D vector map then z-coordinates are used.");
    parm.col->guisection = _("Values");

    parm.output = G_define_standard_option(G_OPT_R_OUTPUT);

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

    parm.power = G_define_option();
    parm.power->key = "power";
    parm.power->type = TYPE_DOUBLE;
    parm.power->answer = "2.0";
    parm.power->label = _("Power parameter");
    parm.power->description =
        _("Greater values assign greater influence to closer points");
    parm.power->guisection = _("Settings");

    flag.noindex = G_define_flag();
    flag.noindex->key = 'n';
    flag.noindex->label = _("Don't index points by raster cell");
    flag.noindex->description = _("Slower but uses"
                                  " less memory and includes points from outside region"
                                  " in the interpolation");
    flag.noindex->guisection = _("Settings");

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

    if (sscanf(parm.npoints->answer, "%d", &search_points) != 1 ||
            search_points < 1)
        G_fatal_error(_("Illegal number (%s) of interpolation points"),
                      parm.npoints->answer);

    list =
        (struct list_Point *) G_calloc((size_t) search_points,
                                       sizeof(struct list_Point));

    p = atof(parm.power->answer);

    /* get the window, dimension arrays */
    G_get_window(&window);

    if (!flag.noindex->answer) {
        npoints_currcell = (long **)G_malloc(window.rows * sizeof(long *));
        points =
            (struct Point ***)G_malloc(window.rows * sizeof(struct Point **));


        for (row = 0; row < window.rows; row++) {
            npoints_currcell[row] =
                (long *)G_malloc(window.cols * sizeof(long));
            points[row] =
                (struct Point **)G_malloc(window.cols *
                                          sizeof(struct Point *));

            for (col = 0; col < window.cols; col++) {
                npoints_currcell[row][col] = 0;
                points[row][col] = NULL;
            }
        }
    }

    /* read the elevation points from the input sites file */
    read_sites(parm.input->answer, parm.dfield->answer,
               parm.col->answer, flag.noindex->answer);

    if (npoints == 0)
        G_fatal_error(_("No points found"));
    nsearch = npoints < search_points ? npoints : search_points;

    if (!flag.noindex->answer) {
        /* Arbitrary point to switch between searching algorithms. Could do
         * with refinement PK */
        if ((window.rows * window.cols) / npoints > 400) {
            /* Using old algorithm.... */
            searchallpoints = 1;
            ncells = 0;

            /* Make an array to contain the row and column indices that have
             * sites in them; later will just search through all these. */
            for (searchrow = 0; searchrow < window.rows; searchrow++)
                for (searchcolumn = 0; searchcolumn < window.cols;
                        searchcolumn++)
                    if (npoints_currcell[searchrow][searchcolumn] > 0) {
                        shortlistrows = (int *)G_realloc(shortlistrows,
                                                         (1 +
                                                          ncells) *
                                                         sizeof(int));
                        shortlistcolumns =
                            (int *)G_realloc(shortlistcolumns,
                                             (1 + ncells) * sizeof(int));
                        shortlistrows[ncells] = searchrow;
                        shortlistcolumns[ncells] = searchcolumn;
                        ncells++;
                    }
        }
        else {
            /* Fill look-up table of row and column offsets for
             * doing a circular region growing search looking for sites */
            /* Use units of column width */
            max_radius = (int)(0.5 + sqrt(window.cols * window.cols +
                                          (window.rows * window.ns_res /
                                           window.ew_res) * (window.rows *
                                                   window.ns_res /
                                                   window.ew_res)));

            search_list =
                (struct cell_list **)G_malloc(max_radius *
                                              sizeof(struct cell_list *));
            search_list_start =
                (struct cell_list **)G_malloc(max_radius *
                                              sizeof(struct cell_list *));

            for (radius = 0; radius < max_radius; radius++)
                search_list[radius] = NULL;

            for (row = 0; row < window.rows; row++)
                for (col = 0; col < window.cols; col++) {
                    radius = (int)sqrt(col * col +
                                       (row * window.ns_res / window.ew_res) *
                                       (row * window.ns_res / window.ew_res));
                    if (search_list[radius] == NULL)
                        search_list[radius] =
                            search_list_start[radius] =
                                G_malloc(sizeof(struct cell_list));
                    else
                        search_list[radius] =
                            search_list[radius]->next =
                                G_malloc(sizeof(struct cell_list));

                    search_list[radius]->row = row;
                    search_list[radius]->column = col;
                    search_list[radius]->next = NULL;
                }
        }
    }

    /* allocate buffers, etc. */

    dcell = Rast_allocate_d_buf();

    if ((maskfd = Rast_maskfd()) >= 0)
        mask = Rast_allocate_c_buf();
    else
        mask = NULL;


    fd = Rast_open_new(parm.output->answer, DCELL_TYPE);

    /* GTC Count of window rows */
    G_asprintf(&tmpstr1, n_("%d row", "%d rows", window.rows), window.rows);
    /* GTC Count of window columns */
    G_asprintf(&tmpstr2, n_("%d column", "%d columns", window.cols), window.cols);
    /* GTC First argument is map name, second - message about number of rows, third - columns. */
    G_important_message(_("Interpolating raster map <%s> (%s, %s)..."),
                        parm.output->answer, tmpstr1, tmpstr2);
    G_free(tmpstr1);
    G_free(tmpstr2);

    north = window.north + window.ns_res / 2.0;
    for (row = 0; row < window.rows; row++) {
        G_percent(row, window.rows, 1);

        if (mask)
            Rast_get_c_row(maskfd, mask, row);

        north -= window.ns_res;
        east = window.west - window.ew_res / 2.0;
        for (col = 0; col < window.cols; col++) {
            east += window.ew_res;
            /* don't interpolate outside of the mask */
            if (mask && mask[col] == 0) {
                Rast_set_d_null_value(&dcell[col], 1);
                continue;
            }

            /* If current cell contains more than nsearch points just average
             * all the points in this cell and don't look in any others */

            if (!(flag.noindex->answer) && npoints_currcell[row][col] >= nsearch) {
                sum1 = 0.0;
                for (i = 0; i < npoints_currcell[row][col]; i++)
                    sum1 += points[row][col][i].z;

                interp_value = sum1 / npoints_currcell[row][col];
            }
            else {
                if (flag.noindex->answer)
                    calculate_distances_noindex(north, east);
                else {
                    pointsfound = 0;
                    i = 0;

                    if (searchallpoints == 1) {
                        /* If there aren't many sites just check them all to find
                         * the nearest */
                        for (n = 0; n < ncells; n++)
                            calculate_distances(shortlistrows[n],
                                                shortlistcolumns[n], north,
                                                east, &pointsfound);
                    }
                    else {
                        radius = 0;
                        while (pointsfound < nsearch) {
                            /* Keep widening the search window until we find
                             * enough points */
                            search_list[radius] = search_list_start[radius];
                            while (search_list[radius] != NULL) {
                                /* Always */
                                if (row <
                                        (window.rows - search_list[radius]->row)
                                        && col <
                                        (window.cols -
                                         search_list[radius]->column)) {
                                    searchrow =
                                        row + search_list[radius]->row;
                                    searchcolumn =
                                        col + search_list[radius]->column;
                                    calculate_distances(searchrow,
                                                        searchcolumn, north,
                                                        east, &pointsfound);
                                }

                                /* Only if at least one offset is not 0 */
                                if ((search_list[radius]->row > 0 ||
                                        search_list[radius]->column > 0) &&
                                        row >= search_list[radius]->row &&
                                        col >= search_list[radius]->column) {
                                    searchrow =
                                        row - search_list[radius]->row;
                                    searchcolumn =
                                        col - search_list[radius]->column;
                                    calculate_distances(searchrow,
                                                        searchcolumn, north,
                                                        east, &pointsfound);
                                }

                                /* Only if both offsets are not 0 */
                                if (search_list[radius]->row > 0 &&
                                        search_list[radius]->column > 0) {
                                    if (row <
                                            (window.rows -
                                             search_list[radius]->row) &&
                                            col >= search_list[radius]->column) {
                                        searchrow =
                                            row + search_list[radius]->row;
                                        searchcolumn =
                                            col - search_list[radius]->column;
                                        calculate_distances(searchrow,
                                                            searchcolumn,
                                                            north, east,
                                                            &pointsfound);
                                    }
                                    if (row >= search_list[radius]->row &&
                                            col <
                                            (window.cols -
                                             search_list[radius]->column)) {
                                        searchrow =
                                            row - search_list[radius]->row;
                                        searchcolumn =
                                            col + search_list[radius]->column;
                                        calculate_distances(searchrow,
                                                            searchcolumn,
                                                            north, east,
                                                            &pointsfound);
                                    }
                                }

                                search_list[radius] =
                                    search_list[radius]->next;
                            }
                            radius++;
                        }
                    }
                }

                /* interpolate */
                sum1 = 0.0;
                sum2 = 0.0;
                for (n = 0; n < nsearch; n++) {
                    if ((dist = sqrt(list[n].dist))) {
                        sum1 += list[n].z / pow(dist, p);
                        sum2 += 1.0 / pow(dist, p);
                    }
                    else {
                        /* If one site is dead on the centre of the cell, ignore
                         * all the other sites and just use this value.
                         * (Unlikely when using floating point numbers?) */
                        sum1 = list[n].z;
                        sum2 = 1.0;
                        break;
                    }
                }
                interp_value = sum1 / sum2;
            }
            dcell[col] = (DCELL) interp_value;
        }
        Rast_put_d_row(fd, dcell);
    }
    G_percent(1, 1, 1);

    Rast_close(fd);

    /* writing history file */
    Rast_short_history(parm.output->answer, "raster", &history);
    Rast_command_history(&history);
    Rast_write_history(parm.output->answer, &history);

    G_done_msg(" ");

    exit(EXIT_SUCCESS);
}
Ejemplo n.º 12
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.º 13
0
int main(int argc, char *argv[])
{
    char *p;
    int method;
    int in_fd;
    int selection_fd;
    int out_fd;
    DCELL *result;
    char *selection;
    RASTER_MAP_TYPE map_type;
    int row, col;
    int readrow;
    int nrows, ncols;
    int n;
    int copycolr;
    int half;
    stat_func *newvalue;
    stat_func_w *newvalue_w;
    ifunc cat_names;
    double quantile;
    const void *closure;
    struct Colors colr;
    struct Cell_head cellhd;
    struct Cell_head window;
    struct History history;
    struct GModule *module;
    struct
    {
	struct Option *input, *output, *selection;
	struct Option *method, *size;
	struct Option *title;
	struct Option *weight;
	struct Option *gauss;
	struct Option *quantile;
    } parm;
    struct
    {
	struct Flag *align, *circle;
    } flag;

    DCELL *values;		/* list of neighborhood values */

    DCELL(*values_w)[2];	/* list of neighborhood values and weights */

    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("raster"));
    G_add_keyword(_("algebra"));
    G_add_keyword(_("statistics"));
    module->description =
	_("Makes each cell category value a "
	  "function of the category values assigned to the cells "
	  "around it, and stores new cell values in an output raster "
	  "map layer.");

    parm.input = G_define_standard_option(G_OPT_R_INPUT);

    parm.selection = G_define_standard_option(G_OPT_R_INPUT);
    parm.selection->key = "selection";
    parm.selection->required = NO;
    parm.selection->description = _("Name of an input raster map to select the cells which should be processed");

    parm.output = G_define_standard_option(G_OPT_R_OUTPUT);

    parm.method = G_define_option();
    parm.method->key = "method";
    parm.method->type = TYPE_STRING;
    parm.method->required = NO;
    parm.method->answer = "average";
    p = G_malloc(1024);
    for (n = 0; menu[n].name; n++) {
	if (n)
	    strcat(p, ",");
	else
	    *p = 0;
	strcat(p, menu[n].name);
    }
    parm.method->options = p;
    parm.method->description = _("Neighborhood operation");
    parm.method->guisection = _("Neighborhood");

    parm.size = G_define_option();
    parm.size->key = "size";
    parm.size->type = TYPE_INTEGER;
    parm.size->required = NO;
    parm.size->description = _("Neighborhood size");
    parm.size->answer = "3";
    parm.size->guisection = _("Neighborhood");

    parm.title = G_define_option();
    parm.title->key = "title";
    parm.title->key_desc = "phrase";
    parm.title->type = TYPE_STRING;
    parm.title->required = NO;
    parm.title->description = _("Title of the output raster map");

    parm.weight = G_define_standard_option(G_OPT_F_INPUT);
    parm.weight->key = "weight";
    parm.weight->required = NO;
    parm.weight->description = _("Text file containing weights");

    parm.gauss = G_define_option();
    parm.gauss->key = "gauss";
    parm.gauss->type = TYPE_DOUBLE;
    parm.gauss->required = NO;
    parm.gauss->description = _("Sigma (in cells) for Gaussian filter");

    parm.quantile = G_define_option();
    parm.quantile->key = "quantile";
    parm.quantile->type = TYPE_DOUBLE;
    parm.quantile->required = NO;
    parm.quantile->description = _("Quantile to calculate for method=quantile");
    parm.quantile->options = "0.0-1.0";
    parm.quantile->answer = "0.5";

    flag.align = G_define_flag();
    flag.align->key = 'a';
    flag.align->description = _("Do not align output with the input");

    flag.circle = G_define_flag();
    flag.circle->key = 'c';
    flag.circle->description = _("Use circular neighborhood");
    flag.circle->guisection = _("Neighborhood");

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

    sscanf(parm.size->answer, "%d", &ncb.nsize);
    if (ncb.nsize <= 0)
	G_fatal_error(_("Neighborhood size must be positive"));
    if (ncb.nsize % 2 == 0)
	G_fatal_error(_("Neighborhood size must be odd"));
    ncb.dist = ncb.nsize / 2;

    if (parm.weight->answer && flag.circle->answer)
	G_fatal_error(_("weight= and -c are mutually exclusive"));

    if (parm.weight->answer && parm.gauss->answer)
	G_fatal_error(_("weight= and gauss= are mutually exclusive"));

    ncb.oldcell = parm.input->answer;
    ncb.newcell = parm.output->answer;

    if (!flag.align->answer) {
	Rast_get_cellhd(ncb.oldcell, "", &cellhd);
	G_get_window(&window);
	Rast_align_window(&window, &cellhd);
	Rast_set_window(&window);
    }

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

    /* open raster maps */
    in_fd = Rast_open_old(ncb.oldcell, "");
    map_type = Rast_get_map_type(in_fd);

    /* get the method */
    for (method = 0; (p = menu[method].name); method++)
	if ((strcmp(p, parm.method->answer) == 0))
	    break;
    if (!p) {
	G_warning(_("<%s=%s> unknown %s"),
		  parm.method->key, parm.method->answer, parm.method->key);
	G_usage();
	exit(EXIT_FAILURE);
    }

    if (menu[method].method == c_quant) {
	quantile = atoi(parm.quantile->answer);
	closure = &quantile;
    }

    half = (map_type == CELL_TYPE) ? menu[method].half : 0;

    /* establish the newvalue routine */
    newvalue = menu[method].method;
    newvalue_w = menu[method].method_w;

    /* copy color table? */
    copycolr = menu[method].copycolr;
    if (copycolr) {
	G_suppress_warnings(1);
	copycolr =
	    (Rast_read_colors(ncb.oldcell, "", &colr) > 0);
	G_suppress_warnings(0);
    }

    /* read the weights */
    if (parm.weight->answer) {
	read_weights(parm.weight->answer);
	if (!newvalue_w)
	    weights_mask();
    }
    else if (parm.gauss->answer) {
	if (!newvalue_w)
	    G_fatal_error(_("Method %s not compatible with Gaussian filter"), parm.method->answer);
	gaussian_weights(atof(parm.gauss->answer));
    }
    else
	newvalue_w = NULL;

    /* allocate the cell buffers */
    allocate_bufs();
    result = Rast_allocate_d_buf();

    /* get title, initialize the category and stat info */
    if (parm.title->answer)
	strcpy(ncb.title, parm.title->answer);
    else
	sprintf(ncb.title, "%dx%d neighborhood: %s of %s",
		ncb.nsize, ncb.nsize, menu[method].name, ncb.oldcell);


    /* initialize the cell bufs with 'dist' rows of the old cellfile */

    readrow = 0;
    for (row = 0; row < ncb.dist; row++)
	readcell(in_fd, readrow++, nrows, ncols);

    /* open the selection raster map */
    if (parm.selection->answer) {
	G_message(_("Opening selection map <%s>"), parm.selection->answer);
	selection_fd = Rast_open_old(parm.selection->answer, "");
        selection = Rast_allocate_null_buf();
    } else {
        selection_fd = -1;
        selection = NULL;
    }

    /*open the new raster map */
    out_fd = Rast_open_new(ncb.newcell, map_type);

    if (flag.circle->answer)
	circle_mask();

    if (newvalue_w)
	values_w =
	    (DCELL(*)[2]) G_malloc(ncb.nsize * ncb.nsize * 2 * sizeof(DCELL));
    else
	values = (DCELL *) G_malloc(ncb.nsize * ncb.nsize * sizeof(DCELL));

    for (row = 0; row < nrows; row++) {
	G_percent(row, nrows, 2);
	readcell(in_fd, readrow++, nrows, ncols);

	if (selection)
            Rast_get_null_value_row(selection_fd, selection, row);

	for (col = 0; col < ncols; col++) {
	    DCELL *rp = &result[col];

            if (selection && selection[col]) {
		*rp = ncb.buf[ncb.dist][col];
		continue;
	    }

	    if (newvalue_w)
		n = gather_w(values_w, col);
	    else
		n = gather(values, col);

	    if (n < 0)
		Rast_set_d_null_value(rp, 1);
	    else {
		if (newvalue_w)
		    newvalue_w(rp, values_w, n, closure);
		else
		    newvalue(rp, values, n, closure);

		if (half && !Rast_is_d_null_value(rp))
		    *rp += 0.5;
	    }
	}

	Rast_put_d_row(out_fd, result);
    }
    G_percent(row, nrows, 2);

    Rast_close(out_fd);
    Rast_close(in_fd);

    if (selection)
        Rast_close(selection_fd);

    /* put out category info */
    null_cats();
    if ((cat_names = menu[method].cat_names))
	cat_names();

    Rast_write_cats(ncb.newcell, &ncb.cats);

    if (copycolr)
	Rast_write_colors(ncb.newcell, G_mapset(), &colr);

    Rast_short_history(ncb.newcell, "raster", &history);
    Rast_command_history(&history);
    Rast_write_history(ncb.newcell, &history);


    exit(EXIT_SUCCESS);
}
Ejemplo n.º 14
0
int main(int argc, char *argv[]) 
{
    struct Cell_head cellhd;	/*region+header info */
    char *mapset;		/*mapset name */
    int nrows, ncols;
    int row, col;
    struct GModule *module;
    struct Option *input1, *input2, *input3, *input4, *input5;
    struct Option *input6, *input7, *input8, *input9, *output1;
    struct Flag *flag1;
    struct History history;	/*metadata */
    struct Colors colors;	/*Color rules */
    char *name;			/*input raster name */
    char *result;		/*output raster name */
    int infd_albedo, infd_ndvi, infd_tempk, infd_time, infd_dtair;
    int infd_emissivity, infd_tsw, infd_doy, infd_sunzangle;
    int outfd;
    char *albedo, *ndvi, *tempk, *time, *dtair, *emissivity;
    char *tsw, *doy, *sunzangle;
    int i = 0, j = 0;
    void *inrast_albedo, *inrast_ndvi, *inrast_tempk, *inrast_rnet;
    void *inrast_time, *inrast_dtair, *inrast_emissivity, *inrast_tsw;
    void *inrast_doy, *inrast_sunzangle;
    DCELL * outrast;
    CELL val1,val2; /*For color range*/

    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("imagery"));
    G_add_keyword(_("energy balance"));
    G_add_keyword(_("net radiation"));
    G_add_keyword(_("SEBAL"));
    module->description =
	_("Net radiation approximation (Bastiaanssen, 1995).");
    
	/* Define the different options */ 
    input1 = G_define_standard_option(G_OPT_R_INPUT);
    input1->key = "albedo";
    input1->description = _("Name of albedo raster map [0.0;1.0]");

    input2 = G_define_standard_option(G_OPT_R_INPUT);
    input2->key = "ndvi";
    input2->description = _("Name of NDVI raster map [-1.0;+1.0]");

    input3 = G_define_standard_option(G_OPT_R_INPUT);
    input3->key = "temperature";
    input3->description =
	_("Name of surface temperature raster map [K]");

    input4 = G_define_standard_option(G_OPT_R_INPUT);
    input4->key = "localutctime";
    input4->description =
	_("Name of time of satellite overpass raster map [local time in UTC]"); 

    input5 = G_define_standard_option(G_OPT_R_INPUT);
    input5->key = "temperaturedifference2m";
    input5->description =
	_("Name of the difference map of temperature from surface skin to about 2 m height [K]");

    input6 = G_define_standard_option(G_OPT_R_INPUT);
    input6->key = "emissivity";
    input6->description = _("Name of the emissivity map [-]");

    input7 = G_define_standard_option(G_OPT_R_INPUT);
    input7->key = "transmissivity_singleway";
    input7->description =
	_("Name of the single-way atmospheric transmissivitymap [-]");

    input8 = G_define_standard_option(G_OPT_R_INPUT);
    input8->key = "dayofyear";
    input8->description = _("Name of the Day Of Year (DOY) map [-]");

    input9 = G_define_standard_option(G_OPT_R_INPUT);
    input9->key = "sunzenithangle";
    input9->description = _("Name of the sun zenith angle map [degrees]");

    output1 = G_define_standard_option(G_OPT_R_OUTPUT);
    output1->description = _("Name of the output net radiation layer");
    
    /********************/ 
    if (G_parser(argc, argv))
	exit(EXIT_FAILURE);

    albedo = input1->answer;
    ndvi = input2->answer;
    tempk = input3->answer;
    time = input4->answer;
    dtair = input5->answer;
    emissivity = input6->answer;
    tsw = input7->answer;
    doy = input8->answer;
    sunzangle = input9->answer;
    result = output1->answer;
    
    /* Open access to image files and allocate row access memory */
    infd_albedo = Rast_open_old(albedo, "");
    inrast_albedo = Rast_allocate_d_buf();
    
    infd_ndvi = Rast_open_old(ndvi, "");
    inrast_ndvi = Rast_allocate_d_buf();

    infd_tempk = Rast_open_old(tempk, "");
    inrast_tempk = Rast_allocate_d_buf();

    infd_dtair = Rast_open_old(dtair, "");
    inrast_dtair = Rast_allocate_d_buf();

    infd_time = Rast_open_old(time, "");
    inrast_time = Rast_allocate_d_buf();

    infd_emissivity = Rast_open_old(emissivity, "");
    inrast_emissivity = Rast_allocate_d_buf();
    
    infd_tsw = Rast_open_old(tsw, "");
    inrast_tsw = Rast_allocate_d_buf();
    
    infd_doy = Rast_open_old(doy, "");
    inrast_doy = Rast_allocate_d_buf();
    
    infd_sunzangle = Rast_open_old(sunzangle, "");
    inrast_sunzangle = Rast_allocate_d_buf();
    
    nrows = Rast_window_rows();
    ncols = Rast_window_cols();

    outfd = Rast_open_new(result, DCELL_TYPE);
    outrast = Rast_allocate_d_buf();
    
    /* Process pixels */ 
    for (row = 0; row < nrows; row++)
    {
	DCELL d;
	DCELL d_albedo;
	DCELL d_ndvi;
	DCELL d_tempk;
	DCELL d_dtair;
	DCELL d_time;
	DCELL d_emissivity;
	DCELL d_tsw;
	DCELL d_doy;
	DCELL d_sunzangle;

	/* Display row process percentage */
	G_percent(row, nrows, 2);

	/* Load rows for each input image  */
	Rast_get_d_row(infd_albedo, inrast_albedo, row);
	Rast_get_d_row(infd_ndvi, inrast_ndvi, row);
	Rast_get_d_row(infd_tempk, inrast_tempk, row);
	Rast_get_d_row(infd_dtair, inrast_dtair, row);
	Rast_get_d_row(infd_time, inrast_time, row);
	Rast_get_d_row(infd_emissivity, inrast_emissivity, row);
	Rast_get_d_row(infd_tsw, inrast_tsw, row);
	Rast_get_d_row(infd_doy, inrast_doy, row);
	Rast_get_d_row(infd_sunzangle, inrast_sunzangle, row);
	
        /*process the data */ 
        for (col = 0; col < ncols; col++)
        {
            d_albedo = (double)((DCELL *) inrast_albedo)[col];
            d_ndvi = (double)((DCELL *) inrast_ndvi)[col];
            d_tempk = (double)((DCELL *) inrast_tempk)[col];
            d_dtair = (double)((DCELL *) inrast_dtair)[col];
            d_time = (double)((DCELL *) inrast_time)[col];
            d_emissivity = (double)((DCELL *) inrast_emissivity)[col];
            d_tsw = (double)((DCELL *) inrast_tsw)[col];
            d_doy = (double)((DCELL *) inrast_doy)[col];
            d_sunzangle = (double)((DCELL *) inrast_sunzangle)[col];
            /* process NULL Values */
	    if (Rast_is_d_null_value(&d_albedo) ||
	         Rast_is_d_null_value(&d_ndvi) ||
		 Rast_is_d_null_value(&d_tempk) ||
		 Rast_is_d_null_value(&d_dtair) || 
		 Rast_is_d_null_value(&d_time) ||
		 Rast_is_d_null_value(&d_emissivity) ||
		 Rast_is_d_null_value(&d_tsw) || 
		 Rast_is_d_null_value(&d_doy) ||
		 Rast_is_d_null_value(&d_sunzangle)) {
		Rast_set_d_null_value(&outrast[col], 1);
	    }
	    else {
                 /************************************/ 
		 /* calculate the net radiation      */ 
		 d = r_net(d_albedo, d_ndvi, d_tempk, d_dtair, d_emissivity, d_tsw, d_doy, d_time, d_sunzangle);
		 outrast[col] = d;
	    }
	}
	Rast_put_d_row(outfd, outrast);
    }
    G_free(inrast_albedo);
    G_free(inrast_ndvi);
    G_free(inrast_tempk);
    G_free(inrast_dtair);
    G_free(inrast_time);
    G_free(inrast_emissivity);
    G_free(inrast_tsw);
    G_free(inrast_doy);
    G_free(inrast_sunzangle);
    Rast_close(infd_albedo);
    Rast_close(infd_ndvi);
    Rast_close(infd_tempk);
    Rast_close(infd_dtair);
    Rast_close(infd_time);
    Rast_close(infd_emissivity);
    Rast_close(infd_tsw);
    Rast_close(infd_doy);
    Rast_close(infd_sunzangle);
    G_free(outrast);
    Rast_close(outfd);
    
    /* Colors in grey shade */ 
    Rast_init_colors(&colors);
    val1=0;
    val2=900;
    Rast_add_c_color_rule(&val1, 0, 0, 0, &val2, 255, 255, 255, &colors);
    
    /* Metadata */ 
    Rast_short_history(result, "raster", &history);
    Rast_command_history(&history);
    Rast_write_history(result, &history);
    exit(EXIT_SUCCESS);
}
Ejemplo n.º 15
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.º 16
0
int main(int argc, char *argv[])
{
    /* buffer for input-output rasters */
    void *inrast_TEMPKA, *inrast_PATM, *inrast_RNET, *inrast_G0;
    DCELL *outrast;

    /* pointers to input-output raster files */
    int infd_TEMPKA, infd_PATM, infd_RNET, infd_G0;
    int outfd;

    /* names of input-output raster files */
    char *RNET, *TEMPKA, *PATM, *G0;
    char *ETa;

    /* input-output cell values */
    DCELL d_tempka, d_pt_patm, d_rnet, d_g0;
    DCELL d_pt_alpha, d_pt_delta, d_pt_ghamma, d_daily_et;

    /* region information and handler */
    struct Cell_head cellhd;
    int nrows, ncols;
    int row, col;

    /* parser stuctures definition */
    struct GModule *module;
    struct Option *input_RNET, *input_TEMPKA, *input_PATM, *input_G0,
	*input_PT;
    struct Option *output;
    struct Flag *zero;
    struct Colors color;
    struct History history;

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

    module = G_define_module();
    G_add_keyword(_("imagery"));
    G_add_keyword(_("evapotranspiration"));
    module->description =
	_("Computes evapotranspiration calculation "
	  "Priestley and Taylor formulation, 1972.");
    
    /* Define different options */
    input_RNET = G_define_standard_option(G_OPT_R_INPUT);
    input_RNET->key = "net_radiation";
    input_RNET->description = _("Name of input net radiation raster map [W/m2]");

    input_G0 = G_define_standard_option(G_OPT_R_INPUT);
    input_G0->key = "soil_heatflux";
    input_G0->description = _("Name of input soil heat flux raster map [W/m2]");

    input_TEMPKA = G_define_standard_option(G_OPT_R_INPUT);
    input_TEMPKA->key = "air_temperature";
    input_TEMPKA->description = _("Name of input air temperature raster map [K]");

    input_PATM = G_define_standard_option(G_OPT_R_INPUT);
    input_PATM->key = "atmospheric_pressure";
    input_PATM->description = _("Name of input atmospheric pressure raster map [millibars]");

    input_PT = G_define_option();
    input_PT->key = "priestley_taylor_coeff";
    input_PT->type = TYPE_DOUBLE;
    input_PT->required = YES;
    input_PT->description = _("Priestley-Taylor coefficient");
    input_PT->answer = "1.26";

    output = G_define_standard_option(G_OPT_R_OUTPUT);
    output->description = _("Name of output evapotranspiration raster map [mm/d]");

    /* Define the different flags */
    zero = G_define_flag();
    zero->key = 'z';
    zero->description = _("Set negative ETa to zero");

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

    /* get entered parameters */
    RNET = input_RNET->answer;
    TEMPKA = input_TEMPKA->answer;
    PATM = input_PATM->answer;
    G0 = input_G0->answer;
    d_pt_alpha = atof(input_PT->answer);

    ETa = output->answer;

    /* open pointers to input raster files */
    infd_RNET = Rast_open_old(RNET, "");
    infd_TEMPKA = Rast_open_old(TEMPKA, "");
    infd_PATM = Rast_open_old(PATM, "");
    infd_G0 = Rast_open_old(G0, "");

    /* read headers of raster files */
    Rast_get_cellhd(RNET, "", &cellhd);
    Rast_get_cellhd(TEMPKA, "", &cellhd);
    Rast_get_cellhd(PATM, "", &cellhd);
    Rast_get_cellhd(G0, "", &cellhd);

    /* Allocate input buffer */
    inrast_RNET = Rast_allocate_d_buf();
    inrast_TEMPKA = Rast_allocate_d_buf();
    inrast_PATM = Rast_allocate_d_buf();
    inrast_G0 = Rast_allocate_d_buf();

    /* get rows and columns number of the current region */
    nrows = Rast_window_rows();
    ncols = Rast_window_cols();

    /* allocate output buffer */
    outrast = Rast_allocate_d_buf();

    /* open pointers to output raster files */
    outfd = Rast_open_new(ETa, DCELL_TYPE);

    /* start the loop through cells */
    for (row = 0; row < nrows; row++) {

	G_percent(row, nrows, 2);
	/* read input raster row into line buffer */
	Rast_get_d_row(infd_RNET, inrast_RNET, row);
	Rast_get_d_row(infd_TEMPKA, inrast_TEMPKA, row);
	Rast_get_d_row(infd_PATM, inrast_PATM, row);
	Rast_get_d_row(infd_G0, inrast_G0, row);

	for (col = 0; col < ncols; col++) {
	    /* read current cell from line buffer */
            d_rnet = ((DCELL *) inrast_RNET)[col];
            d_tempka = ((DCELL *) inrast_TEMPKA)[col];
            d_pt_patm = ((DCELL *) inrast_PATM)[col];
            d_g0 = ((DCELL *) inrast_G0)[col];

	    /*Delta_pt and Ghamma_pt */
	    d_pt_delta = pt_delta(d_tempka);
	    d_pt_ghamma = pt_ghamma(d_tempka, d_pt_patm);

	    /*Calculate ET */
	    d_daily_et =
		pt_daily_et(d_pt_alpha, d_pt_delta, d_pt_ghamma, d_rnet, d_g0,
			    d_tempka);
	    if (zero->answer && d_daily_et < 0)
		d_daily_et = 0.0;

	    /* write calculated ETP to output line buffer */
	    outrast[col] = d_daily_et;
	}

	/* write output line buffer to output raster file */
	Rast_put_d_row(outfd, outrast);
    }
    /* free buffers and close input maps */

    G_free(inrast_RNET);
    G_free(inrast_TEMPKA);
    G_free(inrast_PATM);
    G_free(inrast_G0);
    Rast_close(infd_RNET);
    Rast_close(infd_TEMPKA);
    Rast_close(infd_PATM);
    Rast_close(infd_G0);

    /* generate color table between -20 and 20 */
    Rast_make_rainbow_colors(&color, -20, 20);
    Rast_write_colors(ETa, G_mapset(), &color);

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

    /* free buffers and close output map */
    G_free(outrast);
    Rast_close(outfd);

    return (EXIT_SUCCESS);
}
Ejemplo n.º 17
0
int main(int argc, char *argv[])
{
    unsigned int r, c, rows, cols;	/*  totals  */
    int map1_fd, map2_fd;
    double sumX, sumY, sumsqX, sumsqY, sumXY;
    double meanX, meanY, varX, varY, sdX, sdY;
    double A, B, R, F;
    long count = 0;
    DCELL *map1_buf, *map2_buf, map1_val, map2_val;
    char *name;
    struct Option *input_map1, *input_map2, *output_opt;
    struct Flag *shell_style;
    struct Cell_head region;
    struct GModule *module;

    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("raster"));
    G_add_keyword(_("statistics"));
    module->description =
	_("Calculates linear regression from two raster maps: y = a + b*x.");

    /* Define the different options */
    input_map1 = G_define_standard_option(G_OPT_R_MAP);
    input_map1->key = "map1";
    input_map1->description = (_("Map for x coefficient"));

    input_map2 = G_define_standard_option(G_OPT_R_MAP);
    input_map2->key = "map2";
    input_map2->description = (_("Map for y coefficient"));

    output_opt = G_define_standard_option(G_OPT_F_OUTPUT);
    output_opt->key = "output";
    output_opt->required = NO;
    output_opt->description =
	(_("ASCII file for storing regression coefficients (output to screen if file not specified)."));

    shell_style = G_define_flag();
    shell_style->key = 'g';
    shell_style->description = _("Print in shell script style");

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

    name = output_opt->answer;
    if (name != NULL && strcmp(name, "-") != 0) {
	if (NULL == freopen(name, "w", stdout)) {
	    G_fatal_error(_("Unable to open file <%s> for writing"), name);
	}
    }

    G_get_window(&region);
    rows = region.rows;
    cols = region.cols;

    /* open maps */
    map1_fd = Rast_open_old(input_map1->answer, "");
    map2_fd = Rast_open_old(input_map2->answer, "");

    map1_buf = Rast_allocate_d_buf();
    map2_buf = Rast_allocate_d_buf();

    sumX = sumY = sumsqX = sumsqY = sumXY = 0.0;
    meanX = meanY = varX = varY = sdX = sdY = 0.0;
    for (r = 0; r < rows; r++) {
	G_percent(r, rows, 2);
	Rast_get_d_row(map1_fd, map1_buf, r);
	Rast_get_d_row(map2_fd, map2_buf, r);
	for (c = 0; c < cols; c++) {
	    map1_val = map1_buf[c];
	    map2_val = map2_buf[c];
	    if (Rast_is_d_null_value(&map1_val) ||
		Rast_is_d_null_value(&map2_val))
		continue;

	    sumX += map1_val;
	    sumY += map2_val;
	    sumsqX += map1_val * map1_val;
	    sumsqY += map2_val * map2_val;
	    sumXY += map1_val * map2_val;
	    count++;
	}
    }
    Rast_close(map1_fd);
    Rast_close(map2_fd);
    G_free(map1_buf);
    G_free(map2_buf);

    B = (sumXY - sumX * sumY / count) / (sumsqX - sumX * sumX / count);
    R = (sumXY - sumX * sumY / count) /
	sqrt((sumsqX - sumX * sumX / count) * (sumsqY - sumY * sumY / count));

    meanX = sumX / count;
    sumsqX = sumsqX / count;
    varX = sumsqX - (meanX * meanX);
    sdX = sqrt(varX);

    meanY = sumY / count;
    sumsqY = sumsqY / count;
    varY = sumsqY - (meanY * meanY);
    sdY = sqrt(varY);

    A = meanY - B * meanX;
    F = R * R / (1 - R * R / count - 2);

    if (shell_style->answer) {
	fprintf(stdout, "a=%f\n", A);
	fprintf(stdout, "b=%f\n", B);
	fprintf(stdout, "R=%f\n", R);
	fprintf(stdout, "N=%ld\n", count);
	fprintf(stdout, "F=%f\n", F);
	fprintf(stdout, "meanX=%f\n", meanX);
	fprintf(stdout, "sdX=%f\n", sdX);
	fprintf(stdout, "meanY=%f\n", meanY);
	fprintf(stdout, "sdY=%f\n", sdY);
    }
    else {
	fprintf(stdout, "y = a + b*x\n");
	fprintf(stdout, "   a (Offset): %f\n", A);
	fprintf(stdout, "   b (Gain): %f\n", B);
	fprintf(stdout, "   R (sumXY - sumX*sumY/N): %f\n", R);
	fprintf(stdout, "   N (Number of elements): %ld\n", count);
	fprintf(stdout, "   F (F-test significance): %f\n", F);
	fprintf(stdout, "   meanX (Mean of map1): %f\n", meanX);
	fprintf(stdout, "   sdX (Standard deviation of map1): %f\n", sdX);
	fprintf(stdout, "   meanY (Mean of map2): %f\n", meanY);
	fprintf(stdout, "   sdY (Standard deviation of map2): %f\n", sdY);
    }

    exit(EXIT_SUCCESS);
}
Ejemplo n.º 18
0
int main(int argc, char *argv[]) 
{
    int nrows, ncols;
    int row, col;
    char *nameflag;		/*Switch for particular method */
    struct GModule *module;
    struct Option *input1, *input2, *output;
    struct History history;	/*metadata */

    /************************************/ 
    char *result;		/*output raster name */
    int infd_annual_pmm;
    int outfd;
    char *annual_pmm;

    void *inrast_annual_pmm;
    DCELL * outrast;

    /************************************/ 
    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("raster"));
    G_add_keyword(_("hydrology"));
    G_add_keyword(_("rainfall"));
    G_add_keyword(_("erosion"));
    module->description = _("Computes USLE R factor, Rainfall erosivity index.");
    
    input2 = G_define_standard_option(G_OPT_R_INPUT);
    input2->description = _("Name of annual precipitation raster map [mm/year]");

    output = G_define_standard_option(G_OPT_R_OUTPUT);
    output->description = _("Name for output USLE R raster map [MJ.mm/ha.hr.year]");

    /* Define the different options */ 
    input1 = G_define_option();
    input1->key = "method";
    input1->type = TYPE_STRING;
    input1->required = YES;
    input1->description = _("Name of USLE R equation");
    input1->options = "roose, morgan, foster, elswaify";
    input1->descriptions = _("roose;Roosle (1975);"
			     "morgan;Morgan (1974);"
			     "foster;Foster (1981);"
			     "elswaify;El-Swaify (1985)");
    input1->answer = "morgan";

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

    nameflag = input1->answer;
    annual_pmm = input2->answer;
    result = output->answer;
    
    /***************************************************/ 
    infd_annual_pmm = Rast_open_old(annual_pmm, "");
    inrast_annual_pmm = Rast_allocate_d_buf();
    
    /***************************************************/ 
    nrows = Rast_window_rows();
    ncols = Rast_window_cols();
    outrast = Rast_allocate_d_buf();
    
    /* Create New raster files */ 
    outfd = Rast_open_new(result, DCELL_TYPE);
    
    /* Process pixels */ 
    for (row = 0; row < nrows; row++)
    {
        DCELL d;
	DCELL d_annual_pmm;
	G_percent(row, nrows, 2);
	
	/* read input map */ 
	Rast_get_d_row(infd_annual_pmm, inrast_annual_pmm, row);
	
	/*process the data */ 
	for (col = 0; col < ncols; col++)
	{
	    d_annual_pmm = ((DCELL *) inrast_annual_pmm)[col];
	    if (Rast_is_d_null_value(&d_annual_pmm)) 
		Rast_set_d_null_value(&outrast[col], 1);
	    else 
            {
                /*calculate morgan       */ 
                if (!strcmp(nameflag, "morgan"))
                    d = morgan_1974(d_annual_pmm);
		/*calculate roose        */ 
		if (!strcmp(nameflag, "roose")) 
		    d = roose_1975(d_annual_pmm);
		/*calculate foster       */ 
		if (!strcmp(nameflag, "foster"))
		    d = foster_1981(d_annual_pmm);
		/*calculate elswaify     */ 
		if (!strcmp(nameflag, "elswaify")) 
		    d = elswaify_1985(d_annual_pmm);
		outrast[col] = d ;
	    }
	}
	Rast_put_d_row(outfd, outrast);
    }
    G_free(inrast_annual_pmm);
    Rast_close(infd_annual_pmm);
    G_free(outrast);
    Rast_close(outfd);

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

    exit(EXIT_SUCCESS);
}
Ejemplo n.º 19
0
int open_files(struct globals *globals)
{
    struct Ref Ref;		/* group reference list */
    int *in_fd, bounds_fd, is_null;
    int n, row, col, srows, scols, inlen, outlen, nseg;
    DCELL **inbuf;		/* buffers to store lines from each of the imagery group rasters */
    CELL *boundsbuf, bounds_val;
    int have_bounds = 0;
    CELL s, id;
    struct Range range;	/* min/max values of bounds map */
    struct FPRange *fp_range;	/* min/max values of each input raster */
    DCELL *min, *max;
    struct ngbr_stats Ri, Rk;

    /*allocate memory for flags */
    globals->null_flag = flag_create(globals->nrows, globals->ncols);
    globals->candidate_flag = flag_create(globals->nrows, globals->ncols);

    flag_clear_all(globals->null_flag);
    flag_clear_all(globals->candidate_flag);

    G_debug(1, "Checking image group...");

    /* ****** open the input rasters ******* */

    if (!I_get_group_ref(globals->image_group, &Ref))
	G_fatal_error(_("Group <%s> not found in the current mapset"),
		      globals->image_group);

    if (Ref.nfiles <= 0)
	G_fatal_error(_("Group <%s> contains no raster maps"),
		      globals->image_group);

    /* Read Imagery Group */

    in_fd = G_malloc(Ref.nfiles * sizeof(int));
    inbuf = (DCELL **) G_malloc(Ref.nfiles * sizeof(DCELL *));
    fp_range = G_malloc(Ref.nfiles * sizeof(struct FPRange));
    min = G_malloc(Ref.nfiles * sizeof(DCELL));
    max = G_malloc(Ref.nfiles * sizeof(DCELL));

    G_debug(1, "Opening input rasters...");
    for (n = 0; n < Ref.nfiles; n++) {
	inbuf[n] = Rast_allocate_d_buf();
	in_fd[n] = Rast_open_old(Ref.file[n].name, Ref.file[n].mapset);
    }

    /* Get min/max values of each input raster for scaling */

    globals->max_diff = 0.;
    globals->nbands = Ref.nfiles;

    for (n = 0; n < Ref.nfiles; n++) {
	/* returns -1 on error, 2 on empty range, quitting either way. */
	if (Rast_read_fp_range(Ref.file[n].name, Ref.file[n].mapset, &fp_range[n]) != 1)
	    G_fatal_error(_("No min/max found in raster map <%s>"),
			  Ref.file[n].name);
	Rast_get_fp_range_min_max(&(fp_range[n]), &min[n], &max[n]);

	G_debug(1, "Range for layer %d: min = %f, max = %f",
		    n, min[n], max[n]);
	
    }
    if (globals->weighted == FALSE)
	globals->max_diff = Ref.nfiles;
    else {
	/* max difference with selected similarity method */
	Ri.mean = max;
	Rk.mean = min;
	globals->max_diff = 1;
	globals->max_diff = (*globals->calculate_similarity) (&Ri, &Rk, globals);
    }

    /* ********** find out file segmentation size ************ */
    G_debug(1, "Calculate temp file sizes...");

    /* size of each element to be stored */

    inlen = sizeof(DCELL) * Ref.nfiles;
    outlen = sizeof(CELL);
    G_debug(1, "data element size, in: %d , out: %d ", inlen, outlen);
    globals->datasize = sizeof(double) * globals->nbands;

    /* count non-null cells */
    globals->notnullcells = (long)globals->nrows * globals->ncols;
    for (row = 0; row < globals->nrows; row++) {
	for (n = 0; n < Ref.nfiles; n++) {
	    Rast_get_d_row(in_fd[n], inbuf[n], row);
	}
	for (col = 0; col < globals->ncols; col++) {

	    is_null = 0;	/*Assume there is data */
	    for (n = 0; n < Ref.nfiles; n++) {
		if (Rast_is_d_null_value(&inbuf[n][col])) {
		    is_null = 1;
		}
	    }
	    if (is_null) {
		globals->notnullcells--;
		FLAG_SET(globals->null_flag, row, col);
	    }
	}
    }
    G_verbose_message(_("Non-NULL cells: %ld"), globals->notnullcells);
    if (globals->notnullcells < 2)
	G_fatal_error(_("Insufficient number of non-NULL cells in current region"));

    /* segment lib segment size */
    srows = 64;
    scols = 64;

    nseg = manage_memory(srows, scols, globals);

    /* create segment structures */
    if (Segment_open
	(&globals->bands_seg, G_tempfile(), globals->nrows, globals->ncols, srows,
	 scols, inlen, nseg) != 1)
	G_fatal_error("Unable to create input temporary files");

    if (Segment_open
	(&globals->rid_seg, G_tempfile(), globals->nrows, globals->ncols, srows,
	 scols, outlen, nseg * 2) != 1)
	G_fatal_error("Unable to create input temporary files");

    /* load input bands to segment structure */
    if (Ref.nfiles > 1)
	G_message(_("Loading input bands..."));
    else
	G_message(_("Loading input band..."));

    globals->bands_val = (double *)G_malloc(inlen);
    globals->second_val = (double *)G_malloc(inlen);
    /* initial segment ID */
    s = 1;

    globals->row_min = globals->nrows;
    globals->row_max = 0;
    globals->col_min = globals->ncols;
    globals->col_max = 0;
    for (row = 0; row < globals->nrows; row++) {
	G_percent(row, globals->nrows, 4);
	for (n = 0; n < Ref.nfiles; n++) {
	    Rast_get_d_row(in_fd[n], inbuf[n], row);
	}
	for (col = 0; col < globals->ncols; col++) {

	    is_null = 0;	/*Assume there is data */
	    for (n = 0; n < Ref.nfiles; n++) {
		globals->bands_val[n] = inbuf[n][col];
		if (Rast_is_d_null_value(&inbuf[n][col])) {
		    is_null = 1;
		}
		else {
		    if (globals->weighted == FALSE)
		    	/* scaled version */
			globals->bands_val[n] = (inbuf[n][col] - min[n]) / (max[n] - min[n]);
		}
	    }
	    if (Segment_put(&globals->bands_seg,
	                    (void *)globals->bands_val, row, col) != 1)
		G_fatal_error(_("Unable to write to temporary file"));

	    if (!is_null) {
		if (!globals->seeds) {
		    /* sequentially number all cells with a unique segment ID */
		    id = s;
		    s++;
		}

		/* get min/max row/col to narrow the processing window */
		if (globals->row_min > row)
		    globals->row_min = row;
		if (globals->row_max < row)
		    globals->row_max = row;
		if (globals->col_min > col)
		    globals->col_min = col;
		if (globals->col_max < col)
		    globals->col_max = col;
	    }
	    else {
		/* all input bands NULL */
		Rast_set_c_null_value(&id, 1);
		FLAG_SET(globals->null_flag, row, col);
	    }
	    if (!globals->seeds || is_null) {
		if (Segment_put(&globals->rid_seg,
		                (void *)&id, row, col) != 1)
		    G_fatal_error(_("Unable to write to temporary file"));
	    }
	}
    }
    G_percent(1, 1, 1);
    G_debug(1, "nrows: %d, min row: %d, max row %d",
	       globals->nrows, globals->row_min, globals->row_max);
    G_debug(1, "ncols: %d, min col: %d, max col %d",
               globals->ncols, globals->col_min, globals->col_max);
    
    globals->row_max++;
    globals->col_max++;
    globals->ncells = (long)(globals->row_max - globals->row_min) *
			    (globals->col_max - globals->col_min);

    /* bounds/constraints */

    Rast_set_c_null_value(&globals->upper_bound, 1);
    Rast_set_c_null_value(&globals->lower_bound, 1);

    if (globals->bounds_map != NULL) {
	if (Segment_open
	    (&globals->bounds_seg, G_tempfile(), globals->nrows, globals->ncols,
	     srows, scols, sizeof(CELL), nseg) != TRUE)
	    G_fatal_error("Unable to create bounds temporary files");

	if (Rast_read_range(globals->bounds_map, globals->bounds_mapset, &range) != 1)
	    G_fatal_error(_("No min/max found in raster map <%s>"),
			  globals->bounds_map);
	Rast_get_range_min_max(&range, &globals->upper_bound,
				       &globals->lower_bound);

	if (Rast_is_c_null_value(&globals->upper_bound) ||
	    Rast_is_c_null_value(&globals->lower_bound)) {
	    
	    G_fatal_error(_("No min/max found in raster map <%s>"),
	                  globals->bounds_map);
	}

	bounds_fd = Rast_open_old(globals->bounds_map, globals->bounds_mapset);
	boundsbuf = Rast_allocate_c_buf();

	for (row = 0; row < globals->nrows; row++) {
	    Rast_get_c_row(bounds_fd, boundsbuf, row);
	    for (col = 0; col < globals->ncols; col++) {
		bounds_val = boundsbuf[col];
		if (FLAG_GET(globals->null_flag, row, col)) {
		    Rast_set_c_null_value(&bounds_val, 1);
		}
		else {
		    if (!Rast_is_c_null_value(&bounds_val)) {
			have_bounds = 1;
			if (globals->lower_bound > bounds_val)
			    globals->lower_bound = bounds_val;
			if (globals->upper_bound < bounds_val)
			    globals->upper_bound = bounds_val;
		    }
		}
		if (Segment_put(&globals->bounds_seg, &bounds_val, row, col) != 1)
		    G_fatal_error(_("Unable to write to temporary file"));
	    }
	}
	Rast_close(bounds_fd);
	G_free(boundsbuf);

	if (!have_bounds) {
	    G_warning(_("There are no boundary constraints in '%s'"), globals->bounds_map);
	    Rast_set_c_null_value(&globals->upper_bound, 1);
	    Rast_set_c_null_value(&globals->lower_bound, 1);
	    Segment_close(&globals->bounds_seg);
	    globals->bounds_map = NULL;
	    globals->bounds_mapset = NULL;
	}
    }
    else {
	G_debug(1, "no boundary constraint supplied.");
    }

    /* other info */
    globals->candidate_count = 0;	/* counter for remaining candidate pixels */

    /* Free memory */

    for (n = 0; n < Ref.nfiles; n++) {
	G_free(inbuf[n]);
	Rast_close(in_fd[n]);
    }

    globals->rs.sum = G_malloc(globals->datasize);
    globals->rs.mean = G_malloc(globals->datasize);

    globals->reg_tree = rgtree_create(globals->nbands, globals->datasize);
    globals->n_regions = s - 1;

    if (globals->seeds) {
	load_seeds(globals, srows, scols, nseg);
    }

    G_debug(1, "Number of initial regions: %d", globals->n_regions);

    G_free(inbuf);
    G_free(in_fd);
    G_free(fp_range);
    G_free(min);
    G_free(max);

    return TRUE;
}
Ejemplo n.º 20
0
int main(int argc, char *argv[])
{
    struct Cell_head cellhd;
    /* buffer for in, tmp and out raster */
    void *inrast_Rn, *inrast_g0;
    void *inrast_z0m, *inrast_t0dem;
    DCELL *outrast;
    int nrows, ncols;
    int row, col;
    int row_wet, col_wet;
    int row_dry, col_dry;
    double m_row_wet, m_col_wet;
    double m_row_dry, m_col_dry;
    int infd_Rn, infd_g0;
    int infd_z0m, infd_t0dem;
    int outfd;
    char *Rn, *g0;
    char *z0m, *t0dem;
    char *h0;

    double ustar, ea;
    struct History history;
    struct GModule *module;
    struct Option *input_Rn, *input_g0;
    struct Option *input_z0m, *input_t0dem, *input_ustar;
    struct Option *input_ea, *output;
    struct Option *input_row_wet, *input_col_wet;
    struct Option *input_row_dry, *input_col_dry;
    struct Flag *flag2, *flag3;
    /********************************/
    double xp, yp;
    double xmin, ymin;
    double xmax, ymax;
    double stepx, stepy;
    double latitude, longitude;
    int rowDry, colDry, rowWet, colWet;
    /********************************/
    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("imagery"));
    G_add_keyword(_("energy balance"));
    G_add_keyword(_("soil moisture"));
    G_add_keyword(_("evaporative fraction"));
    G_add_keyword(_("SEBAL"));
    module->description = _("Computes sensible heat flux iteration SEBAL 01.");

    /* Define different options */
    input_Rn = G_define_standard_option(G_OPT_R_INPUT);
    input_Rn->key = "netradiation";
    input_Rn->description =
	_("Name of instantaneous Net Radiation raster map [W/m2]");

    input_g0 = G_define_standard_option(G_OPT_R_INPUT);
    input_g0->key = "soilheatflux";
    input_g0->description =
	_("Name of instantaneous soil heat flux raster map [W/m2]");

    input_z0m = G_define_standard_option(G_OPT_R_INPUT);
    input_z0m->key = "aerodynresistance";
    input_z0m->description =
	_("Name of aerodynamic resistance to heat momentum raster map [s/m]");

    input_t0dem = G_define_standard_option(G_OPT_R_INPUT);
    input_t0dem->key = "temperaturemeansealevel";
    input_t0dem->description =
	_("Name of altitude corrected surface temperature raster map [K]");

    input_ustar = G_define_option();
    input_ustar->key = "frictionvelocitystar";
    input_ustar->type = TYPE_DOUBLE;
    input_ustar->required = YES;
    input_ustar->gisprompt = "old,value";
    input_ustar->answer = "0.32407";
    input_ustar->description = _("Value of the height independent friction velocity (u*) [m/s]");
    input_ustar->guisection = _("Parameters");

    input_ea = G_define_option();
    input_ea->key = "vapourpressureactual";
    input_ea->type = TYPE_DOUBLE;
    input_ea->required = YES;
    input_ea->answer = "1.511";
    input_ea->description = _("Value of the actual vapour pressure (e_act) [KPa]");
    input_ea->guisection = _("Parameters");

    input_row_wet = G_define_option();
    input_row_wet->key = "row_wet_pixel";
    input_row_wet->type = TYPE_DOUBLE;
    input_row_wet->required = NO;
    input_row_wet->description = _("Row value of the wet pixel");
    input_row_wet->guisection = _("Parameters");

    input_col_wet = G_define_option();
    input_col_wet->key = "column_wet_pixel";
    input_col_wet->type = TYPE_DOUBLE;
    input_col_wet->required = NO;
    input_col_wet->description = _("Column value of the wet pixel");
    input_col_wet->guisection = _("Parameters");

    input_row_dry = G_define_option();
    input_row_dry->key = "row_dry_pixel";
    input_row_dry->type = TYPE_DOUBLE;
    input_row_dry->required = NO;
    input_row_dry->description = _("Row value of the dry pixel");
    input_row_dry->guisection = _("Parameters");

    input_col_dry = G_define_option();
    input_col_dry->key = "column_dry_pixel";
    input_col_dry->type = TYPE_DOUBLE;
    input_col_dry->required = NO;
    input_col_dry->description = _("Column value of the dry pixel");
    input_col_dry->guisection = _("Parameters");

    output = G_define_standard_option(G_OPT_R_OUTPUT);
    output->description = _("Name for output sensible heat flux raster map [W/m2]");
    
    /* Define the different flags */
    flag2 = G_define_flag();
    flag2->key = 'a';
    flag2->description = _("Automatic wet/dry pixel (careful!)");

    flag3 = G_define_flag();
    flag3->key = 'c';
    flag3->description =
	_("Dry/Wet pixels coordinates are in image projection, not row/col");

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

    /* get entered parameters */
    Rn = input_Rn->answer;
    g0 = input_g0->answer;
    z0m = input_z0m->answer;
    t0dem = input_t0dem->answer;

    h0 = output->answer;

    ustar = atof(input_ustar->answer);
    ea = atof(input_ea->answer);

    if(input_row_wet->answer&&
    input_col_wet->answer&&
    input_row_dry->answer&&
    input_col_dry->answer){
        m_row_wet = atof(input_row_wet->answer);
        m_col_wet = atof(input_col_wet->answer);
        m_row_dry = atof(input_row_dry->answer);
        m_col_dry = atof(input_col_dry->answer);
    }
    if ((!input_row_wet->answer || !input_col_wet->answer ||
	 !input_row_dry->answer || !input_col_dry->answer) &&
	!flag2->answer) {
	G_fatal_error(_("Either auto-mode either wet/dry pixels coordinates should be provided!"));
    }
    if (flag3->answer) {
	G_message(_("Manual wet/dry pixels in image coordinates"));
	G_message(_("Wet Pixel=> x:%f y:%f"), m_col_wet, m_row_wet);
	G_message(_("Dry Pixel=> x:%f y:%f"), m_col_dry, m_row_dry);
    }
    else {
        if(flag2->answer)
	    G_message(_("Automatic mode selected"));
	else {
	    G_message(_("Wet Pixel=> row:%.0f col:%.0f"), m_row_wet, m_col_wet);
	    G_message(_("Dry Pixel=> row:%.0f col:%.0f"), m_row_dry, m_col_dry);
	}
    }
    /* check legal output name */
    if (G_legal_filename(h0) < 0)
	G_fatal_error(_("<%s> is an illegal name"), h0);

    infd_Rn = Rast_open_old(Rn, "");
    infd_g0 = Rast_open_old(g0, "");
    infd_z0m = Rast_open_old(z0m, "");
    infd_t0dem = Rast_open_old(t0dem, "");

    Rast_get_cellhd(Rn, "", &cellhd);
    Rast_get_cellhd(g0, "", &cellhd);
    Rast_get_cellhd(z0m, "", &cellhd);
    Rast_get_cellhd(t0dem, "", &cellhd);

    /* Allocate input buffer */
    inrast_Rn = Rast_allocate_d_buf();
    inrast_g0 = Rast_allocate_d_buf();
    inrast_z0m = Rast_allocate_d_buf();
    inrast_t0dem = Rast_allocate_d_buf();

    /***************************************************/
    /* Setup pixel location variables */
    /***************************************************/
    stepx = cellhd.ew_res;
    stepy = cellhd.ns_res;

    xmin = cellhd.west;
    xmax = cellhd.east;
    ymin = cellhd.south;
    ymax = cellhd.north;

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

    /***************************************************/
    /* Allocate output buffer */
    /***************************************************/
    outrast = Rast_allocate_d_buf();
    outfd = Rast_open_new(h0, DCELL_TYPE);
    /***************************************************/
    /* Allocate memory for temporary images            */
    double **d_Roh, **d_Rah;

    if ((d_Roh = G_alloc_matrix(nrows, ncols)) == NULL)
	G_message("Unable to allocate memory for temporary d_Roh image");
    if ((d_Rah = G_alloc_matrix(nrows, ncols)) == NULL)
	G_message("Unable to allocate memory for temporary d_Rah image");
    /***************************************************/

    /* MANUAL T0DEM WET/DRY PIXELS */
    DCELL d_Rn_dry,d_g0_dry;
    DCELL d_t0dem_dry,d_t0dem_wet;

    if (flag2->answer) {
	/* Process tempk min / max pixels */
	/* Internal use only */
	DCELL d_Rn_wet,d_g0_wet;
	DCELL d_Rn,d_g0,d_h0;
	DCELL t0dem_min,t0dem_max;
        /*********************/
	for (row = 0; row < nrows; row++) {
	    DCELL d_t0dem;
	    G_percent(row, nrows, 2);
	    Rast_get_d_row(infd_t0dem,inrast_t0dem,row);
	    Rast_get_d_row(infd_Rn,inrast_Rn,row);
	    Rast_get_d_row(infd_g0,inrast_g0,row);
	    /*process the data */
	    for (col = 0; col < ncols; col++) {
		d_t0dem = ((DCELL *) inrast_t0dem)[col];
		d_Rn = ((DCELL *) inrast_Rn)[col];
		d_g0 = ((DCELL *) inrast_g0)[col];
		if (Rast_is_d_null_value(&d_t0dem) ||
		    Rast_is_d_null_value(&d_Rn) || 
                    Rast_is_d_null_value(&d_g0)) {
		    /* do nothing */
		}
		else {
		    if (d_t0dem <= 250.0) {
			/* do nothing */
		    }
		    else {
			d_h0 = d_Rn - d_g0;
			if (d_t0dem < t0dem_min &&
			    d_Rn > 0.0 && d_g0 > 0.0 && d_h0 > 0.0 &&
			    d_h0 < 100.0) {
			    t0dem_min = d_t0dem;
			    d_t0dem_wet = d_t0dem;
			    d_Rn_wet = d_Rn;
			    d_g0_wet = d_g0;
			    m_col_wet = col;
			    m_row_wet = row;
			}
			if (d_t0dem > t0dem_max &&
			    d_Rn > 0.0 && d_g0 > 0.0 && d_h0 > 100.0 &&
			    d_h0 < 500.0) {
			    t0dem_max = d_t0dem;
			    d_t0dem_dry = d_t0dem;
			    d_Rn_dry = d_Rn;
			    d_g0_dry = d_g0;
			    m_col_dry = col;
			    m_row_dry = row;
			}
		    }
		}
	    }
	}
	G_message("row_wet=%d\tcol_wet=%d", row_wet, col_wet);
	G_message("row_dry=%d\tcol_dry=%d", row_dry, col_dry);
	G_message("g0_wet=%f", d_g0_wet);
	G_message("Rn_wet=%f", d_Rn_wet);
	G_message("LE_wet=%f", d_Rn_wet - d_g0_wet);
	G_message("t0dem_dry=%f", d_t0dem_dry);
	G_message("rnet_dry=%f", d_Rn_dry);
	G_message("g0_dry=%f", d_g0_dry);
	G_message("h0_dry=%f", d_Rn_dry - d_g0_dry);
    }/* END OF FLAG2 */

    G_message("Passed here");

    /* MANUAL T0DEM WET/DRY PIXELS */
    /*DRY PIXEL */
    if (flag3->answer) {
	/*Calculate coordinates of row/col from projected ones */
	row = (int)((ymax - m_row_dry) / (double)stepy);
	col = (int)((m_col_dry - xmin) / (double)stepx);
	G_message("Dry Pixel | row:%i col:%i", row, col);
    }
    else {
	row = (int)m_row_dry;
	col = (int)m_col_dry;
	G_message("Dry Pixel | row:%i col:%i", row, col);
    }
    rowDry = row;
    colDry = col;
    Rast_get_d_row(infd_Rn, inrast_Rn, row);
    Rast_get_d_row(infd_g0, inrast_g0, row);
    Rast_get_d_row(infd_t0dem, inrast_t0dem, row);
    d_Rn_dry = ((DCELL *) inrast_Rn)[col];
    d_g0_dry = ((DCELL *) inrast_g0)[col];
    d_t0dem_dry = ((DCELL *) inrast_t0dem)[col];
    /*WET PIXEL */
    if (flag3->answer) {
	/*Calculate coordinates of row/col from projected ones */
	row = (int)((ymax - m_row_wet) / (double)stepy);
	col = (int)((m_col_wet - xmin) / (double)stepx);
	G_message("Wet Pixel | row:%i col:%i", row, col);
    }
    else {
	row = m_row_wet;
	col = m_col_wet;
	G_message("Wet Pixel | row:%i col:%i", row, col);
    }
    rowWet = row;
    colWet = col;
    Rast_get_d_row(infd_t0dem, inrast_t0dem, row);
    d_t0dem_wet = ((DCELL *) inrast_t0dem)[col];
    /* END OF MANUAL WET/DRY PIXELS */
    double h_dry;

    h_dry = d_Rn_dry - d_g0_dry;
    G_message("h_dry = %f", h_dry);
    G_message("t0dem_dry = %f", d_t0dem_dry);
    G_message("t0dem_wet = %f", d_t0dem_wet);
    DCELL d_rah_dry;
    DCELL d_roh_dry;

    /* INITIALIZATION */
    for (row = 0; row < nrows; row++) {
	DCELL d_t0dem,d_z0m;
	DCELL d_rah1,d_roh1;
	DCELL d_u5;
	G_percent(row, nrows, 2);
	/* read a line input maps into buffers */
	Rast_get_d_row(infd_z0m, inrast_z0m, row);
	Rast_get_d_row(infd_t0dem, inrast_t0dem,row);
	/* read every cell in the line buffers */
	for (col = 0; col < ncols; col++) {
            d_z0m = ((DCELL *) inrast_z0m)[col];
            d_t0dem = ((DCELL *) inrast_t0dem)[col];
	    if (Rast_is_d_null_value(&d_t0dem) || Rast_is_d_null_value(&d_z0m)) {
		/* do nothing */
		d_Roh[row][col] = -999.9;
		d_Rah[row][col] = -999.9;
	    }
	    else {
		d_u5 = (ustar / 0.41) * log(5 / d_z0m);
		d_rah1=(1/(d_u5*pow(0.41,2)))*log(5/d_z0m)*log(5/(d_z0m*0.1));
		d_roh1=((998-ea)/(d_t0dem*2.87))+(ea/(d_t0dem*4.61));
		if (d_roh1 > 5)  d_roh1 = 1.0;
		else d_roh1=((1000-4.65)/(d_t0dem*2.87))+(4.65/(d_t0dem*4.61));
		if (row == rowDry && col == colDry) {	/*collect dry pix info */
		    d_rah_dry = d_rah1;
		    d_roh_dry = d_roh1;
		    G_message("d_rah_dry=%f d_roh_dry=%f",d_rah_dry,d_roh_dry);
		}
		d_Roh[row][col] = d_roh1;
		d_Rah[row][col] = d_rah1;
	    }
	}
    }
    DCELL d_dT_dry;

    /*Calculate dT_dry */
    d_dT_dry = (h_dry * d_rah_dry) / (1004 * d_roh_dry);
    double a, b;

    /*Calculate coefficients for next dT equation */
    /*a = 1.0/ ((d_dT_dry-0.0) / (d_t0dem_dry-d_t0dem_wet)); */
    /*b = ( a * d_t0dem_wet ) * (-1.0); */
    double sumx = d_t0dem_wet + d_t0dem_dry;
    double sumy = d_dT_dry + 0.0;
    double sumx2 = pow(d_t0dem_wet, 2) + pow(d_t0dem_dry, 2);
    double sumxy = (d_t0dem_wet * 0.0) + (d_t0dem_dry * d_dT_dry);
    a = (sumxy - ((sumx * sumy) / 2.0)) / (sumx2 - (pow(sumx, 2) / 2.0));
    b = (sumy - (a * sumx)) / 2.0;
    G_message("d_dT_dry=%f", d_dT_dry);
    G_message("dT1=%f * t0dem + (%f)", a, b);
    DCELL d_h_dry;

    /* ITERATION 1 */
    for (row = 0; row < nrows; row++) {
	DCELL d_t0dem,d_z0m;
	DCELL d_h1,d_rah1,d_rah2,d_roh1;
	DCELL d_L,d_x,d_psih,d_psim;
	DCELL d_u5;
	G_percent(row, nrows, 2);
	/* read a line input maps into buffers */
	Rast_get_d_row(infd_z0m, inrast_z0m, row);
	Rast_get_d_row(infd_t0dem, inrast_t0dem,row);
	/* read every cell in the line buffers */
	for (col = 0; col < ncols; col++) {
            d_z0m = ((DCELL *) inrast_z0m)[col];
            d_t0dem = ((DCELL *) inrast_t0dem)[col];
	    d_rah1 = d_Rah[row][col];
	    d_roh1 = d_Roh[row][col];
	    if (Rast_is_d_null_value(&d_t0dem) || Rast_is_d_null_value(&d_z0m)) {
		/* do nothing */
	    }
	    else {
		if (d_rah1 < 1.0) 
		    d_h1 = 0.0;
		else 
		    d_h1 = (1004 * d_roh1) * (a * d_t0dem + b) / d_rah1;
		d_L =-1004*d_roh1*pow(ustar,3)*d_t0dem/(d_h1*9.81*0.41);
		d_x = pow((1-16*(5/d_L)),0.25);
		d_psim =2*log((1+d_x)/2)+log((1+pow(d_x,2))/2)-2*atan(d_x)+0.5*M_PI;
		d_psih =2*log((1+pow(d_x,2))/2);
		d_u5 =(ustar/0.41)*log(5/d_z0m);
		d_rah2 = (1/(d_u5*pow(0.41,2)))*log((5/d_z0m)-d_psim)
                        *log((5/(d_z0m*0.1))-d_psih);
		if (row == rowDry && col == colDry) {/*collect dry pix info */
		    d_rah_dry = d_rah2;
		    d_h_dry = d_h1;
		}
		d_Rah[row][col] = d_rah1;
	    }
	}
    }

    /*Calculate dT_dry */
    d_dT_dry = (d_h_dry * d_rah_dry) / (1004 * d_roh_dry);
    /*Calculate coefficients for next dT equation */
    /*      a = (d_dT_dry-0)/(d_t0dem_dry-d_t0dem_wet); */
    /*      b = (-1.0) * ( a * d_t0dem_wet ); */
    /*      G_message("d_dT_dry=%f",d_dT_dry); */
    /*      G_message("dT2=%f * t0dem + (%f)", a, b); */
    sumx = d_t0dem_wet + d_t0dem_dry;
    sumy = d_dT_dry + 0.0;
    sumx2 = pow(d_t0dem_wet, 2) + pow(d_t0dem_dry, 2);
    sumxy = (d_t0dem_wet * 0.0) + (d_t0dem_dry * d_dT_dry);
    a = (sumxy - ((sumx * sumy) / 2.0)) / (sumx2 - (pow(sumx, 2) / 2.0));
    b = (sumy - (a * sumx)) / 2.0;
    G_message("d_dT_dry=%f", d_dT_dry);
    G_message("dT1=%f * t0dem + (%f)", a, b);

    /* ITERATION 2 */
    /***************************************************/
    /***************************************************/
    for (row = 0; row < nrows; row++) {
	DCELL d_t0dem;
	DCELL d_z0m;
	DCELL d_rah2;
	DCELL d_rah3;
	DCELL d_roh1;
	DCELL d_h2;
	DCELL d_L;
	DCELL d_x;
	DCELL d_psih;
	DCELL d_psim;
	DCELL d_u5;
	G_percent(row, nrows, 2);
	/* read a line input maps into buffers */
	Rast_get_d_row(infd_z0m,inrast_z0m,row);
	Rast_get_d_row(infd_t0dem,inrast_t0dem,row);
	/* read every cell in the line buffers */
	for (col = 0; col < ncols; col++) {
            d_z0m = ((DCELL *) inrast_z0m)[col];
            d_t0dem = ((DCELL *) inrast_t0dem)[col];
	    d_rah2 = d_Rah[row][col];
	    d_roh1 = d_Roh[row][col];
	    if (Rast_is_d_null_value(&d_t0dem) || Rast_is_d_null_value(&d_z0m)) {
		/* do nothing */
	    }
	    else {
		if (d_rah2 < 1.0) {
		    d_h2 = 0.0;
		}
		else {
		    d_h2 =(1004*d_roh1)*(a*d_t0dem+b)/d_rah2;
		}
		d_L =-1004*d_roh1*pow(ustar,3)*d_t0dem/(d_h2*9.81*0.41);
		d_x = pow((1 - 16 * (5 / d_L)), 0.25);
		d_psim =2*log((1+d_x)/2)+log((1+pow(d_x,2))/2)-
		    2*atan(d_x)+0.5*M_PI;
		d_psih =2*log((1+pow(d_x,2))/2);
		d_u5 =(ustar/0.41)*log(5/d_z0m);
		d_rah3=(1/(d_u5*pow(0.41,2)))*log((5/d_z0m)-d_psim)*
                       log((5/(d_z0m*0.1))-d_psih);
		if (row == rowDry && col == colDry) {/*collect dry pix info */
		    d_rah_dry = d_rah2;
		    d_h_dry = d_h2;
		}
		d_Rah[row][col] = d_rah2;
	    }
	}
    }

    /*Calculate dT_dry */
    d_dT_dry = (d_h_dry * d_rah_dry) / (1004 * d_roh_dry);
    /*Calculate coefficients for next dT equation */
    /*      a = (d_dT_dry-0)/(d_t0dem_dry-d_t0dem_wet); */
    /*      b = (-1.0) * ( a * d_t0dem_wet ); */
    /*      G_message("d_dT_dry=%f",d_dT_dry); */
    /*      G_message("dT3=%f * t0dem + (%f)", a, b); */
    sumx = d_t0dem_wet + d_t0dem_dry;
    sumy = d_dT_dry + 0.0;
    sumx2 = pow(d_t0dem_wet, 2) + pow(d_t0dem_dry, 2);
    sumxy = (d_t0dem_wet * 0.0) + (d_t0dem_dry * d_dT_dry);
    a = (sumxy - ((sumx * sumy) / 2.0)) / (sumx2 - (pow(sumx, 2) / 2.0));
    b = (sumy - (a * sumx)) / 2.0;
    G_message("d_dT_dry=%f", d_dT_dry);
    G_message("dT1=%f * t0dem + (%f)", a, b);

    /* ITERATION 3 */
    /***************************************************/
    /***************************************************/

    for (row = 0; row < nrows; row++) {
	DCELL d_t0dem;
	DCELL d_z0m;
	DCELL d_rah3;
	DCELL d_roh1;
	DCELL d_h3;
	DCELL d_L;
	DCELL d_x;
	DCELL d_psih;
	DCELL d_psim;
	DCELL d;		/* Output pixel */
	G_percent(row, nrows, 2);
	/* read a line input maps into buffers */
	Rast_get_d_row(infd_z0m, inrast_z0m, row);
	Rast_get_d_row(infd_t0dem,inrast_t0dem,row);
	/* read every cell in the line buffers */
	for (col = 0; col < ncols; col++) {
            d_z0m = ((DCELL *) inrast_z0m)[col];
            d_t0dem = ((DCELL *) inrast_t0dem)[col];
	    d_rah3 = d_Rah[row][col];
	    d_roh1 = d_Roh[row][col];
	    if (Rast_is_d_null_value(&d_t0dem) || Rast_is_d_null_value(&d_z0m)) {
		Rast_set_d_null_value(&outrast[col], 1);
	    }
	    else {
		if (d_rah3 < 1.0) {
		    d_h3 = 0.0;
		}
		else {
		    d_h3 = (1004 * d_roh1) * (a * d_t0dem + b) / d_rah3;
		}
		if (d_h3 < 0 && d_h3 > -50) {
		    d_h3 = 0.0;
		}
		if (d_h3 < -50 || d_h3 > 1000) {
		    Rast_set_d_null_value(&outrast[col], 1);
		}
		outrast[col] = d_h3;
	    }
	}
	Rast_put_d_row(outfd, outrast);
    }


    G_free(inrast_z0m);
    Rast_close(infd_z0m);
    G_free(inrast_t0dem);
    Rast_close(infd_t0dem);

    G_free(outrast);
    Rast_close(outfd);

    /* add command line incantation to history file */
    Rast_short_history(h0, "raster", &history);
    Rast_command_history(&history);
    Rast_write_history(h0, &history);

    exit(EXIT_SUCCESS);
}
Ejemplo n.º 21
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);
}
Ejemplo n.º 22
0
int main(int argc, char *argv[])
{
    struct Cell_head cellhd;

    /* buffer for in out raster */
    DCELL *inrast_T, *inrast_RH, *inrast_u2;
    DCELL *inrast_Rn, *inrast_DEM, *inrast_hc, *outrast;
    char *EPo;

    int nrows, ncols;
    int row, col;
    int infd_T, infd_RH, infd_u2, infd_Rn, infd_DEM, infd_hc;
    int outfd;

    char *T, *RH, *u2, *Rn, *DEM, *hc;
    DCELL d_T, d_RH, d_u2, d_Rn, d_Z, d_hc;
    DCELL d_EPo;

    int d_night;

    struct History history;
    struct GModule *module;
    struct Option *input_DEM, *input_T, *input_RH;
    struct Option *input_u2, *input_Rn, *input_hc, *output;
    struct Flag *day, *zero;

    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("imagery"));
    G_add_keyword(_("evapotranspiration"));
    module->description =
	_("Computes potential evapotranspiration calculation with hourly Penman-Monteith.");

    /* Define different options */
    input_DEM = G_define_standard_option(G_OPT_R_ELEV);
    input_DEM->description = _("Name of input elevation raster map [m a.s.l.]");
    
    input_T = G_define_standard_option(G_OPT_R_INPUT);
    input_T->key = "temperature";
    input_T->description = _("Name of input temperature raster map [C]");

    input_RH = G_define_standard_option(G_OPT_R_INPUT);
    input_RH->key = "relativehumidity";
    input_RH->description = _("Name of input relative humidity raster map [%]");

    input_u2 = G_define_standard_option(G_OPT_R_INPUT);
    input_u2->key = "windspeed";
    input_u2->description = _("Name of input wind speed raster map [m/s]");

    input_Rn = G_define_standard_option(G_OPT_R_INPUT);
    input_Rn->key = "netradiation";
    input_Rn->description =
	_("Name of input net solar radiation raster map [MJ/m2/h]");

    input_hc = G_define_standard_option(G_OPT_R_INPUT);
    input_hc->key = "cropheight";
    input_hc->description = _("Name of input crop height raster map [m]");

    output = G_define_standard_option(G_OPT_R_OUTPUT);
	_("Name for output raster map [mm/h]");

    zero = G_define_flag();
    zero->key = 'z';
    zero->description = _("Set negative evapotranspiration to zero");

    day = G_define_flag();
    day->key = 'n';
    day->description = _("Use Night-time");

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

    /* get entered parameters */
    T = input_T->answer;
    RH = input_RH->answer;
    u2 = input_u2->answer;
    Rn = input_Rn->answer;
    EPo = output->answer;
    DEM = input_DEM->answer;
    hc = input_hc->answer;

    if (day->answer) {
	d_night = TRUE;
    }
    else {
	d_night = FALSE;
    }

    infd_T = Rast_open_old(T, "");
    infd_RH = Rast_open_old(RH, "");
    infd_u2 = Rast_open_old(u2, "");
    infd_Rn = Rast_open_old(Rn, "");
    infd_DEM = Rast_open_old(DEM, "");
    infd_hc = Rast_open_old(hc, "");

    Rast_get_cellhd(T, "", &cellhd);
    Rast_get_cellhd(RH, "", &cellhd);
    Rast_get_cellhd(u2, "", &cellhd);
    Rast_get_cellhd(Rn, "", &cellhd);
    Rast_get_cellhd(DEM, "", &cellhd);
    Rast_get_cellhd(hc, "", &cellhd);

    /* Allocate input buffer */
    inrast_T = Rast_allocate_d_buf();
    inrast_RH = Rast_allocate_d_buf();
    inrast_u2 = Rast_allocate_d_buf();
    inrast_Rn = Rast_allocate_d_buf();
    inrast_DEM = Rast_allocate_d_buf();
    inrast_hc = Rast_allocate_d_buf();

    /* Allocate output buffer */
    nrows = Rast_window_rows();
    ncols = Rast_window_cols();
    outrast = Rast_allocate_d_buf();

    outfd = Rast_open_new(EPo, DCELL_TYPE);

    for (row = 0; row < nrows; row++) {

	/* read a line input maps into buffers */
	Rast_get_d_row(infd_T, inrast_T, row);
	Rast_get_d_row(infd_RH, inrast_RH, row);
	Rast_get_d_row(infd_u2, inrast_u2, row);
	Rast_get_d_row(infd_Rn, inrast_Rn, row);
	Rast_get_d_row(infd_DEM, inrast_DEM, row);
	Rast_get_d_row(infd_hc, inrast_hc, row);

	/* read every cell in the line buffers */
	for (col = 0; col < ncols; col++) {
	    d_T = ((DCELL *) inrast_T)[col];
	    d_RH = ((DCELL *) inrast_RH)[col];
	    d_u2 = ((DCELL *) inrast_u2)[col];
	    d_Rn = ((DCELL *) inrast_Rn)[col];
	    d_Z = ((DCELL *) inrast_DEM)[col];
	    d_hc = ((DCELL *) inrast_hc)[col];

	    /* calculate evapotranspiration */
	    if (d_hc < 0) {
		/* calculate evaporation */
		d_EPo =
		    calc_openwaterETp(d_T, d_Z, d_u2, d_Rn, d_night, d_RH,
				      d_hc);
	    }
	    else {
		/* calculate evapotranspiration */
		d_EPo = calc_ETp(d_T, d_Z, d_u2, d_Rn, d_night, d_RH, d_hc);
	    }

	    if (zero->answer && d_EPo < 0)
		d_EPo = 0;

	    ((DCELL *) outrast)[col] = d_EPo;
	}
	Rast_put_d_row(outfd, outrast);
    }
    G_free(inrast_T);
    G_free(inrast_RH);
    G_free(inrast_u2);
    G_free(inrast_Rn);
    G_free(inrast_DEM);
    G_free(inrast_hc);
    G_free(outrast);
    Rast_close(infd_T);
    Rast_close(infd_RH);
    Rast_close(infd_u2);
    Rast_close(infd_Rn);
    Rast_close(infd_DEM);
    Rast_close(infd_hc);
    Rast_close(outfd);

    /* add command line incantation to history file */
    Rast_short_history(EPo, "raster", &history);
    Rast_command_history(&history);
    Rast_write_history(EPo, &history);

    exit(EXIT_SUCCESS);
}
Ejemplo n.º 23
0
int calculateD(int fd, struct area_entry *ad, double *result)
{
    DCELL *buf, *buf_sup, *buf_null;
    DCELL 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_d_buf();
    Rast_set_d_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_dcell_raster_row(fd, i + ad->y, ad);
	if (i > 0) {
	    buf_sup = RLI_get_dcell_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_d_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_d_null_value(&corrCell, 1);
	    }

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

	    if (!Rast_is_d_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_d_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.º 24
0
/*!
 *  \brief Extract a cell value from raster map (cubic interpolation).
 *
 *  Extract a cell value from raster map at given northing and easting
 *  with a sampled 3x3 window using a cubic interpolation.
 *
 *  \param fd file descriptor
 *  \param window region settings
 *  \param cats categories
 *  \param north northing position
 *  \param east easting position
 *  \param usedesc flag to scan category label
 *
 *  \return cell value at given position
 */
DCELL Rast_get_sample_cubic(int fd,
			    const struct Cell_head * window,
			    struct Categories * cats,
			    double north, double east, int usedesc)
{
    int i, j, row, col;
    double grid[4][4];
    DCELL *rows[4];
    double frow, fcol, trow, tcol;
    DCELL result;

    for (i = 0; i < 4; i++)
	rows[i] = Rast_allocate_d_buf();

    frow = Rast_northing_to_row(north, window);
    fcol = Rast_easting_to_col(east, window);

    /* convert northing and easting to row and col, resp */
    row = (int)floor(frow - 1.5);
    col = (int)floor(fcol - 1.5);

    trow = frow - row - 1.5;
    tcol = fcol - col - 1.5;

    if (row < 0 || row + 3 >= Rast_window_rows() ||
	col < 0 || col + 3 >= Rast_window_cols()) {
	Rast_set_d_null_value(&result, 1);
	goto done;
    }

    for (i = 0; i < 4; i++)
	Rast_get_d_row(fd, rows[i], row + i);

    for (i = 0; i < 4; i++)
	for (j = 0; j < 4; j++)
	    if (Rast_is_d_null_value(&rows[i][col + j])) {
		Rast_set_d_null_value(&result, 1);
		goto done;
	    }

    /*
     * now were ready to do cubic interpolation over
     * arow[col], arow[col+1], arow[col+2], arow[col+3],
     * brow[col], brow[col+1], brow[col+2], brow[col+3],
     * crow[col], crow[col+1], crow[col+2], crow[col+3],
     * drow[col], drow[col+1], drow[col+2], drow[col+3],
     */

    if (usedesc) {
	char *buf;

	for (i = 0; i < 4; i++) {
	    for (j = 0; j < 4; j++) {
		G_squeeze(buf =
			  Rast_get_c_cat((CELL *) & (rows[i][col + j]),
					 cats));
		grid[i][j] = scancatlabel(buf);
	    }
	}
    }
    else {
	for (i = 0; i < 4; i++)
	    for (j = 0; j < 4; j++)
		grid[i][j] = rows[i][col + j];
    }

    result = Rast_interp_bicubic(tcol, trow,
				 grid[0][0], grid[0][1], grid[0][2],
				 grid[0][3], grid[1][0], grid[1][1],
				 grid[1][2], grid[1][3], grid[2][0],
				 grid[2][1], grid[2][2], grid[2][3],
				 grid[3][0], grid[3][1], grid[3][2],
				 grid[3][3]);

  done:
    for (i = 0; i < 4; i++)
	G_free(rows[i]);

    return result;
}
Ejemplo n.º 25
0
/* ************************************************************************* */
void g3d_to_raster(void *map, RASTER3D_Region region, int *fd)
{
    DCELL d1 = 0;
    FCELL f1 = 0;
    int x, y, z;
    int rows, cols, depths, typeIntern, pos = 0;
    FCELL *fcell = NULL;
    DCELL *dcell = NULL;

    rows = region.rows;
    cols = region.cols;
    depths = region.depths;


    G_debug(2, "g3d_to_raster: Writing %i raster maps with %i rows %i cols.",
            depths, rows, cols);

    typeIntern = Rast3d_tile_type_map(map);

    if (typeIntern == FCELL_TYPE)
        fcell = Rast_allocate_f_buf();
    else if (typeIntern == DCELL_TYPE)
        dcell = Rast_allocate_d_buf();

    pos = 0;
    /*Every Rastermap */
    for (z = 0; z < depths; z++) { /*From the bottom to the top */
        G_debug(2, "Writing raster map %d of %d", z + 1, depths);
        for (y = 0; y < rows; y++) {
            G_percent(y, rows - 1, 10);

            for (x = 0; x < cols; x++) {
                if (typeIntern == FCELL_TYPE) {
                    Rast3d_get_value(map, x, y, z, &f1, typeIntern);
                    if (Rast3d_is_null_value_num(&f1, FCELL_TYPE))
                        Rast_set_null_value(&fcell[x], 1, FCELL_TYPE);
                    else
                        fcell[x] = f1;
                } else {
                    Rast3d_get_value(map, x, y, z, &d1, typeIntern);
                    if (Rast3d_is_null_value_num(&d1, DCELL_TYPE))
                        Rast_set_null_value(&dcell[x], 1, DCELL_TYPE);
                    else
                        dcell[x] = d1;
                }
            }
            if (typeIntern == FCELL_TYPE)
                Rast_put_f_row(fd[pos], fcell);

            if (typeIntern == DCELL_TYPE)
                Rast_put_d_row(fd[pos], dcell);
        }
        G_debug(2, "Finished writing map %d.", z + 1);
        pos++;
    }


    if (dcell)
        G_free(dcell);
    if (fcell)
        G_free(fcell);

}
Ejemplo n.º 26
0
Archivo: Gs3.c Proyecto: caomw/grass
/*!
   \brief Get categories/labels

   Formats label as in d.what.rast -> (catval) catlabel 

   \param filename raster map name
   \param drow
   \param dcol
   \param catstr category string

   \return 1 on success
   \return 0 on failure
 */
int Gs_get_cat_label(const char *filename, int drow, int dcol, char *catstr)
{
    struct Categories cats;
    const char *mapset;
    CELL *buf;
    DCELL *dbuf;
    RASTER_MAP_TYPE map_type;
    int fd = -1;

    if ((mapset = G_find_raster2(filename, "")) == NULL) {
	G_warning(_("Raster map <%s> not found"), filename);
	return 0;
    }

    if (-1 != Rast_read_cats(filename, mapset, &cats)) {
	fd = Rast_open_old(filename, mapset);
	map_type = Rast_get_map_type(fd);

	if (map_type == CELL_TYPE) {
	    buf = Rast_allocate_c_buf();

	    Rast_get_c_row(fd, buf, drow);
	    if (Rast_is_c_null_value(&buf[dcol])) {
		sprintf(catstr, "(NULL) %s",
			Rast_get_c_cat(&buf[dcol], &cats));
	    }
	    else {
		sprintf(catstr, "(%d) %s", buf[dcol],
			Rast_get_c_cat(&buf[dcol], &cats));
	    }

	    G_free(buf);
	}

	else {
	    /* fp map */
	    dbuf = Rast_allocate_d_buf();

	    Rast_get_d_row(fd, dbuf, drow);
	    if (Rast_is_d_null_value(&dbuf[dcol])) {
		sprintf(catstr, "(NULL) %s",
			Rast_get_d_cat(&dbuf[dcol], &cats));
	    }
	    else {
		sprintf(catstr, "(%g) %s", dbuf[dcol],
			Rast_get_d_cat(&dbuf[dcol], &cats));
	    }

	    G_free(dbuf);
	}
    }
    else {
	strcpy(catstr, "no category label");
	return 0;
    }

    /* TODO: may want to keep these around for multiple queries */
    Rast_free_cats(&cats);

    if (fd >= 0)
	Rast_close(fd);

    return (1);
}
Ejemplo n.º 27
0
int main(int argc, char *argv[])
{
    /* variables */
    DCELL *data_buf;
    CELL *clump_buf;
    CELL i, max;

    int row, col, rows, cols;
    int out_mode, use_MASK, *n, *e;
    long int *count;
    int fd_data, fd_clump;

    const char *datamap, *clumpmap, *centroidsmap;
    
    double avg, vol, total_vol, east, north, *sum;

    struct Cell_head window;

    struct Map_info *fd_centroids;
    struct line_pnts *Points;
    struct line_cats *Cats;
    struct field_info *Fi;

    char buf[DB_SQL_MAX];
    dbString sql;
    dbDriver *driver;

    struct GModule *module;
    struct {
        struct Option *input, *clump, *centroids, *output;
    } opt;
    struct {
        struct Flag *report;
    } flag;

    /* define parameters and flags */
    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("raster"));
    G_add_keyword(_("volume"));
    G_add_keyword(_("clumps"));
    module->label =
	_("Calculates the volume of data \"clumps\".");
    module->description = _("Optionally produces a GRASS vector points map "
                            "containing the calculated centroids of these clumps.");

    opt.input = G_define_standard_option(G_OPT_R_INPUT);
    opt.input->description =
	_("Name of input raster map representing data that will be summed within clumps");

    opt.clump = G_define_standard_option(G_OPT_R_INPUT);
    opt.clump->key = "clump";
    opt.clump->required = NO;
    opt.clump->label =
        _("Name of input clump raster map");
    opt.clump->description = _("Preferably the output of r.clump. "
                               "If no clump map is given than MASK is used.");

    opt.centroids = G_define_standard_option(G_OPT_V_OUTPUT);
    opt.centroids->key = "centroids";
    opt.centroids->required = NO;
    opt.centroids->description = _("Name for output vector points map to contain clump centroids");

    opt.output = G_define_standard_option(G_OPT_F_OUTPUT);
    opt.output->required = NO;
    opt.output->label =
	_("Name for output file to hold the report");
    opt.output->description =
	_("If no output file given report is printed to standard output");

    flag.report = G_define_flag();
    flag.report->key = 'f';
    flag.report->description = _("Generate unformatted report (items separated by colon)");

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

    /* get arguments */
    datamap = opt.input->answer;
    
    clumpmap = NULL;
    if (opt.clump->answer)
	clumpmap = opt.clump->answer;
    
    centroidsmap = NULL;
    fd_centroids = NULL;
    Points = NULL;
    Cats = NULL;
    driver = NULL;
    if (opt.centroids->answer) {
	centroidsmap = opt.centroids->answer;
        fd_centroids = G_malloc(sizeof(struct Map_info));
    }
    
    out_mode = (!flag.report->answer);

    /*
     * see if MASK or a separate "clumpmap" raster map is to be used
     * -- it must(!) be one of those two choices.
     */
    use_MASK = 0;
    if (!clumpmap) {
	clumpmap = "MASK";
	use_MASK = 1;
        if (!G_find_raster2(clumpmap, G_mapset()))
            G_fatal_error(_("No MASK found. If no clump map is given than the MASK is required. "
                            "You need to define a clump raster map or create a MASK by r.mask command."));
        G_important_message(_("No clump map given, using MASK"));
    }
    
    /* open input and clump raster maps */
    fd_data = Rast_open_old(datamap, "");
    fd_clump = Rast_open_old(clumpmap, use_MASK ? G_mapset() : "");
    
    /* initialize vector map (for centroids) if needed */
    if (centroidsmap) {
	if (Vect_open_new(fd_centroids, centroidsmap, WITHOUT_Z) < 0)
	    G_fatal_error(_("Unable to create vector map <%s>"), centroidsmap);
        
        Points = Vect_new_line_struct();
        Cats = Vect_new_cats_struct();
        
        /* initialize data structures */
        Vect_append_point(Points, 0., 0., 0.);
        Vect_cat_set(Cats, 1, 1);
    }
    
    /* initialize output file */
    if (opt.output->answer && strcmp(opt.output->answer, "-") != 0) {
	if (freopen(opt.output->answer, "w", stdout) == NULL) {
	    perror(opt.output->answer);
	    exit(EXIT_FAILURE);
	}
    }

    /* initialize data accumulation arrays */
    max = Rast_get_max_c_cat(clumpmap, use_MASK ? G_mapset() : "");

    sum = (double *)G_malloc((max + 1) * sizeof(double));
    count = (long int *)G_malloc((max + 1) * sizeof(long int));

    G_zero(sum, (max + 1) * sizeof(double));
    G_zero(count, (max + 1) * sizeof(long int));
    
    data_buf = Rast_allocate_d_buf();
    clump_buf = Rast_allocate_c_buf();
    
    /* get window size */
    G_get_window(&window);
    rows = window.rows;
    cols = window.cols;

    /* now get the data -- first pass */
    for (row = 0; row < rows; row++) {
	G_percent(row, rows, 2);
	Rast_get_d_row(fd_data, data_buf, row);
	Rast_get_c_row(fd_clump, clump_buf, row);
	for (col = 0; col < cols; col++) {
	    i = clump_buf[col];
	    if (i > max)
		G_fatal_error(_("Invalid category value %d (max=%d): row=%d col=%d"),
                              i, max, row, col);
	    if (i < 1) {
                G_debug(3, "row=%d col=%d: zero or negs ignored", row, col);
		continue;	/* ignore zeros and negs */
            }
	    if (Rast_is_d_null_value(&data_buf[col])) {
                G_debug(3, "row=%d col=%d: NULL ignored", row, col);
		continue;
            }
            
	    sum[i] += data_buf[col];
	    count[i]++;
	}
    }
    G_percent(1, 1, 1);
    
    /* free some buffer space */
    G_free(data_buf);
    G_free(clump_buf);

    /* data lists for centroids of clumps */
    e = (int *)G_malloc((max + 1) * sizeof(int));
    n = (int *)G_malloc((max + 1) * sizeof(int));

    i = centroids(fd_clump, e, n, 1, max);

    /* close raster maps */
    Rast_close(fd_data);
    Rast_close(fd_clump);
    
    /* got everything, now do output */
    if (centroidsmap) {
        G_message(_("Creating vector point map <%s>..."), centroidsmap);
        /* set comment */
	sprintf(buf, _("From '%s' on raster map <%s> using clumps from <%s>"),
                argv[0], datamap, clumpmap);
        Vect_set_comment(fd_centroids, buf);

        /* create attribute table */        
        Fi = Vect_default_field_info(fd_centroids, 1, NULL, GV_1TABLE);
        
        driver = db_start_driver_open_database(Fi->driver,
                                               Vect_subst_var(Fi->database, fd_centroids));
	if (driver == NULL) {
	    G_fatal_error(_("Unable to open database <%s> by driver <%s>"),
			  Vect_subst_var(Fi->database, fd_centroids), Fi->driver);
	}
        db_set_error_handler_driver(driver);
        
	db_begin_transaction(driver);
        
        db_init_string(&sql);
	sprintf(buf, "create table %s (cat integer, volume double precision, "
                "average double precision, sum double precision, count integer)",
                Fi->table);
	db_set_string(&sql, buf);
	Vect_map_add_dblink(fd_centroids, 1, NULL, Fi->table, GV_KEY_COLUMN, Fi->database,
			    Fi->driver);

	G_debug(3, "%s", db_get_string(&sql));
	if (db_execute_immediate(driver, &sql) != DB_OK) {
	    G_fatal_error(_("Unable to create table: %s"), db_get_string(&sql));
	}
    }

    /* print header */
    if (out_mode) {
	fprintf(stdout, _("\nVolume report on data from <%s> using clumps on <%s> raster map"),
                datamap, clumpmap);
        fprintf(stdout, "\n\n");
	fprintf(stdout,
		_("Category   Average   Data   # Cells        Centroid             Total\n"));
	fprintf(stdout,
		_("Number     in clump  Total  in clump   Easting     Northing     Volume"));
        fprintf(stdout, "\n%s\n", SEP);
    }
    total_vol = 0.0;

    /* print output, write centroids */
    for (i = 1; i <= max; i++) {
	if (count[i]) {
	    avg = sum[i] / (double)count[i];
	    vol = sum[i] * window.ew_res * window.ns_res;
	    total_vol += vol;
	    east = window.west + (e[i] + 0.5) * window.ew_res;
	    north = window.north - (n[i] + 0.5) * window.ns_res;
	    if (fd_centroids) { /* write centroids if requested */
                Points->x[0] = east;
                Points->y[0] = north;
                Cats->cat[0] = i;
                Vect_write_line(fd_centroids, GV_POINT, Points, Cats);
	
                sprintf(buf, "insert into %s values (%d, %f, %f, %f, %ld)",
                        Fi->table, i, vol, avg, sum[i], count[i]);
                db_set_string(&sql, buf);

                if (db_execute_immediate(driver, &sql) != DB_OK)
                    G_fatal_error(_("Cannot insert new row: %s"),
                                  db_get_string(&sql));
	    }
	    if (out_mode)
		fprintf(stdout,
			"%8d%10.2f%10.0f %7ld  %10.2f  %10.2f %16.2f\n", i,
			avg, sum[i], count[i], east, north, vol);
	    else
		fprintf(stdout, "%d:%.2f:%.0f:%ld:%.2f:%.2f:%.2f\n",
			i, avg, sum[i], count[i], east, north, vol);
	}
    }

    /* write centroid attributes and close the map*/
    if (fd_centroids) {
        db_commit_transaction(driver);
        Vect_close(fd_centroids);
    }
    
    /* print total value */
    if (total_vol > 0.0 && out_mode) {
        fprintf(stdout, "%s\n", SEP);
	fprintf(stdout, "%60s = %14.2f", _("Total Volume"), total_vol);
        fprintf(stdout, "\n");
    }

    exit(EXIT_SUCCESS);
} 
Ejemplo n.º 28
0
int extract_points(int z_flag)
{
    struct line_pnts *points = Vect_new_line_struct();
    CELL *cellbuf;
    FCELL *fcellbuf;
    DCELL *dcellbuf;
    int row, col;
    double x, y;
    int count;

    switch (data_type) {
    case CELL_TYPE:
	cellbuf = Rast_allocate_c_buf();
	break;
    case FCELL_TYPE:
	fcellbuf = Rast_allocate_f_buf();
	break;
    case DCELL_TYPE:
	dcellbuf = Rast_allocate_d_buf();
	break;
    }

    G_message(_("Extracting points..."));

    count = 1;
    for (row = 0; row < cell_head.rows; row++) {
	G_percent(row, n_rows, 2);

	y = Rast_row_to_northing((double)(row + .5), &cell_head);

	switch (data_type) {
	case CELL_TYPE:
	    Rast_get_c_row(input_fd, cellbuf, row);
	    break;
	case FCELL_TYPE:
	    Rast_get_f_row(input_fd, fcellbuf, row);
	    break;
	case DCELL_TYPE:
	    Rast_get_d_row(input_fd, dcellbuf, row);
	    break;
	}

	for (col = 0; col < cell_head.cols; col++) {
	    int cat, val;
	    double dval;

	    x = Rast_col_to_easting((double)(col + .5), &cell_head);

	    switch (data_type) {
	    case CELL_TYPE:
		if (Rast_is_c_null_value(cellbuf + col))
		    continue;
		val = cellbuf[col];
		dval = val;
		break;
	    case FCELL_TYPE:
		if (Rast_is_f_null_value(fcellbuf + col))
		    continue;
		dval = fcellbuf[col];
		break;
	    case DCELL_TYPE:
		if (Rast_is_d_null_value(dcellbuf + col))
		    continue;
		dval = dcellbuf[col];
		break;
	    }

	    /* value_flag is used only for CELL type */
	    cat = (value_flag) ? val : count;

	    Vect_reset_line(points);
	    Vect_reset_cats(Cats);
	    Vect_cat_set(Cats, 1, cat);

	    Vect_append_point(points, x, y, dval);
	    Vect_write_line(&Map, GV_POINT, points, Cats);

	    if ((driver != NULL) && !value_flag) {
		insert_value(cat, val, dval);
	    }

	    count++;
	}
    }

    G_percent(row, n_rows, 2);

    switch (data_type) {
    case CELL_TYPE:
	G_free(cellbuf);
	break;
    case FCELL_TYPE:
	G_free(fcellbuf);
	break;
    case DCELL_TYPE:
	G_free(dcellbuf);
	break;
    }
    
    Vect_destroy_line_struct(points);

    return (1);
}
Ejemplo n.º 29
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.º 30
0
/*!
 *  \brief Extract a cell value from raster map (bilinear interpolation).
 *
 *  Extract a cell value from raster map at given northing and easting
 *  with a sampled 3x3 window using a bilinear interpolation.
 *
 *  \param fd file descriptor
 *  \param window region settings
 *  \param cats categories
 *  \param north northing position
 *  \param east easting position
 *  \param usedesc flag to scan category label
 *
 *  \return cell value at given position
 */
DCELL Rast_get_sample_bilinear(int fd,
			       const struct Cell_head * window,
			       struct Categories * cats,
			       double north, double east, int usedesc)
{
    int row, col;
    double grid[2][2];
    DCELL *arow = Rast_allocate_d_buf();
    DCELL *brow = Rast_allocate_d_buf();
    double frow, fcol, trow, tcol;
    DCELL result;

    frow = Rast_northing_to_row(north, window);
    fcol = Rast_easting_to_col(east, window);

    /* convert northing and easting to row and col, resp */
    row = (int)floor(frow - 0.5);
    col = (int)floor(fcol - 0.5);

    trow = frow - row - 0.5;
    tcol = fcol - col - 0.5;

    if (row < 0 || row + 1 >= Rast_window_rows() ||
	col < 0 || col + 1 >= Rast_window_cols()) {
	Rast_set_d_null_value(&result, 1);
	goto done;
    }

    Rast_get_d_row(fd, arow, row);
    Rast_get_d_row(fd, brow, row + 1);

    if (Rast_is_d_null_value(&arow[col]) ||
	Rast_is_d_null_value(&arow[col + 1]) ||
	Rast_is_d_null_value(&brow[col]) ||
	Rast_is_d_null_value(&brow[col + 1])) {
	Rast_set_d_null_value(&result, 1);
	goto done;
    }

    /*-
     * now were ready to do bilinear interpolation over
     * arow[col], arow[col+1],
     * brow[col], brow[col+1]
     */

    if (usedesc) {
	char *buf;

	G_squeeze(buf = Rast_get_c_cat((int *)&(arow[col]), cats));
	grid[0][0] = scancatlabel(buf);
	G_squeeze(buf = Rast_get_c_cat((CELL *) & (arow[col + 1]), cats));
	grid[0][1] = scancatlabel(buf);
	G_squeeze(buf = Rast_get_c_cat((CELL *) & (brow[col]), cats));
	grid[1][0] = scancatlabel(buf);
	G_squeeze(buf = Rast_get_c_cat((CELL *) & (brow[col + 1]), cats));
	grid[1][1] = scancatlabel(buf);
    }
    else {
	grid[0][0] = arow[col];
	grid[0][1] = arow[col + 1];
	grid[1][0] = brow[col];
	grid[1][1] = brow[col + 1];
    }

    result = Rast_interp_bilinear(tcol, trow,
				  grid[0][0], grid[0][1], grid[1][0],
				  grid[1][1]);

  done:
    G_free(arow);
    G_free(brow);

    return result;
}