Beispiel #1
0
/*
 * check_stats() - Check and update statistics 
 *
 * RETURN: EXIT_SUCCESS / EXIT_FAILURE
 */
int check_stats(const char *name)
{
    struct Categories cats;
    struct FPRange fprange;
    int cats_ok;

    G_message(_("Updating statistics for <%s>"), name);
    
    /* Get category status and max */
    cats_ok = (Rast3d_read_cats(name, "", &cats) >= 0);
    Rast3d_read_range(name, "", &fprange);

    /* Further category checks */
    if (!cats_ok)
	Rast_init_cats("", &cats);
    else if (cats.num != fprange.max) {
	cats.num = fprange.max;
	cats_ok = 0;
    }

    /* Update categories if needed */
    if (!cats_ok) {
	G_message(_("Updating the number of categories for <%s>"), name);
	Rast3d_write_cats(name, &cats);
    }
    Rast_free_cats(&cats);

    return 0;
}
Beispiel #2
0
/*!
   \brief Sort categories

   \param pcats pointer to Categories structure

   \return -1 on error (nothing to sort)
   \return 0 on success
 */
int Rast_sort_cats(struct Categories *pcats)
{
    int *indexes, i, ncats;
    char *descr;
    DCELL d1, d2;

    if (pcats->ncats <= 1)
	return -1;

    ncats = pcats->ncats;
    G_debug(3, "Rast_sort_cats(): Copying to save cats buffer");
    Rast_copy_cats(&save_cats, pcats);
    Rast_free_cats(pcats);

    indexes = (int *)G_malloc(sizeof(int) * ncats);
    for (i = 0; i < ncats; i++)
	indexes[i] = i;

    qsort(indexes, ncats, sizeof(int), cmp);
    Rast_init_cats(save_cats.title, pcats);
    for (i = 0; i < ncats; i++) {
	descr = Rast_get_ith_d_cat(&save_cats, indexes[i], &d1, &d2);
	G_debug(4, "  Write sorted cats, pcats = %p pcats->labels = %p",
		pcats, pcats->labels);
	Rast_set_d_cat(&d1, &d2, descr, pcats);
    }
    Rast_free_cats(&save_cats);

    return 0;
}
Beispiel #3
0
/*!
 * \brief Copy raster categories
 *
 * Allocates NEW space for quant rules and labels n <i>pcats_to</i>
 * and copies all info from <i>pcats_from</i> cats to
 * <i>pcats_to</i> cats.
 *
 * \param pcats_to pointer to destination Categories structure
 * \param pcats_from pointer to source Categories structure
 */
void Rast_copy_cats(struct Categories *pcats_to,
		    const struct Categories *pcats_from)
{
    int i;
    char *descr;
    DCELL d1, d2;

    Rast_init_cats(pcats_from->title, pcats_to);
    for (i = 0; i < pcats_from->ncats; i++) {
	descr = Rast_get_ith_d_cat(pcats_from, i, &d1, &d2);
	Rast_set_d_cat(&d1, &d2, descr, pcats_to);
    }
}
Beispiel #4
0
int write_form_cat_colors (char* raster, CATCOLORS* ccolors) {
struct Colors colors;
struct Categories cats;
int i;

Rast_init_colors(&colors);

	for(i=1;i<CNT;++i)
Rast_add_color_rule(
	&ccolors[i].cat, ccolors[i].r, ccolors[i].g, ccolors[i].b,
	&ccolors[i].cat, ccolors[i].r, ccolors[i].g, ccolors[i].b,
	&colors, CELL_TYPE);
Rast_write_colors(raster, G_mapset(), &colors);
Rast_free_colors(&colors);
Rast_init_cats("Forms", &cats);
	for(i=1;i<CNT;++i)
Rast_set_cat(&ccolors[i].cat, &ccolors[i].cat, ccolors[i].label, &cats, CELL_TYPE);
Rast_write_cats(raster, &cats);
Rast_free_cats(&cats);
return 0;
}
Beispiel #5
0
static CELL read_cats(const char *element,
		      const char *name,
		      const char *mapset, struct Categories *pcats, int full)
{
    FILE *fd;
    char buff[1024];
    CELL cat;
    DCELL val1, val2;
    int old = 0, fp_map;
    long num = -1;


    if (strncmp(element, "dig", 3) == 0)
	fp_map = 0;
    else
	fp_map = Rast_map_is_fp(name, mapset);

    if (!(fd = G_fopen_old(element, name, mapset)))
	return -2;

    /* Read the number of categories */
    if (G_getl(buff, sizeof buff, fd) == 0)
	goto error;

    if (sscanf(buff, "# %ld", &num) == 1)
	old = 0;
    else if (sscanf(buff, "%ld", &num) == 1)
	old = 1;

    if (!full) {
	fclose(fd);
	if (num < 0)
	    return 0;		/* coorect */
	return (CELL) num;
    }

    /* Read the title for the file */
    if (G_getl(buff, sizeof buff, fd) == 0)
	goto error;
    G_strip(buff);
    /*    G_ascii_check(buff) ; */

    Rast_init_cats(buff, pcats);
    if (num >= 0)
	pcats->num = num;

    if (!old) {
	char fmt[256];
	float m1, a1, m2, a2;

	if (G_getl(fmt, sizeof fmt, fd) == 0)
	    goto error;
	/* next line contains equation coefficients */
	if (G_getl(buff, sizeof buff, fd) == 0)
	    goto error;
	if (sscanf(buff, "%f %f %f %f", &m1, &a1, &m2, &a2) != 4)
	    goto error;
	Rast_set_cats_fmt(fmt, m1, a1, m2, a2, pcats);
    }

    /* Read all category names */
    for (cat = 0;; cat++) {
	char label[1024];

	if (G_getl(buff, sizeof buff, fd) == 0)
	    break;
	if (old)
	    Rast_set_c_cat(&cat, &cat, buff, pcats);
	else {
	    *label = 0;
	    if (sscanf(buff, "%1s", label) != 1)
		continue;
	    if (*label == '#')
		continue;
	    *label = 0;
	    /* for fp maps try to read a range of data */
	    if (fp_map
		&& sscanf(buff, "%lf:%lf:%[^\n]", &val1, &val2, label) == 3)
		Rast_set_cat(&val1, &val2, label, pcats, DCELL_TYPE);
	    else if (sscanf(buff, "%d:%[^\n]", &cat, label) >= 1)
		Rast_set_cat(&cat, &cat, label, pcats, CELL_TYPE);
	    else if (sscanf(buff, "%lf:%[^\n]", &val1, label) >= 1)
		Rast_set_cat(&val1, &val1, label, pcats, DCELL_TYPE);
	    else
		goto error;
	}
    }

    fclose(fd);
    return 0;
  error:
    fclose(fd);
    return -1;
}
Beispiel #6
0
int main(int argc, char *argv[])
{
    const char *name;
    const char *mapset;

    long x, y;
    double dx;
    RASTER_MAP_TYPE map_type;
    int i;
    int from_stdin = FALSE;
    struct GModule *module;

    struct
    {
	struct Option *map, *fs, *cats, *vals, *raster, *file, *fmt_str,
	    *fmt_coeff;
    } parm;

    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("raster"));
    G_add_keyword(_("category"));
    module->description =
	_("Manages category values and labels associated "
	  "with user-specified raster map layers.");

    parm.map = G_define_standard_option(G_OPT_R_MAP);

    parm.cats = G_define_standard_option(G_OPT_V_CATS);
    parm.cats->multiple = YES;
    parm.cats->guisection = _("Selection");

    parm.vals = G_define_option();
    parm.vals->key = "vals";
    parm.vals->type = TYPE_DOUBLE;
    parm.vals->multiple = YES;
    parm.vals->required = NO;
    parm.vals->label = _("Comma separated value list");
    parm.vals->description = _("Example: 1.4,3.8,13");
    parm.vals->guisection = _("Selection");

    parm.fs = G_define_standard_option(G_OPT_F_SEP);
    parm.fs->answer = "tab";

    parm.raster = G_define_standard_option(G_OPT_R_INPUT);
    parm.raster->key = "raster";
    parm.raster->required = NO;
    parm.raster->description =
	_("Raster map from which to copy category table");
    parm.raster->guisection = _("Define");

    parm.file = G_define_standard_option(G_OPT_F_INPUT);
    parm.file->key = "rules";
    parm.file->required = NO;
    parm.file->description =
	_("File containing category label rules (or \"-\" to read from stdin)");
    parm.file->guisection = _("Define");

    parm.fmt_str = G_define_option();
    parm.fmt_str->key = "format";
    parm.fmt_str->type = TYPE_STRING;
    parm.fmt_str->required = NO;
    parm.fmt_str->label =
	_("Default label or format string for dynamic labeling");
    parm.fmt_str->description =
	_("Used when no explicit label exists for the category");

    parm.fmt_coeff = G_define_option();
    parm.fmt_coeff->key = "coefficients";
    parm.fmt_coeff->type = TYPE_DOUBLE;
    parm.fmt_coeff->required = NO;
    parm.fmt_coeff->key_desc = "mult1,offset1,mult2,offset2";
    /*    parm.fmt_coeff->answer   = "0.0,0.0,0.0,0.0"; */
    parm.fmt_coeff->label = _("Dynamic label coefficients");
    parm.fmt_coeff->description =
	_("Two pairs of category multiplier and offsets, for $1 and $2");

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


    name = parm.map->answer;

    fs = G_option_to_separator(parm.fs);
    
    mapset = G_find_raster2(name, "");
    if (mapset == NULL)
	G_fatal_error(_("Raster map <%s> not found"), name);

    map_type = Rast_map_type(name, mapset);


    /* create category labels */
    if (parm.raster->answer || parm.file->answer ||
	parm.fmt_str->answer || parm.fmt_coeff->answer) {

	/* restrict editing to current mapset */
	if (strcmp(mapset, G_mapset()) != 0)
	    G_fatal_error(_("Raster map <%s> not found in current mapset"),
			  name);

	/* use cats from another map */
	if (parm.raster->answer) {
	    int fd;
	    const char *cmapset;

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

	    fd = Rast_open_old(name, mapset);

	    Rast_init_cats("", &cats);

	    if (0 > Rast_read_cats(parm.raster->answer, cmapset, &cats))
		G_fatal_error(_("Unable to read category file of raster map <%s@%s>"),
			      parm.raster->answer, cmapset);

	    Rast_write_cats(name, &cats);
	    G_message(_("Category table for <%s> set from <%s>"),
		      name, parm.raster->answer);

	    Rast_close(fd);
	}

	/* load cats from rules file */
	if (parm.file->answer) {
	    FILE *fp;
	    char **tokens;
	    int ntokens;
	    char *e1;
	    char *e2;

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

	    Rast_init_cats("", &cats);

	    for (;;) {
		char buf[1024];
		DCELL d1, d2;
		int parse_error = 0;

		if (!G_getl2(buf, sizeof(buf), fp))
		    break;

		tokens = G_tokenize(buf, fs);
		ntokens = G_number_of_tokens(tokens);

		if (ntokens == 3) {
		    d1 = strtod(tokens[0], &e1);
		    d2 = strtod(tokens[1], &e2);
		    if (*e1 == 0 && *e2 == 0)
			Rast_set_d_cat(&d1, &d2, tokens[2], &cats);
		    else
			parse_error = 1;
		}
		else if (ntokens == 2) {
		    d1 = strtod(tokens[0], &e1);
		    if (*e1 == 0)
			Rast_set_d_cat(&d1, &d1, tokens[1], &cats);
		    else
			parse_error = 1;
		}
		else if (!strlen(buf))
		    continue;
		else
		    parse_error = 1;

		if (parse_error)
		    G_fatal_error(_("Incorrect format of input rules. "
				    "Check separators. Invalid line is:\n%s"), buf);
	    }
	    G_free_tokens(tokens);
	    Rast_write_cats(name, &cats);

	    if (!from_stdin)
		fclose(fp);
	}

	/* set dynamic cat rules for cats without explicit labels */
	if (parm.fmt_str->answer || parm.fmt_coeff->answer) {
	    char *fmt_str;
	    double m1, a1, m2, a2;

	    /* read existing values */
	    Rast_init_cats("", &cats);

	    if (0 > Rast_read_cats(name, G_mapset(), &cats))
		G_warning(_("Unable to read category file of raster map <%s@%s>"),
			  name, G_mapset());

	    if (parm.fmt_str->answer) {
		fmt_str =
		    G_malloc(strlen(parm.fmt_str->answer) > strlen(cats.fmt)
			     ? strlen(parm.fmt_str->answer) +
			     1 : strlen(cats.fmt) + 1);
		strcpy(fmt_str, parm.fmt_str->answer);
	    }
	    else {
		fmt_str = G_malloc(strlen(cats.fmt) + 1);
		strcpy(fmt_str, cats.fmt);
	    }

	    m1 = cats.m1;
	    a1 = cats.a1;
	    m2 = cats.m2;
	    a2 = cats.a2;

	    if (parm.fmt_coeff->answer) {
		m1 = atof(parm.fmt_coeff->answers[0]);
		a1 = atof(parm.fmt_coeff->answers[1]);
		m2 = atof(parm.fmt_coeff->answers[2]);
		a2 = atof(parm.fmt_coeff->answers[3]);
	    }

	    Rast_set_cats_fmt(fmt_str, m1, a1, m2, a2, &cats);

	    Rast_write_cats(name, &cats);
	}

	Rast_free_cats(&cats);
	exit(EXIT_SUCCESS);
    }
    else {
	if (Rast_read_cats(name, mapset, &cats) < 0)
	    G_fatal_error(_("Unable to read category file of raster map <%s> in <%s>"),
			  name, mapset);
    }

    /* describe the category labels */
    /* if no cats requested, use r.describe to get the cats */
    if (parm.cats->answer == NULL) {
	if (map_type == CELL_TYPE) {
	    get_cats(name, mapset);
	    while (next_cat(&x))
		print_label(x);
	    exit(EXIT_SUCCESS);
	}
    }
    else {
	if (map_type != CELL_TYPE)
	    G_warning(_("The map is floating point! Ignoring cats list, using vals list"));
	else {			/* integer map */

	    for (i = 0; parm.cats->answers[i]; i++)
		if (!scan_cats(parm.cats->answers[i], &x, &y)) {
		    G_usage();
		    exit(EXIT_FAILURE);
		}
	    for (i = 0; parm.cats->answers[i]; i++) {
		scan_cats(parm.cats->answers[i], &x, &y);
		while (x <= y)
		    print_label(x++);
	    }
	    exit(EXIT_SUCCESS);
	}
    }
    if (parm.vals->answer == NULL)
	G_fatal_error(_("vals argument is required for floating point map!"));
    for (i = 0; parm.vals->answers[i]; i++)
	if (!scan_vals(parm.vals->answers[i], &dx)) {
	    G_usage();
	    exit(EXIT_FAILURE);
	}
    for (i = 0; parm.vals->answers[i]; i++) {
	scan_vals(parm.vals->answers[i], &dx);
	print_d_label(dx);
    }
    exit(EXIT_SUCCESS);
}
Beispiel #7
0
int main(int argc, char *argv[])
{
    int *fd;
    char **names;
    char **ptr;
    char *name;

    /* flags */
    int raw_data;
    int with_coordinates;
    int with_xy;
    int with_percents;
    int with_counts;
    int with_areas;
    int with_labels;

    /* printf format */
    char fmt[20];
    int dp;
    struct Range range;
    struct FPRange fp_range;
    struct Quant q;
    CELL min, max, null_set = 0;
    DCELL dmin, dmax;
    struct GModule *module;
    struct
    {
	struct Flag *A;		/* print averaged values instead of intervals */
	struct Flag *a;		/* area */
	struct Flag *c;		/* cell counts */
	struct Flag *p;		/* percents */
	struct Flag *l;		/* with labels */
	struct Flag *q;		/* quiet */
	struct Flag *n;		/* Suppress reporting of any NULLs */
	struct Flag *N;		/* Suppress reporting of NULLs when 
				   all values are NULL */
	struct Flag *one;	/* one cell per line */
	struct Flag *x;		/*    with row/col */
	struct Flag *g;		/*    with east/north */
	struct Flag *i;		/* use quant rules for fp map, i.e. read it as int */
	struct Flag *r;		/*    raw output: when nsteps option is used,
				   report indexes of ranges instead of ranges
				   themselves; when -C (cats) option is used
				   reports indexes of fp ranges = ind. of labels */
	struct Flag *C;		/* report stats for labeled ranges in cats files */
    } flag;
    struct
    {
	struct Option *cell;
	struct Option *fs;
	struct Option *nv;
	struct Option *output;
	struct Option *nsteps;	/* divide data range into nsteps and report stats
				   for these ranges: only for fp maps
				   NOTE: when -C flag is used, and there are 
				   explicit fp ranges in cats or when the map 
				   is int, nsteps is ignored */
    } option;

    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("raster"));
    G_add_keyword(_("statistics"));
    module->description =
	_("Generates area statistics for raster map layers.");

    /* Define the different options */

    option.cell = G_define_standard_option(G_OPT_R_INPUTS);

    option.output = G_define_standard_option(G_OPT_F_OUTPUT);
    option.output->required = NO;
    option.output->description =
	_("Name for output file (if omitted or \"-\" output to stdout)");

    option.fs = G_define_standard_option(G_OPT_F_SEP);
    option.fs->key_desc = "character|space|tab";
    option.fs->answer = "space";
    option.fs->description = _("Output field separator");

    option.nv = G_define_option();
    option.nv->key = "nv";
    option.nv->type = TYPE_STRING;
    option.nv->required = NO;
    option.nv->multiple = NO;
    option.nv->answer = "*";
    option.nv->description = _("String representing no data cell value");

    option.nsteps = G_define_option();
    option.nsteps->key = "nsteps";
    option.nsteps->type = TYPE_INTEGER;
    option.nsteps->required = NO;
    option.nsteps->multiple = NO;
    option.nsteps->answer = "255";
    option.nsteps->description =
	_("Number of fp subranges to collect stats from");

    /* Define the different flags */

    flag.one = G_define_flag();
    flag.one->key = '1';
    flag.one->description = _("One cell (range) per line");

    flag.A = G_define_flag();
    flag.A->key = 'A';
    flag.A->description = _("Print averaged values instead of intervals");
    flag.A->guisection = _("Print");

    flag.a = G_define_flag();
    flag.a->key = 'a';
    flag.a->description = _("Print area totals");
    flag.a->guisection = _("Print");

    flag.c = G_define_flag();
    flag.c->key = 'c';
    flag.c->description = _("Print cell counts");
    flag.c->guisection = _("Print");

    flag.p = G_define_flag();
    flag.p->key = 'p';
    flag.p->description =
	_("Print APPROXIMATE percents (total percent may not be 100%)");
    flag.p->guisection = _("Print");

    flag.l = G_define_flag();
    flag.l->key = 'l';
    flag.l->description = _("Print category labels");
    flag.l->guisection = _("Print");

    flag.g = G_define_flag();
    flag.g->key = 'g';
    flag.g->description = _("Print grid coordinates (east and north)");
    flag.g->guisection = _("Print");

    flag.x = G_define_flag();
    flag.x->key = 'x';
    flag.x->description = _("Print x and y (column and row)");
    flag.x->guisection = _("Print");

    flag.r = G_define_flag();
    flag.r->key = 'r';
    flag.r->description = _("Print raw indexes of fp ranges (fp maps only)");
    flag.r->guisection = _("Print");

    flag.n = G_define_flag();
    flag.n->key = 'n';
    flag.n->description = _("Suppress reporting of any NULLs");

    flag.N = G_define_flag();
    flag.N->key = 'N';
    flag.N->description =
	_("Suppress reporting of NULLs when all values are NULL");

    flag.C = G_define_flag();
    flag.C->key = 'C';
    flag.C->description = _("Report for cats fp ranges (fp maps only)");

    flag.i = G_define_flag();
    flag.i->key = 'i';
    flag.i->description = _("Read fp map as integer (use map's quant rules)");

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

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

    sscanf(option.nsteps->answer, "%d", &nsteps);
    if (nsteps <= 0) {
	G_warning(_("'%s' must be greater than zero; using %s=255"),
		  option.nsteps->key, option.nsteps->key);
	nsteps = 255;
    }
    cat_ranges = flag.C->answer;

    averaged = flag.A->answer;
    raw_output = flag.r->answer;
    as_int = flag.i->answer;
    nrows = Rast_window_rows();
    ncols = Rast_window_cols();

    fd = NULL;
    nfiles = 0;
    dp = -1;

    with_percents = flag.p->answer;
    with_counts = flag.c->answer;
    with_areas = flag.a->answer;
    with_labels = flag.l->answer;

    no_nulls = flag.n->answer;
    no_nulls_all = flag.N->answer;
    no_data_str = option.nv->answer;

    raw_data = flag.one->answer;
    with_coordinates = flag.g->answer;
    with_xy = flag.x->answer;
    if (with_coordinates || with_xy)
	raw_data = 1;

    /* get field separator */
    strcpy(fs, " ");
    if (option.fs->answer) {
	if (strcmp(option.fs->answer, "space") == 0)
	    *fs = ' ';
	else if (strcmp(option.fs->answer, "tab") == 0)
	    *fs = '\t';
	else if (strcmp(option.fs->answer, "\\t") == 0)
	    *fs = '\t';
	else
	    *fs = *option.fs->answer;
    }


    /* open all raster maps */
    if (option.cell->answers[0] == NULL)
	G_fatal_error(_("Raster map not found"));

    names = option.cell->answers;
    ptr = option.cell->answers;

    for (; *ptr != NULL; ptr++) {
	name = *ptr;
	fd = (int *)G_realloc(fd, (nfiles + 1) * sizeof(int));
	is_fp = (int *)G_realloc(is_fp, (nfiles + 1) * sizeof(int));
	DMAX = (DCELL *) G_realloc(DMAX, (nfiles + 1) * sizeof(DCELL));
	DMIN = (DCELL *) G_realloc(DMIN, (nfiles + 1) * sizeof(DCELL));

	fd[nfiles] = Rast_open_old(name, "");
	if (!as_int)
	    is_fp[nfiles] = Rast_map_is_fp(name, "");
	else {
	    is_fp[nfiles] = 0;
	    if (cat_ranges || nsteps != 255)
		G_warning(_("Raster map <%s> is reading as integer map! "
			    "Flag '-%c' and/or '%s' option will be ignored."),
			  name, flag.C->key, option.nsteps->key);
	}
	if (with_labels || (cat_ranges && is_fp[nfiles])) {
	    labels = (struct Categories *)
		G_realloc(labels, (nfiles + 1) * sizeof(struct Categories));
	    if (Rast_read_cats(name, "", &labels[nfiles]) < 0)
		Rast_init_cats("", &labels[nfiles]);
	}
	if (is_fp[nfiles])
	    /* floating point map */
	{
	    Rast_quant_init(&q);
	    if (cat_ranges) {
		if (!Rast_quant_nof_rules(&labels[nfiles].q)) {
		    G_warning(_("Cats for raster map <%s> are either missing or have no explicit labels. "
			       "Using %s=%d."),
			      name, option.nsteps->key, nsteps);
		    cat_ranges = 0;
		}
		else if (nsteps != 255)
		    G_warning(_("Flag '-%c' was given, using cats fp ranges of raster map <%s>, "
			       "ignoring '%s' option"),
			      flag.C->key, name, option.nsteps->key);
	    }
	    if (!cat_ranges) {	/* DO NOT use else here, cat_ranges can change */
		if (Rast_read_fp_range(name, "", &fp_range) < 0)
		    G_fatal_error(_("Unable to read fp range of raster map <%s>"),
				  name);
		Rast_get_fp_range_min_max(&fp_range, &DMIN[nfiles],
				       &DMAX[nfiles]);
		G_debug(3, "file %2d: dmin=%f  dmax=%f", nfiles, DMIN[nfiles], 
			DMAX[nfiles]);

		Rast_quant_add_rule(&q, DMIN[nfiles], DMAX[nfiles], 1, nsteps+1);

		/* set the quant rules for reading the map */
		Rast_set_quant_rules(fd[nfiles], &q);
		Rast_quant_get_limits(&q, &dmin, &dmax, &min, &max);
		G_debug(2, "overall: dmin=%f  dmax=%f,  qmin=%d  qmax=%d",
			dmin, dmax, min, max);

		Rast_quant_free(&q);
	    }
	    else {		/* cats ranges */

		/* set the quant rules for reading the map */
		Rast_set_quant_rules(fd[nfiles], &labels[nfiles].q);
		Rast_quant_get_limits(&labels[nfiles].q, &dmin, &dmax, &min,
				   &max);
	    }
	}
	else {
	    if (Rast_read_range(name, "", &range) < 0)
		G_fatal_error(_("Unable to read range for map <%s>"), name);
	    Rast_get_range_min_max(&range, &min, &max);
	}
	if (!null_set) {
	    null_set = 1;
	    NULL_CELL = max + 1;
	}
	else if (NULL_CELL < max + 1)
	    NULL_CELL = max + 1;

	nfiles++;
    }

    if (dp < 0)
	strcpy(fmt, "%lf");
    else
	sprintf(fmt, "%%.%dlf", dp);

    if (raw_data)
	raw_stats(fd, with_coordinates, with_xy, with_labels);
    else
	cell_stats(fd, with_percents, with_counts, with_areas, with_labels,
		   fmt);

    exit(EXIT_SUCCESS);
}
Beispiel #8
0
/*
 * check_stats() - Check and update statistics 
 *
 * RETURN: 0 on success / 1 on failure
 */
int check_stats(const char *name)
{
    RASTER_MAP_TYPE data_type;
    struct Histogram histogram;
    struct Categories cats;
    struct Range range;
    struct FPRange fprange;
    int i, histo_num;
    int cats_ok;
    int max;

    data_type = Rast_map_type(name, "");

    G_message(_("Updating statistics for [%s]..."), name);

    if (!do_histogram(name))
	return 1;
    if (Rast_read_histogram(name, "", &histogram) <= 0)
	return 1;

    /* Init histogram range */
    if (data_type == CELL_TYPE)
	Rast_init_range(&range);
    else
	Rast_init_fp_range(&fprange);

    G_message(_("Updating histogram range..."));
    i = histo_num = Rast_get_histogram_num(&histogram);
    while (i >= 0) {
	G_percent(i, histo_num, 2);

	if (data_type == CELL_TYPE)
	    Rast_update_range(Rast_get_histogram_cat(i--, &histogram), &range);
	else
	    Rast_update_fp_range((DCELL) Rast_get_histogram_cat(i--, &histogram),
			      &fprange);
    }

    /* Write histogram range */
    if (data_type == CELL_TYPE)
	Rast_write_range(name, &range);
    else
	Rast_write_fp_range(name, &fprange);

    /* Get category status and max */
    cats_ok = (Rast_read_cats(name, "", &cats) >= 0);
    max = (data_type == CELL_TYPE ? range.max : fprange.max);

    /* Further category checks */
    if (!cats_ok)
	Rast_init_cats("", &cats);
    else if (cats.num != max) {
	cats.num = max;
	cats_ok = 0;
    }

    /* Update categories if needed */
    if (!cats_ok) {
	G_message(_("Updating the number of categories for [%s]..."), name);
	Rast_write_cats(name, &cats);
    }

    Rast_free_histogram(&histogram);
    Rast_free_cats(&cats);

    return 0;
}
Beispiel #9
0
int main(int argc, char *argv[])
{
    int fd[NFILES];
    int outfd;
    int i;
    const char *name;
    const char *output;
    const char *mapset;
    int non_zero;
    struct Range range;
    CELL ncats, max_cats;
    int primary;
    struct Categories pcats;
    struct Colors pcolr;
    char buf[1024];
    CELL result;
    struct GModule *module;
    struct
    {
	struct Option *input, *output;
    } parm;
    struct
    {
	struct Flag *z;
    } flag;

    G_gisinit(argv[0]);

    /* Define the different options */

    module = G_define_module();
    G_add_keyword(_("raster"));
    G_add_keyword(_("statistics"));
    module->description =
	_("Creates a cross product of the category values from "
	  "multiple raster map layers.");

    parm.input = G_define_option();
    parm.input->key = "input";
    parm.input->type = TYPE_STRING;
    parm.input->required = YES;
    parm.input->multiple = YES;
    parm.input->gisprompt = "old,cell,raster";
    sprintf(buf, _("Names of 2-%d input raster maps"), NFILES);
    parm.input->description = G_store(buf);

    parm.output = G_define_standard_option(G_OPT_R_OUTPUT);

    /* Define the different flags */

    flag.z = G_define_flag();
    flag.z->key = 'z';
    flag.z->description = _("Non-zero data only");

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

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

    nfiles = 0;
    non_zero = flag.z->answer;

    for (nfiles = 0; (name = parm.input->answers[nfiles]); nfiles++) {
	if (nfiles >= NFILES)
	    G_fatal_error(_("More than %d files not allowed"), NFILES);
	mapset = G_find_raster2(name, "");
	if (!mapset)
	    G_fatal_error(_("Raster map <%s> not found"), name);
	names[nfiles] = name;
	fd[nfiles] = Rast_open_old(name, mapset);
	Rast_read_range(name, mapset, &range);
	ncats = range.max - range.min;

	if (nfiles == 0 || ncats > max_cats) {
	    primary = nfiles;
	    max_cats = ncats;
	}
    }

    if (nfiles <= 1)
	G_fatal_error(_("Must specify 2 or more input maps"));
    output = parm.output->answer;
    outfd = Rast_open_c_new(output);

    sprintf(buf, "Cross of %s", names[0]);
    for (i = 1; i < nfiles - 1; i++) {
	strcat(buf, ", ");
	strcat(buf, names[i]);
    }
    strcat(buf, " and ");
    strcat(buf, names[i]);
    Rast_init_cats(buf, &pcats);

    /* first step is cross product, but un-ordered */
    result = cross(fd, non_zero, primary, outfd);

    /* print message STEP mesage */
    G_message(_("%s: STEP 2 ..."), G_program_name());

    /* now close all files */
    for (i = 0; i < nfiles; i++)
	Rast_close(fd[i]);
    Rast_close(outfd);

    if (result <= 0)
	exit(0);


    /* build the renumbering/reclass and the new cats file */
    qsort(reclass, result + 1, sizeof(RECLASS), cmp);
    table = (CELL *) G_calloc(result + 1, sizeof(CELL));
    for (i = 0; i < nfiles; i++) {
	mapset = G_find_raster2(names[i], "");
	Rast_read_cats(names[i], mapset, &labels[i]);
    }

    for (ncats = 0; ncats <= result; ncats++) {
	table[reclass[ncats].result] = ncats;
	set_cat(ncats, reclass[ncats].cat, &pcats);
    }

    for (i = 0; i < nfiles; i++)
	Rast_free_cats(&labels[i]);

    /* reopen the output cell for reading and for writing */
    fd[0] = Rast_open_old(output, G_mapset());
    outfd = Rast_open_c_new(output);

    renumber(fd[0], outfd);

    G_message(_("Creating support files for <%s>..."), output);
    Rast_close(fd[0]);
    Rast_close(outfd);
    Rast_write_cats(output, &pcats);
    Rast_free_cats(&pcats);
    if (result > 0) {
	Rast_make_random_colors(&pcolr, (CELL) 1, result);
	Rast_write_colors(output, G_mapset(), &pcolr);
    }

    G_message(_("%ld categories"), (long)result);
    exit(EXIT_SUCCESS);
}
Beispiel #10
0
int main(int argc, char *argv[])
{
    struct Categories cats;
    struct FPRange range;
    DCELL min, max;
    RASTER_MAP_TYPE map_type;
    char buf[1024];
    RULE *rules, *tail;
    int any;
    const char *old_mapset;
    FILE *srcfp;
    int tty;
    struct GModule *module;
    struct
    {
	struct Option *input, *output, *title, *rules;
    } parm;

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

    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("raster"));
    G_add_keyword(_("reclassification"));
    module->label = _("Reclassify raster map based on category values.");
    module->description =
	_("Creates a new raster map whose category values are based "
	  "upon a reclassification of the categories in an existing "
	  "raster map.");

    parm.input = G_define_standard_option(G_OPT_R_INPUT);
    parm.input->description = _("Name of raster map to be reclassified");
    
    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 reclass 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");

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

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

    if (strcmp(parm.input->answer, parm.output->answer) == 0 &&
	strcmp(old_mapset, G_mapset()) == 0)
	G_fatal_error(_("Input map can NOT be the same as output map"));

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

    Rast_init_cats("", &cats);
    map_type = Rast_map_type(parm.input->answer, old_mapset);
    Rast_read_fp_range(parm.input->answer, old_mapset, &range);
    Rast_get_fp_range_min_max(&range, &min, &max);
    rules = tail = NULL;
    any = 0;

    if (tty) {
	fprintf(stderr,
		_("Enter rule(s), \"end\" when done, \"help\" if you need it\n"));
	if (map_type == FCELL_TYPE)
	    fprintf(stderr, _("FCELL: Data range is %.7g to %.7g\n"),
		    (double)min, (double)max);
	else if (map_type == DCELL_TYPE)
	    fprintf(stderr, _("DCELL: Data range is %.15g to %.15g\n"),
		    (double)min, (double)max);
	else
	    fprintf(stderr, _("CELL: Data range is %ld to %ld\n"), (long)min,
		    (long)max);
    }

    while (input(srcfp, tty, buf)) {
	switch (parse(buf, &rules, &tail, &cats)) {
	case -1:
	    if (tty) {
		fprintf(stderr, _("Illegal reclass rule -"));
		fprintf(stderr, _(" ignored\n"));
	    }
	    else {
		strcat(buf, _(" - invalid reclass rule"));
		G_fatal_error("%s", buf);
	    }
	    break;

	case 0:
	    break;

	default:
	    any = 1;
	    break;
	}
    }

    if (!any) {
	if (tty)
	    G_fatal_error(_("No rules specified. Raster map <%s> not created"),
			  parm.output->answer);
	else
	    G_fatal_error(_("No rules specified"));
    }

    reclass(parm.input->answer, old_mapset, parm.output->answer, rules, &cats,
	    parm.title->answer);

    exit(EXIT_SUCCESS);
}
Beispiel #11
0
int main(int argc, char *argv[])
{
    const char *mapset;
    struct GModule *module;
    struct Option *raster, *title_opt, *history_opt;
    struct Option *datasrc1_opt, *datasrc2_opt, *datadesc_opt;
    struct Option *map_opt, *units_opt, *vunits_opt;
    struct Option *load_opt, *save_opt;
    struct Flag *stats_flag;
    const char *infile;
    char title[MAX_TITLE_LEN + 1];
    struct History hist;

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

    module = G_define_module();
    G_add_keyword(_("raster3d"));
    G_add_keyword(_("metadata"));
    G_add_keyword(_("voxel"));
    module->description = _("Allows creation and/or modification of "
			    "3D raster map layer support files.");

    raster = G_define_standard_option(G_OPT_R3_MAP);

    title_opt = G_define_option();
    title_opt->key = "title";
    title_opt->key_desc = "phrase";
    title_opt->type = TYPE_STRING;
    title_opt->required = NO;
    title_opt->description = _("Text to use for map title");

    history_opt = G_define_option();
    history_opt->key = "history";
    history_opt->key_desc = "phrase";
    history_opt->type = TYPE_STRING;
    history_opt->required = NO;
    history_opt->description =
	_("Text to append to the next line of the map's metadata file");

    units_opt = G_define_option();
    units_opt->key = "unit";
    units_opt->type = TYPE_STRING;
    units_opt->required = NO;
    units_opt->description = _("The map data unit");

    vunits_opt = G_define_option();
    vunits_opt->key = "vunit";
    vunits_opt->type = TYPE_STRING;
    vunits_opt->required = NO;
    vunits_opt->description = _("The vertical unit of the map");
    
    datasrc1_opt = G_define_option();
    datasrc1_opt->key = "source1";
    datasrc1_opt->key_desc = "phrase";
    datasrc1_opt->type = TYPE_STRING;
    datasrc1_opt->required = NO;
    datasrc1_opt->description = _("Text to use for data source, line 1");

    datasrc2_opt = G_define_option();
    datasrc2_opt->key = "source2";
    datasrc2_opt->key_desc = "phrase";
    datasrc2_opt->type = TYPE_STRING;
    datasrc2_opt->required = NO;
    datasrc2_opt->description = _("Text to use for data source, line 2");

    datadesc_opt = G_define_option();
    datadesc_opt->key = "description";
    datadesc_opt->key_desc = "phrase";
    datadesc_opt->type = TYPE_STRING;
    datadesc_opt->required = NO;
    datadesc_opt->description =
	_("Text to use for data description or keyword(s)");

    map_opt = G_define_option();
    map_opt->key = "raster";
    map_opt->type = TYPE_STRING;
    map_opt->required = NO;
    map_opt->gisprompt = "old,cell,raster";
    map_opt->description = _("Raster map from which to copy category table");

    load_opt = G_define_standard_option(G_OPT_F_INPUT);
    load_opt->key = "loadhistory";
    load_opt->required = NO;
    load_opt->description = _("Text file from which to load history");

    save_opt = G_define_standard_option(G_OPT_F_OUTPUT);
    save_opt->key = "savehistory";
    save_opt->required = NO;
    save_opt->description = _("Text file in which to save history");

    stats_flag = G_define_flag();
    stats_flag->key = 's';
    stats_flag->description = _("Update range");

    /* Parse command-line options */
    if (G_parser(argc, argv))
	exit(EXIT_FAILURE);

    /* Make sure raster exists and set mapset */
    infile = raster->answer;
    mapset = G_find_raster3d(infile, G_mapset());	/* current mapset only for editing */
    if (!mapset || strcmp(mapset, G_mapset()) != 0)
	G_fatal_error(_("3D raster map <%s> not found"), infile);

    if (title_opt->answer) {
	strncpy(title, title_opt->answer, MAX_TITLE_LEN);
	title[MAX_TITLE_LEN - 1] = '\0';	/* strncpy doesn't null terminate over-sized input */
	G_strip(title);
	G_debug(3, "map title= [%s]  (%d chars)", title, (int)strlen(title));
        
        Rast3d_read_history(raster->answer, "", &hist);
        Rast_set_history(&hist, HIST_TITLE, title);
	Rast3d_write_history(raster->answer, &hist);
    }

    if (save_opt->answer) {
	FILE *fp = fopen(save_opt->answer, "w");
	int i;

	if (!fp)
	    G_fatal_error(_("Unable to open output file <%s>"), save_opt->answer);

	Rast3d_read_history(raster->answer, "", &hist);

	for (i = 0; i < Rast_history_length(&hist); i++)
	    fprintf(fp, "%s\n", Rast_history_line(&hist, i));

	fclose(fp);
    }

    if (load_opt->answer) {
	FILE *fp = fopen(load_opt->answer, "r");

	if (!fp)
	    G_fatal_error(_("Unable to open input file <%s>"), load_opt->answer);

	Rast3d_read_history(raster->answer, "", &hist);

	Rast_clear_history(&hist);

	for (;;) {
	    char buf[80];
	    if (!G_getl2(buf, sizeof(buf), fp))
		break;
	    Rast_append_history(&hist, buf);
	}

	fclose(fp);

	Rast3d_write_history(raster->answer, &hist);
    }

    if (history_opt->answer) {
	Rast3d_read_history(raster->answer, "", &hist);

	/* two less than defined as if only one less a newline gets appended in the hist file. bug? */
	/* Should be RECORD_LEN, but r.info truncates at > 71 chars */
	if (strlen(history_opt->answer) > 71) {
	    int i;

	    for (i = 0; i < strlen(history_opt->answer); i += 71) {
		char buf[72];

		strncpy(buf, &history_opt->answer[i], sizeof(buf)-1);
		buf[sizeof(buf)-1] = '\0';

		Rast_append_history(&hist, buf);
	    }
	}
	else
	    Rast_append_history(&hist, history_opt->answer);

	Rast3d_write_history(raster->answer, &hist);
    }
    
    if(units_opt->answer || vunits_opt->answer) {
        RASTER3D_Map *map;
        
        map = Rast3d_open_cell_old(raster->answer, G_mapset(), \
                RASTER3D_DEFAULT_WINDOW, RASTER3D_TILE_SAME_AS_FILE, RASTER3D_USE_CACHE_DEFAULT);
        
        /* Modify the units */
        if (units_opt->answer)
            Rast3d_set_unit(map, units_opt->answer);

        if (vunits_opt->answer)
            Rast3d_set_vertical_unit(map, vunits_opt->answer);
        
        Rast3d_rewrite_header(map);
        Rast3d_close(map);
    
    }

    if (datasrc1_opt->answer || datasrc2_opt->answer || datadesc_opt->answer) {
	Rast3d_read_history(raster->answer, "", &hist);

	if (datasrc1_opt->answer)
	    Rast_set_history(&hist, HIST_DATSRC_1, datasrc1_opt->answer);

	if (datasrc2_opt->answer)
	    Rast_set_history(&hist, HIST_DATSRC_2, datasrc2_opt->answer);

	if (datadesc_opt->answer)
	    Rast_set_history(&hist, HIST_KEYWRD, datadesc_opt->answer);

	Rast3d_write_history(raster->answer, &hist);
    }

    if (map_opt->answer) {	/* use cats from another map */
	int fd;
	struct Categories cats;

	fd = Rast_open_old(infile, "");
	Rast_init_cats("", &cats);
	if (Rast3d_read_cats(map_opt->answer, "", &cats) < 0)
	    G_fatal_error(_("Unable to read category file of raster map <%s>"),
			  map_opt->answer);

	Rast3d_write_cats(infile, &cats);
	G_message(_("cats table for [%s] set to %s"),
		  infile, map_opt->answer);
	Rast_close(fd);
	Rast_free_cats(&cats);
    }

    /* Check the histogram and range */
    if (stats_flag->answer)
	check_stats(raster->answer);

    return EXIT_SUCCESS;
}
Beispiel #12
0
int main(int argc, char *argv[])
{
    char rname[GNAME_MAX];	/* Reclassed map name */
    char rmapset[GMAPSET_MAX];	/* Reclassed mapset   */
    const char *mapset;		/* Raster mapset      */
    struct Cell_head cellhd;
    struct GModule *module;
    struct Option *raster, *title_opt, *history_opt;
    struct Option *datasrc1_opt, *datasrc2_opt, *datadesc_opt;
    struct Option *map_opt, *units_opt, *vdatum_opt;
    struct Option *load_opt, *save_opt;
    struct Flag *stats_flag, *null_flag, *del_flag;
    int is_reclass;		/* Is raster reclass? */
    const char *infile;
    char title[MAX_TITLE_LEN + 1];
    struct History hist;

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

    module = G_define_module();
    G_add_keyword(_("raster"));
    G_add_keyword(_("metadata"));
    module->description = _("Allows creation and/or modification of "
			    "raster map layer support files.");

    raster = G_define_standard_option(G_OPT_R_MAP);

    title_opt = G_define_option();
    title_opt->key = "title";
    title_opt->key_desc = "phrase";
    title_opt->type = TYPE_STRING;
    title_opt->required = NO;
    title_opt->description = _("Title for resultant raster map");

    history_opt = G_define_option();
    history_opt->key = "history";
    history_opt->key_desc = "phrase";
    history_opt->type = TYPE_STRING;
    history_opt->required = NO;
    history_opt->description =
	_("Text to append to the next line of the map's metadata file");

    units_opt = G_define_option();
    units_opt->key = "units";
    units_opt->type = TYPE_STRING;
    units_opt->required = NO;
    units_opt->description = _("Text to use for map data units");

    vdatum_opt = G_define_option();
    vdatum_opt->key = "vdatum";
    vdatum_opt->type = TYPE_STRING;
    vdatum_opt->required = NO;
    vdatum_opt->description = _("Text to use for map vertical datum");

    datasrc1_opt = G_define_option();
    datasrc1_opt->key = "source1";
    datasrc1_opt->key_desc = "phrase";
    datasrc1_opt->type = TYPE_STRING;
    datasrc1_opt->required = NO;
    datasrc1_opt->description = _("Text to use for data source, line 1");

    datasrc2_opt = G_define_option();
    datasrc2_opt->key = "source2";
    datasrc2_opt->key_desc = "phrase";
    datasrc2_opt->type = TYPE_STRING;
    datasrc2_opt->required = NO;
    datasrc2_opt->description = _("Text to use for data source, line 2");

    datadesc_opt = G_define_option();
    datadesc_opt->key = "description";
    datadesc_opt->key_desc = "phrase";
    datadesc_opt->type = TYPE_STRING;
    datadesc_opt->required = NO;
    datadesc_opt->description =
	_("Text to use for data description or keyword(s)");

    map_opt = G_define_option();
    map_opt->key = "raster";
    map_opt->type = TYPE_STRING;
    map_opt->required = NO;
    map_opt->gisprompt = "old,cell,raster";
    map_opt->description = _("Raster map from which to copy category table");

    load_opt = G_define_standard_option(G_OPT_F_INPUT);
    load_opt->key = "loadhistory";
    load_opt->required = NO;
    load_opt->description = _("Text file from which to load history");

    save_opt = G_define_standard_option(G_OPT_F_OUTPUT);
    save_opt->key = "savehistory";
    save_opt->required = NO;
    save_opt->description = _("Text file in which to save history");

    stats_flag = G_define_flag();
    stats_flag->key = 's';
    stats_flag->description = _("Update statistics (histogram, range)");

    null_flag = G_define_flag();
    null_flag->key = 'n';
    null_flag->description = _("Create/reset the null file");

    del_flag = G_define_flag();
    del_flag->key = 'd';
    del_flag->description = _("Delete the null file");

    /* Parse command-line options */
    if (G_parser(argc, argv))
	exit(EXIT_FAILURE);

    /* Make sure raster exists and set mapset */
    infile = raster->answer;
    mapset = G_find_raster2(infile, G_mapset());	/* current mapset only for editing */
    if (!mapset || strcmp(mapset, G_mapset()) != 0)
	G_fatal_error(_("Raster map <%s> not found in current mapset"), infile);

    Rast_get_cellhd(raster->answer, "", &cellhd);
    is_reclass = (Rast_is_reclass(raster->answer, "", rname, rmapset) > 0);

    if (title_opt->answer) {
	strncpy(title, title_opt->answer, MAX_TITLE_LEN);
	title[MAX_TITLE_LEN - 1] = '\0';	/* strncpy doesn't null terminate oversized input */
	G_strip(title);
	G_debug(3, "map title= [%s]  (%li chars)", title, strlen(title));
	Rast_read_history(raster->answer, "", &hist);
	Rast_set_history(&hist, HIST_TITLE, title);
	Rast_write_history(raster->answer, &hist);
    }

    if (save_opt->answer) {
	FILE *fp = fopen(save_opt->answer, "w");
	int i;

	if (!fp)
	    G_fatal_error(_("Unable to open output file <%s>"), save_opt->answer);

	Rast_read_history(raster->answer, "", &hist);

	for (i = 0; i < Rast_history_length(&hist); i++)
	    fprintf(fp, "%s\n", Rast_history_line(&hist, i));

	fclose(fp);
    }

    if (load_opt->answer) {
	FILE *fp = fopen(load_opt->answer, "r");

	if (!fp)
	    G_fatal_error(_("Unable to open input file <%s>"), load_opt->answer);

	Rast_read_history(raster->answer, "", &hist);

	Rast_clear_history(&hist);

	for (;;) {
	    char buf[80];
	    if (!G_getl2(buf, sizeof(buf), fp))
		break;
	    Rast_append_history(&hist, buf);
	}

	fclose(fp);

	Rast_write_history(raster->answer, &hist);
    }

    if (history_opt->answer) {
	Rast_read_history(raster->answer, "", &hist);

	/* two less than defined as if only one less a newline gets appended in the hist file. bug? */
	/* Should be RECORD_LEN, but r.info truncates at > 71 chars */
	if (strlen(history_opt->answer) > 71) {
	    int i;

	    for (i = 0; i < strlen(history_opt->answer); i += 71) {
		char buf[72];

		strncpy(buf, &history_opt->answer[i], sizeof(buf)-1);
		buf[sizeof(buf)-1] = '\0';

		Rast_append_history(&hist, buf);
	    }
	}
	else
	    Rast_append_history(&hist, history_opt->answer);

	Rast_write_history(raster->answer, &hist);
    }

    if (units_opt->answer)
	Rast_write_units(raster->answer, units_opt->answer);

    if (vdatum_opt->answer)
	Rast_write_vdatum(raster->answer, vdatum_opt->answer);

    if (datasrc1_opt->answer || datasrc2_opt->answer || datadesc_opt->answer) {
	Rast_read_history(raster->answer, "", &hist);

	if (datasrc1_opt->answer)
	    Rast_set_history(&hist, HIST_DATSRC_1, datasrc1_opt->answer);

	if (datasrc2_opt->answer)
	    Rast_set_history(&hist, HIST_DATSRC_2, datasrc2_opt->answer);

	if (datadesc_opt->answer)
	    Rast_set_history(&hist, HIST_KEYWRD, datadesc_opt->answer);

	Rast_write_history(raster->answer, &hist);
    }

    if (map_opt->answer) {	/* use cats from another map */
	int fd;
	struct Categories cats;

	fd = Rast_open_old(infile, "");
	Rast_init_cats("", &cats);
	if (Rast_read_cats(map_opt->answer, "", &cats) < 0)
	    G_fatal_error(_("Unable to read category file of raster map <%s>"),
			  map_opt->answer);

	Rast_write_cats(infile, &cats);
	G_message(_("cats table for [%s] set to %s"),
		  infile, map_opt->answer);
	Rast_close(fd);
	Rast_free_cats(&cats);
    }


    if (title_opt->answer || history_opt->answer || units_opt->answer
	|| vdatum_opt->answer || datasrc1_opt->answer || datasrc2_opt->answer
	|| datadesc_opt->answer || map_opt->answer)
	exit(EXIT_SUCCESS);


    /* Check the histogram and range */
    if (stats_flag->answer)
	check_stats(raster->answer);

    /* null file */
    if (null_flag->answer) {
	unsigned char *null_bits;
	int row, col;
	int fd;

	if (is_reclass)
	    G_fatal_error(_("[%s] is a reclass of another map. Exiting."),
			  raster->answer);

	/* Create a file of no-nulls */
	null_bits = Rast__allocate_null_bits(cellhd.cols);
	for (col = 0; col < Rast__null_bitstream_size(cellhd.cols); col++)
	    null_bits[col] = 0;

	/* Open null file for writing */
	Rast_set_window(&cellhd);
	fd = Rast__open_null_write(raster->answer);

	G_message(_("Writing new null file for [%s]... "), raster->answer);
	for (row = 0; row < cellhd.rows; row++) {
	    G_percent(row, cellhd.rows, 1);
	    Rast__write_null_bits(fd, null_bits);
	}
	G_percent(row, cellhd.rows, 1);

	/* Cleanup */
	Rast__close_null(fd);
	G_free(null_bits);
    }

    if (del_flag->answer) {
	char path[GPATH_MAX];

	if (is_reclass)
	    G_fatal_error(_("[%s] is a reclass of another map. Exiting."),
			  raster->answer);

	/* Write a file of no-nulls */
	G_message(_("Removing null file for [%s]...\n"), raster->answer);

	G_file_name_misc(path, "cell_misc", "null", raster->answer, G_mapset());
	unlink(path);
	G_file_name_misc(path, "cell_misc", "null2", raster->answer, G_mapset());
	unlink(path);

	G_done_msg(_("Done."));
    }

    return EXIT_SUCCESS;
}
Beispiel #13
0
static int
read_cats(const char *name, const char *mapset, struct Categories *pcats)
 /* adapted from G__read_cats */
{
    FILE *fd;
    char buff[1024];
    CELL cat;
    DCELL val1, val2;
    int old;
    long num = -1;

    fd = G_fopen_old_misc(RASTER3D_DIRECTORY, RASTER3D_CATS_ELEMENT, name, mapset);
    if (!fd)
	return -2;

    /* Read the number of categories */
    if (G_getl(buff, sizeof(buff), fd) == 0)
	goto error;

    if (sscanf(buff, "# %ld", &num) == 1)
	old = 0;
    else if (sscanf(buff, "%ld", &num) == 1)
	old = 1;

    /* Read the title for the file */
    if (G_getl(buff, sizeof(buff), fd) == 0)
	goto error;
    G_strip(buff);

    Rast_init_cats(buff, pcats);
    if (num >= 0)
	pcats->num = num;

    if (!old) {
	char fmt[256];
	float m1, a1, m2, a2;

	if (G_getl(fmt, sizeof(fmt), fd) == 0)
	    goto error;
	/* next line contains equation coefficients */
	if (G_getl(buff, sizeof(buff), fd) == 0)
	    goto error;
	if (sscanf(buff, "%f %f %f %f", &m1, &a1, &m2, &a2) != 4)
	    goto error;
	Rast_set_cats_fmt(fmt, m1, a1, m2, a2, pcats);
    }

    /* Read all category names */
    for (cat = 0;; cat++) {
	char label[1024];

	if (G_getl(buff, sizeof(buff), fd) == 0)
	    break;

	if (old)
	    Rast_set_c_cat(&cat, &cat, buff, pcats);
	else {
	    *label = 0;
	    if (sscanf(buff, "%1s", label) != 1)
		continue;
	    if (*label == '#')
		continue;
	    *label = 0;

	    /* try to read a range of data */
	    if (sscanf(buff, "%lf:%lf:%[^\n]", &val1, &val2, label) == 3)
		Rast_set_cat(&val1, &val2, label, pcats, DCELL_TYPE);
	    else if (sscanf(buff, "%d:%[^\n]", &cat, label) >= 1)
		Rast_set_cat(&cat, &cat, label, pcats, CELL_TYPE);
	    else if (sscanf(buff, "%lf:%[^\n]", &val1, label) >= 1)
		Rast_set_cat(&val1, &val1, label, pcats, DCELL_TYPE);
	    else
		goto error;
	}
    }

    fclose(fd);
    return 0;

  error:
    fclose(fd);
    return -1;
}
Beispiel #14
0
static int close_new(RASTER3D_Map * map)
{
    char path[GPATH_MAX];
    struct Categories cats;
    struct History hist;

    Rast3d_remove_color(map->fileName);

    /* create empty cats file */
    Rast_init_cats(NULL, &cats);
    Rast3d_write_cats(map->fileName, &cats);
    Rast_free_cats(&cats);

    /*generate the history file, use the normal G_ functions */
    Rast_short_history(map->fileName, "raster3d", &hist);
    Rast_command_history(&hist);
    /*Use the G3d function to write the history file,
     * otherwise the path is wrong */
    if (Rast3d_write_history(map->fileName, &hist) < 0) {
	G_warning(_("Unable to write history for 3D raster map <%s>"), map->fileName);
    }

    Rast3d_range_write(map);

    close(map->data_fd);

    /* finally move tempfile to data file */
    Rast3d_filename(path, RASTER3D_CELL_ELEMENT, map->fileName, map->mapset);
#ifdef __MINGW32__
    if (CopyFile(map->tempName, path, FALSE) == 0) {
#else
    if (link(map->tempName, path) < 0) {
#endif
	if (rename(map->tempName, path)) {
	    G_warning(_("Unable to move temp raster map <%s> to 3D raster map <%s>"),
		      map->tempName, path);
	    return 0;
	}
    }
    else
	remove(map->tempName);

    return 1;
}

static int close_cell_new(RASTER3D_Map * map)
{
    long ltmp;

    if (map->useCache)
	if (!Rast3d_flush_all_tiles(map)) {
	    G_warning(_("Unable to flush all tiles"));
	    return 0;
	}

    if (!Rast3d_flush_index(map)) {
	G_warning(_("Unable to flush index"));
	return 0;
    }

    /* write the header info which was filled with dummy values at the */
    /* opening time */

    if (lseek(map->data_fd,
	      (long)(map->offset - sizeof(int) - sizeof(long)),
	      SEEK_SET) == -1) {
	G_warning(_("Unable to position file"));
	return 0;
    }

    if (!Rast3d_write_ints(map->data_fd, map->useXdr, &(map->indexNbytesUsed), 1)) {
	G_warning(_("Unable to write header for 3D raster map <%s>"), map->fileName);
	return 0;
    }

    Rast3d_long_encode(&(map->indexOffset), (unsigned char *)&ltmp, 1);
    if (write(map->data_fd, &ltmp, sizeof(long)) != sizeof(long)) {
	G_warning(_("Unable to write header for 3D raster map <%s>"), map->fileName);
	return 0;
    }

    if (!close_new(map) != 0) {
	G_warning(_("Unable to create 3D raster map <%s>"), map->fileName);
	return 0;
    }

    return 1;
}