예제 #1
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;
}
예제 #2
0
void array2raster(const void* data, const char* name,
		const RASTER_MAP_TYPE type, const int maxr, const int maxc) {
	//ORG void* rast = G_allocate_raster_buf(type);
	void* rast = Rast_allocate_buf(type);
	
	int fd;
	//ORG if ((fd = G_open_raster_new(name, type)) < 0) {
	if ((fd = Rast_open_new(name, type)) < 0) {
		G_fatal_error("Unable to create raster map <%s>", name);
	}

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

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

	G_free(rast);
	//ORG G_close_cell(fd);
	Rast_close(fd);
	 
	return;
}
예제 #3
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;
}
예제 #4
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);
}
예제 #5
0
파일: main.c 프로젝트: GRASS-GIS/grass-ci
int main(int argc, char *argv[])
{
    int nrows, ncols;
    int row, col;
    char *viflag;		/*Switch for particular index */
    char *desc;
    struct GModule *module;
    struct {
        struct Option *viname, *red, *nir, *green, *blue, *chan5,
            *chan7, *sl_slope, *sl_int, *sl_red, *bits, *output;
    } opt;
    struct History history;	/*metadata */
    struct Colors colors;	/*Color rules */

    char *result;		/*output raster name */
    int infd_redchan, infd_nirchan, infd_greenchan;
    int infd_bluechan, infd_chan5chan, infd_chan7chan;
    int outfd;
    char *bluechan, *greenchan, *redchan, *nirchan, *chan5chan, *chan7chan;
    DCELL *inrast_redchan, *inrast_nirchan, *inrast_greenchan;
    DCELL *inrast_bluechan, *inrast_chan5chan, *inrast_chan7chan;
    DCELL *outrast;
    RASTER_MAP_TYPE data_type_redchan;
    RASTER_MAP_TYPE data_type_nirchan, data_type_greenchan;
    RASTER_MAP_TYPE data_type_bluechan;
    RASTER_MAP_TYPE data_type_chan5chan, data_type_chan7chan;
    DCELL msavip1, msavip2, msavip3, dnbits;
    CELL val1, val2;

    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("imagery"));
    G_add_keyword(_("vegetation index"));
    G_add_keyword(_("biophysical parameters"));
    module->label =
	_("Calculates different types of vegetation indices.");
    module->description = _("Uses red and nir bands mostly, "
			    "and some indices require additional bands.");

    /* Define the different options */
    opt.red = G_define_standard_option(G_OPT_R_INPUT);
    opt.red->key = "red";
    opt.red->label =
	_("Name of input red channel surface reflectance map");
    opt.red->description = _("Range: [0.0;1.0]");

    opt.output = G_define_standard_option(G_OPT_R_OUTPUT);

    opt.viname = G_define_option();
    opt.viname->key = "viname";
    opt.viname->type = TYPE_STRING;
    opt.viname->required = YES;
    opt.viname->description = _("Type of vegetation index");
    desc = NULL;
    G_asprintf(&desc,
	       "arvi;%s;dvi;%s;evi;%s;evi2;%s;gvi;%s;gari;%s;gemi;%s;ipvi;%s;msavi;%s;"
	       "msavi2;%s;ndvi;%s;pvi;%s;savi;%s;sr;%s;vari;%s;wdvi;%s",
	       _("Atmospherically Resistant Vegetation Index"),
	       _("Difference Vegetation Index"),
	       _("Enhanced Vegetation Index"),
	       _("Enhanced Vegetation Index 2"),
	       _("Green Vegetation Index"),
	       _("Green Atmospherically Resistant Vegetation Index"),
	       _("Global Environmental Monitoring Index"),
	       _("Infrared Percentage Vegetation Index"),
	       _("Modified Soil Adjusted Vegetation Index"),
	       _("second Modified Soil Adjusted Vegetation Index"),
	       _("Normalized Difference Vegetation Index"),
	       _("Perpendicular Vegetation Index"),
	       _("Soil Adjusted Vegetation Index"),
	       _("Simple Ratio"),
	       _("Visible Atmospherically Resistant Index"),
	       _("Weighted Difference Vegetation Index"));
    opt.viname->descriptions = desc;
    opt.viname->options = "arvi,dvi,evi,evi2,gvi,gari,gemi,ipvi,msavi,msavi2,ndvi,pvi,savi,sr,vari,wdvi";
    opt.viname->answer = "ndvi";
    opt.viname->key_desc = _("type");

    opt.nir = G_define_standard_option(G_OPT_R_INPUT);
    opt.nir->key = "nir";
    opt.nir->required = NO;
    opt.nir->label =
	_("Name of input nir channel surface reflectance map");
    opt.nir->description = _("Range: [0.0;1.0]");
    opt.nir->guisection = _("Optional inputs");

    opt.green = G_define_standard_option(G_OPT_R_INPUT);
    opt.green->key = "green";
    opt.green->required = NO;
    opt.green->label =
	_("Name of input green channel surface reflectance map");
    opt.green->description = _("Range: [0.0;1.0]");
    opt.green->guisection = _("Optional inputs");

    opt.blue = G_define_standard_option(G_OPT_R_INPUT);
    opt.blue->key = "blue";
    opt.blue->required = NO;
    opt.blue->label =
	_("Name of input blue channel surface reflectance map");
    opt.blue->description = _("Range: [0.0;1.0]");
    opt.blue->guisection = _("Optional inputs");

    opt.chan5 = G_define_standard_option(G_OPT_R_INPUT);
    opt.chan5->key = "band5";
    opt.chan5->required = NO;
    opt.chan5->label =
	_("Name of input 5th channel surface reflectance map");
    opt.chan5->description = _("Range: [0.0;1.0]");
    opt.chan5->guisection = _("Optional inputs");

    opt.chan7 = G_define_standard_option(G_OPT_R_INPUT);
    opt.chan7->key = "band7";
    opt.chan7->required = NO;
    opt.chan7->label =
	_("Name of input 7th channel surface reflectance map");
    opt.chan7->description = _("Range: [0.0;1.0]");
    opt.chan7->guisection = _("Optional inputs");

    opt.sl_slope = G_define_option();
    opt.sl_slope->key = "soil_line_slope";
    opt.sl_slope->type = TYPE_DOUBLE;
    opt.sl_slope->required = NO;
    opt.sl_slope->description = _("Value of the slope of the soil line (MSAVI only)");
    opt.sl_slope->guisection = _("MSAVI settings");

    opt.sl_int = G_define_option();
    opt.sl_int->key = "soil_line_intercept";
    opt.sl_int->type = TYPE_DOUBLE;
    opt.sl_int->required = NO;
    opt.sl_int->description = _("Value of the intercept of the soil line (MSAVI only)");
    opt.sl_int->guisection = _("MSAVI settings");

    opt.sl_red = G_define_option();
    opt.sl_red->key = "soil_noise_reduction";
    opt.sl_red->type = TYPE_DOUBLE;
    opt.sl_red->required = NO;
    opt.sl_red->description = _("Value of the factor of reduction of soil noise (MSAVI only)");
    opt.sl_red->guisection = _("MSAVI settings");

    opt.bits = G_define_option();
    opt.bits->key = "storage_bit";
    opt.bits->type = TYPE_INTEGER;
    opt.bits->required = NO;
    opt.bits->label = _("Maximum bits for digital numbers");
    opt.bits->description = _("If data is in Digital Numbers (i.e. integer type), give the max bits (i.e. 8 for Landsat -> [0-255])");
    opt.bits->options = "7,8,10,16";
    opt.bits->answer = "8";

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

    viflag = opt.viname->answer;
    redchan = opt.red->answer;
    nirchan = opt.nir->answer;
    greenchan = opt.green->answer;
    bluechan = opt.blue->answer;
    chan5chan = opt.chan5->answer;
    chan7chan = opt.chan7->answer;
    if(opt.sl_slope->answer)
        msavip1 = atof(opt.sl_slope->answer);
    if(opt.sl_int->answer)
        msavip2 = atof(opt.sl_int->answer);
    if(opt.sl_red->answer)
        msavip3 = atof(opt.sl_red->answer);
    if(opt.bits->answer)
        dnbits = atof(opt.bits->answer);
    result = opt.output->answer;
    G_verbose_message(_("Calculating %s..."), viflag);

    if (!strcasecmp(viflag, "sr") && (!(opt.red->answer) || !(opt.nir->answer)) )
	G_fatal_error(_("sr index requires red and nir maps"));

    if (!strcasecmp(viflag, "ndvi") && (!(opt.red->answer) || !(opt.nir->answer)) )
	G_fatal_error(_("ndvi index requires red and nir maps"));

    if (!strcasecmp(viflag, "ipvi") && (!(opt.red->answer) || !(opt.nir->answer)) )
	G_fatal_error(_("ipvi index requires red and nir maps"));

    if (!strcasecmp(viflag, "dvi") && (!(opt.red->answer) || !(opt.nir->answer)) )
	G_fatal_error(_("dvi index requires red and nir maps"));

    if (!strcasecmp(viflag, "pvi") && (!(opt.red->answer) || !(opt.nir->answer)) )
	G_fatal_error(_("pvi index requires red and nir maps"));

    if (!strcasecmp(viflag, "wdvi") && (!(opt.red->answer) || !(opt.nir->answer)) )
	G_fatal_error(_("wdvi index requires red and nir maps"));

    if (!strcasecmp(viflag, "savi") && (!(opt.red->answer) || !(opt.nir->answer)) )
	G_fatal_error(_("savi index requires red and nir maps"));

    if (!strcasecmp(viflag, "msavi") && (!(opt.red->answer) || !(opt.nir->answer) || 
                                          !(opt.sl_slope->answer) || !(opt.sl_int->answer) || 
                                          !(opt.sl_red->answer)) )
	G_fatal_error(_("msavi index requires red and nir maps, and 3 parameters related to soil line"));

    if (!strcasecmp(viflag, "msavi2") && (!(opt.red->answer) || !(opt.nir->answer)) )
	G_fatal_error(_("msavi2 index requires red and nir maps"));

    if (!strcasecmp(viflag, "gemi") && (!(opt.red->answer) || !(opt.nir->answer)) )
	G_fatal_error(_("gemi index requires red and nir maps"));

    if (!strcasecmp(viflag, "arvi") && (!(opt.red->answer) || !(opt.nir->answer)
                || !(opt.blue->answer)) )
	G_fatal_error(_("arvi index requires blue, red and nir maps"));

    if (!strcasecmp(viflag, "evi") && (!(opt.red->answer) || !(opt.nir->answer)
                || !(opt.blue->answer)) )
	G_fatal_error(_("evi index requires blue, red and nir maps"));

	if (!strcasecmp(viflag, "evi2") && (!(opt.red->answer) || !(opt.nir->answer) ) )
	G_fatal_error(_("evi2 index requires red and nir maps"));
	
    if (!strcasecmp(viflag, "vari") && (!(opt.red->answer) || !(opt.green->answer)
                || !(opt.blue->answer)) )
	G_fatal_error(_("vari index requires blue, green and red maps"));

    if (!strcasecmp(viflag, "gari") && (!(opt.red->answer) || !(opt.nir->answer)
                || !(opt.green->answer) || !(opt.blue->answer)) )
	G_fatal_error(_("gari index requires blue, green, red and nir maps"));

    if (!strcasecmp(viflag, "gvi") && (!(opt.red->answer) || !(opt.nir->answer)
                || !(opt.green->answer) || !(opt.blue->answer)
                || !(opt.chan5->answer) || !(opt.chan7->answer)) )
	G_fatal_error(_("gvi index requires blue, green, red, nir, chan5 and chan7 maps"));

    infd_redchan = Rast_open_old(redchan, "");
    data_type_redchan = Rast_map_type(redchan, "");
    inrast_redchan = Rast_allocate_buf(data_type_redchan);

    if (nirchan) {
        infd_nirchan = Rast_open_old(nirchan, "");
        data_type_nirchan = Rast_map_type(nirchan, "");
        inrast_nirchan = Rast_allocate_buf(data_type_nirchan);
    }

    if (greenchan) {
        infd_greenchan = Rast_open_old(greenchan, "");
        data_type_greenchan = Rast_map_type(greenchan, "");
        inrast_greenchan = Rast_allocate_buf(data_type_greenchan);
    }

    if (bluechan) {
        infd_bluechan = Rast_open_old(bluechan, "");
        data_type_bluechan = Rast_map_type(bluechan, "");
        inrast_bluechan = Rast_allocate_buf(data_type_bluechan);
    }

    if (chan5chan) {
        infd_chan5chan = Rast_open_old(chan5chan, "");
        data_type_chan5chan = Rast_map_type(chan5chan, "");
        inrast_chan5chan = Rast_allocate_buf(data_type_chan5chan);
    }

    if (chan7chan) {
        infd_chan7chan = Rast_open_old(chan7chan, "");
        data_type_chan7chan = Rast_map_type(chan7chan, "");
        inrast_chan7chan = Rast_allocate_buf(data_type_chan7chan);
    }

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

    /* Create New raster files */
    outfd = Rast_open_new(result, DCELL_TYPE);
    outrast = Rast_allocate_d_buf();

    /* Process pixels */
    for (row = 0; row < nrows; row++)
    {
	DCELL d_bluechan;
	DCELL d_greenchan;
	DCELL d_redchan;
	DCELL d_nirchan;
	DCELL d_chan5chan;
	DCELL d_chan7chan;

	G_percent(row, nrows, 2);

	/* read input maps */
	Rast_get_row(infd_redchan,inrast_redchan,row,data_type_redchan);
	if (nirchan) {
	    Rast_get_row(infd_nirchan,inrast_nirchan,row,data_type_nirchan);
	}
	if (bluechan) {
	    Rast_get_row(infd_bluechan,inrast_bluechan,row,data_type_bluechan);
	}
	if (greenchan) {
	    Rast_get_row(infd_greenchan,inrast_greenchan,row,data_type_greenchan);
	}
	if (chan5chan) {
	    Rast_get_row(infd_chan5chan,inrast_chan5chan,row,data_type_chan5chan);
	}
	if (chan7chan) {
	    Rast_get_row(infd_chan7chan,inrast_chan7chan,row,data_type_chan7chan);
	}
	/* process the data */
	for (col = 0; col < ncols; col++)
	{
	    switch(data_type_redchan){
		    case CELL_TYPE:
			d_redchan   = (double) ((CELL *) inrast_redchan)[col];
			if(opt.bits->answer)
				d_redchan *= 1.0/(pow(2,dnbits)-1);	
			break;
		    case FCELL_TYPE:
			d_redchan   = (double) ((FCELL *) inrast_redchan)[col];
			break;
		    case DCELL_TYPE:
			d_redchan   = ((DCELL *) inrast_redchan)[col];
			break;
	    }
	    if (nirchan) {
		switch(data_type_nirchan){
		    case CELL_TYPE:
			d_nirchan   = (double) ((CELL *) inrast_nirchan)[col];
			if(opt.bits->answer)
				d_nirchan *= 1.0/(pow(2,dnbits)-1);	
			break;
		    case FCELL_TYPE:
			d_nirchan   = (double) ((FCELL *) inrast_nirchan)[col];
			break;
		    case DCELL_TYPE:
			d_nirchan   = ((DCELL *) inrast_nirchan)[col];
			break;
		}
	    }
	    if (greenchan) {
		switch(data_type_greenchan){
		    case CELL_TYPE:
			d_greenchan   = (double) ((CELL *) inrast_greenchan)[col];
			if(opt.bits->answer)
				d_greenchan *= 1.0/(pow(2,dnbits)-1);	
			break;
		    case FCELL_TYPE:
			d_greenchan   = (double) ((FCELL *) inrast_greenchan)[col];
			break;
		    case DCELL_TYPE:
			d_greenchan   = ((DCELL *) inrast_greenchan)[col];
			break;
		}
	    }
	    if (bluechan) {
		switch(data_type_bluechan){
		    case CELL_TYPE:
			d_bluechan   = (double) ((CELL *) inrast_bluechan)[col];
			if(opt.bits->answer)
				d_bluechan *= 1.0/(pow(2,dnbits)-1);	
			break;
		    case FCELL_TYPE:
			d_bluechan   = (double) ((FCELL *) inrast_bluechan)[col];
			break;
		    case DCELL_TYPE:
			d_bluechan   = ((DCELL *) inrast_bluechan)[col];
			break;
		}
	    }
	    if (chan5chan) {
		switch(data_type_chan5chan){
		    case CELL_TYPE:
			d_chan5chan   = (double) ((CELL *) inrast_chan5chan)[col];
			if(opt.bits->answer)
				d_chan5chan *= 1.0/(pow(2,dnbits)-1);	
			break;
		    case FCELL_TYPE:
			d_chan5chan   = (double) ((FCELL *) inrast_chan5chan)[col];
			break;
		    case DCELL_TYPE:
			d_chan5chan   = ((DCELL *) inrast_chan5chan)[col];
			break;
		}
	    }
	    if (chan7chan) {
		switch(data_type_chan7chan){
		    case CELL_TYPE:
			d_chan7chan   = (double) ((CELL *) inrast_chan7chan)[col];
			if(opt.bits->answer)
				d_chan7chan *= 1.0/(pow(2,dnbits)-1);	
			break;
		    case FCELL_TYPE:
			d_chan7chan   = (double) ((FCELL *) inrast_chan7chan)[col];
			break;
		    case DCELL_TYPE:
			d_chan7chan   = ((DCELL *) inrast_chan7chan)[col];
			break;
		}
	    }

	    if (Rast_is_d_null_value(&d_redchan) ||
		((nirchan) && Rast_is_d_null_value(&d_nirchan)) ||
		((greenchan) && Rast_is_d_null_value(&d_greenchan)) ||
		((bluechan) && Rast_is_d_null_value(&d_bluechan)) ||
		((chan5chan) && Rast_is_d_null_value(&d_chan5chan)) ||
		((chan7chan) && Rast_is_d_null_value(&d_chan7chan))) {
		Rast_set_d_null_value(&outrast[col], 1);
	    }
	    else {
		/* calculate simple_ratio        */
		if (!strcasecmp(viflag, "sr"))
		    outrast[col] = s_r(d_redchan, d_nirchan);

		/* calculate ndvi                    */
		if (!strcasecmp(viflag, "ndvi")) {
		    if (d_redchan + d_nirchan < 0.001)
			Rast_set_d_null_value(&outrast[col], 1);
		    else
			outrast[col] = nd_vi(d_redchan, d_nirchan);
		}

		if (!strcasecmp(viflag, "ipvi"))
		    outrast[col] = ip_vi(d_redchan, d_nirchan);

		if (!strcasecmp(viflag, "dvi"))
		    outrast[col] = d_vi(d_redchan, d_nirchan);

		if (!strcasecmp(viflag, "evi"))
		    outrast[col] = e_vi(d_bluechan, d_redchan, d_nirchan);

		if (!strcasecmp(viflag, "evi2"))
		    outrast[col] = e_vi2(d_redchan, d_nirchan);

		if (!strcasecmp(viflag, "pvi"))
		    outrast[col] = p_vi(d_redchan, d_nirchan);

		if (!strcasecmp(viflag, "wdvi"))
		    outrast[col] = wd_vi(d_redchan, d_nirchan);

		if (!strcasecmp(viflag, "savi"))
		    outrast[col] = sa_vi(d_redchan, d_nirchan);

		if (!strcasecmp(viflag, "msavi"))
		    outrast[col] = msa_vi(d_redchan, d_nirchan, msavip1, msavip2, msavip3);

		if (!strcasecmp(viflag, "msavi2"))
		    outrast[col] = msa_vi2(d_redchan, d_nirchan);

		if (!strcasecmp(viflag, "gemi"))
		    outrast[col] = ge_mi(d_redchan, d_nirchan);

		if (!strcasecmp(viflag, "arvi"))
		    outrast[col] = ar_vi(d_redchan, d_nirchan, d_bluechan);

		if (!strcasecmp(viflag, "gvi"))
		    outrast[col] = g_vi(d_bluechan, d_greenchan, d_redchan, d_nirchan, d_chan5chan, d_chan7chan);

		if (!strcasecmp(viflag, "gari"))
		    outrast[col] = ga_ri(d_redchan, d_nirchan, d_bluechan, d_greenchan);

		if (!strcasecmp(viflag, "vari"))
		    outrast[col] = va_ri(d_redchan, d_greenchan, d_bluechan);
	    }
	}
	Rast_put_d_row(outfd, outrast);
    }
    G_percent(1, 1, 1);
      
    G_free(inrast_redchan);
    Rast_close(infd_redchan);
    if (nirchan) {
    	G_free(inrast_nirchan);
    	Rast_close(infd_nirchan);
    }
    if (greenchan) {
	G_free(inrast_greenchan);
	Rast_close(infd_greenchan);
    }
    if (bluechan) {
	G_free(inrast_bluechan);
	Rast_close(infd_bluechan);
    }
    if (chan5chan) {
	G_free(inrast_chan5chan);
	Rast_close(infd_chan5chan);
    }
    if (chan7chan) {
	G_free(inrast_chan7chan);
	Rast_close(infd_chan7chan);
    }

    G_free(outrast);
    Rast_close(outfd);

    if (!strcasecmp(viflag, "ndvi")) {
 	/* apply predefined NDVI color table */
	const char *style = "ndvi";
	if (G_find_color_rule("ndvi")) {
	   Rast_make_fp_colors(&colors, style, -1.0, 1.0);
	} else
	   G_fatal_error(_("Unknown color request '%s'"), style);
    } else {
	/* Color from -1.0 to +1.0 in grey */
	Rast_init_colors(&colors);
	val1 = -1;
	val2 = 1;
	Rast_add_c_color_rule(&val1, 0, 0, 0, &val2, 255, 255, 255, &colors);
    }
    Rast_write_colors(result, G_mapset(), &colors);

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

    exit(EXIT_SUCCESS);
}
예제 #6
0
파일: main.c 프로젝트: rashadkm/grass_cmake
int main(int argc, char *argv[])
{
    struct GModule *module;
    int infile;
    const char *mapset;
    size_t cell_size;
    int ytile, xtile, y, overlap;
    int *outfiles;
    void *inbuf;

    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("raster"));
    G_add_keyword(_("tiling"));
    module->description =
	_("Splits a raster map into tiles.");

    parm.rastin = G_define_standard_option(G_OPT_R_INPUT);

    parm.rastout = G_define_option();
    parm.rastout->key = "output";
    parm.rastout->type = TYPE_STRING;
    parm.rastout->required = YES;
    parm.rastout->multiple = NO;
    parm.rastout->description = _("Output base name");

    parm.width = G_define_option();
    parm.width->key = "width";
    parm.width->type = TYPE_INTEGER;
    parm.width->required = YES;
    parm.width->multiple = NO;
    parm.width->description = _("Width of tiles (columns)");

    parm.height = G_define_option();
    parm.height->key = "height";
    parm.height->type = TYPE_INTEGER;
    parm.height->required = YES;
    parm.height->multiple = NO;
    parm.height->description = _("Height of tiles (rows)");

    parm.overlap = G_define_option();
    parm.overlap->key = "overlap";
    parm.overlap->type = TYPE_INTEGER;
    parm.overlap->required = NO;
    parm.overlap->multiple = NO;
    parm.overlap->description = _("Overlap of tiles");

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

    G_get_set_window(&src_w);
    overlap = parm.overlap->answer ? atoi(parm.overlap->answer) : 0;

    mapset = G_find_raster2(parm.rastin->answer, "");
    if (mapset == NULL)
        G_fatal_error(_("Raster map <%s> not found"), parm.rastin->answer);

    /* set window to old map */
    Rast_get_cellhd(parm.rastin->answer, "", &src_w);
    dst_w = src_w;
    dst_w.cols = atoi(parm.width->answer);
    dst_w.rows = atoi(parm.height->answer);
    G_adjust_Cell_head(&dst_w, 1, 1);

    xtiles = (src_w.cols + dst_w.cols - 1) / dst_w.cols;
    ytiles = (src_w.rows + dst_w.rows - 1) / dst_w.rows;

    G_debug(1, "X: %d * %d, Y: %d * %d",
	    xtiles, dst_w.cols, ytiles, dst_w.rows);

    src_w.cols = xtiles * dst_w.cols + 2 * overlap;
    src_w.rows = ytiles * dst_w.rows + 2 * overlap;
    src_w.west = src_w.west - overlap * src_w.ew_res;
    src_w.east = src_w.west + (src_w.cols + 2 * overlap) * src_w.ew_res;
    src_w.north = src_w.north + overlap * src_w.ns_res;
    src_w.south = src_w.north - (src_w.rows + 2 * overlap) * src_w.ns_res;

    Rast_set_input_window(&src_w);

    /* set the output region */
    ovl_w = dst_w;
    ovl_w.cols = ovl_w.cols + 2 * overlap;
    ovl_w.rows = ovl_w.rows + 2 * overlap;

    G_adjust_Cell_head(&ovl_w, 1, 1);
    Rast_set_output_window(&ovl_w);

    infile = Rast_open_old(parm.rastin->answer, "");
    map_type = Rast_get_map_type(infile);
    cell_size = Rast_cell_size(map_type);

    inbuf = Rast_allocate_input_buf(map_type);

    outfiles = G_malloc(xtiles * sizeof(int));

    G_debug(1, "X: %d * %d, Y: %d * %d",
	    xtiles, dst_w.cols, ytiles, dst_w.rows);

    G_message(_("Generating %d x %d = %d tiles..."), xtiles, ytiles, xtiles * ytiles);
    for (ytile = 0; ytile < ytiles; ytile++) {
	G_debug(1, "reading y tile: %d", ytile);
	G_percent(ytile, ytiles, 2);
	for (xtile = 0; xtile < xtiles; xtile++) {
	    char name[GNAME_MAX];
	    sprintf(name, "%s-%03d-%03d", parm.rastout->answer, ytile, xtile);
	    outfiles[xtile] = Rast_open_new(name, map_type);
	}
	
	for (y = 0; y < ovl_w.rows; y++) {
	    int row = ytile * dst_w.rows + y;
	    G_debug(1, "reading row: %d", row);
	    Rast_get_row(infile, inbuf, row, map_type);
	    
	    for (xtile = 0; xtile < xtiles; xtile++) {
		int cells = xtile * dst_w.cols;
		void *ptr = G_incr_void_ptr(inbuf, cells * cell_size);
		Rast_put_row(outfiles[xtile], ptr, map_type);
	    }
	}

	for (xtile = 0; xtile < xtiles; xtile++) {
	    Rast_close(outfiles[xtile]);
	    write_support_files(xtile, ytile, overlap);
	}
    }

    Rast_close(infile);

    return EXIT_SUCCESS;
}
예제 #7
0
int main(int argc, char *argv[])
{
    struct GModule *module;
    struct Option *rastin, *rastout, *method;
    struct History history;
    char title[64];
    char buf_nsres[100], buf_ewres[100];
    struct Colors colors;
    int infile, outfile;
    DCELL *outbuf;
    int row, col;
    struct Cell_head dst_w, src_w;

    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("raster"));
    G_add_keyword(_("resample"));
    module->description =
	_("Resamples raster map layers to a finer grid using interpolation.");

    rastin = G_define_standard_option(G_OPT_R_INPUT);
    rastout = G_define_standard_option(G_OPT_R_OUTPUT);

    method = G_define_option();
    method->key = "method";
    method->type = TYPE_STRING;
    method->required = NO;
    method->description = _("Interpolation method");
    method->options = "nearest,bilinear,bicubic,lanczos";
    method->answer = "bilinear";

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

    if (G_strcasecmp(method->answer, "nearest") == 0)
	neighbors = 1;
    else if (G_strcasecmp(method->answer, "bilinear") == 0)
	neighbors = 2;
    else if (G_strcasecmp(method->answer, "bicubic") == 0)
	neighbors = 4;
    else if (G_strcasecmp(method->answer, "lanczos") == 0)
	neighbors = 5;
    else
	G_fatal_error(_("Invalid method: %s"), method->answer);

    G_get_set_window(&dst_w);

    /* set window to old map */
    Rast_get_cellhd(rastin->answer, "", &src_w);

    /* enlarge source window */
    {
	double north = Rast_row_to_northing(0.5, &dst_w);
	double south = Rast_row_to_northing(dst_w.rows - 0.5, &dst_w);
	int r0 = (int)floor(Rast_northing_to_row(north, &src_w) - 0.5) - 2;
	int r1 = (int)floor(Rast_northing_to_row(south, &src_w) - 0.5) + 3;
	double west = Rast_col_to_easting(0.5, &dst_w);
	double east = Rast_col_to_easting(dst_w.cols - 0.5, &dst_w);
	int c0 = (int)floor(Rast_easting_to_col(west, &src_w) - 0.5) - 2;
	int c1 = (int)floor(Rast_easting_to_col(east, &src_w) - 0.5) + 3;

	src_w.south -= src_w.ns_res * (r1 - src_w.rows);
	src_w.north += src_w.ns_res * (-r0);
	src_w.west -= src_w.ew_res * (-c0);
	src_w.east += src_w.ew_res * (c1 - src_w.cols);
	src_w.rows = r1 - r0;
	src_w.cols = c1 - c0;
    }

    Rast_set_input_window(&src_w);

    /* allocate buffers for input rows */
    for (row = 0; row < neighbors; row++)
	bufs[row] = Rast_allocate_d_input_buf();

    cur_row = -100;

    /* open old map */
    infile = Rast_open_old(rastin->answer, "");

    /* reset window to current region */
    Rast_set_output_window(&dst_w);

    outbuf = Rast_allocate_d_output_buf();

    /* open new map */
    outfile = Rast_open_new(rastout->answer, DCELL_TYPE);

    switch (neighbors) {
    case 1:			/* nearest */
	for (row = 0; row < dst_w.rows; row++) {
	    double north = Rast_row_to_northing(row + 0.5, &dst_w);
	    double maprow_f = Rast_northing_to_row(north, &src_w) - 0.5;
	    int maprow0 = (int)floor(maprow_f + 0.5);

	    G_percent(row, dst_w.rows, 2);

	    read_rows(infile, maprow0);

	    for (col = 0; col < dst_w.cols; col++) {
		double east = Rast_col_to_easting(col + 0.5, &dst_w);
		double mapcol_f = Rast_easting_to_col(east, &src_w) - 0.5;
		int mapcol0 = (int)floor(mapcol_f + 0.5);

		double c = bufs[0][mapcol0];

		if (Rast_is_d_null_value(&c)) {
		    Rast_set_d_null_value(&outbuf[col], 1);
		}
		else {
		    outbuf[col] = c;
		}
	    }

	    Rast_put_d_row(outfile, outbuf);
	}
	break;

    case 2:			/* bilinear */
	for (row = 0; row < dst_w.rows; row++) {
	    double north = Rast_row_to_northing(row + 0.5, &dst_w);
	    double maprow_f = Rast_northing_to_row(north, &src_w) - 0.5;
	    int maprow0 = (int)floor(maprow_f);
	    double v = maprow_f - maprow0;

	    G_percent(row, dst_w.rows, 2);

	    read_rows(infile, maprow0);

	    for (col = 0; col < dst_w.cols; col++) {
		double east = Rast_col_to_easting(col + 0.5, &dst_w);
		double mapcol_f = Rast_easting_to_col(east, &src_w) - 0.5;
		int mapcol0 = (int)floor(mapcol_f);
		int mapcol1 = mapcol0 + 1;
		double u = mapcol_f - mapcol0;

		double c00 = bufs[0][mapcol0];
		double c01 = bufs[0][mapcol1];
		double c10 = bufs[1][mapcol0];
		double c11 = bufs[1][mapcol1];

		if (Rast_is_d_null_value(&c00) ||
		    Rast_is_d_null_value(&c01) ||
		    Rast_is_d_null_value(&c10) || Rast_is_d_null_value(&c11)) {
		    Rast_set_d_null_value(&outbuf[col], 1);
		}
		else {
		    outbuf[col] = Rast_interp_bilinear(u, v, c00, c01, c10, c11);
		}
	    }

	    Rast_put_d_row(outfile, outbuf);
	}
	break;

    case 4:			/* bicubic */
	for (row = 0; row < dst_w.rows; row++) {
	    double north = Rast_row_to_northing(row + 0.5, &dst_w);
	    double maprow_f = Rast_northing_to_row(north, &src_w) - 0.5;
	    int maprow1 = (int)floor(maprow_f);
	    int maprow0 = maprow1 - 1;
	    double v = maprow_f - maprow1;

	    G_percent(row, dst_w.rows, 2);

	    read_rows(infile, maprow0);

	    for (col = 0; col < dst_w.cols; col++) {
		double east = Rast_col_to_easting(col + 0.5, &dst_w);
		double mapcol_f = Rast_easting_to_col(east, &src_w) - 0.5;
		int mapcol1 = (int)floor(mapcol_f);
		int mapcol0 = mapcol1 - 1;
		int mapcol2 = mapcol1 + 1;
		int mapcol3 = mapcol1 + 2;
		double u = mapcol_f - mapcol1;

		double c00 = bufs[0][mapcol0];
		double c01 = bufs[0][mapcol1];
		double c02 = bufs[0][mapcol2];
		double c03 = bufs[0][mapcol3];

		double c10 = bufs[1][mapcol0];
		double c11 = bufs[1][mapcol1];
		double c12 = bufs[1][mapcol2];
		double c13 = bufs[1][mapcol3];

		double c20 = bufs[2][mapcol0];
		double c21 = bufs[2][mapcol1];
		double c22 = bufs[2][mapcol2];
		double c23 = bufs[2][mapcol3];

		double c30 = bufs[3][mapcol0];
		double c31 = bufs[3][mapcol1];
		double c32 = bufs[3][mapcol2];
		double c33 = bufs[3][mapcol3];

		if (Rast_is_d_null_value(&c00) ||
		    Rast_is_d_null_value(&c01) ||
		    Rast_is_d_null_value(&c02) ||
		    Rast_is_d_null_value(&c03) ||
		    Rast_is_d_null_value(&c10) ||
		    Rast_is_d_null_value(&c11) ||
		    Rast_is_d_null_value(&c12) ||
		    Rast_is_d_null_value(&c13) ||
		    Rast_is_d_null_value(&c20) ||
		    Rast_is_d_null_value(&c21) ||
		    Rast_is_d_null_value(&c22) ||
		    Rast_is_d_null_value(&c23) ||
		    Rast_is_d_null_value(&c30) ||
		    Rast_is_d_null_value(&c31) ||
		    Rast_is_d_null_value(&c32) || Rast_is_d_null_value(&c33)) {
		    Rast_set_d_null_value(&outbuf[col], 1);
		}
		else {
		    outbuf[col] = Rast_interp_bicubic(u, v,
						   c00, c01, c02, c03,
						   c10, c11, c12, c13,
						   c20, c21, c22, c23,
						   c30, c31, c32, c33);
		}
	    }

	    Rast_put_d_row(outfile, outbuf);
	}
	break;

    case 5:			/* lanczos */
	for (row = 0; row < dst_w.rows; row++) {
	    double north = Rast_row_to_northing(row + 0.5, &dst_w);
	    double maprow_f = Rast_northing_to_row(north, &src_w) - 0.5;
	    int maprow1 = (int)floor(maprow_f + 0.5);
	    int maprow0 = maprow1 - 2;
	    double v = maprow_f - maprow1;

	    G_percent(row, dst_w.rows, 2);

	    read_rows(infile, maprow0);

	    for (col = 0; col < dst_w.cols; col++) {
		double east = Rast_col_to_easting(col + 0.5, &dst_w);
		double mapcol_f = Rast_easting_to_col(east, &src_w) - 0.5;
		int mapcol2 = (int)floor(mapcol_f + 0.5);
		int mapcol0 = mapcol2 - 2;
		int mapcol4 = mapcol2 + 2;
		double u = mapcol_f - mapcol2;
		double c[25];
		int ci = 0, i, j, do_lanczos = 1;

		for (i = 0; i < 5; i++) {
		    for (j = mapcol0; j <= mapcol4; j++) {
			c[ci] = bufs[i][j];
			if (Rast_is_d_null_value(&(c[ci]))) {
			    Rast_set_d_null_value(&outbuf[col], 1);
			    do_lanczos = 0;
			    break;
			}
			ci++;
		    }
		    if (!do_lanczos)
			break;
		}

		if (do_lanczos) {
		    outbuf[col] = Rast_interp_lanczos(u, v, c);
		}
	    }

	    Rast_put_d_row(outfile, outbuf);
	}
	break;
    }

    G_percent(dst_w.rows, dst_w.rows, 2);

    Rast_close(infile);
    Rast_close(outfile);


    /* record map metadata/history info */
    sprintf(title, "Resample by %s interpolation", method->answer);
    Rast_put_cell_title(rastout->answer, title);

    Rast_short_history(rastout->answer, "raster", &history);
    Rast_set_history(&history, HIST_DATSRC_1, rastin->answer);
    G_format_resolution(src_w.ns_res, buf_nsres, src_w.proj);
    G_format_resolution(src_w.ew_res, buf_ewres, src_w.proj);
    Rast_format_history(&history, HIST_DATSRC_2,
			"Source map NS res: %s   EW res: %s",
			buf_nsres, buf_ewres);
    Rast_command_history(&history);
    Rast_write_history(rastout->answer, &history);

    /* copy color table from source map */
    if (Rast_read_colors(rastin->answer, "", &colors) < 0)
	G_fatal_error(_("Unable to read color table for %s"), rastin->answer);
    Rast_mark_colors_as_fp(&colors);
    Rast_write_colors(rastout->answer, G_mapset(), &colors);

    return (EXIT_SUCCESS);
}
예제 #8
0
int rectify(char *name, char *mapset, struct cache *ebuffer,
            double aver_z, char *result, char *interp_method)
{
    struct Cell_head cellhd;
    int ncols, nrows;
    int row, col;
    double row_idx, col_idx;
    int infd, outfd;
    RASTER_MAP_TYPE map_type;
    int cell_size;
    void *trast, *tptr;
    double n1, e1, z1;
    double nx, ex, nx1, ex1, zx1;
    struct cache *ibuffer;

    select_current_env();
    Rast_get_cellhd(name, mapset, &cellhd);

    /* open the file to be rectified
     * set window to cellhd first to be able to read file exactly
     */
    Rast_set_input_window(&cellhd);
    infd = Rast_open_old(name, mapset);
    map_type = Rast_get_map_type(infd);
    cell_size = Rast_cell_size(map_type);

    ibuffer = readcell(infd, seg_mb_img, 0);

    Rast_close(infd);		/* (pmx) 17 april 2000 */

    G_message(_("Rectify <%s@%s> (location <%s>)"),
	      name, mapset, G_location());
    select_target_env();
    G_set_window(&target_window);
    G_message(_("into  <%s@%s> (location <%s>) ..."),
	      result, G_mapset(), G_location());

    nrows = target_window.rows;
    ncols = target_window.cols;

    if (strcmp(interp_method, "nearest") != 0) {
	map_type = DCELL_TYPE;
	cell_size = Rast_cell_size(map_type);
    }

    /* open the result file into target window
     * this open must be first since we change the window later
     * raster maps open for writing are not affected by window changes
     * but those open for reading are
     */

    outfd = Rast_open_new(result, map_type);
    trast = Rast_allocate_output_buf(map_type);

    for (row = 0; row < nrows; row++) {
	n1 = target_window.north - (row + 0.5) * target_window.ns_res;

	G_percent(row, nrows, 2);

	Rast_set_null_value(trast, ncols, map_type);
	tptr = trast;
	for (col = 0; col < ncols; col++) {
	    DCELL *zp = CPTR(ebuffer, row, col);

	    e1 = target_window.west + (col + 0.5) * target_window.ew_res;
	    
	    /* if target cell has no elevation, set to aver_z */
	    if (Rast_is_d_null_value(zp)) {
		G_warning(_("No elevation available at row = %d, col = %d"), row, col);
		z1 = aver_z;
	    }
	    else
		z1 = *zp;

	    /* target coordinates e1, n1 to photo coordinates ex1, nx1 */
	    I_ortho_ref(e1, n1, z1, &ex1, &nx1, &zx1, &group.camera_ref,
			group.XC, group.YC, group.ZC, group.M);

	    G_debug(5, "\t\tAfter ortho ref (photo cords): ex = %f \t nx =  %f",
		    ex1, nx1);

	    /* photo coordinates ex1, nx1 to image coordinates ex, nx */
	    I_georef(ex1, nx1, &ex, &nx, group.E21, group.N21, 1);

	    G_debug(5, "\t\tAfter geo ref: ex = %f \t nx =  %f", ex, nx);

	    /* convert to row/column indices of source raster */
	    row_idx = (cellhd.north - nx) / cellhd.ns_res;
	    col_idx = (ex - cellhd.west) / cellhd.ew_res;

	    /* resample data point */
	    interpolate(ibuffer, tptr, map_type, &row_idx, &col_idx, &cellhd);

	    tptr = G_incr_void_ptr(tptr, cell_size);
	}
	Rast_put_row(outfd, trast, map_type);
    }
    G_percent(1, 1, 1);

    Rast_close(outfd);		/* (pmx) 17 april 2000 */
    G_free(trast);

    close(ibuffer->fd);
    release_cache(ibuffer);

    Rast_get_cellhd(result, G_mapset(), &cellhd);

    if (cellhd.proj == 0) {	/* x,y imagery */
	cellhd.proj = target_window.proj;
	cellhd.zone = target_window.zone;
    }

    if (target_window.proj != cellhd.proj) {
	cellhd.proj = target_window.proj;
	G_warning(_("Raster map <%s@%s>: projection don't match current settings"),
		  name, mapset);
    }

    if (target_window.zone != cellhd.zone) {
	cellhd.zone = target_window.zone;
	G_warning(_("Raster map <%s@%s>: zone don't match current settings"),
		  name, mapset);
    }

    select_current_env();

    return 1;
}
예제 #9
0
파일: main.c 프로젝트: rashadkm/grass_cmake
/* ************************************************************************* */
int open_output_map(const char *name, int res_type)
{
    return Rast_open_new(name, res_type);
}
예제 #10
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);
}
예제 #11
0
int main(int argc, char *argv[])
{
    struct GModule *module;
    struct
    {
	struct Option *rastin, *rastout, *method, *quantile;
    } parm;
    struct
    {
	struct Flag *nulls, *weight;
    } flag;
    struct History history;
    char title[64];
    char buf_nsres[100], buf_ewres[100];
    struct Colors colors;
    int row;

    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("raster"));
    G_add_keyword(_("resample"));
    module->description =
	_("Resamples raster map layers to a coarser grid using aggregation.");

    parm.rastin = G_define_standard_option(G_OPT_R_INPUT);

    parm.rastout = 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->description = _("Aggregation method");
    parm.method->options = build_method_list();
    parm.method->answer = "average";

    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.nulls = G_define_flag();
    flag.nulls->key = 'n';
    flag.nulls->description = _("Propagate NULLs");

    flag.weight = G_define_flag();
    flag.weight->key = 'w';
    flag.weight->description = _("Weight according to area (slower)");

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

    nulls = flag.nulls->answer;

    method = find_method(parm.method->answer);
    if (method < 0)
	G_fatal_error(_("Unknown method <%s>"), parm.method->answer);

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

    G_get_set_window(&dst_w);

    /* set window to old map */
    Rast_get_cellhd(parm.rastin->answer, "", &src_w);

    /* enlarge source window */
    {
	int r0 = (int)floor(Rast_northing_to_row(dst_w.north, &src_w));
	int r1 = (int)ceil(Rast_northing_to_row(dst_w.south, &src_w));
	int c0 = (int)floor(Rast_easting_to_col(dst_w.west, &src_w));
	int c1 = (int)ceil(Rast_easting_to_col(dst_w.east, &src_w));

	src_w.south -= src_w.ns_res * (r1 - src_w.rows);
	src_w.north += src_w.ns_res * (-r0);
	src_w.west -= src_w.ew_res * (-c0);
	src_w.east += src_w.ew_res * (c1 - src_w.cols);
	src_w.rows = r1 - r0;
	src_w.cols = c1 - c0;
    }

    Rast_set_input_window(&src_w);
    Rast_set_output_window(&dst_w);

    row_scale = 2 + ceil(dst_w.ns_res / src_w.ns_res);
    col_scale = 2 + ceil(dst_w.ew_res / src_w.ew_res);

    /* allocate buffers for input rows */
    bufs = G_malloc(row_scale * sizeof(DCELL *));
    for (row = 0; row < row_scale; row++)
	bufs[row] = Rast_allocate_d_input_buf();

    /* open old map */
    infile = Rast_open_old(parm.rastin->answer, "");

    /* allocate output buffer */
    outbuf = Rast_allocate_d_output_buf();

    /* open new map */
    outfile = Rast_open_new(parm.rastout->answer, DCELL_TYPE);

    if (flag.weight->answer && menu[method].method_w)
	resamp_weighted();
    else
	resamp_unweighted();

    G_percent(dst_w.rows, dst_w.rows, 2);

    Rast_close(infile);
    Rast_close(outfile);

    /* record map metadata/history info */
    sprintf(title, "Aggregate resample by %s", parm.method->answer);
    Rast_put_cell_title(parm.rastout->answer, title);

    Rast_short_history(parm.rastout->answer, "raster", &history);
    Rast_set_history(&history, HIST_DATSRC_1, parm.rastin->answer);
    G_format_resolution(src_w.ns_res, buf_nsres, src_w.proj);
    G_format_resolution(src_w.ew_res, buf_ewres, src_w.proj);
    Rast_format_history(&history, HIST_DATSRC_2,
			"Source map NS res: %s   EW res: %s",
			buf_nsres, buf_ewres);
    Rast_command_history(&history);
    Rast_write_history(parm.rastout->answer, &history);

    /* copy color table from source map */
    if (strcmp(parm.method->answer, "sum") != 0) {
	if (Rast_read_colors(parm.rastin->answer, "", &colors) < 0)
	    G_fatal_error(_("Unable to read color table for %s"),
			  parm.rastin->answer);
	Rast_mark_colors_as_fp(&colors);
	Rast_write_colors(parm.rastout->answer, G_mapset(), &colors);
    }

    return (EXIT_SUCCESS);
}
예제 #12
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);
}
예제 #13
0
파일: main.c 프로젝트: GRASS-GIS/grass-ci
int main(int argc, char *argv[])
{
    int out_fd, base_raster;
    char *infile, *outmap;
    int percent;
    double zrange_min, zrange_max, d_tmp;
    double irange_min, irange_max;
    unsigned long estimated_lines;

    RASTER_MAP_TYPE rtype, base_raster_data_type;
    struct History history;
    char title[64];
    SEGMENT base_segment;
    struct PointBinning point_binning;
    void *base_array;
    void *raster_row;
    struct Cell_head region;
    struct Cell_head input_region;
    int rows, last_rows, row0, cols;		/* scan box size */
    int row;		/* counters */

    int pass, npasses;
    unsigned long line, line_total;
    unsigned int counter;
    unsigned long n_invalid;
    char buff[BUFFSIZE];
    double x, y, z;
    double intensity;
    int arr_row, arr_col;
    unsigned long count, count_total;
    int point_class;

    double zscale = 1.0;
    double iscale = 1.0;
    double res = 0.0;

    struct BinIndex bin_index_nodes;
    bin_index_nodes.num_nodes = 0;
    bin_index_nodes.max_nodes = 0;
    bin_index_nodes.nodes = 0;

    struct GModule *module;
    struct Option *input_opt, *output_opt, *percent_opt, *type_opt, *filter_opt, *class_opt;
    struct Option *method_opt, *base_raster_opt;
    struct Option *zrange_opt, *zscale_opt;
    struct Option *irange_opt, *iscale_opt;
    struct Option *trim_opt, *pth_opt, *res_opt;
    struct Option *file_list_opt;
    struct Flag *print_flag, *scan_flag, *shell_style, *over_flag, *extents_flag;
    struct Flag *intens_flag, *intens_import_flag;
    struct Flag *set_region_flag;
    struct Flag *base_rast_res_flag;
    struct Flag *only_valid_flag;

    /* LAS */
    LASReaderH LAS_reader;
    LASHeaderH LAS_header;
    LASSRSH LAS_srs;
    LASPointH LAS_point;
    int return_filter;

    const char *projstr;
    struct Cell_head cellhd, loc_wind;

    unsigned int n_filtered;

    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("raster"));
    G_add_keyword(_("import"));
    G_add_keyword(_("LIDAR"));
    G_add_keyword(_("statistics"));
    G_add_keyword(_("conversion"));
    G_add_keyword(_("aggregation"));
    G_add_keyword(_("binning"));
    module->description =
	_("Creates a raster map from LAS LiDAR points using univariate statistics.");

    input_opt = G_define_standard_option(G_OPT_F_BIN_INPUT);
    input_opt->required = NO;
    input_opt->label = _("LAS input file");
    input_opt->description = _("LiDAR input files in LAS format (*.las or *.laz)");
    input_opt->guisection = _("Input");

    output_opt = G_define_standard_option(G_OPT_R_OUTPUT);
    output_opt->required = NO;
    output_opt->guisection = _("Output");

    file_list_opt = G_define_standard_option(G_OPT_F_INPUT);
    file_list_opt->key = "file";
    file_list_opt->label = _("File containing names of LAS input files");
    file_list_opt->description = _("LiDAR input files in LAS format (*.las or *.laz)");
    file_list_opt->required = NO;
    file_list_opt->guisection = _("Input");

    method_opt = G_define_option();
    method_opt->key = "method";
    method_opt->type = TYPE_STRING;
    method_opt->required = NO;
    method_opt->description = _("Statistic to use for raster values");
    method_opt->options =
	"n,min,max,range,sum,mean,stddev,variance,coeff_var,median,percentile,skewness,trimmean";
    method_opt->answer = "mean";
    method_opt->guisection = _("Statistic");
    G_asprintf((char **)&(method_opt->descriptions),
               "n;%s;"
               "min;%s;"
               "max;%s;"
               "range;%s;"
               "sum;%s;"
               "mean;%s;"
               "stddev;%s;"
               "variance;%s;"
               "coeff_var;%s;"
               "median;%s;"
               "percentile;%s;"
               "skewness;%s;"
               "trimmean;%s",
               _("Number of points in cell"),
               _("Minimum value of point values in cell"),
               _("Maximum value of point values in cell"),
               _("Range of point values in cell"),
               _("Sum of point values in cell"),
               _("Mean (average) value of point values in cell"),
               _("Standard deviation of point values in cell"),
               _("Variance of point values in cell"),
               _("Coefficient of variance of point values in cell"),
               _("Median value of point values in cell"),
               _("pth (nth) percentile of point values in cell"),
               _("Skewness of point values in cell"),
               _("Trimmed mean of point values in cell"));

    type_opt = G_define_standard_option(G_OPT_R_TYPE);
    type_opt->required = NO;
    type_opt->answer = "FCELL";

    base_raster_opt = G_define_standard_option(G_OPT_R_INPUT);
    base_raster_opt->key = "base_raster";
    base_raster_opt->required = NO;
    base_raster_opt->label =
        _("Subtract raster values from the Z coordinates");
    base_raster_opt->description =
        _("The scale for Z is applied beforehand, the range filter for"
          " Z afterwards");
    base_raster_opt->guisection = _("Transform");

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

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

    irange_opt = G_define_option();
    irange_opt->key = "intensity_range";
    irange_opt->type = TYPE_DOUBLE;
    irange_opt->required = NO;
    irange_opt->key_desc = "min,max";
    irange_opt->description = _("Filter range for intensity values (min,max)");
    irange_opt->guisection = _("Selection");

    iscale_opt = G_define_option();
    iscale_opt->key = "intensity_scale";
    iscale_opt->type = TYPE_DOUBLE;
    iscale_opt->required = NO;
    iscale_opt->answer = "1.0";
    iscale_opt->description = _("Scale to apply to intensity values");
    iscale_opt->guisection = _("Transform");

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

    /* I would prefer to call the following "percentile", but that has too
     * much namespace overlap with the "percent" option above */
    pth_opt = G_define_option();
    pth_opt->key = "pth";
    pth_opt->type = TYPE_INTEGER;
    pth_opt->required = NO;
    pth_opt->options = "1-100";
    pth_opt->description = _("pth percentile of the values");
    pth_opt->guisection = _("Statistic");

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

    res_opt = G_define_option();
    res_opt->key = "resolution";
    res_opt->type = TYPE_DOUBLE;
    res_opt->required = NO;
    res_opt->description =
	_("Output raster resolution");
    res_opt->guisection = _("Output");

    filter_opt = G_define_option();
    filter_opt->key = "return_filter";
    filter_opt->type = TYPE_STRING;
    filter_opt->required = NO;
    filter_opt->label = _("Only import points of selected return type");
    filter_opt->description = _("If not specified, all points are imported");
    filter_opt->options = "first,last,mid";
    filter_opt->guisection = _("Selection");

    class_opt = G_define_option();
    class_opt->key = "class_filter";
    class_opt->type = TYPE_INTEGER;
    class_opt->multiple = YES;
    class_opt->required = NO;
    class_opt->label = _("Only import points of selected class(es)");
    class_opt->description = _("Input is comma separated integers. "
                               "If not specified, all points are imported.");
    class_opt->guisection = _("Selection");

    print_flag = G_define_flag();
    print_flag->key = 'p';
    print_flag->description =
	_("Print LAS file info and exit");

    extents_flag = G_define_flag();
    extents_flag->key = 'e';
    extents_flag->label =
        _("Use the extent of the input for the raster extent");
    extents_flag->description =
        _("Set internally computational region extents based on the"
          " point cloud");
    extents_flag->guisection = _("Output");

    set_region_flag = G_define_flag();
    set_region_flag->key = 'n';
    set_region_flag->label =
        _("Set computation region to match the new raster map");
    set_region_flag->description =
        _("Set computation region to match the 2D extent and resolution"
          " of the newly created new raster map");
    set_region_flag->guisection = _("Output");

    over_flag = G_define_flag();
    over_flag->key = 'o';
    over_flag->label =
	_("Override projection check (use current location's projection)");
    over_flag->description =
	_("Assume that the dataset has same projection as the current location");

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

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

    intens_flag = G_define_flag();
    intens_flag->key = 'i';
    intens_flag->label =
        _("Use intensity values rather than Z values");
    intens_flag->description =
        _("Uses intensity values everywhere as if they would be Z"
          " coordinates");

    intens_import_flag = G_define_flag();
    intens_import_flag->key = 'j';
    intens_import_flag->description =
        _("Use Z values for filtering, but intensity values for statistics");

    base_rast_res_flag = G_define_flag();
    base_rast_res_flag->key = 'd';
    base_rast_res_flag->label =
        _("Use base raster resolution instead of computational region");
    base_rast_res_flag->description =
        _("For getting values from base raster, use its actual"
          " resolution instead of computational region resolution");

    only_valid_flag = G_define_flag();
    only_valid_flag->key = 'v';
    only_valid_flag->label = _("Use only valid points");
    only_valid_flag->description =
        _("Points invalid according to APSRS LAS specification will be"
          " filtered out");
    only_valid_flag->guisection = _("Selection");

    G_option_required(input_opt, file_list_opt, NULL);
    G_option_exclusive(input_opt, file_list_opt, NULL);
    G_option_required(output_opt, print_flag, scan_flag, shell_style, NULL);
    G_option_exclusive(intens_flag, intens_import_flag, NULL);
    G_option_requires(base_rast_res_flag, base_raster_opt, NULL);

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

    int only_valid = FALSE;
    n_invalid = 0;
    if (only_valid_flag->answer)
        only_valid = TRUE;

    /* we could use rules but this gives more info and allows continuing */
    if (set_region_flag->answer && !(extents_flag->answer || res_opt->answer)) {
        G_warning(_("Flag %c makes sense only with %s option or -%c flag"),
                  set_region_flag->key, res_opt->key, extents_flag->key);
        /* avoid the call later on */
        set_region_flag->answer = '\0';
    }

    struct StringList infiles;

    if (file_list_opt->answer) {
        if (access(file_list_opt->answer, F_OK) != 0)
            G_fatal_error(_("File <%s> does not exist"), file_list_opt->answer);
        string_list_from_file(&infiles, file_list_opt->answer);
    }
    else {
        string_list_from_one_item(&infiles, input_opt->answer);
    }

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

    if (shell_style->answer && !scan_flag->answer) {
	scan_flag->answer = 1; /* pointer not int, so set = shell_style->answer ? */
    }

    /* check zrange and extent relation */
    if (scan_flag->answer || extents_flag->answer) {
        if (zrange_opt->answer)
            G_warning(_("zrange will not be taken into account during scan"));
    }

    Rast_get_window(&region);
    /* G_get_window seems to be unreliable if the location has been changed */
    G_get_set_window(&loc_wind);        /* TODO: v.in.lidar uses G_get_default_window() */

    estimated_lines = 0;
    int i;
    for (i = 0; i < infiles.num_items; i++) {
        infile = infiles.items[i];
        /* don't if file not found */
        if (access(infile, F_OK) != 0)
            G_fatal_error(_("Input file <%s> does not exist"), infile);
        /* Open LAS file*/
        LAS_reader = LASReader_Create(infile);
        if (LAS_reader == NULL)
            G_fatal_error(_("Unable to open file <%s> as a LiDAR point cloud"),
                          infile);
        LAS_header = LASReader_GetHeader(LAS_reader);
        if  (LAS_header == NULL) {
            G_fatal_error(_("Unable to read LAS header of <%s>"), infile);
        }

        LAS_srs = LASHeader_GetSRS(LAS_header);

        /* print info or check projection if we are actually importing */
        if (print_flag->answer) {
            /* print filename when there is more than one file */
            if (infiles.num_items > 1)
                fprintf(stdout, "File: %s\n", infile);
            /* Print LAS header */
            print_lasinfo(LAS_header, LAS_srs);
        }
        else {
            /* report that we are checking more files */
            if (i == 1)
                G_message(_("First file's projection checked,"
                            " checking projection of the other files..."));
            /* Fetch input map projection in GRASS form. */
            projstr = LASSRS_GetWKT_CompoundOK(LAS_srs);
            /* we are printing the non-warning messages only for first file */
            projection_check_wkt(cellhd, loc_wind, projstr, over_flag->answer,
                                 shell_style->answer || i);
            /* if there is a problem in some other file, first OK message
             * is printed but than a warning, this is not ideal but hopefully
             * not so confusing when importing multiple files */
        }
        if (scan_flag->answer || extents_flag->answer) {
            /* we assign to the first one (i==0) but update for the rest */
            scan_bounds(LAS_reader, shell_style->answer, extents_flag->answer, i,
                        zscale, &region);
        }
        /* number of estimated point across all files */
        /* TODO: this should be ull which won't work with percent report */
        estimated_lines += LASHeader_GetPointRecordsCount(LAS_header);
        /* We are closing all again and we will be opening them later,
         * so we don't have to worry about limit for open files. */
        LASSRS_Destroy(LAS_srs);
        LASHeader_Destroy(LAS_header);
        LASReader_Destroy(LAS_reader);
    }
    /* if we are not importing, end */
    if (print_flag->answer || scan_flag->answer)
        exit(EXIT_SUCCESS);

    return_filter = LAS_ALL;
    if (filter_opt->answer) {
	if (strcmp(filter_opt->answer, "first") == 0)
	    return_filter = LAS_FIRST;
	else if (strcmp(filter_opt->answer, "last") == 0)
	    return_filter = LAS_LAST;
	else if (strcmp(filter_opt->answer, "mid") == 0)
	    return_filter = LAS_MID;
	else
	    G_fatal_error(_("Unknown filter option <%s>"), filter_opt->answer);
    }
    struct ReturnFilter return_filter_struct;
    return_filter_struct.filter = return_filter;
    struct ClassFilter class_filter;
    class_filter_create_from_strings(&class_filter, class_opt->answers);

    percent = atoi(percent_opt->answer);
    /* TODO: we already used zscale */
    /* TODO: we don't report intensity range */
    if (zscale_opt->answer)
        zscale = atof(zscale_opt->answer);
    if (iscale_opt->answer)
        iscale = atof(iscale_opt->answer);

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

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

	if (zrange_min > zrange_max) {
	    d_tmp = zrange_max;
	    zrange_max = zrange_min;
	    zrange_min = d_tmp;
	}
    }
    /* parse irange */
    if (irange_opt->answer != NULL) {
        if (irange_opt->answers[0] == NULL)
            G_fatal_error(_("Invalid %s"), irange_opt->key);

        sscanf(irange_opt->answers[0], "%lf", &irange_min);
        sscanf(irange_opt->answers[1], "%lf", &irange_max);

        if (irange_min > irange_max) {
            d_tmp = irange_max;
            irange_max = irange_min;
            irange_min = d_tmp;
        }
    }

    point_binning_set(&point_binning, method_opt->answer, pth_opt->answer,
                      trim_opt->answer, FALSE);

    base_array = NULL;

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

    if (point_binning.method == METHOD_N)
	rtype = CELL_TYPE;

    if (res_opt->answer) {
	/* align to resolution */
	res = atof(res_opt->answer);

	if (!G_scan_resolution(res_opt->answer, &res, region.proj))
	    G_fatal_error(_("Invalid input <%s=%s>"), res_opt->key, res_opt->answer);

	if (res <= 0)
	    G_fatal_error(_("Option '%s' must be > 0.0"), res_opt->key);
	
	region.ns_res = region.ew_res = res;

	region.north = ceil(region.north / res) * res;
	region.south = floor(region.south / res) * res;
	region.east = ceil(region.east / res) * res;
	region.west = floor(region.west / res) * res;

	G_adjust_Cell_head(&region, 0, 0);
    }
    else if (extents_flag->answer) {
	/* align to current region */
	Rast_align_window(&region, &loc_wind);
    }
    Rast_set_output_window(&region);

    rows = last_rows = region.rows;
    npasses = 1;
    if (percent < 100) {
	rows = (int)(region.rows * (percent / 100.0));
	npasses = region.rows / rows;
	last_rows = region.rows - npasses * rows;
	if (last_rows)
	    npasses++;
	else
	    last_rows = rows;

    }
    cols = region.cols;

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

    /* using row-based chunks (used for output) when input and output
     * region matches and using segment library when they don't */
    int use_segment = 0;
    int use_base_raster_res = 0;
    /* TODO: see if the input region extent is smaller than the raster
     * if yes, the we need to load the whole base raster if the -e
     * flag was defined (alternatively clip the regions) */
    if (base_rast_res_flag->answer)
        use_base_raster_res = 1;
    if (base_raster_opt->answer && (res_opt->answer || use_base_raster_res
                                    || extents_flag->answer))
        use_segment = 1;
    if (base_raster_opt->answer && !use_segment) {
        /* TODO: do we need to test existence first? mapset? */
        base_raster = Rast_open_old(base_raster_opt->answer, "");
        base_raster_data_type = Rast_get_map_type(base_raster);
        base_array = G_calloc((size_t)rows * (cols + 1), Rast_cell_size(base_raster_data_type));
    }
    if (base_raster_opt->answer && use_segment) {
        if (use_base_raster_res) {
            /* read raster actual extent and resolution */
            Rast_get_cellhd(base_raster_opt->answer, "", &input_region);
            /* TODO: make it only as small as the output is or points are */
            Rast_set_input_window(&input_region);  /* we have split window */
        } else {
            Rast_get_input_window(&input_region);
        }
        rast_segment_open(&base_segment, base_raster_opt->answer, &base_raster_data_type);
    }

    if (!scan_flag->answer) {
        if (!check_rows_cols_fit_to_size_t(rows, cols))
		G_fatal_error(_("Unable to process the hole map at once. "
                        "Please set the '%s' option to some value lower than 100."),
				percent_opt->key);
        point_binning_memory_test(&point_binning, rows, cols, rtype);
	}

    /* open output map */
    out_fd = Rast_open_new(outmap, rtype);

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

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

    count_total = line_total = 0;

    /* main binning loop(s) */
    for (pass = 1; pass <= npasses; pass++) {

	if (npasses > 1)
	    G_message(_("Pass #%d (of %d) ..."), pass, npasses);

	/* figure out segmentation */
	row0 = (pass - 1) * rows;
	if (pass == npasses) {
	    rows = last_rows;
	}

        if (base_array) {
            G_debug(2, "filling base raster array");
            for (row = 0; row < rows; row++) {
                Rast_get_row(base_raster, base_array + ((size_t) row * cols * Rast_cell_size(base_raster_data_type)), row, base_raster_data_type);
            }
        }

	G_debug(2, "pass=%d/%d  rows=%d", pass, npasses, rows);

    point_binning_allocate(&point_binning, rows, cols, rtype);

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

        /* loop of input files */
        for (i = 0; i < infiles.num_items; i++) {
            infile = infiles.items[i];
            /* we already know file is there, so just do basic checks */
            LAS_reader = LASReader_Create(infile);
            if (LAS_reader == NULL)
                G_fatal_error(_("Unable to open file <%s>"), infile);

            while ((LAS_point = LASReader_GetNextPoint(LAS_reader)) != NULL) {
                line++;
                counter++;

                if (counter == 100000) {        /* speed */
                    if (line < estimated_lines)
                        G_percent(line, estimated_lines, 3);
                    counter = 0;
                }

                /* We always count them and report because behavior
                 * changed in between 7.0 and 7.2 from undefined (but skipping
                 * invalid points) to filtering them out only when requested. */
                if (!LASPoint_IsValid(LAS_point)) {
                    n_invalid++;
                    if (only_valid)
                        continue;
                }

                x = LASPoint_GetX(LAS_point);
                y = LASPoint_GetY(LAS_point);
                if (intens_flag->answer)
                    /* use intensity as z here to allow all filters (and
                     * modifications) below to be applied for intensity */
                    z = LASPoint_GetIntensity(LAS_point);
                else
                    z = LASPoint_GetZ(LAS_point);

                int return_n = LASPoint_GetReturnNumber(LAS_point);
                int n_returns = LASPoint_GetNumberOfReturns(LAS_point);
                if (return_filter_is_out(&return_filter_struct, return_n, n_returns)) {
                    n_filtered++;
                    continue;
                }
                point_class = (int) LASPoint_GetClassification(LAS_point);
                if (class_filter_is_out(&class_filter, point_class))
                    continue;

                if (y <= region.south || y > region.north) {
                    continue;
                }
                if (x < region.west || x >= region.east) {
                    continue;
                }

                /* find the bin in the current array box */
		arr_row = (int)((region.north - y) / region.ns_res) - row0;
		if (arr_row < 0 || arr_row >= rows)
		    continue;
                arr_col = (int)((x - region.west) / region.ew_res);

                z = z * zscale;

                if (base_array) {
                    double base_z;
                    if (row_array_get_value_row_col(base_array, arr_row, arr_col,
                                                    cols, base_raster_data_type,
                                                    &base_z))
                        z -= base_z;
                    else
                        continue;
                }
                else if (use_segment) {
                    double base_z;
                    if (rast_segment_get_value_xy(&base_segment, &input_region,
                                                  base_raster_data_type, x, y,
                                                  &base_z))
                        z -= base_z;
                    else
                        continue;
                }

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

                if (intens_import_flag->answer || irange_opt->answer) {
                    intensity = LASPoint_GetIntensity(LAS_point);
                    intensity *= iscale;
                    if (irange_opt->answer) {
                        if (intensity < irange_min || intensity > irange_max) {
                            continue;
                        }
                    }
                    /* use intensity for statistics */
                    if (intens_import_flag->answer)
                        z = intensity;
                }

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

                update_value(&point_binning, &bin_index_nodes, cols,
                             arr_row, arr_col, rtype, x, y, z);
            }                        /* while !EOF of one input file */
            /* close input LAS file */
            LASReader_Destroy(LAS_reader);
        }           /* end of loop for all input files files */

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

	/* calc stats and output */
	G_message(_("Writing to map ..."));
	for (row = 0; row < rows; row++) {
        /* potentially vector writing can be independent on the binning */
        write_values(&point_binning, &bin_index_nodes, raster_row, row,
            cols, rtype, NULL);
	    /* write out line of raster data */
        Rast_put_row(out_fd, raster_row, rtype);
	}

	/* free memory */
	point_binning_free(&point_binning, &bin_index_nodes);
    }				/* passes loop */
    if (base_array)
        Rast_close(base_raster);
    if (use_segment)
        Segment_close(&base_segment);

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

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

    sprintf(title, "Raw X,Y,Z data binned into a raster grid by cell %s",
            method_opt->answer);
    Rast_put_cell_title(outmap, title);

    Rast_short_history(outmap, "raster", &history);
    Rast_command_history(&history);
    Rast_set_history(&history, HIST_DATSRC_1, infile);
    Rast_write_history(outmap, &history);

    /* set computation region to the new raster map */
    /* TODO: should be in the done message */
    if (set_region_flag->answer)
        G_put_window(&region);

    if (n_invalid && only_valid)
        G_message(_("%lu input points were invalid and filtered out"),
                  n_invalid);
    if (n_invalid && !only_valid)
        G_message(_("%lu input points were invalid, use -%c flag to filter"
                    " them out"), n_invalid, only_valid_flag->key);
    if (infiles.num_items > 1) {
        sprintf(buff, _("Raster map <%s> created."
                        " %lu points from %d files found in region."),
                outmap, count_total, infiles.num_items);
    }
    else {
        sprintf(buff, _("Raster map <%s> created."
                        " %lu points found in region."),
                outmap, count_total);
    }

    G_done_msg("%s", buff);
    G_debug(1, "Processed %lu points.", line_total);

    string_list_free(&infiles);

    exit(EXIT_SUCCESS);

}
예제 #14
0
int main(int argc, char *argv[])
{
    int r, c;
    DCELL con1, con2;
    double d1, d2;
    DCELL *alt_row;
    const char *con_name, *alt_name;
    int file_fd;
    DCELL value;
    struct History history;
    struct GModule *module;
    struct Option *opt1, *opt2;

    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("raster"));
    G_add_keyword(_("surface"));
    G_add_keyword(_("interpolation"));
    module->description =
	_("Generates surface raster map from rasterized contours.");

    opt1 = G_define_standard_option(G_OPT_R_INPUT);
    opt1->description = _("Name of input raster map containing contours");

    opt2 = G_define_standard_option(G_OPT_R_OUTPUT);

    if (G_parser(argc, argv))
	exit(EXIT_FAILURE);
    
    con_name = opt1->answer;
    alt_name = opt2->answer;

    nrows = Rast_window_rows();
    ncols = Rast_window_cols();
    i_val_l_f = nrows + ncols;
    con = read_cell(con_name);
    alt_row = (DCELL *) G_malloc(ncols * sizeof(DCELL));
    seen = flag_create(nrows, ncols);
    mask = flag_create(nrows, ncols);
    if (NULL != G_find_file("cell", "MASK", G_mapset())) {
	file_fd = Rast_open_old("MASK", G_mapset());
	for (r = 0; r < nrows; r++) {
	    Rast_get_d_row_nomask(file_fd, alt_row, r);
	    for (c = 0; c < ncols; c++)
		if (Rast_is_d_null_value(&(alt_row[c])) || alt_row[c] == 0)
		    FLAG_SET(mask, r, c);
	}
	Rast_close(file_fd);
    }
    zero = (NODE *) G_malloc(INIT_AR * sizeof(NODE));
    minc = minr = 0;
    maxc = ncols - 1;
    maxr = nrows - 1;
    array_size = INIT_AR;
    file_fd = Rast_open_new(alt_name, DCELL_TYPE);
    for (r = 0; r < nrows; r++) {
	G_percent(r, nrows, 1);
	Rast_set_d_null_value(alt_row, ncols);
	for (c = 0; c < ncols; c++) {
	    if (FLAG_GET(mask, r, c))
		continue;
	    value = con[r][c];
	    if (!Rast_is_d_null_value(&value)) {
		alt_row[c] = value;
		continue;
	    }
	    find_con(r, c, &d1, &d2, &con1, &con2);
	    if (!Rast_is_d_null_value(&con2))
		alt_row[c] = d2 * con1 / (d1 + d2) + 
		             d1 * con2 / (d1 + d2);
	    else
		alt_row[c] = con1;
	}
	Rast_put_row(file_fd, alt_row, DCELL_TYPE);
    }
    G_percent(1, 1, 1);
    
    free_cell(con);
    flag_destroy(seen);
    flag_destroy(mask);
    Rast_close(file_fd);
    
    Rast_short_history(alt_name, "raster", &history);
    Rast_command_history(&history);
    Rast_write_history(alt_name, &history);

    exit(EXIT_SUCCESS);
}
예제 #15
0
파일: main.c 프로젝트: rkrug/grass-ci
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);
}
예제 #16
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);
}
예제 #17
0
int main( int argc, char **argv )
{
  char *name = nullptr;
  struct Option *map;
  struct Cell_head window;

  G_gisinit( argv[0] );

  G_define_module();

  map = G_define_standard_option( G_OPT_R_OUTPUT );

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

  name = map->answer;

#ifdef Q_OS_WIN
  _setmode( _fileno( stdin ), _O_BINARY );
  _setmode( _fileno( stdout ), _O_BINARY );
  //setvbuf( stdin, NULL, _IONBF, BUFSIZ );
  // setting _IONBF on stdout works on windows correctly, data written immediately even without fflush(stdout)
  //setvbuf( stdout, NULL, _IONBF, BUFSIZ );
#endif

  QgsGrassDataFile stdinFile;
  stdinFile.open( stdin );
  QDataStream stdinStream( &stdinFile );

  QFile stdoutFile;
  stdoutFile.open( stdout, QIODevice::WriteOnly | QIODevice::Unbuffered );
  QDataStream stdoutStream( &stdoutFile );

  qint32 proj, zone;
  stdinStream >> proj >> zone;

  QgsRectangle extent;
  qint32 rows, cols;
  stdinStream >> extent >> cols >> rows;
  checkStream( stdinStream );

  QString err = QgsGrass::setRegion( &window, extent, rows, cols );
  if ( !err.isEmpty() )
  {
    G_fatal_error( "Cannot set region: %s", err.toUtf8().constData() );
  }
  window.proj = ( int ) proj;
  window.zone = ( int ) zone;

  G_set_window( &window );

  Qgis::DataType qgis_type;
  qint32 type;
  stdinStream >> type;
  checkStream( stdinStream );
  qgis_type = ( Qgis::DataType )type;

  RASTER_MAP_TYPE grass_type;
  switch ( qgis_type )
  {
    case Qgis::Int32:
      grass_type = CELL_TYPE;
      break;
    case Qgis::Float32:
      grass_type = FCELL_TYPE;
      break;
    case Qgis::Float64:
      grass_type = DCELL_TYPE;
      break;
    default:
      G_fatal_error( "QGIS data type %d not supported", qgis_type );
      return 1;
  }

  cf = Rast_open_new( name, grass_type );
  if ( cf < 0 )
  {
    G_fatal_error( "Unable to create raster map <%s>", name );
    return 1;
  }

  void *buf = Rast_allocate_buf( grass_type );

  int expectedSize = cols * QgsRasterBlock::typeSize( qgis_type );
  bool isCanceled = false;
  QByteArray byteArray;
  for ( int row = 0; row < rows; row++ )
  {
    stdinStream >> isCanceled;
    checkStream( stdinStream );
    if ( isCanceled )
    {
      break;
    }
    double noDataValue;
    stdinStream >> noDataValue;
    stdinStream >> byteArray;
    checkStream( stdinStream );

    if ( byteArray.size() != expectedSize )
    {
      G_fatal_error( "Wrong byte array size, expected %d bytes, got %d, row %d / %d", expectedSize, byteArray.size(), row, rows );
      return 1;
    }

    qint32 *cell = nullptr;
    float *fcell = nullptr;
    double *dcell = nullptr;
    if ( grass_type == CELL_TYPE )
      cell = ( qint32 * ) byteArray.data();
    else if ( grass_type == FCELL_TYPE )
      fcell = ( float * ) byteArray.data();
    else if ( grass_type == DCELL_TYPE )
      dcell = ( double * ) byteArray.data();

    void *ptr = buf;
    for ( int col = 0; col < cols; col++ )
    {
      if ( grass_type == CELL_TYPE )
      {
        if ( ( CELL )cell[col] == ( CELL )noDataValue )
        {
          Rast_set_c_null_value( ( CELL * )ptr, 1 );
        }
        else
        {
          Rast_set_c_value( ptr, ( CELL )( cell[col] ), grass_type );
        }
      }
      else if ( grass_type == FCELL_TYPE )
      {
        if ( ( FCELL )fcell[col] == ( FCELL )noDataValue )
        {
          Rast_set_f_null_value( ( FCELL * )ptr, 1 );
        }
        else
        {
          Rast_set_f_value( ptr, ( FCELL )( fcell[col] ), grass_type );
        }
      }
      else if ( grass_type == DCELL_TYPE )
      {
        if ( ( DCELL )dcell[col] == ( DCELL )noDataValue )
        {
          Rast_set_d_null_value( ( DCELL * )ptr, 1 );
        }
        else
        {
          Rast_set_d_value( ptr, ( DCELL )dcell[col], grass_type );
        }
      }

      ptr = G_incr_void_ptr( ptr, Rast_cell_size( grass_type ) );
    }
    Rast_put_row( cf, buf, grass_type );

#ifndef Q_OS_WIN
    // Because stdin is somewhere buffered on Windows (not clear if in QProcess or by Windows)
    // we cannot in QgsGrassImport wait for this because it hangs. Setting _IONBF on stdin does not help
    // and there is no flush() on QProcess.
    // OTOH, smaller stdin buffer is probably blocking QgsGrassImport so that the import can be canceled immediately.
    stdoutStream << ( bool )true; // row written
    stdoutFile.flush();
#endif
  }

  if ( isCanceled )
  {
    Rast_unopen( cf );
  }
  else
  {
    Rast_close( cf );
    struct History history;
    Rast_short_history( name, "raster", &history );
    Rast_command_history( &history );
    Rast_write_history( name, &history );
  }

  exit( EXIT_SUCCESS );
}
예제 #18
0
파일: main.cpp 프로젝트: rkrug/grass-ci
int main(int argc, char *argv[])
{
    struct Options opts;
    struct ScaleRange iscale;	/* input file's data is scaled to this interval */
    struct ScaleRange oscale;	/* output file's scale */
    int iimg_fd;		/* input image's file descriptor */
    int oimg_fd;		/* output image's file descriptor */
    int ialt_fd = -1;		/* input elevation map's file descriptor */
    int ivis_fd = -1;		/* input visibility map's file descriptor */
    struct History hist;
    struct Cell_head orig_window;

    /* Define module */
    define_module();

    /* Define the different input options */
    opts = define_options();

    /**** Start ****/
    G_gisinit(argv[0]);
    if (G_parser(argc, argv) < 0)
	exit(EXIT_FAILURE);

    G_get_set_window(&orig_window);
    adjust_region(opts.iimg->answer);

    /* open input raster */
    if ((iimg_fd = Rast_open_old(opts.iimg->answer, "")) < 0)
	G_fatal_error(_("Unable to open raster map <%s>"), opts.iimg->answer);

    if (opts.ialt->answer) {
	if ((ialt_fd = Rast_open_old(opts.ialt->answer, "")) < 0)
	    G_fatal_error(_("Unable to open raster map <%s>"),
			  opts.ialt->answer);
    }

    if (opts.ivis->answer) {
	if ((ivis_fd = Rast_open_old(opts.ivis->answer, "")) < 0)
	    G_fatal_error(_("Unable to open raster map <%s>"),
			  opts.ivis->answer);
    }

    /* open a floating point raster or not? */
    if (opts.oint->answer) {
	if ((oimg_fd = Rast_open_new(opts.oimg->answer, CELL_TYPE)) < 0)
	    G_fatal_error(_("Unable to create raster map <%s>"),
			  opts.oimg->answer);
    }
    else {
	if ((oimg_fd = Rast_open_fp_new(opts.oimg->answer)) < 0)
	    G_fatal_error(_("Unable to create raster map <%s>"),
			  opts.oimg->answer);
    }

    /* read the scale parameters */
    read_scale(opts.iscl, iscale);
    read_scale(opts.oscl, oscale);

    /* initialize this 6s computation and parse the input conditions file */
    init_6S(opts.icnd->answer);

    InputMask imask = RADIANCE;	/* the input mask tells us what transformations if any
				   needs to be done to make our input values, reflectance
				   values scaled between 0 and 1 */
    if (opts.irad->answer)
	imask = REFLECTANCE;
    if (opts.etmbefore->answer)
	imask = (InputMask) (imask | ETM_BEFORE);
    if (opts.etmafter->answer)
	imask = (InputMask) (imask | ETM_AFTER);

    /* process the input raster and produce our atmospheric corrected output raster. */
    G_message(_("Atmospheric correction..."));
    process_raster(iimg_fd, imask, iscale, ialt_fd, ivis_fd,
		   oimg_fd, opts.oint->answer, oscale);


    /* Close the input and output file descriptors */
    Rast_short_history(opts.oimg->answer, "raster", &hist);
    Rast_close(iimg_fd);
    if (opts.ialt->answer)
	Rast_close(ialt_fd);
    if (opts.ivis->answer)
	Rast_close(ivis_fd);
    Rast_close(oimg_fd);

    Rast_command_history(&hist);
    Rast_write_history(opts.oimg->answer, &hist);

    /* Copy the colors of the input raster to the output raster.
       Scaling is ignored and color ranges might not be correct. */
    copy_colors(opts.iimg->answer, opts.oimg->answer);

    Rast_set_window(&orig_window);
    G_message(_("Atmospheric correction complete."));

    exit(EXIT_SUCCESS);
}
예제 #19
0
파일: main.c 프로젝트: rashadkm/grass_cmake
/* ************************************************************************* */
int main(int argc, char *argv[])
{
    RASTER3D_Region region;
    struct Cell_head window2d;
    struct GModule *module;
    void *map = NULL; /*The 3D Rastermap */
    int changemask = 0;
    int elevfd = -1, outfd = -1; /*file descriptors */
    int output_type, cols, rows;

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

    module = G_define_module();
    G_add_keyword(_("raster3d"));
    G_add_keyword(_("profile"));
    G_add_keyword(_("raster"));
    G_add_keyword(_("voxel"));
    module->description =
        _("Creates cross section 2D raster map from 3D raster map based on 2D elevation map");

    /* Get parameters from user */
    set_params();

    /* Have GRASS get inputs */
    if (G_parser(argc, argv))
        exit(EXIT_FAILURE);

    G_debug(3, "Open 3D raster map %s", param.input->answer);

    if (NULL == G_find_raster3d(param.input->answer, ""))
        Rast3d_fatal_error(_("3D raster map <%s> not found"),
                       param.input->answer);

    /* Figure out the region from the map */
    Rast3d_init_defaults();
    Rast3d_get_window(&region);

    /*Check if the g3d-region is equal to the 2d rows and cols */
    rows = Rast_window_rows();
    cols = Rast_window_cols();

    /*If not equal, set the 2D windows correct */
    if (rows != region.rows || cols != region.cols) {
        G_message
            (_("The 2D and 3D region settings are different. Using the 3D raster map settings to adjust the 2D region."));
        G_get_set_window(&window2d);
        window2d.ns_res = region.ns_res;
        window2d.ew_res = region.ew_res;
        window2d.rows = region.rows;
        window2d.cols = region.cols;
        Rast_set_window(&window2d);
    }


    /*******************/
    /*Open the 3d raster map */

    /*******************/
    map = Rast3d_open_cell_old(param.input->answer,
                          G_find_raster3d(param.input->answer, ""),
                          &region, RASTER3D_TILE_SAME_AS_FILE,
                          RASTER3D_USE_CACHE_DEFAULT);

    if (map == NULL)
        Rast3d_fatal_error(_("Unable to open 3D raster map <%s>"),
                       param.input->answer);

    /*Get the output type */
    output_type = Rast3d_file_type_map(map);

    if (output_type == FCELL_TYPE || output_type == DCELL_TYPE) {

        /********************************/
        /*Open the elevation raster map */

        /********************************/

        elevfd = Rast_open_old(param.elevation->answer, "");

        globalElevMapType = Rast_get_map_type(elevfd);

        /**********************/
        /*Open the Outputmap */

        /**********************/

        if (G_find_raster2(param.output->answer, ""))
            G_message(_("Output map already exists. Will be overwritten!"));

        if (output_type == FCELL_TYPE)
            outfd = Rast_open_new(param.output->answer, FCELL_TYPE);
        else if (output_type == DCELL_TYPE)
            outfd = Rast_open_new(param.output->answer, DCELL_TYPE);

        /*if requested set the Mask on */
        if (param.mask->answer) {
            if (Rast3d_mask_file_exists()) {
                changemask = 0;
                if (Rast3d_mask_is_off(map)) {
                    Rast3d_mask_on(map);
                    changemask = 1;
                }
            }
        }

        /************************/
        /*Create the Rastermaps */

        /************************/
        rast3d_cross_section(map, region, elevfd, outfd);

        /*We set the Mask off, if it was off before */
        if (param.mask->answer) {
            if (Rast3d_mask_file_exists())
                if (Rast3d_mask_is_on(map) && changemask)
                    Rast3d_mask_off(map);
        }

        Rast_close(outfd);
        Rast_close(elevfd);

    } else {
        fatal_error(map, -1, -1,
                    _("Wrong 3D raster datatype! Cannot create raster map"));
    }

    /* Close files and exit */
    if (!Rast3d_close(map))
        Rast3d_fatal_error(_("Unable to close 3D raster map <%s>"),
                       param.input->answer);

    return (EXIT_SUCCESS);
}
예제 #20
0
파일: main.c 프로젝트: GRASS-GIS/grass-ci
int main(int argc, char *argv[])
{
    char *terrainmap, *seedmap, *lakemap;
    int rows, cols, in_terran_fd, out_fd, lake_fd, row, col, pases, pass;
    int lastcount, curcount, start_col = 0, start_row = 0;
    double east, north, area = 0, volume = 0;
    FCELL **in_terran, **out_water, water_level, max_depth = 0, min_depth = 0;
    FCELL water_window[3][3];
    struct Option *tmap_opt, *smap_opt, *wlvl_opt, *lake_opt, *sdxy_opt;
    struct Flag *negative_flag, *overwrite_flag;
    struct GModule *module;
    struct Colors colr;
    struct Cell_head window;
    struct History history;

    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("raster"));
    G_add_keyword(_("hydrology"));
    G_add_keyword(_("hazard"));
    G_add_keyword(_("flood"));
    module->description = _("Fills lake at given point to given level.");

    tmap_opt = G_define_standard_option(G_OPT_R_ELEV);

    wlvl_opt = G_define_option();
    wlvl_opt->key = "water_level";
    wlvl_opt->description = _("Water level");
    wlvl_opt->type = TYPE_DOUBLE;
    wlvl_opt->required = YES;

    lake_opt = G_define_standard_option(G_OPT_R_OUTPUT);
    lake_opt->key = "lake";
    lake_opt->required = NO;
    lake_opt->guisection = _("Output");

    sdxy_opt = G_define_standard_option(G_OPT_M_COORDS);
    sdxy_opt->label = _("Seed point coordinates");
    sdxy_opt->description = _("Either this coordinates pair or a seed"
	" map have to be specified");
    sdxy_opt->required = NO;
    sdxy_opt->multiple = NO;
    sdxy_opt->guisection = _("Seed");

    smap_opt = G_define_standard_option(G_OPT_R_MAP);
    smap_opt->key = "seed";
    smap_opt->label =
	_("Input raster map with given starting point(s) (at least 1 cell > 0)");
    smap_opt->description =
	_("Either this parameter or a coordinates pair have to be specified");
    smap_opt->required = NO;
    smap_opt->guisection = _("Seed");

    negative_flag = G_define_flag();
    negative_flag->key = 'n';
    negative_flag->description =
	_("Use negative depth values for lake raster map");

    overwrite_flag = G_define_flag();
    overwrite_flag->key = 'o';
    overwrite_flag->description =
	_("Overwrite seed map with result (lake) map");
    overwrite_flag->guisection = _("Output");

    if (G_parser(argc, argv))	/* Returns 0 if successful, non-zero otherwise */
	exit(EXIT_FAILURE);

    if (smap_opt->answer && sdxy_opt->answer)
	G_fatal_error(_("Both seed map and coordinates cannot be specified"));

    if (!smap_opt->answer && !sdxy_opt->answer)
	G_fatal_error(_("Seed map or seed coordinates must be set!"));

    if (sdxy_opt->answer && !lake_opt->answer)
	G_fatal_error(_("Seed coordinates and output map lake= must be set!"));

    if (lake_opt->answer && overwrite_flag->answer)
	G_fatal_error(_("Both lake and overwrite cannot be specified"));

    if (!lake_opt->answer && !overwrite_flag->answer)
	G_fatal_error(_("Output lake map or overwrite flag must be set!"));

    terrainmap = tmap_opt->answer;
    seedmap = smap_opt->answer;
    sscanf(wlvl_opt->answer, "%f", &water_level);
    lakemap = lake_opt->answer;

    /* If lakemap is set, write to it, else is set overwrite flag and we should write to seedmap. */
    if (lakemap)
	lake_fd = Rast_open_new(lakemap, 1);

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

    /* If we use x,y as seed... */
    if (sdxy_opt->answer) {
	G_get_window(&window);
	east = window.east;
	north = window.north;

	G_scan_easting(sdxy_opt->answers[0], &east, G_projection());
	G_scan_northing(sdxy_opt->answers[1], &north, G_projection());
	start_col = (int)Rast_easting_to_col(east, &window);
	start_row = (int)Rast_northing_to_row(north, &window);

	if (start_row < 0 || start_row > rows ||
	    start_col < 0 || start_col > cols)
	    G_fatal_error(_("Seed point outside the current region"));
    }

    /* Open terrain map */
    in_terran_fd = Rast_open_old(terrainmap, "");

    /* Open seed map */
    if (smap_opt->answer)
	out_fd = Rast_open_old(seedmap, "");

    /* Pointers to rows. Row = ptr to 'col' size array. */
    in_terran = (FCELL **) G_malloc(rows * sizeof(FCELL *));
    out_water = (FCELL **) G_malloc(rows * sizeof(FCELL *));
    if (in_terran == NULL || out_water == NULL)
	G_fatal_error(_("G_malloc: out of memory"));


    G_debug(1, "Loading maps...");
    /* foo_rows[row] == array with data (2d array). */
    for (row = 0; row < rows; row++) {
	in_terran[row] = (FCELL *) G_malloc(cols * sizeof(FCELL));
	out_water[row] = (FCELL *) G_calloc(cols, sizeof(FCELL));

	/* In newly created space load data from file. */
	Rast_get_f_row(in_terran_fd, in_terran[row], row);

	if (smap_opt->answer)
	    Rast_get_f_row(out_fd, out_water[row], row);

	G_percent(row + 1, rows, 5);
    }

    /* Set seed point */
    if (sdxy_opt->answer)
	/* Check is water level higher than seed point */
	if (in_terran[start_row][start_col] >= water_level)
	    G_fatal_error(_("Given water level at seed point is below earth surface. "
			   "Increase water level or move seed point."));
    out_water[start_row][start_col] = 1;

    /* Close seed map for reading. */
    if (smap_opt->answer)
	Rast_close(out_fd);

    /* Open output map for writing. */
    if (lakemap)
	out_fd = lake_fd;
    else
	out_fd = Rast_open_new(seedmap, 1);

    /* More pases are renudant. Real pases count is controlled by altered cell count. */
    pases = (int)(rows * cols) / 2;

    G_debug(1,
	    "Starting lake filling at level of %8.4f in %d passes. Percent done:",
	    water_level, pases);

    lastcount = 0;

    for (pass = 0; pass < pases; pass++) {
	G_debug(3, "Pass: %d", pass);
	curcount = 0;
	/* Move from left upper corner to right lower corner. */
	for (row = 0; row < rows; row++) {
	    for (col = 0; col < cols; col++) {
		/* Loading water data into window. */
		load_window_values(out_water, water_window, rows, cols, row,
				   col);

		/* Cheking presence of water. */
		if (is_near_water(water_window) == 1) {
		    if (in_terran[row][col] < water_level) {
			out_water[row][col] =
			    water_level - in_terran[row][col];
			curcount++;
		    }
		    else {
			out_water[row][col] = 0;	/* Cell is higher than water level -> NULL. */
		    }
		}
	    }
	}
	if (curcount == lastcount)
	    break;		/* We done. */
	lastcount = curcount;
	curcount = 0;
	/* Move backwards - from lower right corner to upper left corner. */
	for (row = rows - 1; row >= 0; row--) {
	    for (col = cols - 1; col >= 0; col--) {
		load_window_values(out_water, water_window, rows, cols, row,
				   col);

		if (is_near_water(water_window) == 1) {
		    if (in_terran[row][col] < water_level) {
			out_water[row][col] =
			    water_level - in_terran[row][col];
			curcount++;
		    }
		    else {
			out_water[row][col] = 0;
		    }
		}
	    }
	}
	G_percent(pass + 1, pases, 10);
	if (curcount == lastcount)
	    break;		/* We done. */
	lastcount = curcount;
    }				/*pases */

    G_percent(pases, pases, 10);	/* Show 100%. */

    save_map(out_water, out_fd, rows, cols, negative_flag->answer, &min_depth,
	     &max_depth, &area, &volume);

    G_message(_("Lake depth from %f to %f (specified water level is taken as zero)"), min_depth, max_depth);
    G_message(_("Lake area %f square meters"), area);
    G_message(_("Lake volume %f cubic meters"), volume);
    G_important_message(_("Volume is correct only if lake depth (terrain raster map) is in meters"));

    /* Close all files. Lake map gets written only now. */
    Rast_close(in_terran_fd);
    Rast_close(out_fd);

    /* Add blue color gradient from light bank to dark depth */
    Rast_init_colors(&colr);
    if (negative_flag->answer == 1) {
	Rast_add_f_color_rule(&max_depth, 0, 240, 255,
				  &min_depth, 0, 50, 170, &colr);
    }
    else {
	Rast_add_f_color_rule(&min_depth, 0, 240, 255,
				  &max_depth, 0, 50, 170, &colr);
    }

    Rast_write_colors(lakemap, G_mapset(), &colr);

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

    return EXIT_SUCCESS;
}
예제 #21
0
int main(int argc, char **argv)
{
    int fe, fd, fm;
    int i, j, type;
    int new_id;
    int nrows, ncols, nbasins;
    int map_id, dir_id, bas_id;
    char map_name[GNAME_MAX], new_map_name[GNAME_MAX];
    const char *tempfile1, *tempfile2, *tempfile3;
    char dir_name[GNAME_MAX];
    char bas_name[GNAME_MAX];

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    in_buf = get_buf();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	Rast_close(bas_id);
	close(fm);
    }

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

	read(fd, out_buf, bufsz);

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

	Rast_put_row(dir_id, out_buf, CELL_TYPE);

    }

    Rast_close(new_id);
    close(fe);

    Rast_close(dir_id);
    close(fd);

    G_free(in_buf);
    G_free(out_buf);

    exit(EXIT_SUCCESS);
}
예제 #22
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);
}
예제 #23
0
int execute_random(struct rr_state *theState)
{
    long nt;
    long nc;
    struct Cell_head window;
    int nrows, ncols, row, col;
    int infd, cinfd, outfd;
    struct Map_info Out;
    struct field_info *fi;
    dbTable *table;
    dbColumn *column;
    dbString sql;
    dbDriver *driver;
    struct line_pnts *Points;
    struct line_cats *Cats;
    int cat;
    RASTER_MAP_TYPE type;
    int do_check;

    G_get_window(&window);

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

    /* open the data files, input raster should be set-up already */
    if ((infd = theState->fd_old) < 0)
	G_fatal_error(_("Unable to open raster map <%s>"),
		      theState->inraster);
    if (theState->docover == TRUE) {
	if ((cinfd = theState->fd_cold) < 0)
	    G_fatal_error(_("Unable to open raster map <%s>"),
			  theState->inrcover);
    }

    if (theState->outraster != NULL) {
	if (theState->docover == TRUE)
	    type = theState->cover.type;
	else
	    type = theState->buf.type;
	outfd = Rast_open_new(theState->outraster, type);
	theState->fd_new = outfd;

    }

    if (theState->outvector) {
	if (Vect_open_new(&Out, theState->outvector, theState->z_geometry) < 0)
	    G_fatal_error(_("Unable to create vector map <%s>"),
			    theState->outvector);
	Vect_hist_command(&Out);

	fi = Vect_default_field_info(&Out, 1, NULL, GV_1TABLE);

	driver =
	    db_start_driver_open_database(fi->driver,
					  Vect_subst_var(fi->database, &Out));
	if (!driver)
	    G_fatal_error(_("Unable to open database <%s> by driver <%s>"),
			  Vect_subst_var(fi->database, &Out), fi->driver);
        db_set_error_handler_driver(driver);
        
	Vect_map_add_dblink(&Out, 1, NULL, fi->table, GV_KEY_COLUMN, fi->database,
			    fi->driver);

	if (theState->docover == TRUE)
	    table = db_alloc_table(3);
	else
	    table = db_alloc_table(2);
	db_set_table_name(table, fi->table);

	column = db_get_table_column(table, 0);
	db_set_column_name(column, GV_KEY_COLUMN);
	db_set_column_sqltype(column, DB_SQL_TYPE_INTEGER);

	column = db_get_table_column(table, 1);
	db_set_column_name(column, "value");
	db_set_column_sqltype(column, DB_SQL_TYPE_DOUBLE_PRECISION);

	if (theState->docover == TRUE) {
	    column = db_get_table_column(table, 2);
	    db_set_column_name(column, "covervalue");
	    db_set_column_sqltype(column, DB_SQL_TYPE_DOUBLE_PRECISION);
	}
	if (db_create_table(driver, table) != DB_OK)
	    G_warning(_("Cannot create new table"));

	db_begin_transaction(driver);

	Points = Vect_new_line_struct();
	Cats = Vect_new_cats_struct();
	db_init_string(&sql);
    }

    if (theState->outvector && theState->outraster)
	G_message(_("Writing raster map <%s> and vector map <%s> ..."),
		  theState->outraster, theState->outvector);
    else if (theState->outraster)
	G_message(_("Writing raster map <%s> ..."), theState->outraster);
    else if (theState->outvector)
	G_message(_("Writing vector map <%s> ..."), theState->outvector);

    G_percent(0, theState->nRand, 2);

    init_rand();
    nc = (theState->use_nulls) ? theState->nCells :
	theState->nCells - theState->nNulls;
    nt = theState->nRand;	/* Number of points to generate */
    cat = 1;

    /* Execute for loop for every row if nt>1 */
    for (row = 0; row < nrows && nt; row++) {
	Rast_get_row(infd, theState->buf.data.v, row, theState->buf.type);
	if (theState->docover == TRUE) {
	    Rast_get_row(cinfd, theState->cover.data.v, row,
			 theState->cover.type);
	}

	for (col = 0; col < ncols && nt; col++) {
	    do_check = 0;

	    if (theState->use_nulls || !is_null_value(theState->buf, col))
		do_check = 1;
	    if (do_check && theState->docover == TRUE) {	/* skip no data cover points */
		if (!theState->use_nulls &&
		    is_null_value(theState->cover, col))
		    do_check = 0;
	    }

	    if (do_check && make_rand() % nc < nt) {
		nt--;
		if (is_null_value(theState->buf, col))
		    cpvalue(&theState->nulls, 0, &theState->buf, col);
		if (theState->docover == TRUE) {
		    if (is_null_value(theState->cover, col))
			cpvalue(&theState->cnulls, 0, &theState->cover, col);
		}

		if (theState->outvector) {
		    double x, y, val, coverval;
		    char buf[500];

		    Vect_reset_line(Points);
		    Vect_reset_cats(Cats);

		    x = window.west + (col + .5) * window.ew_res;
		    y = window.north - (row + .5) * window.ns_res;

		    val = cell_as_dbl(&theState->buf, col);
		    if (theState->docover == 1)
			coverval = cell_as_dbl(&theState->cover, col);

		    if (theState->z_geometry)
			Vect_append_point(Points, x, y, val);
		    else
			Vect_append_point(Points, x, y, 0.0);
		    Vect_cat_set(Cats, 1, cat);

		    Vect_write_line(&Out, GV_POINT, Points, Cats);

		    if (theState->docover == 1)
			if (is_null_value(theState->cover, col))
			    sprintf(buf,
				    "insert into %s values ( %d, %f, NULL )",
				    fi->table, cat, val);
			else
			    sprintf(buf,
				    "insert into %s values ( %d, %f, %f )",
				    fi->table, cat, val, coverval);
		    else
			sprintf(buf, "insert into %s values ( %d, %f )",
				fi->table, cat, val);
		    db_set_string(&sql, buf);

		    if (db_execute_immediate(driver, &sql) != DB_OK)
			G_fatal_error(_("Cannot insert new record: %s"),
				      db_get_string(&sql));

		    cat++;
		}
		G_percent((theState->nRand - nt), theState->nRand, 2);
	    }
	    else {
		set_to_null(&theState->buf, col);
		if (theState->docover == 1)
		    set_to_null(&theState->cover, col);
	    }

	    if (do_check)
		nc--;
	}

	while (col < ncols) {
	    set_to_null(&theState->buf, col);
	    if (theState->docover == 1)
		set_to_null(&theState->cover, col);
	    col++;
	}

	if (theState->outraster) {
	    if (theState->docover == 1)
		Rast_put_row(outfd, theState->cover.data.v,
				 theState->cover.type);
	    else
		Rast_put_row(outfd, theState->buf.data.v,
				 theState->buf.type);
	}
    }

    /* Catch any remaining rows in the window */
    if (theState->outraster && row < nrows) {
	for (col = 0; col < ncols; col++) {
	    if (theState->docover == 1)
		set_to_null(&theState->cover, col);
	    else
		set_to_null(&theState->buf, col);
	}
	for (; row < nrows; row++) {
	    if (theState->docover == 1)
		Rast_put_row(outfd, theState->cover.data.v,
				 theState->cover.type);
	    else
		Rast_put_row(outfd, theState->buf.data.v,
				 theState->buf.type);
	}
    }

    if (nt > 0)
	G_warning(_("Only [%ld] random points created"),
		  theState->nRand - nt);

    /* close files */
    Rast_close(infd);
    if (theState->docover == TRUE)
	Rast_close(cinfd);
    if (theState->outvector) {
	db_commit_transaction(driver);
	if (db_create_index2(driver, fi->table, GV_KEY_COLUMN) != DB_OK)
	    G_warning(_("Unable to create index"));
	if (db_grant_on_table
	    (driver, fi->table, DB_PRIV_SELECT,
	     DB_GROUP | DB_PUBLIC) != DB_OK) {
	    G_fatal_error(_("Unable to grant privileges on table <%s>"),
			  fi->table);
	}
	db_close_database_shutdown_driver(driver);
	if (theState->notopol != 1)
	    Vect_build(&Out);
	Vect_close(&Out);
    }
    if (theState->outraster)
	Rast_close(outfd);

    return 0;
}				/* execute_random() */
예제 #24
0
int close_maps(char *stream_rast, char *stream_vect, char *dir_rast)
{
    int stream_fd, dir_fd, r, c, i;
    CELL *cell_buf1, *cell_buf2;
    struct History history;
    CELL stream_id;
    ASP_FLAG af;

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

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

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

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

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

	Rast_close(dir_fd);
	G_free(cell_buf2);

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

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

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

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

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

    return 1;
}
예제 #25
0
파일: tools.c 프로젝트: rkrug/grass-ci
void filter_holes(Gfile * out)
{
    int row, col, nrows, ncols;

    void *arast, *brast, *crast;
    int i, pixel[9], cold, warm, shadow, nulo, lim;

    Gfile tmp;

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

    if (nrows < 3 || ncols < 3)
        return;

    /* Open to read */
    if ((out->fd = Rast_open_old(out->name, "")) < 0)
        G_fatal_error(_("Unable to open raster map <%s>"), out->name);

    arast = Rast_allocate_buf(CELL_TYPE);
    brast = Rast_allocate_buf(CELL_TYPE);
    crast = Rast_allocate_buf(CELL_TYPE);

    /* Open to write */
    sprintf(tmp.name, "_%d.BBB", getpid());
    tmp.rast = Rast_allocate_buf(CELL_TYPE);
    if ((tmp.fd = Rast_open_new(tmp.name, CELL_TYPE)) < 0)
        G_fatal_error(_("Unable to create raster map <%s>"), tmp.name);

    G_important_message(_("Filling small holes in clouds..."));

    /* Se puede acelerar creandolos nulos y luego arast = brast
       brast = crast y cargando crast solamente
       G_set_f_null_value(cell[2], ncols);
     */

    for (row = 0; row < nrows; row++) {
        G_percent(row, nrows, 2);
        /* Read row values */
        if (row != 0) {
            Rast_get_c_row(out->fd, arast, row - 1);
        }
        Rast_get_c_row(out->fd, brast, row);
        if (row != (nrows - 1)) {
            Rast_get_c_row(out->fd, crast, row + 1);
        }
        /* Analysis of all pixels */
        for (col = 0; col < ncols; col++) {
            pixel[0] = pval(brast, col);
            if (pixel[0] == 0) {
                if (row == 0) {
                    pixel[1] = -1;
                    pixel[2] = -1;
                    pixel[3] = -1;
                    if (col == 0) {
                        pixel[4] = -1;
                        pixel[5] = pval(brast, col + 1);
                        pixel[6] = -1;
                        pixel[7] = pval(crast, col);
                        pixel[8] = pval(crast, col + 1);
                    }
                    else if (col != (ncols - 1)) {
                        pixel[4] = pval(brast, col - 1);
                        pixel[5] = pval(brast, col + 1);
                        pixel[6] = pval(crast, col - 1);
                        pixel[7] = pval(crast, col);
                        pixel[8] = pval(crast, col + 1);
                    }
                    else {
                        pixel[4] = pval(brast, col - 1);
                        pixel[5] = -1;
                        pixel[6] = pval(crast, col - 1);
                        pixel[7] = pval(crast, col);
                        pixel[8] = -1;
                    }
                }
                else if (row != (nrows - 1)) {
                    if (col == 0) {
                        pixel[1] = -1;
                        pixel[2] = pval(arast, col);
                        pixel[3] = pval(arast, col + 1);
                        pixel[4] = -1;
                        pixel[5] = pval(brast, col + 1);
                        pixel[6] = -1;
                        pixel[7] = pval(crast, col);
                        pixel[8] = pval(crast, col + 1);
                    }
                    else if (col != (ncols - 1)) {
                        pixel[1] = pval(arast, col - 1);
                        pixel[2] = pval(arast, col);
                        pixel[3] = pval(arast, col + 1);
                        pixel[4] = pval(brast, col - 1);
                        pixel[5] = pval(brast, col + 1);
                        pixel[6] = pval(crast, col - 1);
                        pixel[7] = pval(crast, col);
                        pixel[8] = pval(crast, col + 1);
                    }
                    else {
                        pixel[1] = pval(arast, col - 1);
                        pixel[2] = pval(arast, col);
                        pixel[3] = -1;
                        pixel[4] = pval(brast, col - 1);
                        pixel[5] = -1;
                        pixel[6] = pval(crast, col - 1);
                        pixel[7] = pval(crast, col);
                        pixel[8] = -1;
                    }
                }
                else {
                    pixel[6] = -1;
                    pixel[7] = -1;
                    pixel[8] = -1;
                    if (col == 0) {
                        pixel[1] = -1;
                        pixel[2] = pval(arast, col);
                        pixel[3] = pval(arast, col + 1);
                        pixel[4] = -1;
                        pixel[5] = pval(brast, col + 1);
                    }
                    else if (col != (ncols - 1)) {
                        pixel[1] = pval(arast, col - 1);
                        pixel[2] = pval(arast, col);
                        pixel[3] = pval(arast, col + 1);
                        pixel[4] = pval(brast, col - 1);
                        pixel[5] = pval(brast, col + 1);
                    }
                    else {
                        pixel[1] = pval(arast, col - 1);
                        pixel[2] = pval(arast, col);
                        pixel[3] = -1;
                        pixel[4] = pval(brast, col - 1);
                        pixel[5] = -1;
                    }
                }

                cold = warm = shadow = nulo = 0;
                for (i = 1; i < 9; i++) {
                    switch (pixel[i]) {
                    case IS_COLD_CLOUD:
                        cold++;
                        break;
                    case IS_WARM_CLOUD:
                        warm++;
                        break;
                    case IS_SHADOW:
                        shadow++;
                        break;
                    default:
                        nulo++;
                        break;
                    }
                }
                lim = (int)(cold + warm + shadow + nulo) / 2;

                /* Entra pixel[0] = 0 */
                if (nulo < lim) {
                    if (shadow >= (cold + warm))
                        pixel[0] = IS_SHADOW;
                    else
                        pixel[0] =
                            (warm > cold) ? IS_WARM_CLOUD : IS_COLD_CLOUD;
                }
            }
            if (pixel[0] != 0) {
                ((CELL *) tmp.rast)[col] = pixel[0];
            }
            else {
                Rast_set_c_null_value((CELL *) tmp.rast + col, 1);
            }
        }
        Rast_put_row(tmp.fd, tmp.rast, CELL_TYPE);
    }
    G_percent(1, 1, 1);

    G_free(arast);
    G_free(brast);
    G_free(crast);
    Rast_close(out->fd);

    G_free(tmp.rast);
    Rast_close(tmp.fd);

    G_remove("cats", out->name);
    G_remove("cell", out->name);
    G_remove("cellhd", out->name);
    G_remove("cell_misc", out->name);
    G_remove("hist", out->name);

    G_rename("cats", tmp.name, out->name);
    G_rename("cell", tmp.name, out->name);
    G_rename("cellhd", tmp.name, out->name);
    G_rename("cell_misc", tmp.name, out->name);
    G_rename("hist", tmp.name, out->name);

    return;
}
예제 #26
0
파일: main.c 프로젝트: caomw/grass
int main(int argc, char *argv[]) 
{
    int nrows, ncols;
    int row, col;
    int makin = 0;		/*Makin Flag for root zone soil moisture output */
    struct GModule *module;
    struct Option *input1, *input2, *input3, *output1, *output2;
    struct Flag *flag1;
    struct History history;	/*metadata */
    char *result1, *result2;	/*output raster name */
    
    int infd_rnet, infd_g0, infd_h0;
    int outfd1, outfd2;
    char *rnet, *g0, *h0;
    void *inrast_rnet, *inrast_g0, *inrast_h0;

    DCELL * outrast1, *outrast2;

    /************************************/ 
    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 evaporative fraction (Bastiaanssen, 1995) and "
	  "root zone soil moisture (Makin, Molden and Bastiaanssen, 2001).");
    
    /* Define the different options */ 
    input1 = G_define_standard_option(G_OPT_R_INPUT);
    input1->key = "netradiation";
    input1->description = _("Name of Net Radiation raster map [W/m2]");

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

    input3 = G_define_standard_option(G_OPT_R_INPUT);
    input3->key = "sensibleheatflux";
    input3->description = _("Name of sensible heat flux raster map [W/m2]");

    output1 = G_define_standard_option(G_OPT_R_OUTPUT);
    output1->key = "evaporativefraction";
    output1->description =
	_("Name for output evaporative fraction raster map");

    output2 = G_define_standard_option(G_OPT_R_OUTPUT);
    output2->key = "soilmoisture";
    output2->required = NO;
    output2->description =
	_("Name for output root zone soil moisture raster map");

    flag1 = G_define_flag();
    flag1->key = 'm';
    flag1->description =
	_("Root zone soil moisture output (Makin, Molden and Bastiaanssen, 2001)");
    
    /********************/
    if (G_parser(argc, argv))
	exit(EXIT_FAILURE);
    
    rnet = input1->answer;
    g0 = input2->answer;
    h0 = input3->answer;
    result1 = output1->answer;
    result2 = output2->answer;
    makin = flag1->answer;
    
    /***************************************************/ 
    infd_rnet = Rast_open_old(rnet, "");
    inrast_rnet = Rast_allocate_d_buf();
    
    /***************************************************/ 
    infd_g0 = Rast_open_old(g0, "");
    inrast_g0 = Rast_allocate_d_buf();
    
    /***************************************************/ 
    infd_h0 = Rast_open_old(h0, "");
    inrast_h0 = Rast_allocate_d_buf();
    
    /***************************************************/ 
    nrows = Rast_window_rows();
    ncols = Rast_window_cols();
    outrast1 = Rast_allocate_d_buf();

    if (makin) 
	outrast2 = Rast_allocate_d_buf();
    
    /* Create New raster files */ 
    outfd1 = Rast_open_new(result1, DCELL_TYPE);
    if (makin) 
	outfd2 = Rast_open_new(result2, DCELL_TYPE);
        
    /* Process pixels */ 
    for (row = 0; row < nrows; row++)
    {
	DCELL d;
	DCELL d_rnet;
	DCELL d_g0;
	DCELL d_h0;
	G_percent(row, nrows, 2);
	
        /* read input maps */ 
        Rast_get_d_row(infd_rnet, inrast_rnet, row);
	Rast_get_d_row(infd_g0, inrast_g0, row);
	Rast_get_d_row(infd_h0, inrast_h0, row);
	
        /*process the data */ 
        for (col = 0; col < ncols; col++)
        {
            d_rnet = ((DCELL *) inrast_rnet)[col];
            d_g0 = ((DCELL *) inrast_g0)[col];
            d_h0 = ((DCELL *) inrast_h0)[col];
	    if (Rast_is_d_null_value(&d_rnet) || 
                Rast_is_d_null_value(&d_g0) ||
		Rast_is_d_null_value(&d_h0)) {
		Rast_set_d_null_value(&outrast1[col], 1);
		if (makin) 
		    Rast_set_d_null_value(&outrast2[col], 1);
	    }
	    else {
                /* calculate evaporative fraction       */ 
                d = evap_fr(d_rnet, d_g0, d_h0);
		outrast1[col] = d;
                /* calculate soil moisture              */ 
                if (makin) 
                {
                    d = soilmoisture(d);
                    outrast2[col] = d;
		}
	    }
        }
	Rast_put_d_row(outfd1, outrast1);
	if (makin) 
            Rast_put_d_row(outfd2, outrast2);
    }
    G_free(inrast_rnet);
    G_free(inrast_g0);
    G_free(inrast_h0);
    Rast_close(infd_rnet);
    Rast_close(infd_g0);
    Rast_close(infd_h0);
    G_free(outrast1);
    Rast_close(outfd1);
    if (makin) {
        G_free(outrast2);
	Rast_close(outfd2);
    }
    Rast_short_history(result1, "raster", &history);
    Rast_command_history(&history);
    Rast_write_history(result1, &history);
    if (makin) {
	Rast_short_history(result2, "raster", &history);
	Rast_command_history(&history);
	Rast_write_history(result2, &history);
    }

    exit(EXIT_SUCCESS);
}
예제 #27
0
int camera_angle(char *name)
{
    int row, col, nrows, ncols;
    double XC = group.XC;
    double YC = group.YC;
    double ZC = group.ZC;
    double c_angle, c_angle_min, c_alt, c_az, slope, aspect;
    double radians_to_degrees = 180.0 / M_PI;
    /* double degrees_to_radians = M_PI / 180.0; */
    DCELL e1, e2, e3, e4, e5, e6, e7, e8, e9;
    double factor, V, H, dx, dy, dz, key;
    double north, south, east, west, ns_med;
    FCELL *fbuf0, *fbuf1, *fbuf2, *tmpbuf, *outbuf;
    int elevfd, outfd;
    struct Cell_head cellhd;
    struct Colors colr;
    FCELL clr_min, clr_max;
    struct History hist;
    char *type;

    G_message(_("Calculating camera angle to local surface..."));
    
    select_target_env();
    
    /* align target window to elevation map, otherwise we get artefacts
     * like in r.slope.aspect -a */
     
    Rast_get_cellhd(elev_name, elev_mapset, &cellhd);

    Rast_align_window(&target_window, &cellhd);
    Rast_set_window(&target_window);
    
    elevfd = Rast_open_old(elev_name, elev_mapset);
    if (elevfd < 0) {
	G_fatal_error(_("Could not open elevation raster"));
	return 1;
    }

    nrows = target_window.rows;
    ncols = target_window.cols;
    
    outfd = Rast_open_new(name, FCELL_TYPE);
    fbuf0 = Rast_allocate_buf(FCELL_TYPE);
    fbuf1 = Rast_allocate_buf(FCELL_TYPE);
    fbuf2 = Rast_allocate_buf(FCELL_TYPE);
    outbuf = Rast_allocate_buf(FCELL_TYPE);
    
    /* give warning if location units are different from meters and zfactor=1 */
    factor = G_database_units_to_meters_factor();
    if (factor != 1.0)
	G_warning(_("Converting units to meters, factor=%.6f"), factor);

    G_begin_distance_calculations();
    north = Rast_row_to_northing(0.5, &target_window);
    ns_med = Rast_row_to_northing(1.5, &target_window);
    south = Rast_row_to_northing(2.5, &target_window);
    east = Rast_col_to_easting(2.5, &target_window);
    west = Rast_col_to_easting(0.5, &target_window);
    V = G_distance(east, north, east, south) * 4;
    H = G_distance(east, ns_med, west, ns_med) * 4;
    
    c_angle_min = 90;
    Rast_get_row(elevfd, fbuf1, 0, FCELL_TYPE);
    Rast_get_row(elevfd, fbuf2, 1, FCELL_TYPE);

    for (row = 0; row < nrows; row++) {
	G_percent(row, nrows, 2);
	
	Rast_set_null_value(outbuf, ncols, FCELL_TYPE);

	/* first and last row */
	if (row == 0 || row == nrows - 1) {
	    Rast_put_row(outfd, outbuf, FCELL_TYPE);
	    continue;
	}
	
	tmpbuf = fbuf0;
	fbuf0 = fbuf1;
	fbuf1 = fbuf2;
	fbuf2 = tmpbuf;
	
	Rast_get_row(elevfd, fbuf2, row + 1, FCELL_TYPE);

	north = Rast_row_to_northing(row + 0.5, &target_window);

	for (col = 1; col < ncols - 1; col++) {
	    
	    e1 = fbuf0[col - 1];
	    if (Rast_is_d_null_value(&e1))
		continue;
	    e2 = fbuf0[col];
	    if (Rast_is_d_null_value(&e2))
		continue;
	    e3 = fbuf0[col + 1];
	    if (Rast_is_d_null_value(&e3))
		continue;
	    e4 = fbuf1[col - 1];
	    if (Rast_is_d_null_value(&e4))
		continue;
	    e5 = fbuf1[col];
	    if (Rast_is_d_null_value(&e5))
		continue;
	    e6 = fbuf1[col + 1];
	    if (Rast_is_d_null_value(&e6))
		continue;
	    e7 = fbuf2[col - 1];
	    if (Rast_is_d_null_value(&e7))
		continue;
	    e8 = fbuf2[col];
	    if (Rast_is_d_null_value(&e8))
		continue;
	    e9 = fbuf2[col + 1];
	    if (Rast_is_d_null_value(&e9))
		continue;
	    
	    dx = ((e1 + e4 + e4 + e7) - (e3 + e6 + e6 + e9)) / H;
	    dy = ((e7 + e8 + e8 + e9) - (e1 + e2 + e2 + e3)) / V;
	    
	    /* compute topographic parameters */
	    key = dx * dx + dy * dy;
	    /* slope in radians */
	    slope = atan(sqrt(key));

	    /* aspect in radians */
	    if (key == 0.)
		aspect = 0.;
	    else if (dx == 0) {
		if (dy > 0)
		    aspect = M_PI / 2;
		else
		    aspect = 1.5 * M_PI;
	    }
	    else {
		aspect = atan2(dy, dx);
		if (aspect <= 0.)
		    aspect = 2 * M_PI + aspect;
	    }
	    
	    /* camera altitude angle in radians */
	    east = Rast_col_to_easting(col + 0.5, &target_window);
	    dx = east - XC;
	    dy = north - YC;
	    dz = ZC - e5;
	    c_alt = atan(sqrt(dx * dx + dy * dy) / dz);

	    /* camera azimuth angle in radians */
	    c_az = atan(dy / dx);
	    if (east < XC && north != YC)
		c_az += M_PI;
	    else if (north < YC && east > XC)
		c_az += 2 * M_PI;
		
	    /* camera angle to real ground */
	    /* orthogonal to ground: 90 degrees */
	    /* parallel to ground: 0 degrees */
	    c_angle = asin(cos(c_alt) * cos(slope) - sin(c_alt) * sin(slope) * cos(c_az - aspect));
	    
	    outbuf[col] = c_angle * radians_to_degrees;
	    if (c_angle_min > outbuf[col])
		c_angle_min = outbuf[col];
	}
	Rast_put_row(outfd, outbuf, FCELL_TYPE);
    }
    G_percent(row, nrows, 2);

    Rast_close(elevfd);
    Rast_close(outfd);
    G_free(fbuf0);
    G_free(fbuf1);
    G_free(fbuf2);
    G_free(outbuf);

    type = "raster";
    Rast_short_history(name, type, &hist);
    Rast_command_history(&hist);
    Rast_write_history(name, &hist);
    
    Rast_init_colors(&colr);
    if (c_angle_min < 0) {
	clr_min = (FCELL)((int)(c_angle_min / 10 - 1)) * 10;
	clr_max = 0;
	Rast_add_f_color_rule(&clr_min, 0, 0, 0, &clr_max, 0,
				  0, 0, &colr);
    }
    clr_min = 0;
    clr_max = 10;
    Rast_add_f_color_rule(&clr_min, 0, 0, 0, &clr_max, 255,
			      0, 0, &colr);
    clr_min = 10;
    clr_max = 40;
    Rast_add_f_color_rule(&clr_min, 255, 0, 0, &clr_max, 255,
			      255, 0, &colr);
    clr_min = 40;
    clr_max = 90;
    Rast_add_f_color_rule(&clr_min, 255, 255, 0, &clr_max, 0,
			      255, 0, &colr);

    Rast_write_colors(name, G_mapset(), &colr);

    select_current_env();

    return 1;
}
예제 #28
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 *input, *input1, *input2, *input3, *input4, *input5, *output;
    struct History history;	/*metadata */
    struct Colors colors;	/*Color rules */

    /************************************/
    char *name, *name1, *name2;	/*input raster name */
    char *result;		/*output raster name */

    /*File Descriptors */
    int nfiles, nfiles1, nfiles2;
    int infd[MAXFILES], infd1[MAXFILES], infd2[MAXFILES];
    int outfd;

    /****************************************/
    /* Pointers for file names              */
    char **names;
    char **ptr;
    char **names1;
    char **ptr1;
    char **names2;
    char **ptr2;

    /****************************************/
    int DOYbeforeETa[MAXFILES], DOYafterETa[MAXFILES];
    int bfr, aft;

    /****************************************/
    int ok;
    int i = 0, j = 0;
    double etodoy;		/*minimum ETo DOY */
    double startperiod, endperiod;  /*first and last days (DOYs) of the period studied */
    void *inrast[MAXFILES], *inrast1[MAXFILES], *inrast2[MAXFILES];
    DCELL *outrast;
    CELL val1, val2;
    
    RASTER_MAP_TYPE in_data_type[MAXFILES];	/* ETa */
    RASTER_MAP_TYPE in_data_type1[MAXFILES];	/* DOY of ETa */
    RASTER_MAP_TYPE in_data_type2[MAXFILES];	/* ETo */
    RASTER_MAP_TYPE out_data_type = DCELL_TYPE;

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

    module = G_define_module();
    G_add_keyword(_("imagery"));
    G_add_keyword(_("evapotranspiration"));
    module->description =_("Computes temporal integration of satellite "
			   "ET actual (ETa) following the daily ET reference "
			   "(ETo) from meteorological station(s).");
    
    /* Define the different options */
    input = G_define_standard_option(G_OPT_R_INPUTS);
    input->key = "eta";
    input->description = _("Names of satellite ETa raster maps [mm/d or cm/d]");

    input1 = G_define_standard_option(G_OPT_R_INPUTS);
    input1->key = "eta_doy";
    input1->description =
	_("Names of satellite ETa Day of Year (DOY) raster maps [0-400] [-]");

    input2 = G_define_standard_option(G_OPT_R_INPUTS);
    input2->key = "eto";
    input2->description =
	_("Names of meteorological station ETo raster maps [0-400] [mm/d or cm/d]");

    input3 = G_define_option();
    input3->key = "eto_doy_min";
    input3->type = TYPE_DOUBLE;
    input3->required = YES;
    input3->description = _("Value of DOY for ETo first day");
    
    input4 = G_define_option();
    input4->key = "start_period";
    input4->type = TYPE_DOUBLE;
    input4->required = YES;
    input4->description = _("Value of DOY for the first day of the period studied");

    input5 = G_define_option();
    input5->key = "end_period";
    input5->type = TYPE_DOUBLE;
    input5->required = YES;
    input5->description = _("Value of DOY for the last day of the period studied");

    output = G_define_standard_option(G_OPT_R_OUTPUT);
    
    /* init nfiles */
    nfiles = 1;
    nfiles1 = 1;
    nfiles2 = 1;

    /********************/

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

    ok = 1;
    names = input->answers;
    ptr = input->answers;
    names1 = input1->answers;
    ptr1 = input1->answers;
    names2 = input2->answers;
    ptr2 = input2->answers;
    etodoy = atof(input3->answer);
    startperiod = atof(input4->answer);
    endperiod = atof(input5->answer);
    result = output->answer;

    /****************************************/
    if (endperiod<startperiod) {
	G_fatal_error(_("The DOY for end_period can not be smaller than start_period"));
	ok = 0;
    }
    if (etodoy>startperiod) {
	G_fatal_error(_("The DOY for start_period can not be smaller than eto_doy_min"));
	ok = 0;
    }
    for (; *ptr != NULL; ptr++) {
	if (nfiles > MAXFILES)
	    G_fatal_error(_("Too many ETa files. Only %d allowed."),
			  MAXFILES);
	name = *ptr;
	/* Allocate input buffer */
	infd[nfiles] = Rast_open_old(name, "");
	Rast_get_cellhd(name, "", &cellhd);
	inrast[nfiles] = Rast_allocate_d_buf();
	nfiles++;
    }
    nfiles--;
    if (nfiles <= 1)
	G_fatal_error(_("The min specified input map is two"));
	
	/****************************************/
    for (; *ptr1 != NULL; ptr1++) {
	if (nfiles1 > MAXFILES)
	    G_fatal_error(_("Too many ETa_doy files. Only %d allowed."),
			  MAXFILES);
	name1 = *ptr1;
	/* Allocate input buffer */
	infd1[nfiles1] = Rast_open_old(name1, "");
	Rast_get_cellhd(name1, "", &cellhd);
	inrast1[nfiles1] = Rast_allocate_d_buf();
	nfiles1++;
    }
    nfiles1--;
    if (nfiles1 <= 1)
	G_fatal_error(_("The min specified input map is two"));


	/****************************************/
    if (nfiles != nfiles1)
	G_fatal_error(_("ETa and ETa_DOY file numbers are not equal!"));

	/****************************************/

    for (; *ptr2 != NULL; ptr2++) {
	if (nfiles > MAXFILES)
	    G_fatal_error(_("Too many ETo files. Only %d allowed."),
			  MAXFILES);
	name2 = *ptr2;
	/* Allocate input buffer */
	infd2[nfiles2] = Rast_open_old(name2, "");
	Rast_get_cellhd(name2, "", &cellhd);
	inrast2[nfiles2] = Rast_allocate_d_buf();
	nfiles2++;
    }
    nfiles2--;
    if (nfiles2 <= 1)
	G_fatal_error(_("The min specified input map is two"));

    /* Allocate output buffer, use input map data_type */
    nrows = Rast_window_rows();
    ncols = Rast_window_cols();
    outrast = Rast_allocate_d_buf();

    /* Create New raster files */
    outfd = Rast_open_new(result, 1);

    /*******************/
    /* Process pixels */
    double doy[MAXFILES];
    double sum[MAXFILES];

    for (row = 0; row < nrows; row++) 
    {
	DCELL d_out;
	DCELL d_ETrF[MAXFILES];
	DCELL d[MAXFILES];
	DCELL d1[MAXFILES];
	DCELL d2[MAXFILES];
	G_percent(row, nrows, 2);

	/* read input map */
	for (i = 1; i <= nfiles; i++) 
	    Rast_get_d_row(infd[i], inrast[i], row);
	
	for (i = 1; i <= nfiles1; i++) 
	    Rast_get_d_row(infd1[i], inrast1[i], row);

	for (i = 1; i <= nfiles2; i++) 
	    Rast_get_d_row (infd2[i], inrast2[i], row);

	/*process the data */
	for (col = 0; col < ncols; col++) 
        {
            int	d1_null=0;
            int	d_null=0;
	    for (i = 1; i <= nfiles; i++) 
            {
		    if (Rast_is_d_null_value(&((DCELL *) inrast[i])[col]))
		    	d_null=1;
		    else
	                d[i] = ((DCELL *) inrast[i])[col];
	    }
	    for (i = 1; i <= nfiles1; i++) 
            {
		    if (Rast_is_d_null_value(&((DCELL *) inrast1[i])[col]))
			d1_null=1;
		    else
	                d1[i] = ((DCELL *) inrast1[i])[col];
	    }

	    for (i = 1; i <= nfiles2; i++) 
		    d2[i] = ((DCELL *) inrast2[i])[col];

	    /* Find out the DOY of the eto image    */
	    for (i = 1; i <= nfiles1; i++) 
            {
		if ( d_null==1 || d1_null==1 )
			Rast_set_d_null_value(&outrast[col],1);	
		else
		{
			doy[i] = d1[i] - etodoy+1;
			if (Rast_is_d_null_value(&d2[(int)doy[i]]) || d2[(int)doy[i]]==0 )
				Rast_set_d_null_value(&outrast[col],1);
			else
				d_ETrF[i] = d[i] / d2[(int)doy[i]];
		} 
	    }

	    for (i = 1; i <= nfiles1; i++) 
            {
		/* do nothing	*/
		if ( d_null==1 || d1_null==1)
                {
			/*G_message("  null value ");*/
                }
		else
		{
			DOYbeforeETa[i]=0; DOYafterETa[i]=0;
			if (i == 1)   
				DOYbeforeETa[i] = startperiod;
			else
			{
 				int k=i-1;
				while (d1[k]>=startperiod )
				{
					if (d1[k]<0)	 // case were d1[k] is null
						k=k-1;					
					else
					{
						DOYbeforeETa[i] = 1+((d1[i] + d1[k])/2.0);
						break;
					}			
				}

			}
	
			if (i == nfiles1)  
				DOYafterETa[i] = endperiod;
			else
			{
				int k=i+1;
				while (d1[k]<=endperiod)
				{
					if (d1[k]<0)   // case were d1[k] is null
						k=k+1;
					else
					{
						DOYafterETa[i] = (d1[i] + d1[k]) / 2.0;
						break;
	   				}					
				}
			}
		}	
	    }

	    sum[MAXFILES] = 0.0;
	    for (i = 1; i <= nfiles1; i++) 
            {
		if(d_null==1 || d1_null==1)
                {
		    /* do nothing	 */
		} 
                else
                {
			if (DOYbeforeETa[i]==0 || DOYbeforeETa[i]==0 ) 	
                            Rast_set_d_null_value(&outrast[col],1);
			else 
                        {
				bfr = (int)DOYbeforeETa[i];
				aft = (int)DOYafterETa[i];
				sum[i]=0.0;
				for (j = bfr; j < aft; j++) 
					sum[i] += d2[(int)(j-etodoy+1)];
			}
		}
	    }
	
	    d_out = 0.0;
	    for (i = 1; i <= nfiles1; i++)
            {
		if(d_null==1 || d_null==1)
			Rast_set_d_null_value(&outrast[col],1);
		else
                {	
			d_out += d_ETrF[i] * sum[i];
		     	outrast[col] = d_out;
		}	
	    }
	}
	Rast_put_row(outfd, outrast, out_data_type);
    }

    for (i = 1; i <= nfiles; i++) {
	G_free(inrast[i]);
	Rast_close(infd[i]);
    }
    for (i = 1; i <= nfiles1; i++) {
	G_free(inrast1[i]);
	Rast_close(infd1[i]);
    }
    for (i = 1; i <= nfiles2; i++) {
	G_free(inrast2[i]);
	Rast_close(infd2[i]);
    }
    G_free(outrast);
    Rast_close(outfd);

    /* Color table from 0.0 to 10.0 */
    Rast_init_colors(&colors);
    val1 = 0;
    val2 = 10;
    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);
}
예제 #29
0
int main(int argc, char **argv)
{
    char *mapname,		/* ptr to name of output layer  */
     *setname,			/* ptr to name of input mapset  */
     *ipolname;			/* name of interpolation method */

    int fdi,			/* input map file descriptor    */
      fdo,			/* output map file descriptor   */
      method,			/* position of method in table  */
      permissions,		/* mapset permissions           */
      cell_type,		/* output celltype              */
      cell_size,		/* size of a cell in bytes      */
      row, col,			/* counters                     */
      irows, icols,		/* original rows, cols          */
      orows, ocols, have_colors,	/* Input map has a colour table */
      overwrite,		/* Overwrite                    */
      curr_proj;		/* output projection (see gis.h) */

    void *obuffer,		/* buffer that holds one output row     */
     *obufptr;			/* column ptr in output buffer  */
    struct cache *ibuffer;	/* buffer that holds the input map      */
    func interpolate;		/* interpolation routine        */

    double xcoord1, xcoord2,	/* temporary x coordinates      */
      ycoord1, ycoord2,		/* temporary y coordinates      */
      col_idx,			/* column index in input matrix */
      row_idx,			/* row index in input matrix    */
      onorth, osouth,		/* save original border coords  */
      oeast, owest, inorth, isouth, ieast, iwest;
    char north_str[30], south_str[30], east_str[30], west_str[30];

    struct Colors colr;		/* Input map colour table       */
    struct History history;

    struct pj_info iproj,	/* input map proj parameters    */
      oproj;			/* output map proj parameters   */

    struct Key_Value *in_proj_info,	/* projection information of    */
     *in_unit_info,		/* input and output mapsets     */
     *out_proj_info, *out_unit_info;

    struct GModule *module;

    struct Flag *list,		/* list files in source location */
     *nocrop,			/* don't crop output map        */
     *print_bounds,		/* print output bounds and exit */
     *gprint_bounds;		/* same but print shell style	*/

    struct Option *imapset,	/* name of input mapset         */
     *inmap,			/* name of input layer          */
     *inlocation,		/* name of input location       */
     *outmap,			/* name of output layer         */
     *indbase,			/* name of input database       */
     *interpol,			/* interpolation method:
				   nearest neighbor, bilinear, cubic */
     *memory,			/* amount of memory for cache   */
     *res;			/* resolution of target map     */
    struct Cell_head incellhd,	/* cell header of input map     */
      outcellhd;		/* and output map               */


    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("raster"));
    G_add_keyword(_("projection"));
    G_add_keyword(_("transformation"));
    module->description =
	_("Re-projects a raster map from given location to the current location.");

    inmap = G_define_standard_option(G_OPT_R_INPUT);
    inmap->description = _("Name of input raster map to re-project");
    inmap->required = NO;
    inmap->guisection = _("Source");

    inlocation = G_define_option();
    inlocation->key = "location";
    inlocation->type = TYPE_STRING;
    inlocation->required = YES;
    inlocation->description = _("Location containing input raster map");
    inlocation->gisprompt = "old,location,location";
    inlocation->key_desc = "name";

    imapset = G_define_standard_option(G_OPT_M_MAPSET);
    imapset->label = _("Mapset containing input raster map");
    imapset->description = _("default: name of current mapset");
    imapset->guisection = _("Source");

    indbase = G_define_option();
    indbase->key = "dbase";
    indbase->type = TYPE_STRING;
    indbase->required = NO;
    indbase->description = _("Path to GRASS database of input location");
    indbase->gisprompt = "old,dbase,dbase";
    indbase->key_desc = "path";
    indbase->guisection = _("Source");

    outmap = G_define_standard_option(G_OPT_R_OUTPUT);
    outmap->required = NO;
    outmap->description = _("Name for output raster map (default: same as 'input')");
    outmap->guisection = _("Target");

    ipolname = make_ipol_list();
    
    interpol = G_define_option();
    interpol->key = "method";
    interpol->type = TYPE_STRING;
    interpol->required = NO;
    interpol->answer = "nearest";
    interpol->options = ipolname;
    interpol->description = _("Interpolation method to use");
    interpol->guisection = _("Target");
    interpol->descriptions = make_ipol_desc();

    memory = G_define_option();
    memory->key = "memory";
    memory->type = TYPE_INTEGER;
    memory->required = NO;
    memory->description = _("Cache size (MiB)");

    res = G_define_option();
    res->key = "resolution";
    res->type = TYPE_DOUBLE;
    res->required = NO;
    res->description = _("Resolution of output raster map");
    res->guisection = _("Target");

    list = G_define_flag();
    list->key = 'l';
    list->description = _("List raster maps in input location and exit");

    nocrop = G_define_flag();
    nocrop->key = 'n';
    nocrop->description = _("Do not perform region cropping optimization");

    print_bounds = G_define_flag();
    print_bounds->key = 'p';
    print_bounds->description =
	_("Print input map's bounds in the current projection and exit");
    print_bounds->guisection = _("Target");
    
    gprint_bounds = G_define_flag();
    gprint_bounds->key = 'g';
    gprint_bounds->description =
	_("Print input map's bounds in the current projection and exit (shell style)");
    gprint_bounds->guisection = _("Target");

    /* The parser checks if the map already exists in current mapset,
       we switch out the check and do it
       in the module after the parser */
    overwrite = G_check_overwrite(argc, argv);

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


    /* get the method */
    for (method = 0; (ipolname = menu[method].name); method++)
	if (strcmp(ipolname, interpol->answer) == 0)
	    break;

    if (!ipolname)
	G_fatal_error(_("<%s=%s> unknown %s"),
		      interpol->key, interpol->answer, interpol->key);
    interpolate = menu[method].method;

    mapname = outmap->answer ? outmap->answer : inmap->answer;
    if (mapname && !list->answer && !overwrite &&
	G_find_raster(mapname, G_mapset()))
	G_fatal_error(_("option <%s>: <%s> exists."), "output", mapname);

    setname = imapset->answer ? imapset->answer : G_store(G_mapset());
    if (strcmp(inlocation->answer, G_location()) == 0 &&
        (!indbase->answer || strcmp(indbase->answer, G_gisdbase()) == 0))
#if 0
	G_fatal_error(_("Input and output locations can not be the same"));
#else
	G_warning(_("Input and output locations are the same"));
#endif
    G_get_window(&outcellhd);

    if(gprint_bounds->answer && !print_bounds->answer)
	print_bounds->answer = gprint_bounds->answer;
    curr_proj = G_projection();

    /* Get projection info for output mapset */
    if ((out_proj_info = G_get_projinfo()) == NULL)
	G_fatal_error(_("Unable to get projection info of output raster map"));

    if ((out_unit_info = G_get_projunits()) == NULL)
	G_fatal_error(_("Unable to get projection units of output raster map"));

    if (pj_get_kv(&oproj, out_proj_info, out_unit_info) < 0)
	G_fatal_error(_("Unable to get projection key values of output raster map"));

    /* Change the location           */
    G__create_alt_env();
    G__setenv("GISDBASE", indbase->answer ? indbase->answer : G_gisdbase());
    G__setenv("LOCATION_NAME", inlocation->answer);

    permissions = G__mapset_permissions(setname);
    if (permissions < 0)	/* can't access mapset       */
	G_fatal_error(_("Mapset <%s> in input location <%s> - %s"),
		      setname, inlocation->answer,
		      permissions == 0 ? _("permission denied")
		      : _("not found"));

    /* if requested, list the raster maps in source location - MN 5/2001 */
    if (list->answer) {
	int i;
	char **list;
	G_verbose_message(_("Checking location <%s> mapset <%s>"),
			  inlocation->answer, setname);
	list = G_list(G_ELEMENT_RASTER, G__getenv("GISDBASE"),
		      G__getenv("LOCATION_NAME"), setname);
	for (i = 0; list[i]; i++) {
	    fprintf(stdout, "%s\n", list[i]);
	}
	fflush(stdout);
	exit(EXIT_SUCCESS);	/* leave r.proj after listing */
    }

    if (!inmap->answer)
	G_fatal_error(_("Required parameter <%s> not set"), inmap->key);

    if (!G_find_raster(inmap->answer, setname))
	G_fatal_error(_("Raster map <%s> in location <%s> in mapset <%s> not found"),
		      inmap->answer, inlocation->answer, setname);

    /* Read input map colour table */
    have_colors = Rast_read_colors(inmap->answer, setname, &colr);

    /* Get projection info for input mapset */
    if ((in_proj_info = G_get_projinfo()) == NULL)
	G_fatal_error(_("Unable to get projection info of input map"));

    if ((in_unit_info = G_get_projunits()) == NULL)
	G_fatal_error(_("Unable to get projection units of input map"));

    if (pj_get_kv(&iproj, in_proj_info, in_unit_info) < 0)
	G_fatal_error(_("Unable to get projection key values of input map"));

    G_free_key_value(in_proj_info);
    G_free_key_value(in_unit_info);
    G_free_key_value(out_proj_info);
    G_free_key_value(out_unit_info);
    if (G_verbose() > G_verbose_std())
	pj_print_proj_params(&iproj, &oproj);

    /* this call causes r.proj to read the entire map into memeory */
    Rast_get_cellhd(inmap->answer, setname, &incellhd);

    Rast_set_input_window(&incellhd);

    if (G_projection() == PROJECTION_XY)
	G_fatal_error(_("Unable to work with unprojected data (xy location)"));

    /* Save default borders so we can show them later */
    inorth = incellhd.north;
    isouth = incellhd.south;
    ieast = incellhd.east;
    iwest = incellhd.west;
    irows = incellhd.rows;
    icols = incellhd.cols;

    onorth = outcellhd.north;
    osouth = outcellhd.south;
    oeast = outcellhd.east;
    owest = outcellhd.west;
    orows = outcellhd.rows;
    ocols = outcellhd.cols;


    if (print_bounds->answer) {
	G_message(_("Input map <%s@%s> in location <%s>:"),
	    inmap->answer, setname, inlocation->answer);

	if (pj_do_proj(&iwest, &isouth, &iproj, &oproj) < 0)
	    G_fatal_error(_("Error in pj_do_proj (projection of input coordinate pair)"));
	if (pj_do_proj(&ieast, &inorth, &iproj, &oproj) < 0)
	    G_fatal_error(_("Error in pj_do_proj (projection of input coordinate pair)"));

	G_format_northing(inorth, north_str, curr_proj);
	G_format_northing(isouth, south_str, curr_proj);
	G_format_easting(ieast, east_str, curr_proj);
	G_format_easting(iwest, west_str, curr_proj);

	if(gprint_bounds->answer) {
	    fprintf(stdout, "n=%s s=%s w=%s e=%s rows=%d cols=%d\n",
		north_str, south_str, west_str, east_str, irows, icols);
	}
	else {
	    fprintf(stdout, "Source cols: %d\n", icols);
	    fprintf(stdout, "Source rows: %d\n", irows);
	    fprintf(stdout, "Local north: %s\n",  north_str);
	    fprintf(stdout, "Local south: %s\n", south_str);
	    fprintf(stdout, "Local west: %s\n", west_str);
	    fprintf(stdout, "Local east: %s\n", east_str);
	}

	/* somehow approximate local ewres, nsres ?? (use 'g.region -m' on lat/lon side) */

	exit(EXIT_SUCCESS);
    }


    /* Cut non-overlapping parts of input map */
    if (!nocrop->answer)
	bordwalk(&outcellhd, &incellhd, &oproj, &iproj);

    /* Add 2 cells on each side for bilinear/cubic & future interpolation methods */
    /* (should probably be a factor based on input and output resolution) */
    incellhd.north += 2 * incellhd.ns_res;
    incellhd.east += 2 * incellhd.ew_res;
    incellhd.south -= 2 * incellhd.ns_res;
    incellhd.west -= 2 * incellhd.ew_res;
    if (incellhd.north > inorth)
	incellhd.north = inorth;
    if (incellhd.east > ieast)
	incellhd.east = ieast;
    if (incellhd.south < isouth)
	incellhd.south = isouth;
    if (incellhd.west < iwest)
	incellhd.west = iwest;

    Rast_set_input_window(&incellhd);

    /* And switch back to original location */

    G__switch_env();

    /* Adjust borders of output map */

    if (!nocrop->answer)
	bordwalk(&incellhd, &outcellhd, &iproj, &oproj);

#if 0
    outcellhd.west = outcellhd.south = HUGE_VAL;
    outcellhd.east = outcellhd.north = -HUGE_VAL;
    for (row = 0; row < incellhd.rows; row++) {
	ycoord1 = Rast_row_to_northing((double)(row + 0.5), &incellhd);
	for (col = 0; col < incellhd.cols; col++) {
	    xcoord1 = Rast_col_to_easting((double)(col + 0.5), &incellhd);
	    pj_do_proj(&xcoord1, &ycoord1, &iproj, &oproj);
	    if (xcoord1 > outcellhd.east)
		outcellhd.east = xcoord1;
	    if (ycoord1 > outcellhd.north)
		outcellhd.north = ycoord1;
	    if (xcoord1 < outcellhd.west)
		outcellhd.west = xcoord1;
	    if (ycoord1 < outcellhd.south)
		outcellhd.south = ycoord1;
	}
    }
#endif

    if (res->answer != NULL)	/* set user defined resolution */
	outcellhd.ns_res = outcellhd.ew_res = atof(res->answer);

    G_adjust_Cell_head(&outcellhd, 0, 0);
    Rast_set_output_window(&outcellhd);

    G_message(" ");
    G_message(_("Input:"));
    G_message(_("Cols: %d (%d)"), incellhd.cols, icols);
    G_message(_("Rows: %d (%d)"), incellhd.rows, irows);
    G_message(_("North: %f (%f)"), incellhd.north, inorth);
    G_message(_("South: %f (%f)"), incellhd.south, isouth);
    G_message(_("West: %f (%f)"), incellhd.west, iwest);
    G_message(_("East: %f (%f)"), incellhd.east, ieast);
    G_message(_("EW-res: %f"), incellhd.ew_res);
    G_message(_("NS-res: %f"), incellhd.ns_res);
    G_message(" ");

    G_message(_("Output:"));
    G_message(_("Cols: %d (%d)"), outcellhd.cols, ocols);
    G_message(_("Rows: %d (%d)"), outcellhd.rows, orows);
    G_message(_("North: %f (%f)"), outcellhd.north, onorth);
    G_message(_("South: %f (%f)"), outcellhd.south, osouth);
    G_message(_("West: %f (%f)"), outcellhd.west, owest);
    G_message(_("East: %f (%f)"), outcellhd.east, oeast);
    G_message(_("EW-res: %f"), outcellhd.ew_res);
    G_message(_("NS-res: %f"), outcellhd.ns_res);
    G_message(" ");

    /* open and read the relevant parts of the input map and close it */
    G__switch_env();
    Rast_set_input_window(&incellhd);
    fdi = Rast_open_old(inmap->answer, setname);
    cell_type = Rast_get_map_type(fdi);
    ibuffer = readcell(fdi, memory->answer);
    Rast_close(fdi);

    G__switch_env();
    Rast_set_output_window(&outcellhd);

    if (strcmp(interpol->answer, "nearest") == 0) {
	fdo = Rast_open_new(mapname, cell_type);
	obuffer = (CELL *) Rast_allocate_output_buf(cell_type);
    }
    else {
	fdo = Rast_open_fp_new(mapname);
	cell_type = FCELL_TYPE;
	obuffer = (FCELL *) Rast_allocate_output_buf(cell_type);
    }

    cell_size = Rast_cell_size(cell_type);

    xcoord1 = xcoord2 = outcellhd.west + (outcellhd.ew_res / 2);
    /**/ ycoord1 = ycoord2 = outcellhd.north - (outcellhd.ns_res / 2);
    /**/ G_important_message(_("Projecting..."));
    G_percent(0, outcellhd.rows, 2);

    for (row = 0; row < outcellhd.rows; row++) {
	obufptr = obuffer;

	for (col = 0; col < outcellhd.cols; col++) {
	    /* project coordinates in output matrix to       */
	    /* coordinates in input matrix                   */
	    if (pj_do_proj(&xcoord1, &ycoord1, &oproj, &iproj) < 0)
		Rast_set_null_value(obufptr, 1, cell_type);
	    else {
		/* convert to row/column indices of input matrix */
		col_idx = (xcoord1 - incellhd.west) / incellhd.ew_res;
		row_idx = (incellhd.north - ycoord1) / incellhd.ns_res;

		/* and resample data point               */
		interpolate(ibuffer, obufptr, cell_type,
			    &col_idx, &row_idx, &incellhd);
	    }

	    obufptr = G_incr_void_ptr(obufptr, cell_size);
	    xcoord2 += outcellhd.ew_res;
	    xcoord1 = xcoord2;
	    ycoord1 = ycoord2;
	}

	Rast_put_row(fdo, obuffer, cell_type);

	xcoord1 = xcoord2 = outcellhd.west + (outcellhd.ew_res / 2);
	ycoord2 -= outcellhd.ns_res;
	ycoord1 = ycoord2;
	G_percent(row, outcellhd.rows - 1, 2);
    }

    Rast_close(fdo);

    if (have_colors > 0) {
	Rast_write_colors(mapname, G_mapset(), &colr);
	Rast_free_colors(&colr);
    }

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

    G_done_msg(NULL);
    exit(EXIT_SUCCESS);
}
예제 #30
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);
}