Esempio n. 1
0
/* ************************************************************************* */
void set_params(void)
{
    param.phead =  G_define_standard_option(G_OPT_R_INPUT);
    param.phead->key = "phead";
    param.phead->description = _("The initial piezometric head in [m]");

    param.status =  G_define_standard_option(G_OPT_R_INPUT);
    param.status->key = "status";
    param.status->description =
	_("Boundary condition status, 0-inactive, 1-active, 2-dirichlet");

    param.hc_x =  G_define_standard_option(G_OPT_R_INPUT);
    param.hc_x->key = "hc_x";
    param.hc_x->description =
	_("X-part of the hydraulic conductivity tensor in [m/s]");

    param.hc_y =  G_define_standard_option(G_OPT_R_INPUT);
    param.hc_y->key = "hc_y";
    param.hc_y->description =
	_("Y-part of the hydraulic conductivity tensor in [m/s]");

    param.q =  G_define_standard_option(G_OPT_R_INPUT);
    param.q->key = "q";
    param.q->required = NO;
    param.q->description = _("Water sources and sinks in [m^3/s]");

    param.s =  G_define_standard_option(G_OPT_R_INPUT);
    param.s->key = "s";
    param.s->description = _("Specific yield in [1/m]");

    param.r =  G_define_standard_option(G_OPT_R_INPUT);
    param.r->key = "r";
    param.r->required = NO;
    param.r->guisection = _("Recharge");
    param.r->description =
	_("Recharge map e.g: 6*10^-9 per cell in [m^3/s*m^2]");

    param.top =  G_define_standard_option(G_OPT_R_INPUT);
    param.top->key = "top";
    param.top->description = _("Top surface of the aquifer in [m]");

    param.bottom =  G_define_standard_option(G_OPT_R_INPUT);
    param.bottom->key = "bottom";
    param.bottom->description = _("Bottom surface of the aquifer in [m]");

    param.output =  G_define_standard_option(G_OPT_R_OUTPUT);
    param.output->key = "output";
    param.output->description = _("The map storing the numerical result [m]");

    param.vector = G_define_standard_option(G_OPT_R_OUTPUT);
    param.vector->key = "velocity";
    param.vector->required = NO;
    param.vector->description =
	_("Calculate the groundwater filter velocity vector field [m/s]\n"
	  "and write the x, and y components to maps named name_[xy]");

    param.type = G_define_option();
    param.type->key = "type";
    param.type->type = TYPE_STRING;
    param.type->required = NO;
    param.type->answer = "confined";
    param.type->options = "confined,unconfined";
    param.type->description = _("The type of groundwater flow");

    /*Variants of the cauchy boundary condition */
    param.river_bed =  G_define_standard_option(G_OPT_R_INPUT);
    param.river_bed->key = "river_bed";
    param.river_bed->guisection = "River";
    param.river_bed->required = NO;
    param.river_bed->description = _("The height of the river bed in [m]");

    param.river_head =  G_define_standard_option(G_OPT_R_INPUT);
    param.river_head->key = "river_head";
    param.river_head->guisection = "River";
    param.river_head->required = NO;
    param.river_head->description =
	_("Water level (head) of the river with leakage connection in [m]");

    param.river_leak =  G_define_standard_option(G_OPT_R_INPUT);
    param.river_leak->key = "river_leak";
    param.river_leak->guisection = "River";
    param.river_leak->required = NO;
    param.river_leak->description =
	_("The leakage coefficient of the river bed in [1/s].");

    param.drain_bed =  G_define_standard_option(G_OPT_R_INPUT);
    param.drain_bed->key = "drain_bed";;
    param.drain_bed->guisection = "Drainage";
    param.drain_bed->required = NO;
    param.drain_bed->description = _("The height of the drainage bed in [m]");

    param.drain_leak =  G_define_standard_option(G_OPT_R_INPUT);
    param.drain_leak->key = "drain_leak";
    param.drain_leak->guisection = "Drainage";
    param.drain_leak->required = NO;
    param.drain_leak->description =
	_("The leakage coefficient of the drainage bed in [1/s]");

    param.dt = N_define_standard_option(N_OPT_CALC_TIME);
    param.maxit = N_define_standard_option(N_OPT_MAX_ITERATIONS);
    param.error = N_define_standard_option(N_OPT_ITERATION_ERROR);
    param.solver = N_define_standard_option(N_OPT_SOLVER_SYMM);
    param.sor = N_define_standard_option(N_OPT_SOR_VALUE);

    param.sparse = G_define_flag();
    param.sparse->key = 's';
    param.sparse->guisection = "Solver";
    param.sparse->description =
	_("Use a sparse matrix, only available with iterative solvers");

}
Esempio n. 2
0
int main(int argc, char *argv[])
{
    void *raster, *ptr;

    /*
       char  *null_row;
     */
    RASTER_MAP_TYPE out_type, map_type;
    char *outfile;
    char null_str[80];
    char cell_buf[300];
    int fd;
    int row, col;
    int nrows, ncols, dp;
    int do_stdout;
    FILE *fp;
    double cellsize;
    struct GModule *module;
    struct
    {
	struct Option *map;
	struct Option *output;
	struct Option *dp;
	struct Option *null;
    } parm;
    struct
    {
	struct Flag *noheader;
	struct Flag *singleline;
	struct Flag *ccenter;
    } flag;

    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("raster"));
    G_add_keyword(_("export"));
    module->description =
	_("Converts a raster map layer into an ESRI ARCGRID file.");

    /* Define the different options */
    parm.map = G_define_standard_option(G_OPT_R_INPUT);

    parm.output = G_define_standard_option(G_OPT_R_OUTPUT);
    parm.output->gisprompt = "new_file,file,output";
    parm.output->description =
	_("Name of an output ARC-GRID map (use out=- for stdout)");

    parm.dp = G_define_option();
    parm.dp->key = "dp";
    parm.dp->type = TYPE_INTEGER;
    parm.dp->required = NO;
    parm.dp->answer = "8";
    parm.dp->description = _("Number of decimal places");

    flag.noheader = G_define_flag();
    flag.noheader->key = 'h';
    flag.noheader->description = _("Suppress printing of header information");

    /* Added to optionally produce a single line output.     -- emes -- 12.10.92 */
    flag.singleline = G_define_flag();
    flag.singleline->key = '1';
    flag.singleline->description =
	_("List one entry per line instead of full row");

    /* use cell center in header instead of cell corner */
    flag.ccenter = G_define_flag();
    flag.ccenter->key = 'c';
    flag.ccenter->description =
	_("Use cell center reference in header instead of cell corner");

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


    sscanf(parm.dp->answer, "%d", &dp);
    if (dp > 20 || dp < 0)
	G_fatal_error("dp has to be from 0 to 20");

    outfile = parm.output->answer;
    if ((strcmp("-", outfile)) == 0)
	do_stdout = 1;
    else
	do_stdout = 0;

    sprintf(null_str, "-9999");

    fd = Rast_open_old(parm.map->answer, "");

    map_type = Rast_get_map_type(fd);
    out_type = map_type;

    /*
       null_row = Rast_allocate_null_buf();
     */
    raster = Rast_allocate_buf(out_type);

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

    /* open arc file for writing */
    if (do_stdout)
	fp = stdout;
    else if (NULL == (fp = fopen(outfile, "w")))
	G_fatal_error(_("Unable to open file <%s>"), outfile);

    if (!flag.noheader->answer) {
	struct Cell_head region;
	char buf[128];

	G_get_window(&region);
	fprintf(fp, "ncols %d\n", region.cols);
	fprintf(fp, "nrows %d\n", region.rows);
	cellsize = fabs(region.east - region.west) / region.cols;

	if (G_projection() != PROJECTION_LL) {	/* Is Projection != LL (3) */
	    if (!flag.ccenter->answer) {
		G_format_easting(region.west, buf, region.proj);
		fprintf(fp, "xllcorner %s\n", buf);
		G_format_northing(region.south, buf, region.proj);
		fprintf(fp, "yllcorner %s\n", buf);
	    }
	    else {
		G_format_easting(region.west + cellsize / 2., buf, region.proj);
		fprintf(fp, "xllcenter %s\n", buf);
		G_format_northing(region.south + cellsize / 2., buf, region.proj);
		fprintf(fp, "yllcenter %s\n", buf);
	    }
	}
	else {			/* yes, lat/long */
	    fprintf(fp, "xllcorner %f\n", region.west);
	    fprintf(fp, "yllcorner %f\n", region.south);
	}

	fprintf(fp, "cellsize %f\n", cellsize);
	fprintf(fp, "NODATA_value %s\n", null_str);
    }

    for (row = 0; row < nrows; row++) {
	G_percent(row, nrows, 2);
	Rast_get_row(fd, raster, row, out_type);
	/*
	   Rast_get_null_value_row(fd, null_row, row);
	 */
	for (col = 0, ptr = raster; col < ncols; col++,
	     ptr = G_incr_void_ptr(ptr, Rast_cell_size(out_type))) {
	    if (!Rast_is_null_value(ptr, out_type)) {
		if (out_type == CELL_TYPE)
		    fprintf(fp, "%d", *((CELL *) ptr));

		else if (out_type == FCELL_TYPE) {
		    sprintf(cell_buf, "%.*f", dp, *((FCELL *) ptr));
		    G_trim_decimal(cell_buf);
		    fprintf(fp, "%s", cell_buf);
		}
		else if (out_type == DCELL_TYPE) {
		    sprintf(cell_buf, "%.*f", dp, *((DCELL *) ptr));
		    G_trim_decimal(cell_buf);
		    fprintf(fp, "%s", cell_buf);
		}
	    }
	    else
		fprintf(fp, "%s", null_str);

	    if (!flag.singleline->answer)
		fprintf(fp, " ");
	    else
		fprintf(fp, "\n");
	}

	if (!flag.singleline->answer)
	    fprintf(fp, "\n");

	/*
	   for (col = 0; col < ncols; col++)
	   fprintf (fp,"%d ", null_row[col]);
	   fprintf (fp,"\n");
	 */
    }

    /* make sure it got to 100% */
    G_percent(1, 1, 2);

    Rast_close(fd);
    fclose(fp);

    exit(EXIT_SUCCESS);
}
Esempio n. 3
0
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);

}
Esempio n. 4
0
int main(int argc, char *argv[])
{
    struct GModule *module;
    struct Option *group_opt,
		  *xc_opt, *yc_opt, *zc_opt,
		  *xcsd_opt, *ycsd_opt, *zcsd_opt,
		  *omega_opt, *phi_opt, *kappa_opt,
		  *omegasd_opt, *phisd_opt, *kappasd_opt;
    struct Flag *use_flag, *print_flag;

    struct Ortho_Image_Group group;
    struct Ortho_Camera_Exp_Init *init_info;
    double deg2rad, rad2deg;

    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("imagery"));
    G_add_keyword(_("orthorectify"));
    module->description =
	_("Interactively creates or modifies entries in a camera "
	  "initial exposure station file for imagery group referenced "
	  "by a sub-block.");

    group_opt = G_define_standard_option(G_OPT_I_GROUP);
    group_opt->required = YES;
    group_opt->description =
	_("Name of imagery group for ortho-rectification");

    xc_opt = G_define_option();
    xc_opt->key = "xc";
    xc_opt->type = TYPE_DOUBLE;
    xc_opt->description = _("Initial Camera Exposure X-coordinate");

    yc_opt = G_define_option();
    yc_opt->key = "yc";
    yc_opt->type = TYPE_DOUBLE;
    yc_opt->description = _("Initial Camera Exposure Y-coordinate");

    zc_opt = G_define_option();
    zc_opt->key = "zc";
    zc_opt->type = TYPE_DOUBLE;
    zc_opt->description = _("Initial Camera Exposure Z-coordinate");

    xcsd_opt = G_define_option();
    xcsd_opt->key = "xc_sd";
    xcsd_opt->type = TYPE_DOUBLE;
    xcsd_opt->description = _("X-coordinate standard deviation");

    ycsd_opt = G_define_option();
    ycsd_opt->key = "yc_sd";
    ycsd_opt->type = TYPE_DOUBLE;
    ycsd_opt->description = _("Y-coordinate standard deviation");

    zcsd_opt = G_define_option();
    zcsd_opt->key = "zc_sd";
    zcsd_opt->type = TYPE_DOUBLE;
    zcsd_opt->description = _("Z-coordinate standard deviation");
    
    omega_opt = G_define_option();
    omega_opt->key = "omega";
    omega_opt->type = TYPE_DOUBLE;
    omega_opt->description = _("Initial Camera Omega (roll) degrees");

    phi_opt = G_define_option();
    phi_opt->key = "omega";
    phi_opt->type = TYPE_DOUBLE;
    phi_opt->description = _("Initial Camera Phi (pitch) degrees");

    kappa_opt = G_define_option();
    kappa_opt->key = "omega";
    kappa_opt->type = TYPE_DOUBLE;
    kappa_opt->description = _("Initial Camera Kappa (yaw) degrees");

    omegasd_opt = G_define_option();
    omegasd_opt->key = "omega";
    omegasd_opt->type = TYPE_DOUBLE;
    omegasd_opt->description = _("Omega (roll) standard deviation");

    phisd_opt = G_define_option();
    phisd_opt->key = "omega";
    phisd_opt->type = TYPE_DOUBLE;
    phisd_opt->description = _("Phi (pitch) standard deviation");

    kappasd_opt = G_define_option();
    kappasd_opt->key = "omega";
    kappasd_opt->type = TYPE_DOUBLE;
    kappasd_opt->description = _("Kappa (yaw) standard deviation");

    use_flag = G_define_flag();
    use_flag->key = 'r';
    use_flag->description = _("Use initial values at run time");

    print_flag = G_define_flag();
    print_flag->key = 'p';
    print_flag->description = _("Print initial values");

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

    deg2rad = M_PI / 180.;
    rad2deg = 180. / M_PI;

    /* get group ref */
    strcpy(group.name, group_opt->answer);

    if (!I_find_group(group.name)) {
	G_fatal_error(_("Group [%s] not found"), group.name);
    }
    G_debug(1, "Found group %s", group.name);

    /* get initial camera exposure info */
    if (I_find_initial(group.name)) {
	I_get_init_info(group.name, &group.camera_exp);
    }
    else {
	/* create new initial camera exposure info */
	
	/* all values must be given */
	if (!xc_opt->answer) {
	    G_fatal_error(_("Option '%s' is required for new exposure info"),
			    xc_opt->key);
	}
	if (!yc_opt->answer) {
	    G_fatal_error(_("Option '%s' is required for new exposure info"),
			    yc_opt->key);
	}
	if (!zc_opt->answer) {
	    G_fatal_error(_("Option '%s' is required for new exposure info"),
			    zc_opt->key);
	}
	if (!xcsd_opt->answer) {
	    G_fatal_error(_("Option '%s' is required for new exposure info"),
			    xcsd_opt->key);
	}
	if (!ycsd_opt->answer) {
	    G_fatal_error(_("Option '%s' is required for new exposure info"),
			    ycsd_opt->key);
	}
	if (!zcsd_opt->answer) {
	    G_fatal_error(_("Option '%s' is required for new exposure info"),
			    zcsd_opt->key);
	}
	if (!omega_opt->answer) {
	    G_fatal_error(_("Option '%s' is required for new exposure info"),
			    omega_opt->key);
	}
	if (!phi_opt->answer) {
	    G_fatal_error(_("Option '%s' is required for new exposure info"),
			    phi_opt->key);
	}
	if (!kappa_opt->answer) {
	    G_fatal_error(_("Option '%s' is required for new exposure info"),
			    kappa_opt->key);
	}
	if (!omegasd_opt->answer) {
	    G_fatal_error(_("Option '%s' is required for new exposure info"),
			    omegasd_opt->key);
	}
	if (!phisd_opt->answer) {
	    G_fatal_error(_("Option '%s' is required for new exposure info"),
			    phisd_opt->key);
	}
	if (!kappasd_opt->answer) {
	    G_fatal_error(_("Option '%s' is required for new exposure info"),
			    kappasd_opt->key);
	}
    }

    /* modify info */
    init_info = &group.camera_exp;

    if (xc_opt->answer) {
	init_info->XC_init = atof(xc_opt->answer);
    }
    if (yc_opt->answer) {
	init_info->YC_init = atof(yc_opt->answer);
    }
    if (zc_opt->answer) {
	init_info->ZC_init = atof(zc_opt->answer);
    }
    if (xcsd_opt->answer) {
	init_info->XC_var = atof(xcsd_opt->answer);
    }
    if (ycsd_opt->answer) {
	init_info->YC_var = atof(ycsd_opt->answer);
    }
    if (zcsd_opt->answer) {
	init_info->ZC_var = atof(zcsd_opt->answer);
    }
    if (omega_opt->answer) {
	init_info->omega_init = atof(omega_opt->answer) * deg2rad;
    }
    if (phi_opt->answer) {
	init_info->phi_init = atof(phi_opt->answer) * deg2rad;
    }
    if (kappa_opt->answer) {
	init_info->kappa_init = atof(kappa_opt->answer) * deg2rad;
    }
    if (omegasd_opt->answer) {
	init_info->omega_var = atof(omegasd_opt->answer) * deg2rad;
    }
    if (phisd_opt->answer) {
	init_info->phi_var = atof(phisd_opt->answer) * deg2rad;
    }
    if (kappasd_opt->answer) {
	init_info->kappa_var = atof(kappasd_opt->answer) * deg2rad;
    }
    init_info->status = use_flag->answer != 0;
    
    if (print_flag->answer) {
	/* do not translate, scripts might want to parse the output */
	fprintf(stdout, "xc=%.17g\n", init_info->XC_init);
	fprintf(stdout, "yc=%.17g\n", init_info->YC_init);
	fprintf(stdout, "zc=%.17g\n", init_info->ZC_init);
	fprintf(stdout, "xc_sd=%.17g\n", init_info->XC_var);
	fprintf(stdout, "yc_sd=%.17g\n", init_info->YC_var);
	fprintf(stdout, "zc_sd=%.17g\n", init_info->ZC_var);

	fprintf(stdout, "omega=%.17g\n", init_info->omega_init * rad2deg);
	fprintf(stdout, "phi=%.17g\n", init_info->phi_init * rad2deg);
	fprintf(stdout, "kappa=%.17g\n", init_info->kappa_init * rad2deg);
	fprintf(stdout, "omega_sd=%.17g\n", init_info->omega_var * rad2deg);
	fprintf(stdout, "phi_sd=%.17g\n", init_info->phi_var * rad2deg);
	fprintf(stdout, "kappa_sd=%.17g\n", init_info->kappa_var * rad2deg);
	
	fprintf(stdout, "use=%d", init_info->status);
    }

    /* save info */
    I_put_init_info(group.name, &group.camera_exp);

    exit(EXIT_SUCCESS);
}
Esempio n. 5
0
void user_input(int argc, char **argv)
{
    int i;

    /* setup the GRASS parsing routine
       structures to be used to read 
       in the user's parameter choices */
    struct Flag *units;
    struct Flag *zscore;
    struct Flag *edgemap;
    struct Option *name;
    struct Option *sampling_method;
    struct Option *region;
    struct Option *att;
    struct Option *diversity;
    struct Option *measure_code;
    struct Option *method_code;
    struct Option *juxtaposition;
    struct Option *edge;


    /* use the GRASS parsing routines to read in the user's parameter choices */

    edgemap = G_define_flag();
    edgemap->key = 'e';
    edgemap->description =
	"Output map 'edge' of edges given a '1' in r.le.para/edge file";

    units = G_define_flag();
    units->key = 'u';
    units->description =
	"Output maps 'units_x' with sampling units for each scale x ";

    zscore = G_define_flag();
    zscore->key = 'z';
    zscore->description = "Output map 'zscores' with standardized scores";

    name = G_define_option();
    name->key = "map";
    name->description = "Raster map to be analyzed";
    name->type = TYPE_STRING;
    name->gisprompt = "old,cell,raster";
    name->required = YES;

    sampling_method = G_define_option();
    sampling_method->answer = "w";
    sampling_method->key = "sam";
    sampling_method->description = "Sampling method (choose only 1 method):\n"
	"\tw = whole map      u = units        m = moving window   r = regions";
    sampling_method->type = TYPE_STRING;
    sampling_method->multiple = NO;
    sampling_method->required = NO;

    region = G_define_option();
    region->key = "reg";
    region->description =
	"Name of regions map, only when sam = r; omit otherwise";
    region->type = TYPE_STRING;
    region->gisprompt = "old,cell,raster";
    region->required = NO;

    att = G_define_option();
    att->key = "att";
    att->description =
	"b1 = mn. pixel att.                 b2 = s.d. pixel att.\n"
	"\tb3 = min. pixel att.                b4 = max. pixel att.";
    att->options = "b1,b2,b3,b4";
    att->type = TYPE_STRING;
    att->multiple = YES;
    att->required = NO;

    diversity = G_define_option();
    diversity->key = "div";
    diversity->description =
	"d1 = richness      d2 = Shannon     d3 = dominance     d4 = inv. Simpson";
    diversity->options = "d1,d2,d3,d4";
    diversity->type = TYPE_STRING;
    diversity->multiple = YES;
    diversity->required = NO;

    method_code = G_define_option();
    method_code->key = "te1";
    method_code->description = "Texture method (choose only 1 method):\n"
	"\tm1 = 2N-H          m2 = 2N-45       m3 = 2N-V          m4 = 2N-135\n"
	"\tm5 = 4N-HV         m6 = 4N-DIAG     m7 = 8N";
    method_code->options = "m1,m2,m3,m4,m5,m6,m7";
    method_code->type = TYPE_STRING;
    method_code->multiple = NO;
    method_code->required = NO;

    measure_code = G_define_option();
    measure_code->key = "te2";
    measure_code->description =
	"Texture measures (required if te1 was specified):\n"
	"\tt1 = contagion           t2 = ang. sec. mom.     t3 = inv. diff. mom.\n"
	"\tt4 = entropy             t5 = contrast";
    measure_code->options = "t1,t2,t3,t4,t5";
    measure_code->type = TYPE_STRING;
    measure_code->multiple = YES;
    measure_code->required = NO;

    juxtaposition = G_define_option();
    juxtaposition->key = "jux";
    juxtaposition->description =
	"Juxtaposition measures (weight file in r.le.para needed):\n"
	"\tj1 = mn. juxtaposition              j2 = s.d. juxtaposition";
    juxtaposition->options = "j1,j2";
    juxtaposition->type = TYPE_STRING;
    juxtaposition->multiple = YES;
    juxtaposition->required = NO;

    edge = G_define_option();
    edge->key = "edg";
    edge->description =
	"e1 = sum of edges  e2 = sum of edges by type (need edge file: r.le.para)";
    edge->options = "e1,e2";
    edge->type = TYPE_STRING;
    edge->multiple = YES;
    edge->required = NO;


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

    /* record the user inputs for map,
       sam, run, and out parameters */

    G_strcpy(choice->fn, name->answer);

    choice->wrum = sampling_method->answer[0];


    /* check for unacceptable values for
       input parameters */

    if (strcmp(sampling_method->answer, "w") &&
	strcmp(sampling_method->answer, "u") &&
	strcmp(sampling_method->answer, "m") &&
	strcmp(sampling_method->answer, "r")) {
	fprintf(stdout, "\n");
	fprintf(stdout,
		"   ***************************************************\n");
	fprintf(stdout,
		"    You input an unacceptable value for parameter sam \n");
	fprintf(stdout,
		"   ***************************************************\n");
	exit(EXIT_FAILURE);
    }

    /* check for multiple values for te1 */

    if (method_code->answer)
	if (method_code->answers[1]) {
	    fprintf(stdout, "\n");
	    fprintf(stdout,
		    "   **********************************************\n");
	    fprintf(stdout,
		    "    You input multiple values for parameter te1, \n");
	    fprintf(stdout,
		    "    but only one is allowed                      \n");
	    fprintf(stdout,
		    "   **********************************************\n");
	    exit(EXIT_FAILURE);
	}


    /* if the -u flag is specified, then
       set the choice->units flag to 1 */

    choice->units = 0;
    if (!strcmp(sampling_method->answer, "u") && units->answer)
	choice->units = 1;
    else if (strcmp(sampling_method->answer, "u") && units->answer) {
	fprintf(stdout, "\n");
	fprintf(stdout,
		"   ***************************************************\n");
	fprintf(stdout,
		"    You requested output of map 'units' with sampling \n");
	fprintf(stdout,
		"    units, by using flag -u, but this option is only  \n");
	fprintf(stdout,
		"    available when sam=u                              \n");
	fprintf(stdout,
		"   ***************************************************\n");
	exit(EXIT_FAILURE);
    }

    /* if sampling_method is by REGION
       get region file name.  Check to see
       that the name was input */

    if (!strcmp(sampling_method->answer, "r")) {
	if (region->answer)
	    G_strcpy(choice->reg, region->answer);
	else {
	    fprintf(stdout, "\n");
	    fprintf(stdout,
		    "   ***********************************************\n");
	    fprintf(stdout,
		    "    You requested sampling by region, but did not \n");
	    fprintf(stdout,
		    "    input the name of the region using the reg=   \n");
	    fprintf(stdout,
		    "    parameter                                     \n");
	    fprintf(stdout,
		    "   ***********************************************\n");
	    exit(EXIT_FAILURE);
	}
    }

    if (region->answer)
	if (strcmp(sampling_method->answer, "r")) {
	    fprintf(stdout, "\n");
	    fprintf(stdout,
		    "   ***********************************************\n");
	    fprintf(stdout,
		    "    You requested sampling by region, by using    \n");
	    fprintf(stdout,
		    "    the reg= parameter, but did not input the     \n");
	    fprintf(stdout,
		    "    sam=r parameter                               \n");
	    fprintf(stdout,
		    "   ***********************************************\n");
	    exit(EXIT_FAILURE);
	}

    /* initialize flag arrays in choice
       data structure. */

    for (i = 0; i < 5; i++)
	choice->att[i] = 0;
    for (i = 0; i < 5; i++)
	choice->div[i] = 0;
    for (i = 0; i < 6; i++)
	choice->te2[i] = 0;
    for (i = 0; i < 3; i++)
	choice->jux[i] = 0;
    for (i = 0; i < 3; i++)
	choice->edg[i] = 0;

    /* fill measure_code and method
       code arrays */


    if (att->answer) {
	choice->att[0] = 1;
	for (i = 0; att->answers[i] != NULL; i++) {
	    if (!strcmp(att->answers[i], "b1"))
		choice->att[1] = 1;
	    else if (!strcmp(att->answers[i], "b2"))
		choice->att[2] = 1;
	    else if (!strcmp(att->answers[i], "b3"))
		choice->att[3] = 1;
	    else if (!strcmp(att->answers[i], "b4"))
		choice->att[4] = 1;
	}
    }

    if (edgemap->answer && choice->wrum == 'w') {
	choice->edgemap = edgemap->answer;
	choice->edg[0] = 1;
	choice->edg[2] = 1;
    }
    else if (edgemap->answer && choice->wrum != 'w') {
	fprintf(stdout, "\n");
	fprintf(stdout,
		"   ****************************************************\n");
	fprintf(stdout,
		"    An edge map (flag is -e) is not available unless   \n");
	fprintf(stdout,
		"    sam=w                                              \n");
	fprintf(stdout,
		"   ****************************************************\n");
	exit(EXIT_FAILURE);
    }

    if (zscore->answer && choice->wrum == 'w') {
	choice->z = zscore->answer;
	choice->att[0] = 1;
	choice->att[1] = 1;
	choice->att[2] = 1;
    }
    else if (zscore->answer && choice->wrum != 'w') {
	fprintf(stdout, "\n");
	fprintf(stdout,
		"   ****************************************************\n");
	fprintf(stdout,
		"    A zscores map (flag is -z) is not available unless \n");
	fprintf(stdout,
		"    sam=w                                              \n");
	fprintf(stdout,
		"   ****************************************************\n");
	exit(EXIT_FAILURE);
    }

    if (diversity->answer) {
	choice->div[0] = 1;
	for (i = 0; diversity->answers[i] != NULL; i++) {
	    if (!strcmp(diversity->answers[i], "d1"))
		choice->div[1] = 1;
	    else if (!strcmp(diversity->answers[i], "d2"))
		choice->div[2] = 1;
	    else if (!strcmp(diversity->answers[i], "d3"))
		choice->div[3] = 1;
	    else if (!strcmp(diversity->answers[i], "d4"))
		choice->div[4] = 1;
	}
    }

    choice->tex = 0;
    if (measure_code->answer || method_code->answer) {
	if (measure_code->answer && method_code->answer) {
	    choice->te2[0] = 1;
	    for (i = 0; measure_code->answers[i] != NULL; i++) {
		if (!strcmp(measure_code->answers[i], "t1"))
		    choice->te2[1] = 1;
		else if (!strcmp(measure_code->answers[i], "t2"))
		    choice->te2[2] = 1;
		else if (!strcmp(measure_code->answers[i], "t3"))
		    choice->te2[3] = 1;
		else if (!strcmp(measure_code->answers[i], "t4"))
		    choice->te2[4] = 1;
		else if (!strcmp(measure_code->answers[i], "t5"))
		    choice->te2[5] = 1;
	    }
	    if (!strcmp(method_code->answer, "m1"))
		choice->tex = 1;
	    else if (!strcmp(method_code->answer, "m2"))
		choice->tex = 2;
	    else if (!strcmp(method_code->answer, "m3"))
		choice->tex = 3;
	    else if (!strcmp(method_code->answer, "m4"))
		choice->tex = 4;
	    else if (!strcmp(method_code->answer, "m5"))
		choice->tex = 5;
	    else if (!strcmp(method_code->answer, "m6"))
		choice->tex = 6;
	    else if (!strcmp(method_code->answer, "m7"))
		choice->tex = 7;
	}
	else {
	    fprintf(stdout, "\n");
	    fprintf(stdout,
		    "   ************************************************\n");
	    fprintf(stdout,
		    "    You requested texture measurement, but did not \n");
	    fprintf(stdout,
		    "    input both parameter te1 and te2               \n");
	    fprintf(stdout,
		    "   ************************************************\n");
	    exit(EXIT_FAILURE);
	}
    }

    if (juxtaposition->answer) {
	choice->jux[0] = 1;
	for (i = 0; juxtaposition->answers[i] != NULL; i++) {
	    if (!strcmp(juxtaposition->answers[i], "j1"))
		choice->jux[1] = 1;
	    else if (!strcmp(juxtaposition->answers[i], "j2"))
		choice->jux[2] = 1;
	}
    }

    if (edge->answer) {
	choice->edg[0] = 1;
	for (i = 0; edge->answers[i] != NULL; i++) {
	    if (!strcmp(edge->answers[i], "e1"))
		choice->edg[1] = 1;
	    else if (!strcmp(edge->answers[i], "e2"))
		choice->edg[2] = 1;
	}
    }

    if (!att->answer && !diversity->answer && !measure_code->answer &&
	!juxtaposition->answer && !edge->answer && !zscore->answer &&
	!edgemap->answer) {
	fprintf(stdout, "\n");
	fprintf(stdout,
		"   **************************************************\n");
	fprintf(stdout,
		"    You did not select any measures to be calculated \n");
	fprintf(stdout,
		"   **************************************************\n");
	exit(EXIT_FAILURE);
    }

    return;
}
Esempio n. 6
0
/* ---------------------------------------------------------------------- */
void 
parse_args(int argc, char *argv[]) {

  /* input elevation grid  */
  struct Option *input_elev;
  input_elev = G_define_standard_option(G_OPT_R_ELEV);

  /* output filled elevation grid */
  struct Option *output_elev;
  output_elev = G_define_standard_option(G_OPT_R_OUTPUT);
  output_elev->key        = "filled";
  output_elev->description= _("Name for output filled (flooded) elevation raster map");
  
 /* output direction  grid */
  struct Option *output_dir;
  output_dir = G_define_standard_option(G_OPT_R_OUTPUT);
  output_dir->key        = "direction";
  output_dir->description= _("Name for output flow direction raster map");

  /* output sinkwatershed  grid */
  struct Option *output_watershed;
  output_watershed = G_define_standard_option(G_OPT_R_OUTPUT);
  output_watershed->key        = "swatershed";
  output_watershed->description= _("Name for output sink-watershed raster map");

  /* output flow accumulation grid */
  struct Option *output_accu;
  output_accu = G_define_standard_option(G_OPT_R_OUTPUT);
  output_accu->key        = "accumulation";
  output_accu->description= _("Name for output flow accumulation raster map");

#ifdef OUTPUT_TCI
  struct Option *output_tci;
  output_tci = G_define_standard_option(G_OPT_R_OUTPUT);
  output_tci->key        = "tci";
  output_tci->description=
    _("Name for output topographic convergence index (tci) raster map");
#endif

  /* MFD/SFD flag */
  struct Flag *sfd_flag;
  sfd_flag = G_define_flag() ;
  sfd_flag->key        = 's';
  sfd_flag->description= _("SFD (D8) flow (default is MFD)");

  /* D8CUT value*/
  struct Option *d8cut;
  d8cut = G_define_option();
  d8cut->key  = "d8cut";
  d8cut->type = TYPE_DOUBLE;
  d8cut->required = NO;
  d8cut->answer = G_store("infinity"); /* default value */
  d8cut->label = _("Routing using SFD (D8) direction");
  d8cut->description = 
    _("If flow accumulation is larger than this value it is routed using "
      "SFD (D8) direction (meaningfull only  for MFD flow)");
  
  /* main memory */
  struct Option *mem;
  mem = G_define_option() ;
  mem->key         = "memory";
  mem->type        = TYPE_INTEGER;
  mem->required    = NO;
  mem->answer      = G_store("300"); /* 300MB default value */
  mem->description = _("Maximum runtime memory size (in MB)");

  /* temporary STREAM path */
  struct Option *streamdir;
  streamdir = G_define_option() ;
  streamdir->key        = "stream_dir";
  streamdir->type       = TYPE_STRING;
  streamdir->required   = NO;
#ifdef __MINGW32__
  streamdir->answer     = G_convert_dirseps_from_host(G_store(getenv("TEMP")));
#else
  streamdir->answer     = G_store("/var/tmp/");
#endif
  streamdir->description=
     _("Directory to hold temporary files (they can be large)");

 /* stats file */
  struct Option *stats_opt;
  stats_opt = G_define_option() ;
  stats_opt->key        = "stats";
  stats_opt->type       = TYPE_STRING;
  stats_opt->required   = NO;
  stats_opt->description= _("Name of file containing runtime statistics");
  stats_opt->answer     = G_store("stats.out");


  if (G_parser(argc, argv)) {
    exit (EXIT_FAILURE);
  }
  
  /* ************************* */
  assert(opt);
  opt->elev_grid = input_elev->answer;
  opt->filled_grid = output_elev->answer;
  opt->dir_grid = output_dir->answer; 
  opt->watershed_grid = output_watershed->answer;
  opt->flowaccu_grid = output_accu->answer;
#ifdef OUTPUT_TCI
  opt->tci_grid = output_tci->answer;
#endif

  opt->d8 = sfd_flag->answer;
  if (strcmp(d8cut->answer, "infinity") == 0) {
    opt->d8cut = MAX_ACCU;
  } else {
    opt->d8cut = atof(d8cut->answer);
  }

  opt->mem = atoi(mem->answer);
  opt->streamdir = streamdir->answer;

  opt->verbose = G_verbose() == G_verbose_max();

  opt->stats = stats_opt->answer;

  /* somebody should delete the options */
}
Esempio n. 7
0
int main(int argc, char **argv)
{
    unsigned char *hue_n, *hue_r, *hue_g, *hue_b;
    unsigned char *int_n, *int_r;
    unsigned char *sat_n, *sat_r;
    unsigned char *dummy;
    CELL *r_array, *g_array, *b_array;
    char *name_h, *name_i, *name_s;
    int intensity;
    int saturation;
    int atrow, atcol;
    int hue_file;
    int int_file = 0;
    int int_used;
    int sat_file = 0;
    int sat_used;
    char *name_r, *name_g, *name_b;
    int r_file = 0;
    int r_used;
    int g_file = 0;
    int g_used;
    int b_file = 0;
    int b_used;
    struct Cell_head window;
    struct Colors hue_colors;
    struct Colors int_colors;
    struct Colors sat_colors;
    struct Colors gray_colors;
    struct History history;
    struct GModule *module;
    struct Option *opt_h, *opt_i, *opt_s;
    struct Option *opt_r, *opt_g, *opt_b;
    struct Flag *nulldraw;

    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("raster"));
    G_add_keyword(_("color transformation"));
    G_add_keyword(_("RGB"));
    G_add_keyword(_("HIS"));
    module->description =
	_("Generates red, green and blue raster map layers "
	  "combining hue, intensity and saturation (HIS) "
	  "values from user-specified input raster map layers.");

    opt_h = G_define_option();
    opt_h->key = "h_map";
    opt_h->type = TYPE_STRING;
    opt_h->required = YES;
    opt_h->gisprompt = "old,cell,raster";
    opt_h->description = _("Name of layer to be used for HUE");

    opt_i = G_define_option();
    opt_i->key = "i_map";
    opt_i->type = TYPE_STRING;
    opt_i->required = NO;
    opt_i->gisprompt = "old,cell,raster";
    opt_i->description = _("Name of layer to be used for INTENSITY");

    opt_s = G_define_option();
    opt_s->key = "s_map";
    opt_s->type = TYPE_STRING;
    opt_s->required = NO;
    opt_s->gisprompt = "old,cell,raster";
    opt_s->description = _("Name of layer to be used for SATURATION");

    opt_r = G_define_option();
    opt_r->key = "r_map";
    opt_r->type = TYPE_STRING;
    opt_r->required = YES;
    opt_r->gisprompt = "new,cell,raster";
    opt_r->description = _("Name of output layer to be used for RED");

    opt_g = G_define_option();
    opt_g->key = "g_map";
    opt_g->type = TYPE_STRING;
    opt_g->required = YES;
    opt_g->gisprompt = "new,cell,raster";
    opt_g->description = _("Name of output layer to be used for GREEN");

    opt_b = G_define_option();
    opt_b->key = "b_map";
    opt_b->type = TYPE_STRING;
    opt_b->required = YES;
    opt_b->gisprompt = "new,cell,raster";
    opt_b->description = _("Name of output layer to be used for BLUE");

    nulldraw = G_define_flag();
    nulldraw->key = 'n';
    nulldraw->description = _("Respect NULL values while drawing");

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


    /* read in current window */
    G_get_window(&window);

    /* Get name of layer to be used for hue */
    name_h = opt_h->answer;

    /* Make sure map is available */
    hue_file = Rast_open_old(name_h, "");

    hue_r = G_malloc(window.cols);
    hue_g = G_malloc(window.cols);
    hue_b = G_malloc(window.cols);
    hue_n = G_malloc(window.cols);

    dummy = G_malloc(window.cols);

    /* Reading color lookup table */
    if (Rast_read_colors(name_h, "", &hue_colors) == -1)
	G_fatal_error(_("Color file for <%s> not available"), name_h);

    int_used = 0;

    if (opt_i->answer != NULL) {
	/* Get name of layer to be used for intensity */
	name_i = opt_i->answer;
	int_used = 1;
	/* Make sure map is available */
	int_file = Rast_open_old(name_i, "");

	int_r = G_malloc(window.cols);
	int_n = G_malloc(window.cols);

	/* Reading color lookup table */
	if (Rast_read_colors(name_i, "", &int_colors) == -1)
	    G_fatal_error(_("Color file for <%s> not available"), name_i);
    }

    sat_used = 0;

    if (opt_s->answer != NULL) {
	/* Get name of layer to be used for saturation */
	name_s = opt_s->answer;
	    sat_used = 1;

	    /* Make sure map is available */
	    sat_file = Rast_open_old(name_s, "");

	    sat_r = G_malloc(window.cols);
	    sat_n = G_malloc(window.cols);

	    /* Reading color lookup table */
	    if (Rast_read_colors(name_s, "", &sat_colors) == -1)
		G_fatal_error(_("Color file for <%s> not available"), name_s);
    }

    r_used = 0;

    if (opt_r->answer != NULL) {
	name_r = opt_r->answer;
	r_file = Rast_open_c_new(name_r);
	r_used = 1;
    }

    g_used = 0;

    if (opt_g->answer != NULL) {
	name_g = opt_g->answer;
	g_file = Rast_open_c_new(name_g);
	g_used = 1;
    }

    b_used = 0;

    if (opt_b->answer != NULL) {
	name_b = opt_b->answer;
	b_file = Rast_open_c_new(name_b);
	b_used = 1;
    }

    r_array = Rast_allocate_c_buf();
    g_array = Rast_allocate_c_buf();
    b_array = Rast_allocate_c_buf();

    /* Make color table */
    make_gray_scale(&gray_colors);

    /* Now do the work */
    intensity = 255;		/* default is to not change intensity */
    saturation = 255;		/* default is to not change saturation */


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

	Rast_get_row_colors(hue_file, atrow, &hue_colors, hue_r, hue_g, hue_b, hue_n);
	if (int_used)
	    Rast_get_row_colors(int_file, atrow, &int_colors, int_r, dummy, dummy, int_n);
	if (sat_used)
	    Rast_get_row_colors(sat_file, atrow, &sat_colors, sat_r, dummy, dummy, sat_n);

	for (atcol = 0; atcol < window.cols; atcol++) {
	    if (nulldraw->answer) {
		if (hue_n[atcol]
		    || (int_used && int_n[atcol])
		    || (sat_used && sat_n[atcol])) {
		    Rast_set_c_null_value(&r_array[atcol], 1);
		    Rast_set_c_null_value(&g_array[atcol], 1);
		    Rast_set_c_null_value(&b_array[atcol], 1);
		    continue;
		}
	    }

	    if (int_used)
		intensity = int_r[atcol];

	    if (sat_used)
		saturation = sat_r[atcol];

	    HIS_to_RGB(hue_r[atcol], hue_g[atcol], hue_b[atcol],
		       intensity, saturation,
		       &r_array[atcol], &g_array[atcol], &b_array[atcol]);
	}

	if (r_used)
	    Rast_put_row(r_file, r_array, CELL_TYPE);

	if (g_used)
	    Rast_put_row(g_file, g_array, CELL_TYPE);

	if (b_used)
	    Rast_put_row(b_file, b_array, CELL_TYPE);
    }
    G_percent(window.rows, window.rows, 5);

    /* Close the cell files */
    Rast_close(hue_file);
    if (int_used)
	Rast_close(int_file);
    if (sat_used)
	Rast_close(sat_file);

    if (r_used) {
	Rast_close(r_file);
	Rast_write_colors(name_r, G_mapset(), &gray_colors);
	Rast_short_history(name_r, "raster", &history);
	Rast_command_history(&history);
	Rast_write_history(name_r, &history);
	Rast_put_cell_title(name_r, "Red extracted from HIS");
    }
    if (g_used) {
	Rast_close(g_file);
	Rast_write_colors(name_g, G_mapset(), &gray_colors);
	Rast_short_history(name_g, "raster", &history);
	Rast_command_history(&history);
	Rast_write_history(name_g, &history);
	Rast_put_cell_title(name_g, "Green extracted from HIS");
    }
    if (b_used) {
	Rast_close(b_file);
	Rast_write_colors(name_b, G_mapset(), &gray_colors);
	Rast_short_history(name_b, "raster", &history);
	Rast_command_history(&history);
	Rast_write_history(name_b, &history);
	Rast_put_cell_title(name_b, "Blue extracted from HIS");
    }

    return EXIT_SUCCESS;
}
Esempio n. 8
0
/* Define the options and flags */
static struct Options define_options(void)
{
    struct Options opts;

    opts.iimg = G_define_standard_option(G_OPT_R_INPUT);

    opts.iscl = G_define_option();
    opts.iscl->key = "range";
    opts.iscl->type = TYPE_INTEGER;
    opts.iscl->key_desc = "min,max";
    opts.iscl->required = NO;
    opts.iscl->answer = "0,255";
    opts.iscl->description = _("Input range");
    opts.iscl->guisection = _("Input");

    opts.ialt = G_define_standard_option(G_OPT_R_ELEV);
    opts.ialt->required = NO;
    opts.ialt->description = _("Name of input elevation raster map (in m)");
    opts.ialt->guisection = _("Input");

    opts.ivis = G_define_standard_option(G_OPT_R_INPUT);
    opts.ivis->key = "visibility";
    opts.ivis->required = NO;
    opts.ivis->description = _("Name of input visibility raster map (in km)");
    opts.ivis->guisection = _("Input");

    opts.icnd = G_define_standard_option(G_OPT_F_INPUT);
    opts.icnd->key = "parameters";
    opts.icnd->required = YES;
    opts.icnd->description = _("Name of input text file with 6S parameters");

    opts.oimg = G_define_standard_option(G_OPT_R_OUTPUT);

    opts.oscl = G_define_option();
    opts.oscl->key = "rescale";
    opts.oscl->type = TYPE_INTEGER;
    opts.oscl->key_desc = "min,max";
    opts.oscl->answer = "0,255";
    opts.oscl->required = NO;
    opts.oscl->description = _("Rescale output raster map");
    opts.oscl->guisection = _("Output");

    opts.oint = G_define_flag();
    opts.oint->key = 'i';
    opts.oint->description = _("Output raster map as integer");
    opts.oint->guisection = _("Output");

    opts.irad = G_define_flag();
    opts.irad->key = 'r';
    opts.irad->description =
	_("Input raster map converted to reflectance (default is radiance)");
    opts.irad->guisection = _("Input");

    opts.etmafter = G_define_flag();
    opts.etmafter->key = 'a';
    opts.etmafter->description =
	_("Input from ETM+ image taken after July 1, 2000");
    opts.etmafter->guisection = _("Input");

    opts.etmbefore = G_define_flag();
    opts.etmbefore->key = 'b';
    opts.etmbefore->description =
	_("Input from ETM+ image taken before July 1, 2000");
    opts.etmbefore->guisection = _("Input");

    return opts;
}
Esempio n. 9
0
int main(int argc, char **argv)
{
    struct Cell_head window;
    RASTER_MAP_TYPE raster_type, mag_raster_type = -1;
    int layer_fd;
    void *raster_row, *ptr;
    int nrows, ncols;
    int aspect_c = -1;
    float aspect_f = -1.0;

    double scale;
    int skip, no_arrow;
    char *mag_map = NULL;
    void *mag_raster_row = NULL, *mag_ptr = NULL;
    double length = -1;
    int mag_fd = -1;
    struct FPRange range;
    double mag_min, mag_max;

    struct GModule *module;
    struct Option *opt1, *opt2, *opt3, *opt4, *opt5,
	*opt6, *opt7, *opt8, *opt9;
    struct Flag *align;

    double t, b, l, r;

    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("display"));
    G_add_keyword(_("map annotations"));
    G_add_keyword(_("raster"));
    module->description =
	_("Draws arrows representing cell aspect direction "
	  "for a raster map containing aspect data.");

    opt1 = G_define_standard_option(G_OPT_R_MAP);
    opt1->description = _("Name of raster aspect map to be displayed");

    opt2 = G_define_option();
    opt2->key = "type";
    opt2->type = TYPE_STRING;
    opt2->required = NO;
    opt2->answer = "grass";
    opt2->options = "grass,compass,agnps,answers";
    opt2->description = _("Type of existing raster aspect map");

    opt3 = G_define_standard_option(G_OPT_C);
    opt3->key = "color";
    opt3->answer = "green";
    opt3->label = _("Color for drawing arrows");
    opt3->guisection = _("Colors");
    
    opt4 = G_define_standard_option(G_OPT_CN);
    opt4->key = "grid_color";
    opt4->answer = "gray";
    opt4->label = _("Color for drawing drawing grid");
    opt4->guisection = _("Colors");

    opt5 = G_define_standard_option(G_OPT_CN);
    opt5->key = "null_color";
    opt5->answer = DEFAULT_FG_COLOR;
    opt5->label = _("Color for drawing null values (X symbol)");
    opt5->guisection = _("Colors");

    opt6 = G_define_standard_option(G_OPT_CN);
    opt6->key = "unknown_color";
    opt6->answer = "red";
    opt6->label = _("Color for showing unknown information (? symbol)");
    opt6->guisection = _("Colors");

    opt9 = G_define_option();
    opt9->key = "skip";
    opt9->type = TYPE_INTEGER;
    opt9->required = NO;
    opt9->answer = "1";
    opt9->description = _("Draw arrow every Nth grid cell");

    opt7 = G_define_option();
    opt7->key = "magnitude_map";
    opt7->type = TYPE_STRING;
    opt7->required = NO;
    opt7->multiple = NO;
    opt7->gisprompt = "old,cell,raster";
    opt7->description =
	_("Raster map containing values used for arrow length");

    opt8 = G_define_option();
    opt8->key = "scale";
    opt8->type = TYPE_DOUBLE;
    opt8->required = NO;
    opt8->answer = "1.0";
    opt8->description = _("Scale factor for arrows (magnitude map)");

    align = G_define_flag();
    align->key = 'a';
    align->description = _("Align grids with raster cells");


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


    layer_name = opt1->answer;

    arrow_color = D_translate_color(opt3->answer);

    /* Convert none (transparent) to -1 which in this module means
       that we will not draw things having this color (-1).
       We don't do that for arrow because we always want them.
       (This is specified by the gisprompt ('type') of the options.)
    */
    if (strcmp("none", opt4->answer) == 0)
	grid_color = -1;
    else
	grid_color = D_translate_color(opt4->answer);

    if (strcmp("none", opt5->answer) == 0)
	x_color = -1;
    else
	x_color = D_translate_color(opt5->answer);

    if (strcmp("none", opt6->answer) == 0)
	unknown_color = -1;
    else
	unknown_color = D_translate_color(opt6->answer);

    if (strcmp("grass", opt2->answer) == 0)
	map_type = 1;
    else if (strcmp("agnps", opt2->answer) == 0)
	map_type = 2;
    else if (strcmp("answers", opt2->answer) == 0)
	map_type = 3;
    else if (strcmp("compass", opt2->answer) == 0)
	map_type = 4;


    scale = atof(opt8->answer);
    if (scale <= 0.0)
	G_fatal_error(_("Illegal value for scale factor"));

    skip = atoi(opt9->answer);
    if (skip <= 0)
	G_fatal_error(_("Illegal value for skip factor"));


    if (opt7->answer) {
	if (map_type != 1 && map_type != 4)
	    G_fatal_error(_("Magnitude is only supported for GRASS and compass aspect maps."));

	mag_map = opt7->answer;
    }
    else if (scale != 1.0)
	G_warning(_("Scale option requires magnitude_map"));


    /* Setup driver and check important information */
    D_open_driver();
    
    D_setup(0);

    /* Read in the map window associated with window */
    G_get_window(&window);

    if (align->answer) {
	struct Cell_head wind;

	Rast_get_cellhd(layer_name, "", &wind);

	/* expand window extent by one wind resolution */
	wind.west += wind.ew_res * ((int)((window.west - wind.west) / wind.ew_res) - (window.west < wind.west));
	wind.east += wind.ew_res * ((int)((window.east - wind.east) / wind.ew_res) + (window.east > wind.east));
	wind.south += wind.ns_res * ((int)((window.south - wind.south) / wind.ns_res) - (window.south < wind.south));
	wind.north += wind.ns_res * ((int)((window.north - wind.north) / wind.ns_res) + (window.north > wind.north));

	wind.rows = (wind.north - wind.south) / wind.ns_res;
	wind.cols = (wind.east - wind.west) / wind.ew_res;

	Rast_set_window(&wind);

	nrows = wind.rows;
	ncols = wind.cols;

	t = (wind.north - window.north) * nrows / (wind.north - wind.south);
	b = t + (window.north - window.south) * nrows / (wind.north - wind.south);
	l = (window.west - wind.west) * ncols / (wind.east - wind.west);
	r = l + (window.east - window.west) * ncols / (wind.east - wind.west);
    } else {
        nrows = window.rows;
        ncols = window.cols;

	t = 0;
	b = nrows;
	l = 0;
	r = ncols;
    }

    D_set_src(t, b, l, r);
    D_update_conversions();

    /* figure out arrow scaling if using a magnitude map */
    if (opt7->answer) {
	Rast_init_fp_range(&range);	/* really needed? */
	if (Rast_read_fp_range(mag_map, "", &range) != 1)
	    G_fatal_error(_("Problem reading range file"));
	Rast_get_fp_range_min_max(&range, &mag_min, &mag_max);

	scale *= 1.5 / fabs(mag_max);
	G_debug(3, "scaling=%.2f  rast_max=%.2f", scale, mag_max);
    }

    if (grid_color > 0) {	/* ie not "none" */
	/* Set color */
	D_use_color(grid_color);

	/* Draw vertical grids */
	for (col = 0; col < ncols; col++)
	    D_line_abs(col, 0, col, nrows);

	/* Draw horizontal grids */
	for (row = 0; row < nrows; row++)
	    D_line_abs(0, row, ncols, row);
    }

    /* open the raster map */
    layer_fd = Rast_open_old(layer_name, "");

    raster_type = Rast_get_map_type(layer_fd);

    /* allocate the cell array */
    raster_row = Rast_allocate_buf(raster_type);


    if (opt7->answer) {
	/* open the magnitude raster map */
	mag_fd = Rast_open_old(mag_map, "");

	mag_raster_type = Rast_get_map_type(mag_fd);

	/* allocate the cell array */
	mag_raster_row = Rast_allocate_buf(mag_raster_type);
    }


    /* loop through cells, find value, determine direction (n,s,e,w,ne,se,sw,nw),
       and call appropriate function to draw an arrow on the cell */

    for (row = 0; row < nrows; row++) {
	Rast_get_row(layer_fd, raster_row, row, raster_type);
	ptr = raster_row;

	if (opt7->answer) {
	    Rast_get_row(mag_fd, mag_raster_row, row, mag_raster_type);
	    mag_ptr = mag_raster_row;
	}

	for (col = 0; col < ncols; col++) {

	    if (row % skip != 0)
		no_arrow = TRUE;
	    else
		no_arrow = FALSE;

	    if (col % skip != 0)
		no_arrow = TRUE;

	    /* find aspect direction based on cell value */
	    if (raster_type == CELL_TYPE)
		aspect_f = *((CELL *) ptr);
	    else if (raster_type == FCELL_TYPE)
		aspect_f = *((FCELL *) ptr);
	    else if (raster_type == DCELL_TYPE)
		aspect_f = *((DCELL *) ptr);


	    if (opt7->answer) {

		if (mag_raster_type == CELL_TYPE)
		    length = *((CELL *) mag_ptr);
		else if (mag_raster_type == FCELL_TYPE)
		    length = *((FCELL *) mag_ptr);
		else if (mag_raster_type == DCELL_TYPE)
		    length = *((DCELL *) mag_ptr);

		length *= scale;

		if (Rast_is_null_value(mag_ptr, mag_raster_type)) {
		    G_debug(5, "Invalid arrow length [NULL]. Skipping.");
		    no_arrow = TRUE;
		}
		else if (length <= 0.0) {	/* use fabs() or theta+=180? */
		    G_debug(5, "Illegal arrow length [%.3f]. Skipping.",
			    length);
		    no_arrow = TRUE;
		}
	    }

	    if (no_arrow) {
		ptr = G_incr_void_ptr(ptr, Rast_cell_size(raster_type));
		if (opt7->answer)
		    mag_ptr =
			G_incr_void_ptr(mag_ptr,
					Rast_cell_size(mag_raster_type));
		no_arrow = FALSE;
		continue;
	    }

	    /* treat AGNPS and ANSWERS data like old zero-as-null CELL */
	    /*   TODO: update models */
	    if (map_type == 2 || map_type == 3) {
		if (Rast_is_null_value(ptr, raster_type))
		    aspect_c = 0;
		else
		    aspect_c = (int)(aspect_f + 0.5);
	    }


	    /** Now draw the arrows **/

	    /* case switch for standard GRASS aspect map 
	       measured in degrees counter-clockwise from east */
	    if (map_type == 1) {
		D_use_color(arrow_color);

		if (Rast_is_null_value(ptr, raster_type)) {
		    /* don't draw anything if x_color is none (transparent) */
		    if (x_color > 0) {
			D_use_color(x_color);
			draw_x();
			D_use_color(arrow_color);
		    }
		}
		else if (aspect_f >= 0.0 && aspect_f <= 360.0) {
		    if (opt7->answer)
			arrow_mag(aspect_f, length);
		    else
			arrow_360(aspect_f);
		}
		else if (unknown_color > 0) {
		    /* don't draw if unknown_color is none (transparent) */
		    D_use_color(unknown_color);
		    unknown_();
		    D_use_color(arrow_color);
		}
	    }


	    /* case switch for AGNPS type aspect map */
	    else if (map_type == 2) {
		D_use_color(arrow_color);
		switch (aspect_c) {
		case 0:
		    /* only draw if x_color is not none (transparent) */
		    if (x_color > 0) {
			D_use_color(x_color);
			draw_x();
			D_use_color(arrow_color);
		    }
		    break;
		case 1:
		    arrow_n();
		    break;
		case 2:
		    arrow_ne();
		    break;
		case 3:
		    arrow_e();
		    break;
		case 4:
		    arrow_se();
		    break;
		case 5:
		    arrow_s();
		    break;
		case 6:
		    arrow_sw();
		    break;
		case 7:
		    arrow_w();
		    break;
		case 8:
		    arrow_nw();
		    break;
		default:
		    /* only draw if unknown_color is not none */
		    if (unknown_color > 0) {
			D_use_color(unknown_color);
			unknown_();
			D_use_color(arrow_color);
		    }
		    break;
		}
	    }


	    /* case switch for ANSWERS type aspect map */
	    else if (map_type == 3) {
		D_use_color(arrow_color);
		if (aspect_c >= 15 && aspect_c <= 360)	/* start at zero? */
		    arrow_360((double)aspect_c);
		else if (aspect_c == 400) {
		    if (unknown_color > 0) {
			/* only draw if unknown_color is not none */
			D_use_color(unknown_color);
			unknown_();
			D_use_color(arrow_color);
		    }
		}
		else if (x_color > 0) {
		    /* only draw if x_color is not none (transparent) */
		    D_use_color(x_color);
		    draw_x();
		    D_use_color(arrow_color);
		}
	    }

	    /* case switch for compass type aspect map
	       measured in degrees clockwise from north */
	    else if (map_type == 4) {
		D_use_color(arrow_color);

		if (Rast_is_null_value(ptr, raster_type)) {
		    if (x_color > 0) {
			/* only draw if x_color is not none */
			D_use_color(x_color);
			draw_x();
			D_use_color(arrow_color);
		    }
		}
		else if (aspect_f >= 0.0 && aspect_f <= 360.0) {
		    if (opt7->answer)
			arrow_mag(90 - aspect_f, length);
		    else
			arrow_360(90 - aspect_f);
		}
		else if (unknown_color > 0) {
		    /* only draw if unknown_color is not none */
		    D_use_color(unknown_color);
		    unknown_();
		    D_use_color(arrow_color);
		}
	    }

	    ptr = G_incr_void_ptr(ptr, Rast_cell_size(raster_type));
	    if (opt7->answer)
		mag_ptr =
		    G_incr_void_ptr(mag_ptr, Rast_cell_size(mag_raster_type));
	}
    }

    Rast_close(layer_fd);
    if (opt7->answer)
	Rast_close(mag_fd);

    D_save_command(G_recreate_command());
    D_close_driver();

    exit(EXIT_SUCCESS);
}
Esempio n. 10
0
int main(int argc, char *argv[])
{
    struct GModule *module;
    struct {
        struct Option *input, *output, *zshift, *height, *elevation, *hcolumn,
            *type, *field, *cats, *where, *interp, *scale, *null;
    } opt;
    struct {
        struct Flag *trace;
    } flag;
    
    struct Map_info In, Out;
    struct line_pnts *Points;
    struct line_cats *Cats;
    struct bound_box map_box;

    struct cat_list *cat_list;
    
    struct Cell_head window;
    
    int field;
    int only_type, cat;
    int fdrast, interp_method, trace;
    double objheight, objheight_default, voffset;
    double scale, null_val;
    
    struct field_info *Fi;
    dbDriver *driver = NULL;
    
    char *comment;
    
    module = G_define_module();
    G_add_keyword(_("vector"));
    G_add_keyword(_("geometry"));
    G_add_keyword(_("sampling"));
    G_add_keyword(_("3D"));
    module->label =
	_("Extrudes flat vector features to 3D vector features with defined height.");
    module->description = 
        _("Optionally the height can be derived from sampling of elevation raster map.");
    
    flag.trace = G_define_flag();
    flag.trace->key = 't';
    flag.trace->description = _("Trace elevation");
    flag.trace->guisection = _("Elevation");

    opt.input = G_define_standard_option(G_OPT_V_INPUT);

    opt.field = G_define_standard_option(G_OPT_V_FIELD_ALL);
    opt.field->guisection = _("Selection");

    opt.cats = G_define_standard_option(G_OPT_V_CATS);
    opt.cats->guisection = _("Selection");
    
    opt.where = G_define_standard_option(G_OPT_DB_WHERE);
    opt.where->guisection = _("Selection");

    opt.type = G_define_standard_option(G_OPT_V_TYPE);
    opt.type->answer = "point,line,area";
    opt.type->options = "point,line,area";
    opt.type->guisection = _("Selection");

    opt.output = G_define_standard_option(G_OPT_V_OUTPUT);

    opt.zshift = G_define_option();
    opt.zshift->key = "zshift";
    opt.zshift->description = _("Shifting value for z coordinates");
    opt.zshift->type = TYPE_DOUBLE;
    opt.zshift->required = NO;
    opt.zshift->answer = "0";
    opt.zshift->guisection = _("Height");

    opt.height = G_define_option();
    opt.height->key = "height";
    opt.height->type = TYPE_DOUBLE;
    opt.height->required = NO;
    opt.height->multiple = NO;
    opt.height->description = _("Fixed height for 3D vector features");
    opt.height->guisection = _("Height");

    opt.hcolumn = G_define_standard_option(G_OPT_DB_COLUMN);
    opt.hcolumn->key = "height_column";
    opt.hcolumn->multiple = NO;
    opt.hcolumn->description = _("Name of attribute column with feature height");
    opt.hcolumn->guisection = _("Height");
 
    /* raster sampling */
    opt.elevation = G_define_standard_option(G_OPT_R_ELEV);
    opt.elevation->required = NO;
    opt.elevation->description = _("Elevation raster map for height extraction");
    opt.elevation->guisection = _("Elevation");

    opt.interp = G_define_standard_option(G_OPT_R_INTERP_TYPE);
    opt.interp->answer = "nearest";
    opt.interp->guisection = _("Elevation");

    opt.scale = G_define_option();
    opt.scale->key = "scale";
    opt.scale->type = TYPE_DOUBLE;
    opt.scale->description = _("Scale factor sampled raster values");
    opt.scale->answer = "1.0";
    opt.scale->guisection = _("Elevation");

    opt.null = G_define_option();
    opt.null->key = "null_value";
    opt.null->type = TYPE_DOUBLE;
    opt.null->description =
	_("Height for sampled raster NULL values");
    opt.null->guisection = _("Elevation");

    G_gisinit(argv[0]);

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

    if (!opt.height->answer && !opt.hcolumn->answer) {
	G_fatal_error(_("One of '%s' or '%s' parameters must be set"),
		      opt.height->key, opt.hcolumn->key);
    }

    sscanf(opt.zshift->answer, "%lf", &voffset);
    G_debug(1, "voffset = %f", voffset);
    
    if (opt.height->answer)
	sscanf(opt.height->answer, "%lf", &objheight);
    else
	objheight = 0.;
    G_debug(1, "objheight = %f", objheight);
    objheight_default = objheight;

    only_type = Vect_option_to_types(opt.type);

    /* sampling method */
    interp_method = Rast_option_to_interp_type(opt.interp);

    /* used to scale sampled raster values */
    scale = atof(opt.scale->answer);

    /* is null value defined */
    if (opt.null->answer)
	null_val = atof(opt.null->answer);

    /* trace elevation */
    trace = flag.trace->answer ? TRUE : FALSE;
    
    /* set input vector map name and mapset */
    Vect_check_input_output_name(opt.input->answer, opt.output->answer, G_FATAL_EXIT);

    Points = Vect_new_line_struct();
    Cats = Vect_new_cats_struct();

    Vect_set_open_level(2); /* topology required for input */

    /* opening input vector map */
    if (Vect_open_old2(&In, opt.input->answer, "", opt.field->answer) < 0)
	G_fatal_error(_("Unable to open vector map <%s>"), opt.input->answer);

    Vect_set_error_handler_io(&In, &Out);

    /* creating output vector map */
    if (Vect_open_new(&Out, opt.output->answer, WITH_Z) < 0)
	G_fatal_error(_("Unable to create vector map <%s>"),
			opt.output->answer);

    field = Vect_get_field_number(&In, opt.field->answer);

    if ((opt.hcolumn->answer || opt.cats->answer || opt.where->answer) && field == -1) {
        G_warning(_("Invalid layer number (%d). "
                    "Parameter '%s', '%s' or '%s' specified, assuming layer '1'."),
                  field, opt.hcolumn->key, opt.cats->key, opt.where->key);
        field = 1;
    }

    /* set constraint for cats or where */
    cat_list = NULL;
    if (field > 0)
	cat_list = Vect_cats_set_constraint(&In, field, opt.where->answer,
                                            opt.cats->answer);
    
    
    Vect_hist_copy(&In, &Out);
    Vect_hist_command(&Out);

    /* opening database connection, if required */
    if (opt.hcolumn->answer) {
        int ctype;
        dbColumn *column;
        
	if ((Fi = Vect_get_field(&In, field)) == NULL)
	    G_fatal_error(_("Database connection not defined for layer %d"),
			  field);

	if ((driver =
	     db_start_driver_open_database(Fi->driver, Fi->database)) == NULL)
	    G_fatal_error(_("Unable to open database <%s> by driver <%s>"),
			  Fi->database, Fi->driver);
        db_set_error_handler_driver(driver);
        
	if (db_get_column(driver, Fi->table, opt.hcolumn->answer, &column) != DB_OK)
	    G_fatal_error(_("Column <%s> does not exist"),
			  opt.hcolumn->answer);
	else
	    db_free_column(column);

	ctype = db_column_Ctype(driver, Fi->table, opt.hcolumn->answer);

	if (ctype != DB_C_TYPE_INT && ctype != DB_C_TYPE_STRING &&
	    ctype != DB_C_TYPE_DOUBLE) {
	    G_fatal_error(_("Column <%s>: invalid data type"),
			  opt.hcolumn->answer);
	}
    }

    /* do we work with elevation raster? */
    fdrast = -1;
    if (opt.elevation->answer) {
	/* raster setup */
	G_get_window(&window);

	/* open the elev raster, and check for error condition */
	fdrast = Rast_open_old(opt.elevation->answer, "");
    }

    /* if area */
    if (only_type & GV_AREA) {
        int area, nareas, centroid;
        
        nareas = Vect_get_num_areas(&In);
	G_debug(2, "n_areas = %d", nareas);
	if (nareas > 0)
	    G_message(_("Extruding areas..."));
	for (area = 1; area <= nareas; area++) {
	    G_debug(3, "area = %d", area);
	    G_percent(area, nareas, 2);
            
	    if (!Vect_area_alive(&In, area))
		continue;
            
	    centroid = Vect_get_area_centroid(&In, area);
	    if (!centroid) {
		G_warning(_("Skipping area %d without centroid"), area);
		continue;
	    }

	    Vect_read_line(&In, NULL, Cats, centroid);
	    if (field > 0 && !Vect_cats_in_constraint(Cats, field, cat_list))
		continue;
            
	    /* height attribute */
	    if (opt.hcolumn->answer) {
		cat = Vect_get_area_cat(&In, area, field);
                if (cat == -1) {
                    G_warning(_("No category defined for area %d. Using default fixed height %f."),
                              area, objheight_default);
                    objheight = objheight_default;
                }
                if (get_height(Fi, opt.hcolumn->answer,
                               driver, cat, &objheight) != 0) {
                    G_warning(_("Unable to fetch height from DB for area %d. Using default fixed height %f."),
                              area, objheight_default);
                    objheight = objheight_default;
                }
	    } /* if opt.hcolumn->answer */

	    Vect_get_area_points(&In, area, Points);

	    G_debug(3, "area: %d height: %f", area, objheight);

	    extrude(&In, &Out, Cats, Points,
		    fdrast, trace, interp_method, scale,
                    opt.null->answer ? TRUE : FALSE, null_val,
                    objheight, voffset, &window, GV_AREA,
		    centroid);
	} /* foreach area */

    }

    if (only_type > 0) {
        int line, nlines;
        int type;
        
	G_debug(1, "other than areas");
	/* loop through each line in the dataset */
        nlines = Vect_get_num_lines(&In);
	G_message(_("Extruding features..."));
	for (line = 1; line <= nlines; line++) {
	    /* progress feedback */
	    G_percent(line, nlines, 2);

	    if (!Vect_line_alive(&In, line))
		continue;

	    /* read line */
	    type = Vect_read_line(&In, Points, Cats, line);

	    if (!(type & only_type))
		continue;

	    if (field > 0 && !Vect_cats_in_constraint(Cats, field, cat_list))
		continue;

	    /* height attribute */
	    if (opt.hcolumn->answer) {
		cat = Vect_get_line_cat(&In, line, field);
                if (cat == -1) {
                    G_warning(_("No category defined for feature %d. Using default fixed height %f."),
                              line, objheight_default);
                    objheight = objheight_default;
                }
                if (get_height(Fi, opt.hcolumn->answer,
                               driver, cat, &objheight) != 0) {
                    G_warning(_("Unable to fetch height from DB for line %d. Using default fixed height %f."),
                              line, objheight_default);
                    objheight = objheight_default;
                }
	    } /* if opt.hcolumn->answer */
            
	    extrude(&In, &Out, Cats, Points,
		    fdrast, trace, interp_method, scale,
                    opt.null->answer ? TRUE : FALSE, null_val,
                    objheight, voffset, &window, type, -1);
	} /* for each line */
    }	  /* else if area */

    if (driver) {
	db_close_database(driver);
	db_shutdown_driver(driver);
    }

    G_important_message(_("Copying attribute table..."));
    if (field < 0)
        Vect_copy_tables(&In, &Out, 0);
    else 
        Vect_copy_table_by_cat_list(&In, &Out, field, field, NULL,
                                    GV_1TABLE, cat_list);
    
    Vect_build(&Out);

    /* header */
    G_asprintf(&comment, "Generated by %s from vector map <%s>",
	       G_program_name(), Vect_get_full_name(&In));
    Vect_set_comment(&Out, comment);
    G_free(comment);

    Vect_get_map_box(&Out, &map_box);

    Vect_close(&In);
    Vect_close(&Out);

    Vect_destroy_line_struct(Points);
    Vect_destroy_cats_struct(Cats);

    G_done_msg("T: %f B: %f.", map_box.T, map_box.B);
    
    exit(EXIT_SUCCESS);
}
Esempio n. 11
0
int main(int argc, char *argv[])
{
    short percent;
    double percentage;
    long targets;
    long count;
    struct rr_state myState;

    struct GModule *module;
    struct
    {
	struct Option *input, *cover, *raster, *sites, *npoints;
    } parm;
    struct
    {
	struct Flag *zero, *info, *z_geometry, *notopol_flag;
    } flag;

    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("raster"));
    G_add_keyword(_("sampling"));
    G_add_keyword(_("vector"));
    G_add_keyword(_("random"));
    module->description =
	_("Creates a raster map layer and vector point map "
	  "containing randomly located points.");

    parm.input = G_define_standard_option(G_OPT_R_INPUT);
    parm.input->description = _("Name of input raster map");

    parm.cover = G_define_standard_option(G_OPT_R_INPUT);
    parm.cover->key = "cover";
    parm.cover->required = NO;
    parm.cover->description = _("Name of cover raster map");

    parm.npoints = G_define_option();
    parm.npoints->key = "npoints";
    parm.npoints->key_desc = "number[%]";
    parm.npoints->type = TYPE_STRING;
    parm.npoints->required = YES;
    parm.npoints->description = _("The number of points to allocate");

    parm.raster = G_define_standard_option(G_OPT_R_OUTPUT);
    parm.raster->required = NO;
    parm.raster->key = "raster";

    parm.sites = G_define_standard_option(G_OPT_V_OUTPUT);
    parm.sites->required = NO;
    parm.sites->key = "vector";

    flag.zero = G_define_flag();
    flag.zero->key = 'z';
    flag.zero->description = _("Generate points also for NULL category");

    flag.info = G_define_flag();
    flag.info->key = 'i';
    flag.info->description =
	_("Report information about input raster and exit");

    flag.z_geometry = G_define_flag();
    flag.z_geometry->key = 'd';
    flag.z_geometry->description = _("Generate vector points as 3D points");

    flag.notopol_flag = G_define_standard_flag(G_FLG_V_TOPO);
    flag.notopol_flag->description = _("Do not build topology in points mode");
    flag.notopol_flag->guisection = _("Points");

    if (G_parser(argc, argv) != 0)
	exit(EXIT_FAILURE);

    /* Set some state variables */
    myState.use_nulls = flag.zero->answer;
    myState.inraster = parm.input->answer;
    if (parm.cover->answer) {
	myState.docover = TRUE;
	myState.inrcover = parm.cover->answer;
    }
    else {
	myState.docover = FALSE;
	myState.inrcover = NULL;
    }
    myState.outraster = parm.raster->answer;
    myState.outvector = parm.sites->answer;
    myState.z_geometry = flag.z_geometry->answer;
    myState.notopol = flag.notopol_flag->answer;

    /* If they only want info we ignore the rest */
    get_stats(&myState);

    if (flag.info->answer) {
	G_message("Raster:      %s\n"
		  "Cover:       %s\n"
		  "Cell Count:  %d\n"
		  "Null Cells:  %d\n\n",
		  myState.inraster, myState.inrcover,
		  (int)myState.nCells, (int)myState.nNulls);

	exit(EXIT_SUCCESS);
    }

    if (!(parm.raster->answer || parm.sites->answer))
	G_fatal_error(_("Note: one (or both) of %s and %s must be specified"),
		      parm.raster->key, parm.sites->key);

    /* look for n[%] */
    percent = has_percent(parm.npoints->answer);
    if (percent) {
	if (sscanf(parm.npoints->answer, "%lf", &percentage) != 1
	    || percentage <= 0.0 || percentage > 100.0) {
	    G_fatal_error(_("<%s=%s> invalid percentage"),
			  parm.npoints->key, parm.npoints->answer);
	}
    }
    else {
	if (sscanf(parm.npoints->answer, "%ld", &targets) != 1
	    || targets <= 0) {
	    G_fatal_error(_("<%s=%s> invalid number of points"),
			  parm.npoints->key, parm.npoints->answer);
	}
    }

    count = (myState.use_nulls) ? myState.nCells :
	myState.nCells - myState.nNulls;

    if (percent)
	myState.nRand = (int)(count * percentage / 100.0 + .5);
    else {
	if (targets > count) {
	    if (myState.use_nulls)
		G_fatal_error(_("There aren't [%ld] cells in the current region"),
			      targets);
	    else
		G_fatal_error(_("There aren't [%ld] non-NULL cells in the current region"),
			      targets);
	}

	if (targets <= 0)
	    G_fatal_error(_("There are no valid locations in the current region"));

	myState.nRand = targets;
    }

    execute_random(&myState);

    if (myState.outraster)
	make_support(&myState, percent, percentage);

    return EXIT_SUCCESS;
}
Esempio n. 12
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);
}
Esempio n. 13
0
int main( int argc, char *argv[] )
{
	Shypothesis **samples; /* Data to be combined */
	unsigned int i;
	FILE *kb;
	char **groups;
	int norm = 1; /* turn on normalisation of evidence by default */
	/* these are for time keeping in the logfile */	
	time_t systime;
	clock_t proctime;
	unsigned long timeused;
	unsigned int days, hours, mins, secs;
	
	xmlDocPtr dstXMLFile;
	Sfp_struct* file_pointers;	
	
	G_gisinit ( argv[0] );		
	
	module = G_define_module ();
	module->description = "Combines evidences from a DST knowledge base";
		
	parm.file = G_define_option ();
	parm.file->key = "file";
	parm.file->type = TYPE_STRING;
	parm.file->required = YES;
	parm.file->description = "Name of the knowledge base that contains the evidence";
	
	parm.groups = G_define_option ();
	parm.groups->key = "sources";
	parm.groups->type = TYPE_STRING;
	parm.groups->required = NO;
	parm.groups->multiple = YES;
	parm.groups->description = "Evidences to be combined (default: all)";
			
	parm.type = G_define_option ();
	parm.type->key = "type";
	parm.type->type = TYPE_STRING;
	parm.type->required = NO;
	parm.type->options = "const,rast,vect";
	parm.type->answer = "rast";
	parm.type->description = "Type(s) of evidences to combine";	
	
	parm.output = G_define_option ();
	parm.output->key = "output";
	parm.output->type = TYPE_STRING;
	parm.output->required = NO;
	parm.output->answer = G_location ();
	parm.output->description = "Prefix for result maps (dflt: location name)";

	parm.vals = G_define_option ();
	parm.vals->key = "values";
	parm.vals->type = TYPE_STRING;
	parm.vals->required = NO;
	parm.vals->multiple = YES;
	parm.vals->options = "bel,pl,doubt,common,bint,woc,maxbpa,minbpa,maxsrc,minsrc";
	parm.vals->answer = "bel";
	parm.vals->description = "Dempster-Shafer values to map";

	parm.hyps = G_define_option ();
	parm.hyps->key = "hypotheses";
	parm.hyps->type = TYPE_STRING;
	parm.hyps->required = NO;
	parm.hyps->multiple = NO;
	parm.hyps->description = "Hypotheses to map (default: all)";

	parm.logfile = G_define_option ();
	parm.logfile->key = "logfile";
	parm.logfile->type = TYPE_STRING;
	parm.logfile->required = NO;
	parm.logfile->description = "Name of logfile";

	/* TODO: not implemented yet
	parm.warnings = G_define_option ();
	parm.warnings->key = "warnings";
	parm.warnings->type = TYPE_STRING;
	parm.warnings->required = NO;
	parm.warnings->description = "Name of site list to store locations of warnings." ;
	*/

	flag.norm = G_define_flag ();
	flag.norm->key = 'n';
	flag.norm->description = "Turn off normalisation";

	flag.quiet = G_define_flag ();
	flag.quiet->key = 'q';
	flag.quiet->description = "Quiet operation: no progress diplay";

	/* append output to existing logfile ? */
	flag.append = G_define_flag ();
	flag.append->key = 'a';
	flag.append->description = "Append log output to existing file";
	
	no_assigns = 0;
	
	/* INIT GLOBAL VARS */
	WOC_MIN = 0;
	WOC_MAX = 0;
	
	/* do not pause after a warning message was displayed */
	G_sleep_on_error (0);
	
	/* parse command line */
	if (G_parser (argc, argv))
	{
		exit (-1);
	}			
	
	/* check if given parameters are valid */
	if (G_legal_filename (parm.file->answer) == -1) {
		G_fatal_error ("Please provide the name of an existing DST knowledge base.\n");
	}
	
	if (G_find_file ("DST",parm.file->answer,G_mapset()) == NULL) {
		G_fatal_error ("Knowledge base does not exist in user's MAPSET!\n");
	}
	
	/* check logfile */
	if (parm.logfile->answer != NULL) {		
		if ( !G_legal_filename (parm.logfile->answer) ) {
			G_fatal_error ("Please specify a legal filename for the logfile.\n");
		}
		/* attempt to write to logfile */
		if (flag.append->answer) {
			if (fopen (parm.logfile->answer, "r") == NULL) {
				lp = fopen (parm.logfile->answer, "w+");
				if (lp == NULL) {
					G_fatal_error ("Logfile error: %s\n", strerror (errno));
				}				
			} else {
				lp = fopen (parm.logfile->answer, "a");
				if (lp == NULL) {
					G_fatal_error ("Logfile error: %s\n", strerror (errno));
				}
				fprintf (lp,"\n\n * * * * * \n\n");
			}
		} else {
			if ( (lp = fopen ( parm.logfile->answer, "w+" ) ) == NULL ) {
				G_fatal_error ("Logfile error: %s\n", strerror (errno));
			}
		}
		/* we want unbuffered output for the logfile */
		setvbuf (lp,NULL,_IONBF,0);
	} else {		
		/* log output to stderr by default */
		lp = stderr;
	}
		
	/* setup coordinate file storage, if desired */
	/* try to create a sites file to store coordinates */
	/* set 'warn' to point to the user-defined sites file */	
	/*
	warn = NULL;
	if ( parm.warnings != NULL ) {
	}
	*/
			
	/* check if we have read/write access to knowledge base */
	kb = G_fopen_old ("DST",parm.file->answer,G_mapset());
	if ( kb == NULL ) {
		G_fatal_error ("Cannot open knowledge base file for reading and writing!\n");
	}
	fclose(kb);
	
	/* start logfile */
	if ( parm.logfile->answer != NULL) {
		fprintf (lp,"This is %s, version %.2f\n",argv[0],PROGVERSION);
		systime = time (NULL);
		fprintf (lp,"Calculation started on %s\n",ctime(&systime));
	}		
		
	/* open DST file and get basic evidence group information */
	dstXMLFile = stat_XML ( parm.file->answer, &NO_SINGLETONS, &N );
	groups = get_groups_XML ( N, dstXMLFile );
	
	if ( NO_SINGLETONS == 1 ) {
		G_fatal_error ("Knowledge base does not contain any user-supplied hypotheses.\n");
	}

	if ( parm.groups->answer != NULL ) {
		/* user specified a subset of groups */
		N = check_groups ( groups );
	}
		
	if ( N < 2 ) {
		G_fatal_error ("At least two groups of evidences must be present in the knowledge base.\n");
	}				

	/* allocate memory for all samples 
	 a sample holds one double for bel, pl and bpn for each
	 piece of evidence. The number of pieces of evidence is
	 the number of possible subsets in Theta 
	 = 2^NO_SINGLETONS ! 
	
	 The number of samples is = number of groups in the XML
	 knowledge base file (N) !
	*/
	samples = (Shypothesis**) G_malloc ((N * sizeof(Shypothesis*)));
	for ( i=0; i < N; i ++ ) {
		samples[i] = (Shypothesis*) G_malloc (sizeof(Shypothesis));
	}
	
	
	/* turn off normalisation if user wants it so */
	if ( flag.norm->answer == 1 ) {
		norm = 0;
	}	
			
	/* do some type-dependant checking */
	/* and open file pointers for all the maps to read! */
	file_pointers = NULL;
	if ( !strcmp (parm.type->answer,"rast") ) {
		if ( parm.groups->answer != NULL ) {
			/* check only user-specified groups */
			file_pointers = test_rast_XML ( parm.groups->answers, dstXMLFile );			
		} else {
			/* check all groups */
			file_pointers = test_rast_XML ( groups, dstXMLFile );
		}
	}	
	
	/* read in all samples in a type-dependant manner */
	if ( parm.groups->answer != NULL ) {
		/* read only user-specified groups */
		if ( !strcmp (parm.type->answer,"const") ) {
			if ( strcmp (parm.output->answer,G_location ()) != 0) {
				G_warning ("Ignoring parameter 'output='.\n");
			}
			if ( strcmp (parm.vals->answer,"bel") !=0 ) {
				G_warning ("Ignoring parameter 'values='.\n");
			}
			if ( parm.hyps->answer != NULL ) {
				G_warning ("Ignoring parameter 'hypotheses='.\n");
			}
			do_calculations_const (samples,parm.groups->answers, norm, dstXMLFile);
		}
		if ( !strcmp (parm.type->answer,"rast") ) {
			do_calculations_rast (samples,parm.groups->answers, norm,
								  parm.output->answer, parm.vals->answers, 
								  parm.hyps->answer, flag.quiet->answer,
							      parm.logfile->answer, dstXMLFile, file_pointers );
		}			
	} else {
		/* read all groups */
		if ( !strcmp (parm.type->answer,"const") ) {
			if ( strcmp (parm.output->answer,G_location ()) != 0) {
				G_warning ("Ignoring parameter 'output='.\n");
			}
			if ( strcmp (parm.vals->answer,"bel") !=0 ) {
				G_warning ("Ignoring parameter 'values='.\n");
			}
			if ( parm.hyps->answer != NULL ) {
				G_warning ("Ignoring parameter 'hypotheses='.\n");
			}
			do_calculations_const (samples,groups, norm, dstXMLFile);
		}
		if ( !strcmp (parm.type->answer,"rast") ) {
			do_calculations_rast (samples,groups, norm,
								  parm.output->answer, parm.vals->answers, 
							      parm.hyps->answer, flag.quiet->answer,
								  parm.logfile->answer, dstXMLFile, file_pointers );
		}			
	}	
		
	/* close logfile */
	/* write processing time to logfile */
	proctime = clock ();
	timeused = (unsigned long) proctime / CLOCKS_PER_SEC;
	days = timeused / 86400;
	hours = (timeused - (days * 86400)) / 3600;
	mins = (timeused - (days * 86400) - (hours * 3600)) / 60;		
	secs = (timeused - (days * 86400) - (hours * 3600) - (mins * 60));
	systime = time (NULL);
	
	if ( parm.logfile->answer != NULL ) {
		fprintf (lp,"\nCalculation finished on %s",ctime(&systime));		
		fprintf (lp,"Processing time: %id, %ih, %im, %is\n",
				days, hours, mins, secs );
		fflush (lp);
	}
	
	for (i=0; i<N; i++) {
		G_free (groups[i]);		
	}
	G_free (groups);
	
	return (EXIT_SUCCESS);
}
Esempio n. 14
0
int main(int argc, char **argv)
{
    char name[128] = "";
    struct Option *map;
    struct GModule *module;
    char *mapset;
    char buff[500];

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

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

    module = G_define_module();
    G_add_keyword(_("display"));
    G_add_keyword(_("raster"));
    module->description =
	"Allows the user to interactively change the color table "
	"of a raster map layer displayed on the graphics monitor.";

    map = G_define_option();
    map->key = "map";
    map->type = TYPE_STRING;
    if (*name)
	map->answer = name;
    if (*name)
	map->required = NO;
    else
	map->required = YES;
    map->gisprompt = "old,cell,raster";
    map->description = "Name of raster map";

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

    /* Make sure map is available */
    if (map->answer == NULL)
	exit(0);
    mapset = G_find_raster2(map->answer, "");
    if (mapset == NULL) {
	char msg[256];

	sprintf(msg, "Raster file [%s] not available", map->answer);
	G_fatal_error(msg);
    }

    if (Rast_map_is_fp(map->answer, mapset)) {
	sprintf(buff,
		"Raster file [%s] is floating point! \nd.colors only works with integer maps",
		map->answer);
	G_fatal_error(buff);
    }

    /* connect to the driver */
    if (R_open_driver() != 0)
	G_fatal_error("No graphics device selected");

    /* Read in the map region associated with graphics window */
    D_setup(0);

    get_map_info(map->answer, mapset);

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

    G_gisinit(argv[0]);

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

    parm.input = G_define_standard_option(G_OPT_V_INPUT);

    parm.dfield = G_define_standard_option(G_OPT_V_FIELD);

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

    parm.output = G_define_standard_option(G_OPT_R_OUTPUT);

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

    /* allocate buffers, etc. */

    dcell = Rast_allocate_d_buf();

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


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

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

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

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

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

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

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

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

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

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

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

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

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

    Rast_close(fd);

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

    G_done_msg(" ");

    exit(EXIT_SUCCESS);
}
Esempio n. 16
0
int main(int argc, char *argv[])
{
    struct Flag *tostdout, *overwrite;
    struct Option *extradirs;
    struct GModule *module;

    FILE *outstream;
    char *fontcapfile;
    struct stat status;
    int i;

    G_set_program_name(argv[0]);
    G_no_gisinit();
    G_set_gisrc_mode(G_GISRC_MODE_MEMORY);

    module = G_define_module();
    module->keywords = "general";
    module->description =
	"Generates the font configuration file by scanning various directories "
	"for fonts";

    overwrite = G_define_flag();
    overwrite->key = 'o';
    overwrite->description =
	"Overwrite font configuration file if already existing";

    tostdout = G_define_flag();
    tostdout->key = 's';
    tostdout->description =
	"Write font configuration file to standard output instead of "
	"$GISBASE/etc";

    extradirs = G_define_option();
    extradirs->key = "extradirs";
    extradirs->type = TYPE_STRING;
    extradirs->required = NO;
    extradirs->description =
	"Comma-separated list of extra directories to scan for "
	"Freetype-compatible fonts as well as the defaults (see documentation)";

    if (argc > 1 && G_parser(argc, argv))
	exit(EXIT_FAILURE);

    if (!tostdout->answer) {
	const char *gisbase = G_gisbase();
	const char *alt_file = getenv("GRASS_FONT_CAP");

	if (alt_file)
	    fontcapfile = G_store(alt_file);
	else
	    G_asprintf(&fontcapfile, "%s/etc/fontcap", gisbase);

	if (!stat(fontcapfile, &status)) {	/* File exists? */
	    if (!overwrite->answer)
		G_fatal_error
		    ("Fontcap file %s already exists; use -%c flag if you "
		     "wish to overwrite it", fontcapfile, overwrite->key);
	}
    }

    searchdirs = NULL;
    numsearchdirs = 0;

    /* Prepare list of directories to search */
    if (extradirs->answer) {
#ifndef HAVE_FT2BUILD_H
	G_warning("This GRASS installation was compiled without Freetype support, extradirs parameter ignored");
#endif
	char *str = G_store(extradirs->answer);

	while ((str = strtok(str, ","))) {
	    add_search_dir(str);
	    str = NULL;
	}
    }
    i = -1;
    while (standarddirs[++i])
	add_search_dir(standarddirs[i]);

    totalfonts = maxfonts = 0;
    fontcap = NULL;

    find_stroke_fonts();
    find_freetype_fonts();

    qsort(fontcap, totalfonts, sizeof(struct GFONT_CAP), compare_fonts);

    if (tostdout->answer)
	outstream = stdout;
    else {
	outstream = fopen(fontcapfile, "w");
	if (outstream == NULL)
	    G_fatal_error("Cannot open %s for writing: %s", fontcapfile,
			  strerror(errno));
    }

    for (i = 0; i < totalfonts; i++)
	fprintf(outstream, "%s|%s|%d|%s|%d|%s|\n", fontcap[i].name,
		fontcap[i].longname, fontcap[i].type, fontcap[i].path,
		fontcap[i].index, fontcap[i].encoding);

    fclose(outstream);

    exit(EXIT_SUCCESS);

}
Esempio n. 17
0
File: main.c Progetto: caomw/grass
int main(int argc, char **argv)
{
    int field, type, vertex_type;
    double dmax;
    char buf[DB_SQL_MAX];

    struct {
        struct Option *input, *output, *type, *dmax, *lfield, *use;
    } opt;
    struct {
        struct Flag *table, *inter;
    } flag;
    struct GModule *module;
    struct Map_info In, Out;
    struct line_cats *LCats;
    struct line_pnts *LPoints;

    dbDriver *driver;
    struct field_info *Fi;

    dbString stmt;

    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("vector"));
    G_add_keyword(_("geometry"));
    G_add_keyword("3D");
    G_add_keyword(_("node"));
    G_add_keyword(_("vertex"));
    module->description =
	_("Creates points along input lines in new vector map with 2 layers.");

    opt.input = G_define_standard_option(G_OPT_V_INPUT);

    opt.lfield = G_define_standard_option(G_OPT_V_FIELD);
    opt.lfield->key = "llayer";
    opt.lfield->answer = "1";
    opt.lfield->label = "Line layer number or name";
    opt.lfield->guisection = _("Selection");

    opt.type = G_define_standard_option(G_OPT_V3_TYPE);
    opt.type->answer = "point,line,boundary,centroid,face";
    opt.type->guisection = _("Selection");

    opt.output = G_define_standard_option(G_OPT_V_OUTPUT);

    opt.use = G_define_option();
    opt.use->key = "use";
    opt.use->type = TYPE_STRING;
    opt.use->required = NO;
    opt.use->description = _("Use line nodes or vertices only");
    opt.use->options = "node,vertex";

    opt.dmax = G_define_option();
    opt.dmax->key = "dmax";
    opt.dmax->type = TYPE_DOUBLE;
    opt.dmax->required = NO;
    opt.dmax->answer = "100";
    opt.dmax->description = _("Maximum distance between points in map units");

    flag.inter = G_define_flag();
    flag.inter->key = 'i';
    flag.inter->description = _("Interpolate points between line vertices (only for use=vertex)");
    

    flag.table = G_define_standard_flag(G_FLG_V_TABLE);

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

    LCats = Vect_new_cats_struct();
    LPoints = Vect_new_line_struct();
    db_init_string(&stmt);

    type = Vect_option_to_types(opt.type);
    dmax = atof(opt.dmax->answer);

    vertex_type = 0;
    if (opt.use->answer) {
        if (opt.use->answer[0] == 'n')
            vertex_type = GV_NODE;
        else
            vertex_type = GV_VERTEX;
    }
    
    Vect_check_input_output_name(opt.input->answer, opt.output->answer,
				 G_FATAL_EXIT);

    /* Open input lines */
    Vect_set_open_level(2);

    if (Vect_open_old2(&In, opt.input->answer, "", opt.lfield->answer) < 0)
	G_fatal_error(_("Unable to open vector map <%s>"), opt.input->answer);

    Vect_set_error_handler_io(&In, &Out);
    
    field = Vect_get_field_number(&In, opt.lfield->answer);
    
    /* Open output segments */
    if (Vect_open_new(&Out, opt.output->answer, Vect_is_3d(&In)) < 0)
	G_fatal_error(_("Unable to create vector map <%s>"),
			opt.output->answer);

    Vect_copy_head_data(&In, &Out);
    Vect_hist_copy(&In, &Out);
    Vect_hist_command(&Out);

    /* Table */
    Fi = NULL;
    if (!flag.table->answer) {
	struct field_info *Fin;

	/* copy input table */
	Fin = Vect_get_field(&In, field);
	if (Fin) {		/* table defined */
	    int ret;

	    Fi = Vect_default_field_info(&Out, 1, NULL, GV_MTABLE);
	    Vect_map_add_dblink(&Out, 1, NULL, Fi->table, Fin->key,
				Fi->database, Fi->driver);

	    ret = db_copy_table(Fin->driver, Fin->database, Fin->table,
				Fi->driver, Vect_subst_var(Fi->database,
							   &Out), Fi->table);

	    if (ret == DB_FAILED) {
		G_fatal_error(_("Unable to copy table <%s>"),
			      Fin->table);
	    }
	}

	Fi = Vect_default_field_info(&Out, 2, NULL, GV_MTABLE);
	Vect_map_add_dblink(&Out, 2, NULL, Fi->table, GV_KEY_COLUMN, Fi->database,
			    Fi->driver);

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

	if (field == -1) 
            sprintf(buf,
                "create table %s ( cat int, along double precision )",
                Fi->table);
         else
            sprintf(buf,
		"create table %s ( cat int, lcat int, along double precision )",
		Fi->table);
	db_append_string(&stmt, buf);

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

	if (db_create_index2(driver, Fi->table, GV_KEY_COLUMN) != DB_OK)
	    G_warning(_("Unable to create index for table <%s>, key <%s>"),
		      Fi->table, GV_KEY_COLUMN);

	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_begin_transaction(driver);
    }

    if (type & (GV_POINTS | GV_LINES | GV_FACE)) {
        int line, nlines, nskipped;

        nskipped = 0;
	nlines = Vect_get_num_lines(&In);
	for (line = 1; line <= nlines; line++) {
	    int ltype, cat;

	    G_debug(3, "line = %d", line);
	    G_percent(line, nlines, 2);
            
	    ltype = Vect_read_line(&In, LPoints, LCats, line);
	    if (!(ltype & type))
		continue;
            if (!Vect_cat_get(LCats, field, &cat) && field != -1) {
                nskipped++;
		continue;
            }

            /* Assign CAT for layer 0 objects (i.e. boundaries) */
            if (field == -1)
                cat = -1;

	    if (LPoints->n_points <= 1) {
		write_point(&Out, LPoints->x[0], LPoints->y[0], LPoints->z[0],
			    cat, 0.0, driver, Fi);
	    }
	    else {		/* lines */
		write_line(&Out, LPoints, cat, vertex_type,
			   flag.inter->answer, dmax, driver, Fi);
	    }
	}

        if (nskipped > 0)
            G_warning(_("%d features without category in layer <%d> skipped. "
                        "Note that features without category (usually boundaries) are not "
                        "skipped when '%s=-1' is given."),
                      nskipped, field, opt.lfield->key);
    }

    if (type == GV_AREA) {
	int area, nareas, centroid, cat;

	nareas = Vect_get_num_areas(&In);
	for (area = 1; area <= nareas; area++) {
	    int i, isle, nisles;

	    G_percent(area, nareas, 2);
            
	    centroid = Vect_get_area_centroid(&In, area);
	    cat = -1;
	    if (centroid > 0) {
		Vect_read_line(&In, NULL, LCats, centroid);
		if (!Vect_cat_get(LCats, field, &cat))
		  continue;
	    }

	    Vect_get_area_points(&In, area, LPoints);

	    write_line(&Out, LPoints, cat, vertex_type, flag.inter->answer,
		       dmax, driver, Fi);

	    nisles = Vect_get_area_num_isles(&In, area);

	    for (i = 0; i < nisles; i++) {
		isle = Vect_get_area_isle(&In, area, i);
		Vect_get_isle_points(&In, isle, LPoints);

		write_line(&Out, LPoints, cat, vertex_type,
			   flag.inter->answer, dmax, driver, Fi);
	    }
	}
    }

    if (!flag.table->answer) {
	db_commit_transaction(driver);
	db_close_database_shutdown_driver(driver);
    }

    Vect_build(&Out);

    /* Free, close ... */
    Vect_close(&In);

    G_done_msg(_("%d points written to output vector map."),
               Vect_get_num_primitives(&Out, GV_POINT));

    Vect_close(&Out);
    
    exit(EXIT_SUCCESS);
}
Esempio n. 18
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);
}
Esempio n. 19
0
File: main.c Progetto: caomw/grass
int main(int argc, char *argv[])
{

    /* loop */
    int i, j;

    /* store filename and path  */
    char *dig_file;
    
    char buf[2000];

    /* Other local variables */
    int attCount, nbreaks;

    struct grid_description grid_info;
    struct Cell_head window;
    struct Map_info Map;
    struct Option *vectname, *grid, *coord, *box, *angle, *position_opt, *breaks;
    struct GModule *module;
    struct Flag *points_fl, *line_fl;
    int points_p, line_p, output_type;
    char *desc;

    struct line_pnts *Points;
    struct line_cats *Cats;

    /* Attributes */
    struct field_info *Fi;
    dbDriver *Driver;
    dbString sql;

    G_gisinit(argv[0]);

    /* Set description */
    module = G_define_module();
    G_add_keyword(_("vector"));
    G_add_keyword(_("geometry"));
    module->description = _("Creates a vector map of a user-defined grid.");

    vectname = G_define_standard_option(G_OPT_V_OUTPUT);
    vectname->key = "map";

    grid = G_define_option();
    grid->key = "grid";
    grid->key_desc = _("rows,columns");
    grid->type = TYPE_INTEGER;
    grid->required = YES;
    grid->multiple = NO;
    grid->description = _("Number of rows and columns in grid");

    position_opt = G_define_option();
    position_opt->key = "position";
    position_opt->type = TYPE_STRING;
    position_opt->required = NO;
    position_opt->multiple = NO;
    position_opt->options = "region,coor";
    position_opt->answer = "region";
    position_opt->description = _("Where to place the grid");
    desc = NULL;
    G_asprintf(&desc,
            "region;%s;coor;%s",
            _("current region"),
            _("use 'coor' and 'box' options"));
    position_opt->descriptions = desc;

    coord = G_define_option();
    coord->key = "coor";
    coord->key_desc = "x,y";
    coord->type = TYPE_DOUBLE;
    coord->required = NO;
    coord->multiple = NO;
    coord->description =
	_("Lower left easting and northing coordinates of map");

    box = G_define_option();
    box->key = "box";
    box->key_desc = _("width,height");
    box->type = TYPE_DOUBLE;
    box->required = NO;
    box->multiple = NO;
    box->description = _("Width and height of boxes in grid");

    angle = G_define_option();
    angle->key = "angle";
    angle->type = TYPE_DOUBLE;
    angle->required = NO;
    angle->description =
	_("Angle of rotation (in degrees counter-clockwise)");
    angle->answer = "0";

    breaks = G_define_option();
    breaks->key = "breaks";
    breaks->type = TYPE_INTEGER;
    breaks->required = NO;
    breaks->description =
	_("Number of vertex points per grid cell");
    breaks->options = "0-60";
    breaks->answer = "3";

    points_fl = G_define_flag();
    points_fl->key = 'p';
    points_fl->description =
	_("Create grid of points instead of areas and centroids");

    line_fl = G_define_flag();
    line_fl->key = 'l';
    line_fl->description =
	_("Create grid as lines, instead of areas");

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

    line_p = line_fl->answer;
    if (line_p) {
	output_type = GV_LINE;
    } else {
	output_type = GV_BOUNDARY;
    }

    points_p = points_fl->answer;

    /* get the current window  */
    G_get_window(&window);

    /*
     * information we need to collect from user: origin point x and y (lower
     * left), shift in x, shift in y,  number of rows, number of cols
     */
    dig_file = G_store(vectname->answer);

    /* Number of row and cols */
    grid_info.num_rows = atoi(grid->answers[0]);
    grid_info.num_cols = atoi(grid->answers[1]);

    grid_info.angle = M_PI / 180 * atof(angle->answer);

    nbreaks = atoi(breaks->answer);

    /* Position */
    if (position_opt->answer[0] == 'r') {	/* region */
	if (coord->answer)
	    G_fatal_error(_("'coor' and 'position=region' are exclusive options"));

	if (box->answer)
	    G_fatal_error(_("'box' and 'position=region' are exclusive options"));

	if (grid_info.angle != 0.0)
	    G_fatal_error(_("'angle' and 'position=region' are exclusive options"));

	grid_info.origin_x = window.west;
	grid_info.origin_y = window.south;

	grid_info.length = (window.east - window.west) / grid_info.num_cols;
	grid_info.width = (window.north - window.south) / grid_info.num_rows;

	G_debug(2, "x = %e y = %e l = %e w = %e", grid_info.origin_x,
		grid_info.origin_y, grid_info.length, grid_info.width);
    }
    else {
	if (!coord->answer)
	    G_fatal_error(_("'coor' option missing"));

	if (!box->answer)
	    G_fatal_error(_("'box' option missing"));

	if (!G_scan_easting
	    (coord->answers[0], &(grid_info.origin_x), window.proj))
	    G_fatal_error(_("Invalid easting"));;
	if (!G_scan_northing
	    (coord->answers[1], &(grid_info.origin_y), window.proj))
	    G_fatal_error(_("Invalid northing"));;

	if (!G_scan_resolution
	    (box->answers[0], &(grid_info.length), window.proj))
	    G_fatal_error(_("Invalid distance"));;
	if (!G_scan_resolution
	    (box->answers[1], &(grid_info.width), window.proj))
	    G_fatal_error(_("Invalid distance"));;

    }

    /*
     * vector rows are the actual number of rows of vectors to make up the
     * entire grid.   ditto for cols.
     */
    grid_info.num_vect_rows = grid_info.num_rows + 1;
    grid_info.num_vect_cols = grid_info.num_cols + 1;

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

    /* Open output map */
    if (0 > Vect_open_new(&Map, dig_file, 0)) {
	G_fatal_error(_("Unable to create vector map <%s>"), dig_file);
    }

    Vect_hist_command(&Map);

    /* Open database, create table */
    Fi = Vect_default_field_info(&Map, 1, NULL, GV_1TABLE);
    Vect_map_add_dblink(&Map, Fi->number, Fi->name, Fi->table, Fi->key,
			Fi->database, Fi->driver);

    Driver =
	db_start_driver_open_database(Fi->driver,
				      Vect_subst_var(Fi->database, &Map));
    if (Driver == NULL)
	G_fatal_error(_("Unable to open database <%s> by driver <%s>"),
		      Fi->database, Fi->driver);
    db_set_error_handler_driver(Driver);

    if (grid_info.num_rows < 27 && grid_info.num_cols < 27) {
	sprintf(buf,
		"create table %s ( cat integer, row integer, col integer, "
		"rown varchar(1), coln varchar(1))", Fi->table);
    }
    else {
	sprintf(buf,
		"create table %s ( cat integer, row integer, col integer)",
		Fi->table);
    }
    db_set_string(&sql, buf);

    G_debug(1, "SQL: %s", db_get_string(&sql));

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

    if (db_create_index2(Driver, Fi->table, Fi->key) != 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);

    if (!points_p) {
	/* create areas */
	write_grid(&grid_info, &Map, nbreaks, output_type);
    }

    /* Create a grid of label points at the centres of the grid cells */
    G_verbose_message(_("Creating centroids..."));

    /* Write out centroids and attributes */
    /* If the output id is lines it skips to add centroids and attributes
       TODO decide what to write in the attribute table
     */
    if (!line_p) {
      db_begin_transaction(Driver);
      attCount = 0;
      for (i = 0; i < grid_info.num_rows; ++i) {
	  for (j = 0; j < grid_info.num_cols; ++j) {
	      double x, y;
	      const int point_type = points_p ? GV_POINT : GV_CENTROID;

	      x = grid_info.origin_x + (0.5 + j) * grid_info.length;
	      y = grid_info.origin_y + (0.5 + i) * grid_info.width;

	      rotate(&x, &y, grid_info.origin_x, grid_info.origin_y,
		    grid_info.angle);

	      Vect_reset_line(Points);
	      Vect_reset_cats(Cats);

	      Vect_append_point(Points, x, y, 0.0);
	      Vect_cat_set(Cats, 1, attCount + 1);
	      Vect_write_line(&Map, point_type, Points, Cats);

	      sprintf(buf, "insert into %s values ", Fi->table);
	      if (db_set_string(&sql, buf) != DB_OK)
		  G_fatal_error(_("Unable to fill attribute table"));

	      if (grid_info.num_rows < 27 && grid_info.num_cols < 27) {
		  sprintf(buf,
			  "( %d, %d, %d, '%c', '%c' )",
			  attCount + 1, grid_info.num_rows - i,
			  j + 1, 'A' + grid_info.num_rows - i - 1, 'A' + j);
	      }
	      else {
		  sprintf(buf, "( %d, %d, %d )",
			  attCount + 1, i + 1, j + 1);
	      }
	      if (db_append_string(&sql, buf) != DB_OK)
		      G_fatal_error(_("Unable to fill attribute table"));

	      G_debug(3, "SQL: %s", db_get_string(&sql));

	      if (db_execute_immediate(Driver, &sql) != DB_OK) {
		  G_fatal_error(_("Unable to insert new record: %s"),
			      db_get_string(&sql));
	      }
	      attCount++;
	  }
      }
    }
    db_commit_transaction(Driver);

    db_close_database_shutdown_driver(Driver);

    Vect_build(&Map);
    Vect_close(&Map);

    exit(EXIT_SUCCESS);
}
Esempio n. 20
0
int main( int argc, char **argv )
{
  char *mapset;
  char *name;
  struct GModule *module;
  struct Option *map;
  struct Option *win;
  struct Option *format;
  struct Cell_head window;
  RASTER_MAP_TYPE raster_type;

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

  module = G_define_module();
  module->keywords = ( "display, raster" );
  module->description = ( "Output raster map layers in a format suitable for display in QGIS" );

  map = G_define_standard_option( G_OPT_R_MAP );
  map->description = ( "Raster map to be displayed" );

  format = G_define_option();
  format->key = "format";
  format->type = TYPE_STRING;
  format->description = "format";
  format->options = "color,value";

  win = G_define_option();
  win->key = "window";
  win->type = TYPE_DOUBLE;
  win->multiple = YES;
  win->description = "xmin,ymin,xmax,ymax,ncols,nrows";

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

  name = map->answer;

  /* Make sure map is available */
#if GRASS_VERSION_MAJOR < 7
  mapset = G_find_cell2( name, "" );
  if ( mapset == NULL )
    G_fatal_error(( "Raster map <%s> not found" ), name );
#else
  mapset = "";
#endif

  /* It can happen that GRASS data set is 'corrupted' and zone differs in WIND and
   * cellhd, and G_open_cell_old fails, so it is better to read window from map */
  /* G_get_window( &window ); */
  G_get_cellhd( name, mapset, &window );
  window.west = atof( win->answers[0] );
  window.south = atof( win->answers[1] );
  window.east = atof( win->answers[2] );
  window.north = atof( win->answers[3] );
  window.cols = atoi( win->answers[4] );
  window.rows = atoi( win->answers[5] );
  G_adjust_Cell_head( &window, 1, 1 );
  G_set_window( &window );

  raster_type = G_raster_map_type( name, "" );

  display( name, mapset, raster_type, format->answer );

  exit( EXIT_SUCCESS );
}
Esempio n. 21
0
File: main.c Progetto: caomw/grass
int main(int argc, char *argv[])
{
    FILE *ascii;
    struct Option *input, *output, *type_opt, *dp_opt, *layer_opt, *scale;
    struct Flag *coorcorr, *numatts, *labels;
    int itype, *types = NULL, typenum = 0, dp, i;
    struct Map_info Map;
    struct bound_box box;
    struct GModule *module;
    int layer, level;
    double zscale = 1.0, llscale = 1.0;


    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("vector"));
    G_add_keyword(_("export"));
    G_add_keyword("VTK");
    module->description =
	_("Converts a vector map to VTK ASCII output.");

    input = G_define_standard_option(G_OPT_V_INPUT);

    output = G_define_standard_option(G_OPT_F_OUTPUT);
    output->required = NO;
    output->description = _("Name for output VTK file");

    type_opt = G_define_standard_option(G_OPT_V_TYPE);
    type_opt->answer = "point,kernel,centroid,line,boundary,area,face";
    type_opt->options = "point,kernel,centroid,line,boundary,area,face";

    dp_opt = G_define_option();
    dp_opt->key = "dp";
    dp_opt->type = TYPE_INTEGER;
    dp_opt->required = NO;
    dp_opt->description =
	_("Number of significant digits (floating point only)");

    scale = G_define_option();
    scale->key = "scale";
    scale->type = TYPE_DOUBLE;
    scale->required = NO;
    scale->description = _("Scale factor for elevation");
    scale->answer = "1.0";

    layer_opt = G_define_option();
    layer_opt->key = "layer";
    layer_opt->type = TYPE_INTEGER;
    layer_opt->required = NO;
    layer_opt->answer = "1";
    layer_opt->description = _("Layer number");

    coorcorr = G_define_flag();                                            
    coorcorr->key = 'c';                                                   
    coorcorr->description = 
    	_("Correct the coordinates to fit the VTK-OpenGL precision");
    
    numatts = G_define_flag();
    numatts->key = 'n';
    numatts->description = 
    	_("Export numeric attribute table fields as VTK scalar variables");

    labels = NULL; /* to avoid compiler warning about "unused variable"*/
    /* not yet supported
    labels = G_define_flag();
    labels->key = 'l';
    labels->description = _("Export text attribute table fields as VTK labels");
    */
    
    if (G_parser(argc, argv))
	exit(EXIT_FAILURE);

    for (i = 0; type_opt->answers && type_opt->answers[i]; i++)
	typenum++;

    if (typenum > 0) {
	types = (int *)calloc(typenum, sizeof(int));
    }
    else {
	G_fatal_error("Usage: Wrong vector type");
    }

    i = 0;
    while (type_opt->answers[i]) {
	types[i] = -1;
	switch (type_opt->answers[i][0]) {
	case 'p':
	    types[i] = GV_POINT;
	    break;
	case 'k':
	    types[i] = GV_KERNEL;
	    break;
	case 'c':
	    types[i] = GV_CENTROID;
	    break;
	case 'l':
	    types[i] = GV_LINE;
	    break;
	case 'b':
	    types[i] = GV_BOUNDARY;
	    break;
	case 'a':
	    types[i] = GV_AREA;
	    break;
	case 'f':
	    types[i] = GV_FACE;
	    break;
	}
	i++;
    }
    itype = Vect_option_to_types(type_opt);

    /* read and compute the scale factor */
    sscanf(scale->answer, "%lf", &zscale);
    /*if LL projection, convert the elevation values to degrees */
    if (G_projection() == PROJECTION_LL) {
	llscale = M_PI / (180) * 6378137;
	zscale /= llscale;
	printf("Scale %g\n", zscale);
    }

    /*The precision of the output */
    if (dp_opt->answer) {
	if (sscanf(dp_opt->answer, "%d", &dp) != 1)
	    G_fatal_error(_("Failed to interpret 'dp' parameter as an integer"));
	if (dp > 8 || dp < 0)
	    G_fatal_error(_("dp has to be from 0 to 8"));
    }
    else {
	dp = 8;			/*This value is taken from the lib settings in G_feature_easting */
    }

    /*The Layer */
    if (layer_opt->answer) {
	if (sscanf(layer_opt->answer, "%d", &layer) != 1)
	    G_fatal_error(_("Failed to interpret 'layer' parameter as an integer"));
    }
    else {
	layer = 1;
    }

    if (output->answer) {
	ascii = fopen(output->answer, "w");
	if (ascii == NULL) {
	    G_fatal_error(_("Unable to open file <%s>"), output->answer);
	}
    }
    else {
	ascii = stdout;
    }

    /* Open input vector */
    level = Vect_open_old(&Map, input->answer, "");
    if (level < 2 && (itype & GV_AREA))
	G_fatal_error(_("Export of areas requires topology. "
	                "Please adjust '%s' option or rebuild topology."),
			type_opt->key);

    if (level == 2)
	Vect_get_map_box(&Map, &box);
    else {
	int i, type, first = TRUE;
	struct line_pnts *Points = Vect_new_line_struct();

	Vect_rewind(&Map);
	while ((type = Vect_read_next_line(&Map, Points, NULL)) > 0) {

	    if (first) {
		box.E = box.W = Points->x[0];
		box.N = box.S = Points->y[0];
		box.B = box.T = Points->z[0];
		first = FALSE;
	    }
	    for (i = 1; i < Points->n_points; i++) {
		if (Points->x[i] > box.E)
		    box.E = Points->x[i];
		else if (Points->x[i] < box.W)
		    box.W = Points->x[i];

		if (Points->y[i] > box.N)
		    box.N = Points->y[i];
		else if (Points->y[i] < box.S)
		    box.S = Points->y[i];

		if (Points->z[i] > box.T)
		    box.T = Points->z[i];
		else if (Points->z[i] < box.B)
		    box.B = Points->z[i];
	    }
	}
	Vect_destroy_line_struct(Points);
    }

    /*Correct the coordinates, so the precision of VTK is not hurt :( */
    if (coorcorr->answer) {

	/*Use the center of the vector's bbox as extent */
	y_extent = (box.N + box.S) / 2;
	x_extent = (box.W + box.E) / 2;
    }
    else {
	x_extent = 0;
	y_extent = 0;
    }

    /*Write the header */
    write_vtk_head(ascii, &Map);
    /*Write the geometry and data */
    write_vtk(ascii, &Map, layer, types, typenum, dp, zscale, numatts->answer, 0 );
    /* change to this, when labels get supported:
    write_vtk(ascii, &Map, layer, types, typenum, dp, zscale, numatts->answer, labels->answer );
    */

    if (ascii != NULL)
	fclose(ascii);

    Vect_close(&Map);

    exit(EXIT_SUCCESS);
}
Esempio n. 22
0
int main(int argc, char *argv[])
{
    int i, j;			/* Loop control variables */
    int bands;			/* Number of image bands */
    double *mu;			/* Mean vector for image bands */
    double **covar;		/* Covariance Matrix */
    double *eigval;
    double **eigmat;
    int *inp_fd;
    int scale, scale_max, scale_min;

    struct GModule *module;
    struct Option *opt_in, *opt_out, *opt_scale;

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

    module = G_define_module();
    G_add_keyword(_("imagery"));
    G_add_keyword(_("image transformation"));
    G_add_keyword(_("PCA"));
    module->description = _("Principal components analysis (PCA) "
			    "for image processing.");

    /* Define options */
    opt_in = G_define_standard_option(G_OPT_R_INPUTS);
    opt_in->description = _("Name of two or more input raster maps");

    opt_out = G_define_option();
    opt_out->label = _("Base name for output raster maps");
    opt_out->description =
	_("A numerical suffix will be added for each component map");
    opt_out->key = "output_prefix";
    opt_out->type = TYPE_STRING;
    opt_out->key_desc = "string";
    opt_out->required = YES;

    opt_scale = G_define_option();
    opt_scale->key = "rescale";
    opt_scale->type = TYPE_INTEGER;
    opt_scale->key_desc = "min,max";
    opt_scale->required = NO;
    opt_scale->answer = "0,255";
    opt_scale->label =
	_("Rescaling range for output maps");
    opt_scale->description =
	_("For no rescaling use 0,0");
    opt_scale->guisection = _("Rescale");
    
    if (G_parser(argc, argv))
	exit(EXIT_FAILURE);


    /* determine number of bands passed in */
    for (bands = 0; opt_in->answers[bands] != NULL; bands++) ;

    if (bands < 2)
	G_fatal_error(_("Sorry, at least 2 input bands must be provided"));

    /* default values */
    scale = 1;
    scale_min = 0;
    scale_max = 255;

    /* get scale parameters */
    set_output_scale(opt_scale, &scale, &scale_min, &scale_max);

    /* allocate memory */
    covar = G_alloc_matrix(bands, bands);
    mu = G_alloc_vector(bands);
    inp_fd = G_alloc_ivector(bands);
    eigmat = G_alloc_matrix(bands, bands);
    eigval = G_alloc_vector(bands);

    /* open and check input/output files */
    for (i = 0; i < bands; i++) {
	char tmpbuf[128];

	sprintf(tmpbuf, "%s.%d", opt_out->answer, i + 1);
	G_check_input_output_name(opt_in->answers[i], tmpbuf, GR_FATAL_EXIT);

	inp_fd[i] = Rast_open_old(opt_in->answers[i], "");
    }

    G_verbose_message(_("Calculating covariance matrix..."));
    calc_mu(inp_fd, mu, bands);

    calc_covariance(inp_fd, covar, mu, bands);

    for (i = 0; i < bands; i++) {
	for (j = 0; j < bands; j++) {
	    covar[i][j] =
		covar[i][j] /
		((double)((Rast_window_rows() * Rast_window_cols()) - 1));
	    G_debug(3, "covar[%d][%d] = %f", i, j, covar[i][j]);
	}
    }

    G_math_d_copy(covar[0], eigmat[0], bands*bands);
    G_debug(1, "Calculating eigenvalues and eigenvectors...");
    G_math_eigen(eigmat, eigval, bands);

#ifdef PCA_DEBUG
    /* dump eigen matrix and eigen values */
    dump_eigen(bands, eigmat, eigval);
#endif

    G_debug(1, "Ordering eigenvalues in descending order...");
    G_math_egvorder(eigval, eigmat, bands);

    G_debug(1, "Transposing eigen matrix...");
    G_math_d_A_T(eigmat, bands);

    /* write output images */
    write_pca(eigmat, inp_fd, opt_out->answer, bands, scale, scale_min,
	      scale_max);

    /* write colors and history to output */
    for (i = 0; i < bands; i++) {
	char outname[80];

	sprintf(outname, "%s.%d", opt_out->answer, i + 1);

	/* write colors and history to file */
	write_support(bands, outname, eigmat, eigval);

	/* close output file */
	Rast_unopen(inp_fd[i]);
    }
    
    /* free memory */
    G_free_matrix(covar);
    G_free_vector(mu);
    G_free_ivector(inp_fd);
    G_free_matrix(eigmat);
    G_free_vector(eigval);

    exit(EXIT_SUCCESS);
}
Esempio n. 23
0
int main(int argc, char *argv[])
{
    struct Map_info In, Out;
    static struct line_pnts *Points;
    struct line_cats *Cats;
    struct field_info *Fi;
    struct cat_list *Clist;
    int i, j, ret, option, otype, type, with_z, step, id;
    int n_areas, centr, new_centr, nmodified;
    int open_level;
    double x, y;
    int cat, ocat, scat, *fields, nfields, field;
    struct GModule *module;
    struct Option *in_opt, *out_opt, *option_opt, *type_opt;
    struct Option *cat_opt, *field_opt, *step_opt, *id_opt;
    struct Flag *shell, *notab;
    FREPORT **freps;
    int nfreps, rtype, fld;
    char *desc;

    module = G_define_module();
    G_add_keyword(_("vector"));
    G_add_keyword(_("category"));
    G_add_keyword(_("layer"));
    module->description =
	_("Attaches, deletes or reports vector categories to map geometry.");

    in_opt = G_define_standard_option(G_OPT_V_INPUT);

    field_opt = G_define_standard_option(G_OPT_V_FIELD);
    field_opt->multiple = YES;
    field_opt->guisection = _("Selection");

    type_opt = G_define_standard_option(G_OPT_V3_TYPE);
    type_opt->answer = "point,line,centroid,face";
    type_opt->guisection = _("Selection");

    id_opt = G_define_standard_option(G_OPT_V_IDS);
    id_opt->label = _("Feature ids (by default all features are processed)");
    id_opt->guisection = _("Selection");

    out_opt = G_define_standard_option(G_OPT_V_OUTPUT);
    out_opt->required = NO;

    option_opt = G_define_option();
    option_opt->key = "option";
    option_opt->type = TYPE_STRING;
    option_opt->required = YES;
    option_opt->multiple = NO;
    option_opt->options = "add,del,chlayer,sum,report,print,layers,transfer";
    option_opt->description = _("Action to be done");
    desc = NULL;
    G_asprintf(&desc,
	       "add;%s;"
	       "del;%s;"
	       "chlayer;%s;"
	       "sum;%s;"
	       "transfer;%s;"
	       "report;%s;"
	       "print;%s;"
	       "layers;%s",
	       _("add a category to features without category in the given layer"),
	       _("delete category (cat=-1 to delete all categories of given layer)"),
	       _("change layer number (e.g. layer=3,1 changes layer 3 to layer 1)"),
	       _("add the value specified by cat option to the current category value"),
	       _("copy values from one layer to another (e.g. layer=1,2,3 copies values from layer 1 to layer 2 and 3)"),
	       _("print report (statistics), in shell style: layer type count min max"),
	       _("print category values, layers are separated by '|', more cats in the same layer are separated by '/'"),
	       _("print only layer numbers"));
    option_opt->descriptions = desc;
    
    cat_opt = G_define_standard_option(G_OPT_V_CAT);
    cat_opt->answer = "1";

    step_opt = G_define_option();
    step_opt->key = "step";
    step_opt->type = TYPE_INTEGER;
    step_opt->required = NO;
    step_opt->multiple = NO;
    step_opt->answer = "1";
    step_opt->description = _("Category increment");

    shell = G_define_flag();
    shell->key = 'g';
    shell->label = _("Shell script style, currently only for report");
    shell->description = _("Format: layer type count min max");
    
    notab = G_define_standard_flag(G_FLG_V_TABLE);
    notab->description = _("Do not copy attribute table(s)");

    G_gisinit(argv[0]);

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

    /* read options */
    option = 0;
    switch (option_opt->answer[0]) {
    case ('a'):
	option = O_ADD;
	break;
    case ('d'):
	option = O_DEL;
	break;
    case ('c'):
	option = O_CHFIELD;
	G_warning(_("Database connection and attribute tables for concerned layers are not changed"));
	break;
    case ('s'):
	option = O_SUM;
	break;
    case ('t'):
        option = O_TRANS;
        break;
    case ('r'):
	option = O_REP;
	break;
    case ('p'):
	option = O_PRN;
	break;
    case ('l'):
	option = O_LYR;
	break;
    }

    if (option == O_LYR) {
	/* print vector layer numbers */
	/* open vector on level 2 head only, this is why this option
	 * is processed here, all other options need (?) to fully open 
	 * the input vector */
	Vect_set_open_level(2);
	if (Vect_open_old_head2(&In, in_opt->answer, "", field_opt->answer) < 2) {
	    G_fatal_error(_("Unable to open vector map <%s> at topological level %d"),
			  Vect_get_full_name(&In), 2);
	}
	if (In.format == GV_FORMAT_NATIVE) {
	    nfields = Vect_cidx_get_num_fields(&In);
	    for (i = 0; i < nfields; i++) {
		if ((field = Vect_cidx_get_field_number(&In, i)) > 0)
		    fprintf(stdout, "%d\n", field);
	    }
	}
	else
	    fprintf(stdout, "%s\n", field_opt->answer);

	Vect_close(&In);
	exit(EXIT_SUCCESS);
    }

    cat = atoi(cat_opt->answer);
    step = atoi(step_opt->answer);
    otype = Vect_option_to_types(type_opt);

    if (cat < 0 && option == O_ADD)
	G_fatal_error(_("Invalid category number (must be equal to or greater than 0). "
			"Normally category number starts at 1."));

    /* collect ids */
    if (id_opt->answer) {
	Clist = Vect_new_cat_list();
	Clist->field = atoi(field_opt->answer);
	ret = Vect_str_to_cat_list(id_opt->answer, Clist);
	if (ret > 0) {
	    G_warning(n_("%d error in id option",
                         "%d errors in id option",
                         ret), ret);
	}
    }
    else {
	Clist = NULL;
    }

    if ((option != O_REP) && (option != O_PRN) && (option != O_LYR)) {
	if (out_opt->answer == NULL)
	    G_fatal_error(_("Output vector wasn't entered"));

	Vect_check_input_output_name(in_opt->answer, out_opt->answer,
				     G_FATAL_EXIT);
    }

    Points = Vect_new_line_struct();
    Cats = Vect_new_cats_struct();

    /* do we need topology ? */
    if ((option == O_ADD && (otype & GV_AREA)) ||
	(option == O_REP && (otype & GV_AREA)) ||
        (option == O_TRANS) || /* topo for cidx check */
        (option == O_LYR)) /* topo for cidx check */
	open_level = 2;
    else
	open_level = 1;

    /* open input vector */
    if (open_level > 1) {
	Vect_set_open_level(open_level);
	if (Vect_open_old2(&In, in_opt->answer, "", field_opt->answer) < open_level) {
	    G_warning(_("Unable to open vector map <%s> at topological level %d"),
			  Vect_get_full_name(&In), open_level);
	    open_level = 1;
	}
    }
    if (open_level == 1) {
	Vect_set_open_level(open_level);
	if (Vect_open_old2(&In, in_opt->answer, "", field_opt->answer) < open_level) {
	    G_fatal_error(_("Unable to open vector map <%s> at topological level %d"),
			  Vect_get_full_name(&In), open_level);
	}
    }

    /* read fields */
    i = nfields = 0;
    while (field_opt->answers[i++])
	nfields++;
    fields = (int *)G_malloc(nfields * sizeof(int));
    
    i = 0;
    while (field_opt->answers[i]) {
	fields[i] = Vect_get_field_number(&In, field_opt->answers[i]);
	i++;
    }
    if (nfields > 1 && option != O_PRN && option != O_CHFIELD && option != O_TRANS)
	G_fatal_error(_("Too many layers for this operation"));
    
    if (nfields != 2 && option == O_CHFIELD)
	G_fatal_error(_("2 layers must be specified"));

    if (option == O_TRANS && open_level == 1 && nfields < 2) {
	G_fatal_error(_("2 layers must be specified"));
    }

    if (option == O_TRANS && open_level > 1) {
	/* check if field[>0] already exists */
	if (nfields > 1) {
	    for(i = 1; i < nfields; i++) {
		if (Vect_cidx_get_field_index(&In, fields[i]) != -1)
		    G_warning(_("Categories already exist in layer %d"), fields[i]);
	    }
	}
	/* find next free layer number */
	else if (nfields == 1) {
	    int max = -1;
	    
	    for (i = 0; i < Vect_cidx_get_num_fields(&In); i++) {
		if (max < Vect_cidx_get_field_number(&In, i))
		    max = Vect_cidx_get_field_number(&In, i);
	    }
	    max++;

	    nfields++;
	    fields = (int *)G_realloc(fields, nfields * sizeof(int));
	    fields[nfields - 1] = max;
	}
    }

    if (otype & GV_AREA && option == O_TRANS && !(otype & GV_CENTROID))
	otype |= GV_CENTROID;

    /* open output vector if needed */
    if (option == O_ADD || option == O_DEL || option == O_CHFIELD ||
	option == O_SUM || option == O_TRANS) {
	with_z = Vect_is_3d(&In);

	if (0 > Vect_open_new(&Out, out_opt->answer, with_z)) {
	    Vect_close(&In);
	    exit(EXIT_FAILURE);
	}

	Vect_copy_head_data(&In, &Out);
	Vect_hist_copy(&In, &Out);
	Vect_hist_command(&Out);
    }

    id = 0;

    nmodified = 0;

    if (option == O_ADD || option == O_DEL || option == O_CHFIELD ||
	option == O_SUM || option == O_TRANS) {
	G_message(_("Processing features..."));
    }

    switch (option) {
    case (O_ADD):
	/* Lines */
	while ((type = Vect_read_next_line(&In, Points, Cats)) > 0) {
	    id++;
	    if (type & otype && (!Clist ||
				 (Clist &&
				  Vect_cat_in_cat_list(id, Clist) == TRUE))) {
		if ((Vect_cat_get(Cats, fields[0], &ocat)) == 0) {
		    if (ocat < 0) {
			if (Vect_cat_set(Cats, fields[0], cat) > 0) {
			    nmodified++;
			}
			cat += step;
		    }
		}
	    }
	    Vect_write_line(&Out, type, Points, Cats);
	}
	/* Areas */
	if ((otype & GV_AREA) && open_level > 1) {
	    n_areas = Vect_get_num_areas(&In);
	    new_centr = 0;
	    for (i = 1; i <= n_areas; i++) {
		centr = Vect_get_area_centroid(&In, i);
		if (centr > 0)
		    continue;	/* Centroid exists and may be processed as line */
		ret = Vect_get_point_in_area(&In, i, &x, &y);
		if (ret < 0) {
		    G_warning(_("Unable to calculate area centroid"));
		    continue;
		}
		Vect_reset_line(Points);
		Vect_reset_cats(Cats);
		Vect_append_point(Points, x, y, 0.0);
		if (Vect_cat_set(Cats, fields[0], cat) > 0) {
		    nmodified++;
		}
		cat += step;
		Vect_write_line(&Out, GV_CENTROID, Points, Cats);
		new_centr++;
	    }
	    if (new_centr > 0) 
		G_message(n_("%d new centroid placed in output map",
                             "%d new centroids placed in output map",
                             new_centr), new_centr);
	}
	break;

    case (O_TRANS):
	/* Lines */
	while ((type = Vect_read_next_line(&In, Points, Cats)) > 0) {
	    id++;
	    if (type & otype && (!Clist ||
				 (Clist &&
				  Vect_cat_in_cat_list(id, Clist) == TRUE))) {
		int n = Cats->n_cats;

		scat = -1;
		for (i = 0; i < n; i++) {
		    if (Cats->field[i] == fields[0]) {
			scat = Cats->cat[i];
			for (j = 1; j < nfields; j++) {
			    if (Vect_cat_set(Cats, fields[j], scat) > 0) {
				G_debug(4, "Copy cat %i of field %i to field %i", scat, fields[0], fields[j]);
			    }
			}
		    }
		}
		if (scat != -1)
		    nmodified++;
	    }
	    Vect_write_line(&Out, type, Points, Cats);
	}
	break;

    case (O_DEL):
	while ((type = Vect_read_next_line(&In, Points, Cats)) > 0) {
	    id++;
	    if (type & otype && (!Clist ||
				 (Clist &&
				  Vect_cat_in_cat_list(id, Clist) == TRUE))) {
		ret = Vect_field_cat_del(Cats, fields[0], cat);
		if (ret > 0) {
		    nmodified++;
		}
	    }
	    Vect_write_line(&Out, type, Points, Cats);
	}
	break;

    case (O_CHFIELD):
	while ((type = Vect_read_next_line(&In, Points, Cats)) > 0) {
	    id++;
	    if (type & otype && (!Clist ||
				 (Clist &&
				  Vect_cat_in_cat_list(id, Clist) == TRUE))) {
		i = 0;
		while (i < Cats->n_cats) {
		    if (Cats->field[i] == fields[0]) {
			int found = -1;
			
			/* check if cat already exists in layer fields[1] */
			for (j = 0; j < Cats->n_cats; j++) {
			    if (Cats->field[j] == fields[1] &&
				Cats->cat[j] == Cats->cat[i]) {
				found = j;
				break;
			    }
			}
			/* does not exist, change layer */
			if (found < 0) {
			    Cats->field[i] = fields[1];
			    i++;
			}
			/* exists already in fields[1], delete from fields[0] */
			else
			    Vect_field_cat_del(Cats, fields[0], Cats->cat[found]);
			nmodified++;
		    }
		}
	    }
	    Vect_write_line(&Out, type, Points, Cats);
	}
	break;

    case (O_SUM):
	while ((type = Vect_read_next_line(&In, Points, Cats)) > 0) {
	    id++;
	    if (type & otype && (!Clist ||
				 (Clist &&
				  Vect_cat_in_cat_list(id, Clist) == TRUE))) {
		for (i = 0; i < Cats->n_cats; i++) {
		    if (Cats->field[i] == fields[0]) {
			Cats->cat[i] += cat;
		    }
		}
		nmodified++;
	    }
	    Vect_write_line(&Out, type, Points, Cats);
	}
	break;

    case (O_REP):
	nfreps = 0;
	freps = NULL;
	while ((type = Vect_read_next_line(&In, Points, Cats)) > 0) {
	    id++;
	    if (Clist && Vect_cat_in_cat_list(id, Clist) == FALSE)
		continue;

	    switch (type) {
	    case (GV_POINT):
		rtype = FR_POINT;
		break;
	    case (GV_LINE):
		rtype = FR_LINE;
		break;
	    case (GV_BOUNDARY):
		rtype = FR_BOUNDARY;
		break;
	    case (GV_CENTROID):
		rtype = FR_CENTROID;
		break;
	    case (GV_FACE):
		rtype = FR_FACE;
		break;
	    case (GV_KERNEL):
		rtype = FR_KERNEL;
		break;
	    default:
		rtype = FR_UNKNOWN;
	    }

	    for (i = 0; i < Cats->n_cats; i++) {
		field = Cats->field[i];
		cat = Cats->cat[i];


		ret = FALSE;
		for (j = 0; j < nfreps; j++) {
		    if (freps[j]->field == field) {
			fld = j;
			ret = TRUE;
			break;
		    }
		}
		if (!ret) {	/* field report doesn't exist */
		    nfreps++;
		    freps =
			(FREPORT **) G_realloc(freps,
					       nfreps * sizeof(FREPORT *));
		    fld = nfreps - 1;
		    freps[fld] = (FREPORT *) G_calloc(1, sizeof(FREPORT));
		    freps[fld]->field = field;
		    for (j = 0; j < FRTYPES; j++) {
			/* cat '0' is valid category number */
			freps[fld]->min[j] = -1;
		    }
		    if ((Fi = Vect_get_field(&In, field)) != NULL) {
			freps[fld]->table = G_store(Fi->table);
		    }
		    else {
			freps[fld]->table = '\0';
		    }
		}

		freps[fld]->count[rtype]++;
		freps[fld]->count[FR_ALL]++;

		if (freps[fld]->min[rtype] == -1 ||
		    freps[fld]->min[rtype] > cat)
		    freps[fld]->min[rtype] = cat;

		if ((freps[fld]->max[rtype] == 0) ||
		    freps[fld]->max[rtype] < cat)
		    freps[fld]->max[rtype] = cat;

		if (freps[fld]->min[FR_ALL] == -1 ||
		    freps[fld]->min[FR_ALL] > cat)
		    freps[fld]->min[FR_ALL] = cat;

		if ((freps[fld]->max[FR_ALL] == 0) ||
		    freps[fld]->max[FR_ALL] < cat)
		    freps[fld]->max[FR_ALL] = cat;
	    }
	}
	/* Areas */
	if ((otype & GV_AREA) && open_level > 1 && !Clist) {
	    n_areas = Vect_get_num_areas(&In);
	    for (i = 1; i <= n_areas; i++) {
		int k;

		centr = Vect_get_area_centroid(&In, i);
		if (centr <= 0)
		    continue;	/* Area without centroid */
		    
		Vect_read_line(&In, NULL, Cats, centr);
		for (j = 0; j < Cats->n_cats; j++) {
		    field = Cats->field[j];
		    cat = Cats->cat[j];


		    ret = FALSE;
		    for (k = 0; k < nfreps; k++) {
			if (freps[k]->field == field) {
			    fld = k;
			    ret = TRUE;
			    break;
			}
		    }
		    if (!ret) {	/* field report doesn't exist */
			nfreps++;
			freps =
			    (FREPORT **) G_realloc(freps,
						   nfreps * sizeof(FREPORT *));
			fld = nfreps - 1;
			freps[fld] = (FREPORT *) G_calloc(1, sizeof(FREPORT));
			freps[fld]->field = field;
			for (j = 0; j < FRTYPES; j++) {
			    /* cat '0' is valid category number */
			    freps[fld]->min[k] = -1;
			}
			if ((Fi = Vect_get_field(&In, field)) != NULL) {
			    freps[fld]->table = G_store(Fi->table);
			}
			else {
			    freps[fld]->table = '\0';
			}
		    }

		    freps[fld]->count[FR_AREA]++;

		    if (freps[fld]->min[FR_AREA] == -1 ||
			freps[fld]->min[FR_AREA] > cat)
			freps[fld]->min[FR_AREA] = cat;

		    if ((freps[fld]->max[FR_AREA] == 0) ||
			freps[fld]->max[FR_AREA] < cat)
			freps[fld]->max[FR_AREA] = cat;
		}
	    }
	}
	for (i = 0; i < nfreps; i++) {
	    if (shell->answer) {
		if (freps[i]->count[FR_POINT] > 0)
		    fprintf(stdout, "%d point %d %d %d\n", freps[i]->field,
			    freps[i]->count[FR_POINT],
			    (freps[i]->min[FR_POINT] < 0 ? 0 : freps[i]->min[FR_POINT]),
			    freps[i]->max[FR_POINT]);

		if (freps[i]->count[FR_LINE] > 0)
		    fprintf(stdout, "%d line %d %d %d\n", freps[i]->field,
			    freps[i]->count[FR_LINE],
			    (freps[i]->min[FR_LINE] < 0 ? 0 : freps[i]->min[FR_LINE]),
			    freps[i]->max[FR_LINE]);

		if (freps[i]->count[FR_BOUNDARY] > 0)
		    fprintf(stdout, "%d boundary %d %d %d\n", freps[i]->field,
			    freps[i]->count[FR_BOUNDARY],
			    (freps[i]->min[FR_BOUNDARY] < 0 ? 0 : freps[i]->min[FR_BOUNDARY]),
			    freps[i]->max[FR_BOUNDARY]);

		if (freps[i]->count[FR_CENTROID] > 0)
		    fprintf(stdout, "%d centroid %d %d %d\n", freps[i]->field,
			    freps[i]->count[FR_CENTROID],
			    (freps[i]->min[FR_BOUNDARY] < 0 ? 0 : freps[i]->min[FR_BOUNDARY]),
			    freps[i]->max[FR_CENTROID]);

		if (freps[i]->count[FR_AREA] > 0)
		    fprintf(stdout, "%d area %d %d %d\n", freps[i]->field,
			    freps[i]->count[FR_AREA],
			    (freps[i]->min[FR_AREA] < 0 ? 0 : freps[i]->min[FR_AREA]),
			    freps[i]->max[FR_AREA]);

		if (freps[i]->count[FR_FACE] > 0)
		    fprintf(stdout, "%d face %d %d %d\n", freps[i]->field,
			    freps[i]->count[FR_FACE],
			    (freps[i]->min[FR_FACE] < 0 ? 0 : freps[i]->min[FR_FACE]),
			    freps[i]->max[FR_FACE]);

		if (freps[i]->count[FR_KERNEL] > 0)
		    fprintf(stdout, "%d kernel %d %d %d\n", freps[i]->field,
			    freps[i]->count[FR_KERNEL],
			    (freps[i]->min[FR_KERNEL] < 0 ? 0 : freps[i]->min[FR_KERNEL]),
			    freps[i]->max[FR_KERNEL]);

		if (freps[i]->count[FR_ALL] > 0)
		    fprintf(stdout, "%d all %d %d %d\n", freps[i]->field,
			    freps[i]->count[FR_ALL],
			    (freps[i]->min[FR_ALL] < 0 ? 0 : freps[i]->min[FR_ALL]),
			    freps[i]->max[FR_ALL]);
	    }
	    else {
		if (freps[i]->table != '\0') {
		    fprintf(stdout, "%s: %d/%s\n", _("Layer/table"),
			    freps[i]->field, freps[i]->table);
		}
		else {
		    fprintf(stdout, "%s: %d\n", _("Layer"), freps[i]->field);
		}
		fprintf(stdout, _("type       count        min        max\n"));
		fprintf(stdout, "%s    %7d %10d %10d\n", _("point"),
			freps[i]->count[FR_POINT],
			(freps[i]->min[FR_POINT] < 0) ? 0 : freps[i]->min[FR_POINT],
			freps[i]->max[FR_POINT]);
		fprintf(stdout, "%s     %7d %10d %10d\n", _("line"),
			freps[i]->count[FR_LINE],
			(freps[i]->min[FR_LINE] < 0) ? 0 : freps[i]->min[FR_LINE],
			freps[i]->max[FR_LINE]);
		fprintf(stdout, "%s %7d %10d %10d\n", _("boundary"),
			freps[i]->count[FR_BOUNDARY],
			(freps[i]->min[FR_BOUNDARY] < 0) ? 0 : freps[i]->min[FR_BOUNDARY],
			freps[i]->max[FR_BOUNDARY]);
		fprintf(stdout, "%s %7d %10d %10d\n", _("centroid"),
			freps[i]->count[FR_CENTROID],
			(freps[i]->min[FR_CENTROID] < 0) ? 0 : freps[i]->min[FR_CENTROID],
			freps[i]->max[FR_CENTROID]);
		fprintf(stdout, "%s     %7d %10d %10d\n", _("area"),
			freps[i]->count[FR_AREA],
			(freps[i]->min[FR_AREA] < 0) ? 0 : freps[i]->min[FR_AREA],
			freps[i]->max[FR_AREA]);
		fprintf(stdout, "%s     %7d %10d %10d\n", _("face"),
			freps[i]->count[FR_FACE],
			(freps[i]->min[FR_FACE] < 0) ? 0 : freps[i]->min[FR_FACE],
			freps[i]->max[FR_FACE]);
		fprintf(stdout, "%s   %7d %10d %10d\n", _("kernel"),
			freps[i]->count[FR_KERNEL],
			(freps[i]->min[FR_KERNEL] < 0) ? 0 : freps[i]->min[FR_KERNEL],
			freps[i]->max[FR_KERNEL]);
		fprintf(stdout, "%s      %7d %10d %10d\n", _("all"),
			freps[i]->count[FR_ALL],
			(freps[i]->min[FR_ALL] < 0) ? 0 : freps[i]->min[FR_ALL],
			freps[i]->max[FR_ALL]);
	    }
	}
	break;

    case (O_PRN):
	while ((type = Vect_read_next_line(&In, Points, Cats)) > 0) {
	    id++;
	    int has = 0;

	    if (!(type & otype))
		continue;

	    if (Clist && Vect_cat_in_cat_list(id, Clist) == FALSE)
		continue;

	    /* Check if the line has at least one cat */
	    for (i = 0; i < nfields; i++) {
		for (j = 0; j < Cats->n_cats; j++) {
		    if (Cats->field[j] == fields[i]) {
			has = 1;
			break;
		    }
		}
	    }

	    if (!has)
		continue;

	    for (i = 0; i < nfields; i++) {
		int first = 1;

		if (i > 0)
		    fprintf(stdout, "|");
		for (j = 0; j < Cats->n_cats; j++) {
		    if (Cats->field[j] == fields[i]) {
			if (!first)
			    fprintf(stdout, "/");
			fprintf(stdout, "%d", Cats->cat[j]);
			first = 0;
		    }
		}
	    }
	    fprintf(stdout, "\n");
	}
	break;
    }

    if (option == O_ADD || option == O_DEL || option == O_CHFIELD ||
        option == O_SUM || option == O_TRANS){
        if (!notab->answer){
	    G_message(_("Copying attribute table(s)..."));
            if (Vect_copy_tables(&In, &Out, 0))
                G_warning(_("Failed to copy attribute table to output map"));
	}
	Vect_build(&Out);
	Vect_close(&Out);
    }

    if (option == O_TRANS && nmodified > 0)
        for(i = 1; i < nfields; i++)
	    G_important_message(_("Categories copied from layer %d to layer %d"),
		                  fields[0], fields[i]);

    if (option != O_REP && option != O_PRN) 
        G_done_msg(n_("%d feature modified.",
                      "%d features modified.",
                      nmodified), nmodified);
    
    Vect_close(&In);

    exit(EXIT_SUCCESS);
}
Esempio n. 24
0
void parse_args(int argc, char **argv,
		struct _options *options, struct _flags *flags)
{
    options->dsn = G_define_option();
    options->dsn->key = "output";
    options->dsn->type = TYPE_STRING;
    options->dsn->label = _("Name of output directory or OGR or PostGIS data source");
    options->dsn->description = _("Examples:\n"
				  "\t\tESRI Shapefile: directory containing a shapefile\n"
				  "\t\tMapInfo File: directory containing a mapinfo file\n"
				  "\t\tPostGIS database: connection string, eg. 'PG:dbname=db user=grass'");
    options->dsn->required = NO;
    options->dsn->guisection = _("Settings");

    options->format = G_define_option();
    options->format->key = "format";
    options->format->description = _("Format for output vector data");
    options->format->required = NO;
    options->format->type = TYPE_STRING;
    options->format->options = format_options();
#ifdef HAVE_OGR
    options->format->answer = "ESRI_Shapefile";
#else
#ifdef HAVE_POSTGRES
    options->format->answer = "PostgreSQL";
#endif /* HAVE_POSTGRES */
#endif /* HAVE_OGR */
    options->format->guisection = _("Settings");

    options->opts = G_define_option();
    options->opts->key = "options";
    options->opts->label = _("Creation options");
    options->opts->description = _("Examples:\n"
				  "\t\t'SHPT=POINTZ': create 3D point Shapefile data\n"
				  "\t\t'GEOM_TYPE=geography': use geography PostGIS data\n"
				  "\t\t'SCHEMA=grass': create new PostGIS tables in 'grass' schema");
    options->opts->required = NO;
    options->opts->multiple = YES;
    options->opts->type = TYPE_STRING;
    options->opts->guisection = _("Settings");

    options->input = G_define_standard_option(G_OPT_F_INPUT);
    options->input->key = "loadsettings";
    options->input->required = NO;
    options->input->description = _("Name of input file to read settings from");
    options->input->guisection = _("Settings");

    options->output = G_define_standard_option(G_OPT_F_OUTPUT);
    options->output->key = "savesettings";
    options->output->required = NO;
    options->output->description = _("Name for output file where to save current settings");

    flags->f = G_define_flag();
    flags->f->key = 'f';
    flags->f->description = _("List supported formats and exit");
    flags->f->guisection = _("Print");
    flags->f->suppress_required = YES;

    flags->r = G_define_flag();
    flags->r->key = 'r';
    flags->r->description = _("Cease using OGR/PostGIS, revert to native output and exit");
    flags->r->suppress_required = YES;
    flags->r->guisection = _("Native");
    
    flags->p = G_define_flag();
    flags->p->key = 'p';
    flags->p->description = _("Print current status");
    flags->p->guisection = _("Print");
    flags->p->suppress_required = YES;

    flags->g = G_define_flag();
    flags->g->key = 'g';
    flags->g->description = _("Print current status in shell script style");
    flags->g->guisection = _("Print");
    flags->g->suppress_required = YES;

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

    /* check options */
    if (options->dsn->answer && options->format->answer &&
        options->input->answer)
        G_fatal_error(_("%s= and %s=/%s= are mutually exclusive"),
                      options->input->key,
                      options->dsn->key, options->format->key);
    if (flags->f->answer || flags->p->answer || flags->r->answer || flags->g->answer ||
        options->output->answer)
        return;

    if (!options->dsn->answer && !options->input->answer)
        G_fatal_error(_("%s= or %s= must be specified"),
                      options->dsn->key, options->input->key);
    if (options->dsn->answer && !options->format->answer)
        G_fatal_error(_("%s= must be specified"),
                      options->format->key);
}
Esempio n. 25
0
int main(int argc, char **argv)
{
    int line;
    struct line_pnts *points;
    struct line_cats *Cats;

    struct Map_info map, Out;
    struct GModule *module;
    struct Option *input;
    struct Option *output;
    struct Option *cats;
    struct Option *type_opt;
    char *desc;

    int polyline;
    int *lines_visited;
    int points_in_polyline;
    int start_line;
    int nlines;
    int write_cats, copy_tables;

    int type, ltype;

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

    module = G_define_module();
    G_add_keyword(_("vector"));
    G_add_keyword(_("topology"));
    G_add_keyword(_("geometry"));
    G_add_keyword(_("line"));
    G_add_keyword(_("node"));
    G_add_keyword(_("vertex"));
    module->description = _("Builds polylines from lines or boundaries.");

    /* Define the options */

    input = G_define_standard_option(G_OPT_V_INPUT);
    output = G_define_standard_option(G_OPT_V_OUTPUT);

    cats = G_define_option();
    cats->key = "cats";
    cats->type = TYPE_STRING;
    cats->description = _("Category number mode");
    cats->options = "no,first,multi,same";
    desc = NULL;
    G_asprintf(&desc,
	       "no;%s;first;%s;multi;%s;same;%s",
	       _("Do not assign any category number to polyline"),
	       _("Assign category number of first line to polyline"),
	       _("Assign multiple category numbers to polyline"),
	       _("Create polyline from lines with same categories"));
    cats->descriptions = desc;
    cats->answer = "no";

    type_opt = G_define_standard_option(G_OPT_V_TYPE);
    type_opt->options = "line,boundary";
    type_opt->answer = "line,boundary";

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

    Vect_check_input_output_name(input->answer, output->answer,
				 G_FATAL_EXIT);

    /* Open binary vector map at level 2 */
    Vect_set_open_level(2);
    if (Vect_open_old(&map, input->answer, "") < 0)
	G_fatal_error(_("Unable to open vector map <%s>"), input->answer);

    /* Open new vector */
    G_find_vector2(output->answer, "");
    if (Vect_open_new(&Out, output->answer, Vect_is_3d(&map)) < 0)
	G_fatal_error(_("Unable to create vector map <%s>"), output->answer);

    /* Copy header info. */
    Vect_copy_head_data(&map, &Out);

    /* History */
    Vect_hist_copy(&map, &Out);
    Vect_hist_command(&Out);

    /* Get the number of lines in the binary map and set up record of lines visited */

    lines_visited =
	(int *)G_calloc(Vect_get_num_lines(&map) + 1, sizeof(int));

    /* Set up points structure and coordinate arrays */
    points = Vect_new_line_struct();
    Cats = Vect_new_cats_struct();

    /* Write cats */
    if (strcmp(cats->answer, "no") == 0)
	write_cats = NO_CATS;
    else if (strcmp(cats->answer, "first") == 0)
	write_cats = ONE_CAT;
    else
	write_cats = MULTI_CATS;

    if (type_opt->answer)
	type = Vect_option_to_types(type_opt);
    else
	type = GV_LINES;

    /* Step over all lines in binary map */
    polyline = 0;
    nlines = 0;

    copy_tables = (write_cats != NO_CATS);

    for (line = 1; line <= Vect_get_num_lines(&map); line++) {
	Vect_reset_cats(Cats);
	ltype = Vect_read_line(&map, NULL, NULL, line);

	if ((ltype & GV_LINES) && (ltype & type))
	    nlines++;
	else {
	    /* copy points to output as they are, with cats */
	    Vect_read_line(&map, points, Cats, line);
	    Vect_write_line(&Out, ltype, points, Cats);
	    if (Cats->n_cats > 0)
		copy_tables = 1;
	    continue;
	}

	/* Skip line if already visited from another */
	if (lines_visited[line])
	    continue;

	/* Only get here if line is not previously visited */

	/* Find start of this polyline */
	start_line = walk_back(&map, line, ltype);

	G_debug(1, "Polyline %d: start line = %d", polyline, start_line);

	/* Walk forward and pick up coordinates */
	points_in_polyline =
	    walk_forward_and_pick_up_coords(&map, start_line, ltype, points,
					    lines_visited, Cats, write_cats);

	/* Write the line (type of the first line is used) */
	Vect_write_line(&Out, ltype, points, Cats);

	polyline++;
    }

    G_verbose_message(n_("%d line or boundaries found in input vector map",
                         "%d lines or boundaries found in input vector map",
                         nlines),
		      nlines, Vect_get_name(&map), Vect_get_mapset(&map));
    G_verbose_message(n_("%d polyline stored in output vector map",
                         "%d polylines stored in output vector map",
                         polyline),
		      polyline, Vect_get_name(&Out), Vect_get_mapset(&Out));

    /* Copy (all linked) tables if needed */
    if (copy_tables) {
        if (Vect_copy_tables(&map, &Out, 0))
            G_warning(_("Failed to copy attribute table to output map"));
    }

    /* Tidy up */
    Vect_destroy_line_struct(points);
    Vect_destroy_cats_struct(Cats);
    G_free(lines_visited);
    Vect_close(&map);

    Vect_build(&Out);
    Vect_close(&Out);

    exit(EXIT_SUCCESS);
}
Esempio n. 26
0
int main(int argc, char **argv)
{
    int field, type, vertex_type;
    double dmax;
    struct Option *in_opt, *out_opt, *type_opt, *dmax_opt, *lfield_opt;
    struct Flag *inter_flag, *vertex_flag, *table_flag, *node_flag;
    struct GModule *module;
    char *mapset;
    struct Map_info In, Out;
    struct line_cats *LCats;
    struct line_pnts *LPoints;
    char buf[2000];

    G_gisinit(argv[0]);

    module = G_define_module();
    module->keywords = _("vector, geometry");
    module->description =
	_("Create points along input lines in new vector with 2 layers.");

    in_opt = G_define_standard_option(G_OPT_V_INPUT);
    in_opt->description = _("Input vector map containing lines");

    out_opt = G_define_standard_option(G_OPT_V_OUTPUT);
    out_opt->description =
	_("Output vector map where points will be written");

    type_opt = G_define_standard_option(G_OPT_V_TYPE);
    type_opt->answer = "point,line,boundary,centroid";

    lfield_opt = G_define_standard_option(G_OPT_V_FIELD);
    lfield_opt->key = "llayer";
    lfield_opt->answer = "1";
    lfield_opt->description = "Line layer";

    node_flag = G_define_flag();
    node_flag->key = 'n';
    node_flag->description = _("Write line nodes");

    vertex_flag = G_define_flag();
    vertex_flag->key = 'v';
    vertex_flag->description = _("Write line vertices");

    inter_flag = G_define_flag();
    inter_flag->key = 'i';
    inter_flag->description = _("Interpolate points between line vertices");

    dmax_opt = G_define_option();
    dmax_opt->key = "dmax";
    dmax_opt->type = TYPE_DOUBLE;
    dmax_opt->required = NO;
    dmax_opt->answer = "100";
    dmax_opt->description = _("Maximum distance between points in map units");

    table_flag = G_define_flag();
    table_flag->key = 't';
    table_flag->description = _("Do not create attribute table");

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

    LCats = Vect_new_cats_struct();
    PCats = Vect_new_cats_struct();
    LPoints = Vect_new_line_struct();
    PPoints = Vect_new_line_struct();
    db_init_string(&stmt);

    field = atoi(lfield_opt->answer);
    type = Vect_option_to_types(type_opt);
    dmax = atof(dmax_opt->answer);

    if (node_flag->answer && vertex_flag->answer)
	G_fatal_error(_("Use either -n or -v flag, not both"));

    if (node_flag->answer)
	vertex_type = GV_NODE;
    else if (vertex_flag->answer)
	vertex_type = GV_VERTEX;
    else
	vertex_type = 0;

    Vect_check_input_output_name(in_opt->answer, out_opt->answer,
				 GV_FATAL_EXIT);

    /* Open input lines */
    mapset = G_find_vector2(in_opt->answer, NULL);
    if (mapset == NULL)
	G_fatal_error(_("Vector map <%s> not found"), in_opt->answer);

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

    /* Open output segments */
    Vect_open_new(&Out, out_opt->answer, Vect_is_3d(&In));
    Vect_copy_head_data(&In, &Out);
    Vect_hist_copy(&In, &Out);
    Vect_hist_command(&Out);

    /* Table */
    if (!table_flag->answer) {
	struct field_info *Fin;

	/* copy input table */
	Fin = Vect_get_field(&In, field);
	if (Fin) {		/* table defined */
	    int ret;

	    Fi = Vect_default_field_info(&Out, 1, NULL, GV_MTABLE);
	    Vect_map_add_dblink(&Out, 1, NULL, Fi->table, Fin->key,
				Fi->database, Fi->driver);

	    ret = db_copy_table(Fin->driver, Fin->database, Fin->table,
				Fi->driver, Vect_subst_var(Fi->database,
							   &Out), Fi->table);

	    if (ret == DB_FAILED) {
		G_fatal_error(_("Unable to copy table <%s>"),
			      Fin->table);
	    }
	}

	Fi = Vect_default_field_info(&Out, 2, NULL, GV_MTABLE);
	Vect_map_add_dblink(&Out, 2, NULL, Fi->table, "cat", Fi->database,
			    Fi->driver);

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

	sprintf(buf,
		"create table %s ( cat int, lcat int, along double precision )",
		Fi->table);
	db_append_string(&stmt, buf);

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

	if (db_create_index2(driver, Fi->table, "cat") != DB_OK)
	    G_warning(_("Unable to create index for table <%s>, key <%s>"),
		      Fi->table, "cat");

	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_begin_transaction(driver);
    }

    point_cat = 1;

    if (type & (GV_POINTS | GV_LINES)) {
	int line, nlines;

	nlines = Vect_get_num_lines(&In);
	for (line = 1; line <= nlines; line++) {
	    int ltype, cat;

	    G_debug(3, "line = %d", line);

	    ltype = Vect_read_line(&In, LPoints, LCats, line);
	    if (!(ltype & type))
		continue;

	    Vect_cat_get(LCats, field, &cat);

	    if (LPoints->n_points <= 1) {
		write_point(&Out, LPoints->x[0], LPoints->y[0], LPoints->z[0],
			    cat, 0.0, table_flag->answer);
	    }
	    else {		/* lines */
		write_line(&Out, LPoints, cat, vertex_type,
			   inter_flag->answer, dmax, table_flag->answer);
	    }
	    G_percent(line, nlines, 2);
	}
    }

    if (type == GV_AREA) {
	int area, nareas, centroid, cat;

	nareas = Vect_get_num_areas(&In);
	for (area = 1; area <= nareas; area++) {
	    int i, isle, nisles;

	    centroid = Vect_get_area_centroid(&In, area);
	    cat = -1;
	    if (centroid > 0) {
		Vect_read_line(&In, NULL, LCats, centroid);
		Vect_cat_get(LCats, field, &cat);
	    }

	    Vect_get_area_points(&In, area, LPoints);

	    write_line(&Out, LPoints, cat, vertex_type, inter_flag->answer,
		       dmax, table_flag->answer);

	    nisles = Vect_get_area_num_isles(&In, area);

	    for (i = 0; i < nisles; i++) {
		isle = Vect_get_area_isle(&In, area, i);
		Vect_get_isle_points(&In, isle, LPoints);

		write_line(&Out, LPoints, cat, vertex_type,
			   inter_flag->answer, dmax, table_flag->answer);
	    }
	    G_percent(area, nareas, 2);
	}
    }

    if (!table_flag->answer) {
	db_commit_transaction(driver);
	db_close_database_shutdown_driver(driver);
    }

    Vect_build(&Out);

    /* Free, close ... */
    Vect_close(&In);
    Vect_close(&Out);

    G_done_msg(_("%d points written to output vector map"), point_cat - 1);

    exit(EXIT_SUCCESS);
}
Esempio n. 27
0
int main( int argc, char **argv )
{
  struct GModule *module;
  struct Option *info_opt, *rast_opt, *vect_opt, *coor_opt, *north_opt, *south_opt, *east_opt, *west_opt, *rows_opt, *cols_opt;
  struct Cell_head window;

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

  module = G_define_module();
  module->description = ( "Get info about locations,mapsets,maps" );

  info_opt = G_define_option();
  info_opt->key = "info";
  info_opt->type = TYPE_STRING;
  info_opt->description = "info key";
  info_opt->options = "proj,window,size,query,info,colors,stats";

  rast_opt = G_define_standard_option( G_OPT_R_INPUT );
  rast_opt->key = "rast";
  rast_opt->required = NO;

  vect_opt = G_define_standard_option( G_OPT_V_INPUT );
  vect_opt->key = "vect";
  vect_opt->required = NO;

  coor_opt = G_define_option();
  coor_opt->key = "coor";
  coor_opt->type = TYPE_DOUBLE;
  coor_opt->multiple = YES;

  north_opt = G_define_option();
  north_opt->key = "north";
  north_opt->type = TYPE_STRING;

  south_opt = G_define_option();
  south_opt->key = "south";
  south_opt->type = TYPE_STRING;

  east_opt = G_define_option();
  east_opt->key = "east";
  east_opt->type = TYPE_STRING;

  west_opt = G_define_option();
  west_opt->key = "west";
  west_opt->type = TYPE_STRING;

  rows_opt = G_define_option();
  rows_opt->key = "rows";
  rows_opt->type = TYPE_INTEGER;

  cols_opt = G_define_option();
  cols_opt->key = "cols";
  cols_opt->type = TYPE_INTEGER;

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

  if ( strcmp( "proj", info_opt->answer ) == 0 )
  {
    G_get_window( &window );
    /* code from g.proj */
    if ( window.proj != PROJECTION_XY )
    {
      struct Key_Value *projinfo, *projunits;
      char *wkt;
      projinfo = G_get_projinfo();
      projunits = G_get_projunits();
      wkt = GPJ_grass_to_wkt( projinfo, projunits, 0, 0 );
      fprintf( stdout, "%s", wkt );
    }
  }
  else if ( strcmp( "window", info_opt->answer ) == 0 )
  {
    if ( rast_opt->answer )
    {
      G_get_cellhd( rast_opt->answer, "", &window );
      fprintf( stdout, "%f,%f,%f,%f", window.west, window.south, window.east, window.north );
    }
    else if ( vect_opt->answer )
    {
      G_fatal_error( "Not yet supported" );
    }
  }
  // raster width and height
  else if ( strcmp( "size", info_opt->answer ) == 0 )
  {
    if ( rast_opt->answer )
    {
      G_get_cellhd( rast_opt->answer, "", &window );
      fprintf( stdout, "%d,%d", window.cols, window.rows );
    }
    else if ( vect_opt->answer )
    {
      G_fatal_error( "Not yet supported" );
    }
  }
  // raster information
  else if ( strcmp( "info", info_opt->answer ) == 0 )
  {
    struct FPRange range;
    double zmin, zmax;

    // Data type
    RASTER_MAP_TYPE raster_type = G_raster_map_type( rast_opt->answer, "" );
    fprintf( stdout, "TYPE:%d\n", raster_type );

    // Statistics
    if ( G_read_fp_range( rast_opt->answer, "", &range ) < 0 )
    {
      G_fatal_error(( "Unable to read range file" ) );
    }
    G_get_fp_range_min_max( &range, &zmin, &zmax );
    fprintf( stdout, "MIN_VALUE:%.17e\n", zmin );
    fprintf( stdout, "MAX_VALUE:%.17e\n", zmax );
  }
  else if ( strcmp( "colors", info_opt->answer ) == 0 )
  {
    // Color table
    struct Colors colors;
    int i, ccount;
    if ( G_read_colors( rast_opt->answer, "", &colors ) == 1 )
    {
      //int maxcolor;
      //CELL min, max;

      //G_get_color_range ( &min, &max, &colors);
      ccount = G_colors_count( &colors );
      for ( i = ccount - 1; i >= 0; i-- )
      {
        DCELL val1, val2;
        unsigned char r1, g1, b1, r2, g2, b2;

        G_get_f_color_rule( &val1, &r1, &g1, &b1, &val2, &r2, &g2, &b2, &colors, i );
        fprintf( stdout, "%.17e %.17e %d %d %d %d %d %d\n", val1, val2, r1, g1, b1, r2, g2, b2 );
      }
    }
  }

  else if ( strcmp( "query", info_opt->answer ) == 0 )
  {
    double x, y;
    int row, col;
    //x = atof( coor_opt->answers[0] );
    //y = atof( coor_opt->answers[1] );
    if ( rast_opt->answer )
    {
      int fd;
      RASTER_MAP_TYPE rast_type;
      DCELL *dcell;
      CELL *cell;
      char buff[101];
      G_get_cellhd( rast_opt->answer, "", &window );
      G_set_window( &window );
      G_suppress_masking(); // must be after G_set_window()
      fd = G_open_cell_old( rast_opt->answer, "" );
      // wait for coords from stdin
      while ( fgets( buff, 100, stdin ) != 0 )
      {
        if ( sscanf( buff, "%lf%lf", &x, &y ) != 2 )
        {
          fprintf( stdout, "value:error\n" );
        }
        else
        {
          col = ( int ) G_easting_to_col( x, &window );
          row = ( int ) G_northing_to_row( y, &window );
          if ( col == window.cols )
            col--;
          if ( row == window.rows )
            row--;

          if ( col < 0 || col > window.cols || row < 0 || row > window.rows )
          {
            //fprintf( stdout, "value:out\n" );
            fprintf( stdout, "value:nan\n" );
          }
          else
          {
            void *ptr;
            double val;

#if defined(GRASS_VERSION_MAJOR) && defined(GRASS_VERSION_MINOR) && \
    ( ( GRASS_VERSION_MAJOR == 6 && GRASS_VERSION_MINOR > 2 ) || GRASS_VERSION_MAJOR > 6 )
            rast_type = G_get_raster_map_type( fd );
#else
            rast_type = G_raster_map_type( rast_opt->answer, "" );
#endif
            cell = G_allocate_c_raster_buf();
            dcell = G_allocate_d_raster_buf();

            if ( rast_type == CELL_TYPE )
            {
#if GRASS_VERSION_MAJOR < 7
              if ( G_get_c_raster_row( fd, cell, row ) < 0 )
              {
                G_fatal_error(( "Unable to read raster map <%s> row %d" ),
                              rast_opt->answer, row );
              }
#else
              G_get_c_raster_row( fd, cell, row );
#endif
              val = cell[col];
              ptr = &( cell[col] );
            }
            else
            {
#if GRASS_VERSION_MAJOR < 7
              if ( G_get_d_raster_row( fd, dcell, row ) < 0 )
              {
                G_fatal_error(( "Unable to read raster map <%s> row %d" ),
                              rast_opt->answer, row );
              }
#else
              G_get_d_raster_row( fd, dcell, row );
#endif
              val = dcell[col];
              ptr = &( dcell[col] );
            }
            if ( G_is_null_value( ptr, rast_type ) )
            {
              fprintf( stdout, "value:nan\n" );
            }
            else
            {
              fprintf( stdout, "value:%f\n", val );
            }
          }
        }
        fflush( stdout );
      }
      G_close_cell( fd );
    }
    else if ( vect_opt->answer )
    {
      G_fatal_error( "Not yet supported" );
    }
  }
  else if ( strcmp( "stats", info_opt->answer ) == 0 )
  {
    if ( rast_opt->answer )
    {
      int fd;
      RASTER_MAP_TYPE rast_type;
      DCELL *dcell;
      CELL *cell;
      int ncols, nrows;
      int row, col;
      void *ptr;
      double val;
      double min = DBL_MAX;
      double max = -DBL_MAX;
      double sum = 0; // sum of values
      int count = 0; // count of non null values
      double mean = 0;
      double squares_sum = 0; // sum of squares
      double stdev = 0; // standard deviation

      G_get_cellhd( rast_opt->answer, "", &window );
      window.north = atof( north_opt->answer );
      window.south = atof( south_opt->answer );
      window.east = atof( east_opt->answer );
      window.west = atof( west_opt->answer );
      window.rows = ( int ) atoi( rows_opt->answer );
      window.cols = ( int ) atoi( cols_opt->answer );

      G_set_window( &window );
      G_suppress_masking(); // must be after G_set_window()
      fd = G_open_cell_old( rast_opt->answer, "" );

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

#if defined(GRASS_VERSION_MAJOR) && defined(GRASS_VERSION_MINOR) && \
    ( ( GRASS_VERSION_MAJOR == 6 && GRASS_VERSION_MINOR > 2 ) || GRASS_VERSION_MAJOR > 6 )
      rast_type = G_get_raster_map_type( fd );
#else
      rast_type = G_raster_map_type( rast_opt->answer, "" );
#endif
      cell = G_allocate_c_raster_buf();
      dcell = G_allocate_d_raster_buf();

      // Calc stats is very slow for large rasters -> prefer optimization for speed over
      // code length and readability (which is not currently true)
      for ( row = 0; row < nrows; row++ )
      {
        if ( rast_type == CELL_TYPE )
        {
#if GRASS_VERSION_MAJOR < 7
          if ( G_get_c_raster_row( fd, cell, row ) < 0 )
          {
            G_fatal_error(( "Unable to read raster map <%s> row %d" ),
                          rast_opt->answer, row );
          }
#else
          G_get_c_raster_row( fd, cell, row );
#endif
        }
        else
        {
#if GRASS_VERSION_MAJOR < 7
          if ( G_get_d_raster_row( fd, dcell, row ) < 0 )
          {
            G_fatal_error(( "Unable to read raster map <%s> row %d" ),
                          rast_opt->answer, row );
          }
#else
          G_get_d_raster_row( fd, dcell, row );
#endif
        }

        for ( col = 0; col < ncols; col++ )
        {
          if ( rast_type == CELL_TYPE )
          {
            val = cell[col];
            ptr = &( cell[col] );
          }
          else
          {
            val = dcell[col];
            ptr = &( dcell[col] );
          }
          if ( ! G_is_null_value( ptr, rast_type ) )
          {
            if ( val < min ) min = val;
            if ( val > max ) max = val;
            sum += val;
            count++;
            squares_sum += pow( val, 2 );
          }
        }
      }
      mean = count > 0 ? sum / count : 0;
      squares_sum -= count * pow( mean, 2 );
      stdev = sqrt( squares_sum / ( count - 1 ) );

      fprintf( stdout, "MIN:%.17e\n", min );
      fprintf( stdout, "MAX:%.17e\n", max );
      fprintf( stdout, "SUM:%.17e\n", sum );
      fprintf( stdout, "MEAN:%.17e\n", mean );
      fprintf( stdout, "COUNT:%d\n", count );
      fprintf( stdout, "STDEV:%.17e\n", stdev );
      fprintf( stdout, "SQSUM:%.17e\n", squares_sum );

      G_close_cell( fd );
    }
    else if ( vect_opt->answer )
    {
      G_fatal_error( "Not yet supported" );
    }
  }

  exit( EXIT_SUCCESS );
}
Esempio n. 28
0
int main(int argc, char *argv[])
{
    char *title;
    FILE *srcfp;
    struct GModule *module;
    struct
    {
	struct Option *input, *output, *title, *rules;
	struct Flag *a, *d;
    } parm;

    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("raster"));
    G_add_keyword(_("recode categories"));
    G_add_keyword(_("reclassification"));
    module->description = _("Recodes categorical raster maps.");

    parm.input = G_define_standard_option(G_OPT_R_INPUT);
    parm.input->description = _("Name of raster map to be recoded");
    
    parm.output = G_define_standard_option(G_OPT_R_OUTPUT);

    parm.rules = G_define_standard_option(G_OPT_F_INPUT);
    parm.rules->key = "rules";
    parm.rules->label = _("File containing recode rules");
    parm.rules->description = _("'-' for standard input");
    
    parm.title = G_define_option();
    parm.title->key = "title";
    parm.title->required = NO;
    parm.title->type = TYPE_STRING;
    parm.title->description = _("Title for output raster map");
    
    parm.a = G_define_flag();
    parm.a->key = 'a';
    parm.a->description = _("Align the current region to the input raster map");

    parm.d = G_define_flag();
    parm.d->key = 'd';
    parm.d->description = _("Force output to 'double' raster map type (DCELL)");
    
    if (G_parser(argc, argv))
	exit(EXIT_FAILURE);

    name = parm.input->answer;
    result = parm.output->answer;
    title = parm.title->answer;
    align_wind = parm.a->answer;
    make_dcell = parm.d->answer;

    srcfp = stdin;
    if (strcmp(parm.rules->answer, "-") != 0) {
	srcfp = fopen(parm.rules->answer, "r");
	if (!srcfp)
	    G_fatal_error(_("Unable to open file <%s>"),
			  parm.rules->answer);
    }

    if (!read_rules(srcfp)) {
	if (isatty(fileno(srcfp)))
	    G_fatal_error(_("No rules specified. Raster map <%s> not created."),
			  result);
	else
	    G_fatal_error(_("No rules specified"));
    }

    no_mask = 0;

    do_recode();

    if(title)
	Rast_put_cell_title(result, title);

    exit(EXIT_SUCCESS);
}
Esempio n. 29
0
File: main.c Progetto: caomw/grass
int main(int argc, char *argv[])
{

    struct GModule *module;
    struct Option *in_dir_opt,
	*in_stm_opt,
	*in_elev_opt,
	*in_method_opt, *opt_swapsize, *out_dist_opt, *out_diff_opt;
    struct Flag *flag_outs, *flag_sub, *flag_near, *flag_segmentation;
    char *method_name[] = { "UPSTREAM", "DOWNSTREAM" };
    int method;
    int number_of_segs;
    int outlets_num;
    int number_of_streams;
    int outs, subs, near, segmentation;	/*flags */
    int j;

    G_gisinit(argv[0]);

    module = G_define_module();
    module->label = _("Calculates distance to and elevation above streams and outlet.");
    module->description =
      _("The module can work in stream mode where target are streams and "
        "outlets mode where targets are outlets.");
    G_add_keyword(_("raster"));
    G_add_keyword(_("hydrology"));
    G_add_keyword(_("stream network"));
    G_add_keyword(_("watercourse distance"));

    in_stm_opt = G_define_standard_option(G_OPT_R_INPUT);
    in_stm_opt->key = "stream_rast";
    in_stm_opt->description = _("Name of input raster map with stream network "
                                "(in outlet mode is the name for outlet raster map)");

    in_dir_opt = G_define_standard_option(G_OPT_R_INPUT);
    in_dir_opt->key = "direction";
    in_dir_opt->description = _("Name of input raster map with flow direction");

    in_elev_opt = G_define_standard_option(G_OPT_R_ELEV);
    in_elev_opt->required = NO;
    in_elev_opt->guisection = _("Input maps");

    in_method_opt = G_define_option();
    in_method_opt->key = "method";
    in_method_opt->description = _("Calculation method");
    in_method_opt->type = TYPE_STRING;
    in_method_opt->required = YES;
    in_method_opt->options = "upstream,downstream";
    in_method_opt->answer = "downstream";

    out_dist_opt = G_define_standard_option(G_OPT_R_OUTPUT);
    out_dist_opt->key = "distance";
    out_dist_opt->required = NO;
    out_dist_opt->description = _("Name for output distance raster map");
    out_dist_opt->guisection = _("Output maps");

    out_diff_opt = G_define_standard_option(G_OPT_R_OUTPUT);
    out_diff_opt->key = "difference";
    out_diff_opt->required = NO;
    out_diff_opt->description = _("Name for output elevation difference raster map");
    out_diff_opt->guisection = _("Output maps");

    opt_swapsize = G_define_option();
    opt_swapsize->key = "memory";
    opt_swapsize->type = TYPE_INTEGER;
    opt_swapsize->answer = "300";
    opt_swapsize->description = _("Max memory used in memory swap mode (MB)");
    opt_swapsize->guisection = _("Memory settings");

    flag_outs = G_define_flag();
    flag_outs->key = 'o';
    flag_outs->description =
	_("Calculate parameters for outlets (outlet mode) instead of (default) streams");

    flag_sub = G_define_flag();
    flag_sub->key = 's';
    flag_sub->description =
	_("Calculate parameters for subbasins (ignored in stream mode)");

    flag_near = G_define_flag();
    flag_near->key = 'n';
    flag_near->description =
	_("Calculate nearest local maximum (ignored in downstream calculation)");

    flag_segmentation = G_define_flag();
    flag_segmentation->key = 'm';
    flag_segmentation->description = _("Use memory swap (operation is slow)");
    flag_segmentation->guisection = _("Memory settings");

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

    if (!out_diff_opt->answer && !out_dist_opt->answer)
	G_fatal_error(_("You must select at least one output raster map"));
    if (out_diff_opt->answer && !in_elev_opt->answer)
	G_fatal_error(_("Output elevation difference raster map requires "
                        "input elevation raster map to be specified"));
    
    if (!strcmp(in_method_opt->answer, "upstream"))
	method = UPSTREAM;
    else if (!strcmp(in_method_opt->answer, "downstream"))
	method = DOWNSTREAM;

    outs = (flag_outs->answer != 0);
    subs = (flag_sub->answer != 0);
    near = (flag_near->answer != 0);
    segmentation = (flag_segmentation->answer != 0);

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

    fifo_max = 4 * (nrows + ncols);
    fifo_points = (POINT *) G_malloc((fifo_max + 1) * sizeof(POINT));

    if (!segmentation) {
	G_message(_("All in RAM calculation - method <%s>..."),
		  method_name[method]);
	MAP map_dirs, map_streams, map_distance, map_elevation,
	    map_tmp_elevation;
	CELL **streams, **dirs;
	DCELL **distance;
	DCELL **elevation = NULL;
	DCELL **tmp_elevation = NULL;

	ram_create_map(&map_streams, CELL_TYPE);
	ram_read_map(&map_streams, in_stm_opt->answer, 1, CELL_TYPE);
	ram_create_map(&map_dirs, CELL_TYPE);
	ram_read_map(&map_dirs, in_dir_opt->answer, 1, CELL_TYPE);
	ram_create_map(&map_distance, DCELL_TYPE);

	streams = (CELL **) map_streams.map;
	dirs = (CELL **) map_dirs.map;
	distance = (DCELL **) map_distance.map;
	number_of_streams = (int)map_streams.max + 1;

	outlets_num =
	    ram_find_outlets(streams, number_of_streams, dirs, subs, outs);
	ram_init_distance(streams, distance, outlets_num, outs);
	ram_release_map(&map_streams);

	if (in_elev_opt->answer) {
	    ram_create_map(&map_elevation, DCELL_TYPE);
	    ram_read_map(&map_elevation, in_elev_opt->answer, 0, -1);
	    elevation = (DCELL **) map_elevation.map;
	}			/* map elevation will be replaced by elevation difference map */


	if (method == DOWNSTREAM) {
	    G_message(_("Calculate downstream parameters..."));
	    for (j = 0; j < outlets_num; ++j) {
		G_percent(j, outlets_num, 1);
		ram_calculate_downstream(dirs, distance, elevation,
					 outlets[j], outs);
	    }
	    G_percent(j, outlets_num, 1);

	}
	else if (method == UPSTREAM) {

	    if (out_diff_opt->answer) {
		ram_create_map(&map_tmp_elevation, DCELL_TYPE);
		tmp_elevation = (DCELL **) map_tmp_elevation.map;
	    }

	    for (j = 0; j < outlets_num; ++j)
		ram_fill_basins(outlets[j], distance, dirs);
	    ram_calculate_upstream(distance, dirs, elevation, tmp_elevation,
				   near);

	}
	else {
	    G_fatal_error(_("Unrecognised method of processing"));
	}			/* end methods */

	if (out_diff_opt->answer) {
	    ram_prep_null_elevation(distance, elevation);
	    ram_write_map(&map_elevation, out_diff_opt->answer, DCELL_TYPE, 1,
			  -1);
	}

	if (out_dist_opt->answer)
	    ram_write_map(&map_distance, out_dist_opt->answer, DCELL_TYPE, 1,
			  -1);

	ram_release_map(&map_dirs);
	ram_release_map(&map_distance);

	if (in_elev_opt->answer)
	    ram_release_map(&map_elevation);
	if (in_elev_opt->answer && method == UPSTREAM)
	    ram_release_map(&map_tmp_elevation);
    }

    if (segmentation) {
	G_message(_("Calculating segments in direction <%s> (may take some time)..."),
		  method_name[method]);
	SEG map_dirs, map_streams, map_distance, map_elevation,
	    map_tmp_elevation;
	SEGMENT *streams, *dirs, *distance;
	SEGMENT *elevation = NULL;
	SEGMENT *tmp_elevation = NULL;

	number_of_segs = (int)atof(opt_swapsize->answer);
	if (method == DOWNSTREAM)
	    number_of_segs = number_of_segs < 32 ? (int)(32 / 0.18) : number_of_segs / 0.18;
	else			/* two elevation maps */
	    number_of_segs = number_of_segs < 32 ? (int)(32 / 0.24) : number_of_segs / 0.24;

	seg_create_map(&map_streams, SROWS, SCOLS, number_of_segs, CELL_TYPE);
	seg_read_map(&map_streams, in_stm_opt->answer, 1, CELL_TYPE);
	seg_create_map(&map_dirs, SROWS, SCOLS, number_of_segs, CELL_TYPE);
	seg_read_map(&map_dirs, in_dir_opt->answer, 1, CELL_TYPE);
	seg_create_map(&map_distance, SROWS, SCOLS, number_of_segs,
		       DCELL_TYPE);

	streams = &map_streams.seg;
	dirs = &map_dirs.seg;
	distance = &map_distance.seg;
	number_of_streams = (int)map_streams.max + 1;

	outlets_num =
	    seg_find_outlets(streams, number_of_streams, dirs, subs, outs);
	seg_init_distance(streams, distance, outlets_num, outs);
	seg_release_map(&map_streams);

	if (in_elev_opt->answer) {
	    seg_create_map(&map_elevation, SROWS, SCOLS, number_of_segs,
			   DCELL_TYPE);
	    seg_read_map(&map_elevation, in_elev_opt->answer, 0, -1);
	    elevation = &map_elevation.seg;
	}			/* map elevation will be replaced by elevation difference map */

	if (method == DOWNSTREAM) {
	    G_message(_("Calculate downstream parameters..."));
	    for (j = 0; j < outlets_num; ++j) {
		G_percent(j, outlets_num, 1);
		seg_calculate_downstream(dirs, distance, elevation,
					 outlets[j], outs);
	    }
	    G_percent(j, outlets_num, 1);

	}
	else if (method == UPSTREAM) {

	    if (out_diff_opt->answer) {
		seg_create_map(&map_tmp_elevation, SROWS, SCOLS,
			       number_of_segs, DCELL_TYPE);
		tmp_elevation = &map_tmp_elevation.seg;
	    }

	    for (j = 0; j < outlets_num; ++j)
		seg_fill_basins(outlets[j], distance, dirs);
	    seg_calculate_upstream(distance, dirs, elevation, tmp_elevation,
				   near);

	}
	else {
	    G_fatal_error(_("Unrecognised method of processing"));
	}			/* end methods */

	if (out_dist_opt->answer)
	    seg_write_map(&map_distance, out_dist_opt->answer, DCELL_TYPE, 1,
			  -1);

	if (out_diff_opt->answer) {
	    seg_prep_null_elevation(distance, elevation);
	    seg_write_map(&map_elevation, out_diff_opt->answer, DCELL_TYPE, 1,
			  -1);
	}

	seg_release_map(&map_dirs);
	seg_release_map(&map_distance);

	if (in_elev_opt->answer)
	    seg_release_map(&map_elevation);
	if (in_elev_opt->answer && method == UPSTREAM)
	    seg_release_map(&map_tmp_elevation);
    }

    G_free(fifo_points);
    exit(EXIT_SUCCESS);
}
Esempio n. 30
0
void parse_args(int argc, char **argv,
		char **input, char**output, int *format, int *dp, char **delim,
		char **field, char ***columns, char **where, int *region,
		int *old_format, int *header, struct cat_list **clist)
{
    struct Option *input_opt, *output_opt, *format_opt, *dp_opt, *delim_opt,
	*field_opt, *column_opt, *where_opt, *cats_opt;
    struct Flag *old_flag, *header_flag, *region_flag;
    
    input_opt = G_define_standard_option(G_OPT_V_INPUT);

    field_opt = G_define_standard_option(G_OPT_V_FIELD);
    field_opt->guisection = _("Selection");
    
    output_opt = G_define_standard_option(G_OPT_F_OUTPUT);
    output_opt->label = _("Name for output ASCII file "
			  "or ASCII vector name if '-o' is defined");
    output_opt->description = _("'-' for standard output");
    output_opt->required = NO;
    output_opt->answer = "-";

    column_opt = G_define_standard_option(G_OPT_DB_COLUMNS);
    column_opt->description = _("Name of attribute column(s) to be exported (point mode)");
    column_opt->guisection = _("Points");
    
    cats_opt = G_define_standard_option(G_OPT_V_CATS);
    cats_opt->guisection = _("Selection");
    
    where_opt = G_define_standard_option(G_OPT_DB_WHERE);
    where_opt->guisection = _("Selection");

    format_opt = G_define_option();
    format_opt->key = "format";
    format_opt->type = TYPE_STRING;
    format_opt->required = YES;
    format_opt->multiple = NO;
    format_opt->options = "point,standard,wkt";
    format_opt->answer = "point";
    format_opt->description = _("Output format");
    format_opt->descriptions = _("point;Simple point format (point per row);"
				 "standard;GRASS ASCII vector format;"
				 "wkt;OGC well-known text;");

    delim_opt = G_define_standard_option(G_OPT_F_SEP);
    delim_opt->description = _("Field separator (points mode)");
    delim_opt->guisection = _("Points");
    
    dp_opt = G_define_option();
    dp_opt->key = "dp";
    dp_opt->type = TYPE_INTEGER;
    dp_opt->required = NO;
    dp_opt->options = "0-32";
    dp_opt->answer = "8";	/* This value is taken from the lib settings in G_format_easting() */
    dp_opt->description =
	_("Number of significant digits (floating point only)");
    dp_opt->guisection = _("Points");
    
    old_flag = G_define_flag();
    old_flag->key = 'o';
    old_flag->description = _("Create old (version 4) ASCII file");

    header_flag = G_define_flag();
    header_flag->key = 'c';
    header_flag->description = _("Include column names in output (points mode)");
    header_flag->guisection = _("Points");

    region_flag = G_define_flag();
    region_flag->key = 'r';
    region_flag->description =
	_("Only export points falling within current 3D region (points mode)");
    region_flag->guisection = _("Points");

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

    *input = G_store(input_opt->answer);
    *output = G_store(output_opt->answer);
    if (format_opt->answer[0] == 'p')
	*format = GV_ASCII_FORMAT_POINT;
    else if (format_opt->answer[0] == 's')
	*format = GV_ASCII_FORMAT_STD;
    else
	*format = GV_ASCII_FORMAT_WKT;
    if (sscanf(dp_opt->answer, "%d", dp) != 1)
	G_fatal_error(_("Failed to interpret 'dp' parameter as an integer"));
    /* the field separator */
    if (strcmp(delim_opt->answer, "\\t") == 0)
	*delim = G_store("\t");
    else if (strcmp(delim_opt->answer, "tab") == 0)
	*delim = G_store("\t");
    else if (strcmp(delim_opt->answer, "space") == 0)
	*delim = G_store(" ");
    else if (strcmp(delim_opt->answer, "comma") == 0)
	*delim = G_store(",");
    else
	*delim = G_store(delim_opt->answer);
    
    *field = G_store(field_opt->answer);
    *columns = NULL;
    if (column_opt->answer) {
	int i, nopt;
	nopt = 0;
	while(column_opt->answers[nopt++])
	    ;
	*columns = (char **) G_malloc(nopt * sizeof(char *));
	for (i = 0; i < nopt - 1; i++)
	    (*columns)[i] = G_store(column_opt->answers[i]);
	(*columns)[nopt - 1] = NULL;
    }
    *where = NULL;
    if (where_opt->answer) {
	*where = G_store(where_opt->answer);
    }
    *clist = NULL;
    if (cats_opt->answer) {
	int ret;
	
	*clist = Vect_new_cat_list();
	(*clist)->field = atoi(field_opt->answer);
	if ((*clist)->field < 1)
	    G_fatal_error(_("Option <%s> must be > 0"), field_opt->key);
	ret = Vect_str_to_cat_list(cats_opt->answer, *clist);
	if (ret > 0)
	    G_fatal_error(_("%d errors in cat option"), ret);
    }
    *region = region_flag->answer ? 1 : 0;
    *old_format = old_flag->answer ? 1 : 0;
    *header = header_flag->answer ? 1 : 0;
}