Example #1
0
int support(char **names,
	    struct Cell_stats *statf, int nfiles,
	    struct Categories *cats,
	    int *cats_ok,
	    struct Colors *colr, int *colr_ok, RASTER_MAP_TYPE out_type)
{
    int i;
    struct Categories pcats;
    struct Colors pcolr;
    CELL n;
    long count;
    int red, grn, blu;
    int do_cats, do_colr;

    *cats_ok = 1;
    *colr_ok = 1;
    if (Rast_read_cats(names[0], "", cats) < 0)
	*cats_ok = 0;
    G_suppress_warnings(1);
    if (Rast_read_colors(names[0], "", colr) < 0)
	*colr_ok = 0;
    G_suppress_warnings(0);

    if (*cats_ok == 0 && *colr_ok == 0)
	return 0;

    for (i = 1; i < nfiles; i++) {
	do_cats = *cats_ok && (Rast_read_cats(names[i], "", &pcats) >= 0);
	G_suppress_warnings(1);
	do_colr = *colr_ok && (Rast_read_colors(names[i], "", &pcolr) >= 0);
	G_suppress_warnings(0);
	if (!do_cats && !do_colr)
	    continue;
	if (out_type == CELL_TYPE) {
	    Rast_rewind_cell_stats(statf + i);
	    while (Rast_next_cell_stat(&n, &count, statf + i))
		if (n && !Rast_find_cell_stat(n, &count, statf)) {
		    if (do_cats) {
			Rast_update_cell_stats(&n, 1, statf);
			Rast_set_c_cat(&n, &n, Rast_get_c_cat((CELL *) &n, &pcats), cats);
		    }
		    if (do_colr) {
			Rast_get_c_color(&n, &red, &grn, &blu, &pcolr);
			Rast_set_c_color(n, red, grn, blu, colr);
		    }
		}
	}
	/* else the color will be the color of the first map */

	if (do_cats)
	    Rast_free_cats(&pcats);
	if (do_colr)
	    /* otherwise this memory is used in colr pointer */
	    Rast_free_colors(&pcolr);
    }
    return 1;
}
Example #2
0
/* Copy the colors from map named iname to the map named oname */
static void copy_colors(const char *iname, char *oname)
{
    struct Colors colors;

    Rast_read_colors(iname, "", &colors);
    Rast_write_colors(oname, G_mapset(), &colors);
}
Example #3
0
File: Gs3.c Project: caomw/grass
/*!
   \brief Pack color table (floating-point map)

   Passed a array of floats that will be converted from cell values
   to packed colors (0xbbggrr) and float to int 
   Floating point data not freed here, use: 
   gsds_free_data_buff(id, ATTY_FLOAT)

   \param filename raster map name
   \param fbuf
   \param ibuf
   \param rows number of rows
   \param cols number of cols
 */
void Gs_pack_colors_float(const char *filename, float *fbuf, int *ibuf,
			  int rows, int cols)
{
    const char *mapset;
    struct Colors colrules;
    unsigned char *r, *g, *b, *set;
    int i, j, *icur;
    FCELL *fcur;

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

    r = (unsigned char *)G_malloc(cols);
    g = (unsigned char *)G_malloc(cols);
    b = (unsigned char *)G_malloc(cols);
    set = (unsigned char *)G_malloc(cols);

    Rast_read_colors(filename, mapset, &colrules);

    fcur = fbuf;
    icur = ibuf;

    G_message(_("Translating colors from raster map <%s>..."),
	      G_fully_qualified_name(filename, mapset));
    
    for (i = 0; i < rows; i++) {
	Rast_lookup_f_colors(fcur, r, g, b, set, cols, &colrules);
	G_percent(i, rows, 2);

	for (j = 0; j < cols; j++) {
	    if (set[j]) {
		icur[j] =
		    (r[j] & 0xff) | ((g[j] & 0xff) << 8) | ((b[j] & 0xff) <<
							    16);
	    }
	    else {
		icur[j] = NO_DATA_COL;
	    }
	}

	icur = &(icur[cols]);
	fcur = &(fcur[cols]);
    }
    G_percent(1, 1, 1);
    
    Rast_free_colors(&colrules);

    G_free(r);
    G_free(g);
    G_free(b);
    G_free(set);

    return;
}
Example #4
0
File: Gs3.c Project: caomw/grass
/*!
   \brief Build color table (256)

   Calling function must have already allocated space in buff for range of
   data (256 for now) - simply calls get_color for each cat in color range

   \param filename raster map name
   \param[out] buff data buffer

   \return 1 on success
   \return 0 on failure
 */
int Gs_build_256lookup(const char *filename, int *buff)
{
    const char *mapset;
    struct Colors colrules;
    CELL min, max, cats[256];
    int i;
    unsigned char r[256], g[256], b[256], set[256];

    G_debug(3, "building color table");

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

    Rast_read_colors(filename, mapset, &colrules);
    Rast_get_c_color_range(&min, &max, &colrules);

    if (min < 0 || max > 255) {
	G_warning(_("Color table range doesn't match data (mincol=%d, maxcol=%d"),
		  min, max);

	min = min < 0 ? 0 : min;
	max = max > 255 ? 255 : max;
    }

    G_zero(cats, 256 * sizeof(CELL));

    for (i = min; i <= max; i++) {
	cats[i] = i;
    }

    Rast_lookup_c_colors(cats, r, g, b, set, 256, &colrules);

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

	if (set[i]) {
	    buff[i] =
		(r[i] & 0xff) | ((g[i] & 0xff) << 8) | ((b[i] & 0xff) << 16);
	}
	else {
	    buff[i] = NO_DATA_COL;
	}
    }

    return (1);
}
Example #5
0
static void do_output(int base_fd, char **outputs, const char *covermap)
{
    int *out_fd = G_malloc(num_quants * sizeof(int));
    CELL *base_buf = Rast_allocate_c_buf();
    DCELL *out_buf = Rast_allocate_d_buf();
    const char *mapset = G_mapset();
    struct Colors colors;
    int have_colors;
    int quant;
    int row, col;

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

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

	out_fd[quant] = Rast_open_fp_new(output);
    }

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

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

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

	    Rast_put_d_row(out_fd[quant], out_buf);
	}

	G_percent(row, rows, 2);
    }

    G_percent(row, rows, 2);

    for (quant = 0; quant < num_quants; quant++) {
	Rast_close(out_fd[quant]);
	if (have_colors)
	    Rast_write_colors(outputs[quant], mapset, &colors);
    }
}
Example #6
0
static void write_support_files(int xtile, int ytile, int overlap)
{
    char name[GNAME_MAX];
    struct Cell_head cellhd;
    char title[64];
    struct History history;
    struct Colors colors;
    struct Categories cats;

    sprintf(name, "%s-%03d-%03d", parm.rastout->answer, ytile, xtile);

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

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

    Rast_put_cellhd(name, &cellhd);

    /* copy cats from source map */
    if (Rast_read_cats(parm.rastin->answer, "", &cats) < 0)
	G_fatal_error(_("Unable to read cats for %s"),
		      parm.rastin->answer);
    Rast_write_cats(name, &cats);

    /* record map metadata/history info */
    G_debug(1, "Tile %d,%d of %s: writing %s", xtile, ytile, parm.rastin->answer, name);
    sprintf(title, "Tile %d,%d of %s", xtile, ytile, parm.rastin->answer);
    Rast_put_cell_title(name, title);

    Rast_short_history(name, "raster", &history);
    Rast_set_history(&history, HIST_DATSRC_1, parm.rastin->answer);
    Rast_command_history(&history);
    Rast_write_history(name, &history);

    /* copy color table from source map */
    if (Rast_read_colors(parm.rastin->answer, "", &colors) < 0)
	G_fatal_error(_("Unable to read color table for %s"),
		      parm.rastin->answer);
    if (map_type != CELL_TYPE)
	Rast_mark_colors_as_fp(&colors);
    Rast_write_colors(name, G_mapset(), &colors);
}
Example #7
0
int table_toggle(char *name, char *mapset, struct Colors *colors)
{
    CELL min, max;
    char *msg = '\0';
    char info[100];

    Rast_get_c_color_range(&min, &max, colors);
    Rast_free_colors(colors);
    sprintf(info, "Color range: %d to %d\n", min, max);

    toggle_number++;
    toggle_number &= 6;
    switch (toggle_number) {
    case 0:
	msg = "Original colors";
	Rast_read_colors(name, mapset, colors);
	break;
    case 1:
	msg = "Ramp colors";
	Rast_make_ramp_colors(colors, min, max);
	break;
    case 2:
	msg = "Grey scale colors";
	Rast_make_grey_scale_colors(colors, min, max);
	break;
    case 3:
	msg = "Random colors";
	Rast_make_random_colors(colors, min, max);
	break;
    case 4:
	msg = "Wave colors";
	Rast_make_wave_colors(colors, min, max);
	break;
    case 5:
	msg = "Aspect colors";
	Rast_make_aspect_colors(colors, min, max);
	break;
    }
    Write_message(2, msg);
    Write_message(3, info);

    return 0;
}
Example #8
0
int main(int argc, char **argv)
{
    int text_height;
    int text_width;
    struct Categories cats;
    struct Range range;
    struct Colors pcolors;
    char title[GNAME_MAX];
    double tt, tb, tl, tr;
    double t, b, l, r;
    struct GModule *module;
    struct Option *opt1;
    struct Option *opt2, *bg_opt;
    struct Option *opt4;
    struct Option *opt5;
    struct Flag *flag1;
    struct Flag *flag2;
    struct Flag *flag3;


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

    module = G_define_module();
    G_add_keyword(_("display"));
    G_add_keyword(_("histogram"));
    G_add_keyword(_("statistics"));
    module->description =
	_("Displays a histogram in the form of a pie or bar chart "
	  "for a user-specified raster map.");

    opt1 = G_define_standard_option(G_OPT_R_MAP);
    opt1->description = _("Raster map for which histogram will be displayed");

    opt4 = G_define_option();
    opt4->key = "style";
    opt4->description = _("Indicate if a pie or bar chart is desired");
    opt4->type = TYPE_STRING;
    opt4->required = NO;
    opt4->options = "pie,bar";
    opt4->answer = "bar";

    /* The color option specifies the color for the labels, tic-marks,
     * and borders of the chart. */
    opt2 = G_define_standard_option(G_OPT_C);
    opt2->label = _("Color for text and axes");

    bg_opt = G_define_standard_option(G_OPT_CN);
    bg_opt->key = "bgcolor";
    bg_opt->label = _("Background color");
    bg_opt->answer = DEFAULT_BG_COLOR;

#ifdef CAN_DO_AREAS
    opt3 = G_define_option();
    opt3->key = "type";
    opt3->description =
	_("Indicate if cell counts or map areas should be displayed");
    opt3->type = TYPE_STRING;
    opt3->required = NO;
    opt3->answer = "count";
    opt3->options = "count,area";
#endif

    opt5 = G_define_option();
    opt5->key = "nsteps";
    opt5->description =
	_("Number of steps to divide the data range into (fp maps only)");
    opt5->type = TYPE_INTEGER;
    opt5->required = NO;
    opt5->answer = "255";

    flag1 = G_define_flag();
    flag1->key = 'n';
    flag1->description = _("Display information for null cells");

    flag3 = G_define_flag();
    flag3->key = 'c';
    flag3->description =
	_("Report for ranges defined in cats file (fp maps only)");

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


    map_name = opt1->answer;

    color = D_parse_color(opt2->answer, FALSE);

    type = COUNT;
#ifdef CAN_DO_AREAS
    if (strcmp(opt3->answer, "count") == 0)
	type = COUNT;
    else
	type = AREA;
#endif

    if (strcmp(opt4->answer, "bar") == 0)
	style = BAR;
    else
	style = PIE;

    if (sscanf(opt5->answer, "%d", &nsteps) != 1)
	G_fatal_error(_("Invalid number of steps: %s"), opt5->answer);

    cat_ranges = flag3->answer;

    if (cat_ranges && nsteps != 255)
	G_warning(_("When -C flag is set, the nsteps argument is ignored"));

    nodata = flag1->answer;

    if (Rast_read_colors(map_name, "", &pcolors) == -1)
	G_fatal_error(_("Color file for <%s> not available"), map_name);

    if (Rast_read_cats(map_name, "", &cats) == -1)
	G_fatal_error(_("Category file for <%s> not available"), map_name);

    if (Rast_read_range(map_name, "", &range) == -1)
	G_fatal_error(_("Range information for <%s> not available"),
		      map_name);

    /* get the distribution statistics */

    get_stats(map_name, &dist_stats);

    /* set up the graphics driver and initialize its color-table */

    D_open_driver();
    
    D_setup_unity(0);			/* 0 = don't clear frame */
    D_get_src(&t, &b, &l, &r);

    /* clear the frame, if requested to do so */
    if (strcmp(bg_opt->answer, "none") != 0)
	D_erase(bg_opt->answer);

    /* draw a title for */
    sprintf(title, "%s", map_name);
    text_height = (b - t) * 0.05;
    text_width = (r - l) * 0.05 * 0.50;
    D_text_size(text_width, text_height);
    D_get_text_box(title, &tt, &tb, &tl, &tr);
    D_pos_abs(l + (r - l) / 2 - (tr - tl) / 2,
	      t + (b - t) * 0.07);
    D_use_color(color);
    D_text(title);

    /* plot the distributrion statistics */
    if (style == PIE)
	pie(&dist_stats, &pcolors);
    else
	bar(&dist_stats, &pcolors);

    D_save_command(G_recreate_command());
    D_close_driver();

    exit(EXIT_SUCCESS);
}
Example #9
0
int main(int argc, char **argv)
{
    struct band B[3];
    int row;
    int next_row;
    int overlay;
    struct Cell_head window;
    struct GModule *module;
    struct Flag *flag_n;
    int i;

    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("display"));
    G_add_keyword(_("graphics"));
    G_add_keyword(_("raster"));
    G_add_keyword("RGB");
    module->description =
	_("Displays three user-specified raster maps "
	  "as red, green, and blue overlays in the active graphics frame.");

    flag_n = G_define_flag();
    flag_n->key = 'n';
    flag_n->description = _("Make null cells opaque");
    flag_n->guisection = _("Null cells");
    
    for (i = 0; i < 3; i++) {
	char buff[80];

	sprintf(buff, _("Name of raster map to be used for <%s>"),
		color_names[i]);

	B[i].opt = G_define_standard_option(G_OPT_R_MAP);
	B[i].opt->key = G_store(color_names[i]);
	B[i].opt->description = G_store(buff);
    }

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

    /* Do screen initializing stuff */
    D_open_driver();
    
    overlay = !flag_n->answer;

    D_setup(0);
    D_set_overlay_mode(overlay);

    for (i = 0; i < 3; i++) {
	/* Get name of layer to be used */
	char *name = B[i].opt->answer;

	/* Make sure map is available */
	B[i].file = Rast_open_old(name, "");

	B[i].type = Rast_get_map_type(B[i].file);

	/* Reading color lookup table */
	if (Rast_read_colors(name, "", &B[i].colors) == -1)
	    G_fatal_error(_("Color file for <%s> not available"), name);

	B[i].array = Rast_allocate_buf(B[i].type);
    }

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

    D_raster_draw_begin();

    next_row = 0;
    for (row = 0; row < window.rows;) {
	G_percent(row, window.rows, 5);

	for (i = 0; i < 3; i++)
	    Rast_get_row(B[i].file, B[i].array, row, B[i].type);

	if (row == next_row)
	    next_row = D_draw_raster_RGB(next_row,
					 B[0].array, B[1].array, B[2].array,
					 &B[0].colors, &B[1].colors,
					 &B[2].colors, B[0].type, B[1].type,
					 B[2].type);
	else if (next_row > 0)
	    row = next_row;
	else
	    break;
    }
    G_percent(window.rows, window.rows, 5);
    D_raster_draw_end();
    
    D_save_command(G_recreate_command());
    D_close_driver();

    /* Close the raster maps */
    for (i = 0; i < 3; i++)
	Rast_close(B[i].file);

    exit(EXIT_SUCCESS);
}
Example #10
0
int main(int argc, char *argv[])
{
    struct GModule *module;
    struct
    {
	struct Option *rastin, *rastout, *method, *quantile;
    } parm;
    struct
    {
	struct Flag *nulls, *weight;
    } flag;
    struct History history;
    char title[64];
    char buf_nsres[100], buf_ewres[100];
    struct Colors colors;
    int row;

    G_gisinit(argv[0]);

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

    parm.rastin = G_define_standard_option(G_OPT_R_INPUT);

    parm.rastout = G_define_standard_option(G_OPT_R_OUTPUT);

    parm.method = G_define_option();
    parm.method->key = "method";
    parm.method->type = TYPE_STRING;
    parm.method->required = NO;
    parm.method->description = _("Aggregation method");
    parm.method->options = build_method_list();
    parm.method->answer = "average";

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

    flag.nulls = G_define_flag();
    flag.nulls->key = 'n';
    flag.nulls->description = _("Propagate NULLs");

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

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

    nulls = flag.nulls->answer;

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

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

    G_get_set_window(&dst_w);

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

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

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

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

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

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

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

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

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

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

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

    Rast_close(infile);
    Rast_close(outfile);

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

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

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

    return (EXIT_SUCCESS);
}
Example #11
0
int MyApp::load_files(void)
{
    DCELL *dcell;
    unsigned char *tr, *tg, *tb, *tset;
    int tsiz, coff;
    int rowoff, row, col, vxoff, vyoff;
    int cnt, ret, fd;
    int vnum;
    const char *name;
    struct Colors colors;

    dcell = Rast_allocate_d_buf();

    tsiz = Rast_window_cols();

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

    wxImage img(ncols, nrows);

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

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

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

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

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

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

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

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

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

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

	    Rast_close(fd);
	}

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

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

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

    return cnt;
}
Example #12
0
/* actual raster band export
 * returns 0 on success
 * -1 on raster data read/write error
 * */
int export_band(GDALDatasetH hMEMDS, int band,
		const char *name, const char *mapset,
		struct Cell_head *cellhead, RASTER_MAP_TYPE maptype,
		double nodataval, int suppress_main_colortable)
{
    struct Colors sGrassColors;
    GDALColorTableH hCT;
    int iColor;
    int bHaveMinMax;
    double dfCellMin;
    double dfCellMax;
    struct FPRange sRange;
    int fd;
    int cols = cellhead->cols;
    int rows = cellhead->rows;
    int ret = 0;
    char value[200];

    /* Open GRASS raster */
    fd = Rast_open_old(name, mapset);

    /* Get raster band  */
    GDALRasterBandH hBand = GDALGetRasterBand(hMEMDS, band);

    if (hBand == NULL) {
	G_warning(_("Unable to get raster band"));
	return -1;
    }

    /* Get min/max values. */
    if (Rast_read_fp_range(name, mapset, &sRange) == -1) {
	bHaveMinMax = FALSE;
    }
    else {
	bHaveMinMax = TRUE;
	Rast_get_fp_range_min_max(&sRange, &dfCellMin, &dfCellMax);
    }

    sprintf(value, "GRASS GIS %s", GRASS_VERSION_NUMBER);
    GDALSetMetadataItem(hBand, "Generated_with", value, NULL);

    /* use default color rules if no color rules are given */
    if (Rast_read_colors(name, mapset, &sGrassColors) >= 0) {
	int maxcolor, i;
	CELL min, max;
	char key[200];
	int rcount;

	Rast_get_c_color_range(&min, &max, &sGrassColors);
	if (bHaveMinMax) {
	    if (max < dfCellMax) {
		maxcolor = max;
	    }
	    else {
		maxcolor = (int)ceil(dfCellMax);
	    }
	    if (maxcolor > GRASS_MAX_COLORS) {
		maxcolor = GRASS_MAX_COLORS;
		G_warning("Too many values, color table cut to %d entries",
			  maxcolor);
	    }
	}
	else {
	    if (max < GRASS_MAX_COLORS) {
		maxcolor = max;
	    }
	    else {
		maxcolor = GRASS_MAX_COLORS;
		G_warning("Too many values, color table set to %d entries",
			  maxcolor);
	    }
	}

	rcount = Rast_colors_count(&sGrassColors);

	G_debug(3, "dfCellMin: %f, dfCellMax: %f, maxcolor: %d", dfCellMin,
		dfCellMax, maxcolor);

	if (!suppress_main_colortable) {
	    hCT = GDALCreateColorTable(GPI_RGB);

	    for (iColor = 0; iColor <= maxcolor; iColor++) {
		int nRed, nGreen, nBlue;
		GDALColorEntry sColor;

		if (Rast_get_c_color(&iColor, &nRed, &nGreen, &nBlue,
				     &sGrassColors)) {
		    sColor.c1 = nRed;
		    sColor.c2 = nGreen;
		    sColor.c3 = nBlue;
		    sColor.c4 = 255;

		    G_debug(3,
			    "Rast_get_c_color: Y, rcount %d, nRed %d, nGreen %d, nBlue %d",
			    rcount, nRed, nGreen, nBlue);
		    GDALSetColorEntry(hCT, iColor, &sColor);
		}
		else {
		    sColor.c1 = 0;
		    sColor.c2 = 0;
		    sColor.c3 = 0;
		    sColor.c4 = 0;

		    G_debug(3,
			    "Rast_get_c_color: N, rcount %d, nRed %d, nGreen %d, nBlue %d",
			    rcount, nRed, nGreen, nBlue);
		    GDALSetColorEntry(hCT, iColor, &sColor);
		}
	    }

	    GDALSetRasterColorTable(hBand, hCT);
	}

	if (rcount > 0) {
	    /* Create metadata entries for color table rules */
	    sprintf(value, "%d", rcount);
	    GDALSetMetadataItem(hBand, "COLOR_TABLE_RULES_COUNT", value,
				NULL);
	}

	/* Add the rules in reverse order */
	/* This can cause a GDAL warning with many rules, something like
	 * Warning 1: Lost metadata writing to GeoTIFF ... too large to fit in tag. */
	for (i = rcount - 1; i >= 0; i--) {
	    DCELL val1, val2;
	    unsigned char r1, g1, b1, r2, g2, b2;

	    Rast_get_fp_color_rule(&val1, &r1, &g1, &b1, &val2, &r2, &g2, &b2,
			       &sGrassColors, i);


	    sprintf(key, "COLOR_TABLE_RULE_RGB_%d", rcount - i - 1);
	    sprintf(value, "%e %e %d %d %d %d %d %d", val1, val2, r1, g1, b1,
		    r2, g2, b2);
	    GDALSetMetadataItem(hBand, key, value, NULL);
	}
    }

    /* Create GRASS raster buffer */
    void *bufer = Rast_allocate_buf(maptype);

    if (bufer == NULL) {
	G_warning(_("Unable to allocate buffer for reading raster map"));
	return -1;
    }

    /* the following routine must be kept identical to exact_checks */

    /* Copy data form GRASS raster to GDAL raster */
    int row, col;
    int n_nulls = 0;

    /* Better use selected GDAL datatype instead of 
     * the best match with GRASS raster map types ? */

    if (maptype == FCELL_TYPE) {

	/* Source datatype understandable by GDAL */
	GDALDataType datatype = GDT_Float32;
	FCELL fnullval = (FCELL) nodataval;

	G_debug(1, "FCELL nodata val: %f", fnullval);

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

	    Rast_get_row(fd, bufer, row, maptype);
	    for (col = 0; col < cols; col++) {
		if (Rast_is_f_null_value(&((FCELL *) bufer)[col])) {
		    ((FCELL *) bufer)[col] = fnullval;
		    if (n_nulls == 0) {
			GDALSetRasterNoDataValue(hBand, nodataval);
		    }
		    n_nulls++;
		}
	    }

	    if (GDALRasterIO
		(hBand, GF_Write, 0, row, cols, 1, bufer, cols, 1, datatype,
		 0, 0) >= CE_Failure) {
		G_warning(_("Unable to write GDAL raster file"));
		return -1;
	    }
	    G_percent(row + 1, rows, 2);
	}
    }
    else if (maptype == DCELL_TYPE) {

	GDALDataType datatype = GDT_Float64;
	DCELL dnullval = (DCELL) nodataval;

	G_debug(1, "DCELL nodata val: %f", dnullval);

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

	    Rast_get_row(fd, bufer, row, maptype);
	    for (col = 0; col < cols; col++) {
		if (Rast_is_d_null_value(&((DCELL *) bufer)[col])) {
		    ((DCELL *) bufer)[col] = dnullval;
		    if (n_nulls == 0) {
			GDALSetRasterNoDataValue(hBand, nodataval);
		    }
		    n_nulls++;
		}
	    }

	    if (GDALRasterIO
		(hBand, GF_Write, 0, row, cols, 1, bufer, cols, 1, datatype,
		 0, 0) >= CE_Failure) {
		G_warning(_("Unable to write GDAL raster file"));
		return -1;
	    }
	    G_percent(row + 1, rows, 2);
	}
    }
    else {

	GDALDataType datatype = GDT_Int32;
	CELL inullval = (CELL) nodataval;

	G_debug(1, "CELL nodata val: %d", inullval);

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

	    Rast_get_row(fd, bufer, row, maptype);
	    for (col = 0; col < cols; col++) {
		if (Rast_is_c_null_value(&((CELL *) bufer)[col])) {
		    ((CELL *) bufer)[col] = inullval;
		    if (n_nulls == 0) {
			GDALSetRasterNoDataValue(hBand, nodataval);
		    }
		    n_nulls++;
		}
	    }

	    if (GDALRasterIO
		(hBand, GF_Write, 0, row, cols, 1, bufer, cols, 1, datatype,
		 0, 0) >= CE_Failure) {
		G_warning(_("Unable to write GDAL raster file"));
		return -1;
	    }
	    G_percent(row + 1, rows, 2);
	}
    }

    Rast_close(fd);

    G_free(bufer);

    return ret;
}
Example #13
0
int make_support(struct rr_state *theState, int percent, double percentage)
{
    char title[100];
    struct History hist;
    struct Categories cats;
    struct Colors clr;
    char *inraster;
    struct RASTER_MAP_PTR nulls;

    /* write categories for output raster 
       use values from input or cover map
     */
    if (theState->docover == 1) {
	inraster = theState->inrcover;
	nulls = theState->cnulls;
    }
    else {
	inraster = theState->inraster;
	nulls = theState->nulls;
    }
    if (Rast_read_cats(inraster, "", &cats) >= 0) {
	sprintf(title, "Random points on <%s>", inraster);
	Rast_set_cats_title(title, &cats);
	if (theState->use_nulls)
	    Rast_set_cat(nulls.data.v,
			     nulls.data.v,
			     "Points with NULL values in original",
			     &cats, nulls.type);
	Rast_write_cats(theState->outraster, &cats);
    }

    /* write history for output raster */
    if (Rast_read_history(theState->outraster, G_mapset(), &hist) >= 0) {
	Rast_short_history(theState->outraster, "raster", &hist);
	Rast_format_history(&hist, HIST_DATSRC_1, "Based on map <%s>", inraster);
	if (percent)
	    Rast_format_history(
		&hist, HIST_DATSRC_2,
		"Random points over %.2f percent of the base map <%s>",
		percentage, inraster);
	else
	    Rast_format_history(
		&hist, HIST_DATSRC_2,
		"%ld random points on the base map <%s>",
		theState->nRand, theState->inraster);

	Rast_command_history(&hist);
	Rast_write_history(theState->outraster, &hist);
    }

    /* write commandline to output vector */
    if (theState->outvector) {
	struct Map_info map;

	Vect_open_old(&map, theState->outvector, G_mapset());
	Vect_hist_command(&map);
	Vect_close(&map);
    }

    /* set colors for output raster */
    if (Rast_read_colors(inraster, "", &clr) >= 0) {
	if (theState->use_nulls) {
	    Rast_add_color_rule(nulls.data.v, 127, 127, 127,
				nulls.data.v, 127, 127, 127, &clr,
				nulls.type);
	}
	Rast_write_colors(theState->outraster, G_mapset(), &clr);
    }

    return 0;
}
Example #14
0
int main(int argc, char *argv[])
{
    struct GModule *module;
    struct {
	struct Flag *r, *w, *l, *g, *a, *n, *c;
    } flag; 

    struct {
	struct Option *map, *field, *colr, *rast, *volume, *rules,
          *attrcol, *rgbcol, *range, *use;
    } opt;

    int layer;
    int overwrite, remove, is_from_stdin, stat, have_colors, convert, use;
    const char *mapset, *cmapset;
    const char *style, *rules, *cmap, *attrcolumn, *rgbcolumn;
    char *name;
    
    struct Map_info Map;
    struct FPRange range;
    struct Colors colors, colors_tmp;
    /* struct Cell_stats statf; */
    
    G_gisinit(argv[0]);
    
    module = G_define_module();
    G_add_keyword(_("vector"));
    G_add_keyword(_("color table"));
    module->description =
	_("Creates/modifies the color table associated with a vector map.");

    opt.map = G_define_standard_option(G_OPT_V_MAP);

    opt.field = G_define_standard_option(G_OPT_V_FIELD);

    opt.use = G_define_option();
    opt.use->key = "use";
    opt.use->type = TYPE_STRING;
    opt.use->required = YES;
    opt.use->multiple = NO;
    opt.use->options = "attr,cat,z";
    opt.use->description = _("Source values");
    G_asprintf((char **) &(opt.use->descriptions),
	       "attr;%s;cat;%s;z;%s",
	       _("read values from attribute table (requires <column> option)"),
	       _("use category values"),
	       _("use z coordinate (3D points or centroids only)"));
    opt.use->answer = "cat";
    
    opt.attrcol = G_define_standard_option(G_OPT_DB_COLUMN);
    opt.attrcol->label = _("Name of column containing numeric data");
    opt.attrcol->description = _("Required for use=attr");
    opt.attrcol->guisection = _("Define");

    opt.range = G_define_option();
    opt.range->key = "range";
    opt.range->type = TYPE_DOUBLE;
    opt.range->required = NO;
    opt.range->label = _("Manually set range (refers to 'column' option)");
    opt.range->description = _("Ignored when 'rules' given");
    opt.range->key_desc = "min,max";

    opt.colr = G_define_standard_option(G_OPT_M_COLR);
    opt.colr->guisection = _("Define");

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

    opt.volume = G_define_standard_option(G_OPT_R3_INPUT);
    opt.volume->key = "raster_3d";
    opt.volume->required = NO;
    opt.volume->description =
        _("3D raster map from which to copy color table");
    opt.volume->guisection = _("Define");

    opt.rules = G_define_standard_option(G_OPT_F_INPUT);
    opt.rules->key = "rules";
    opt.rules->required = NO;
    opt.rules->description = _("Path to rules file");
    opt.rules->guisection = _("Define");

    opt.rgbcol = G_define_standard_option(G_OPT_DB_COLUMN);
    opt.rgbcol->key = "rgb_column";
    opt.rgbcol->label = _("Name of color column to populate RGB values");
    opt.rgbcol->description = _("If not given writes color table");
    
    flag.r = G_define_flag();
    flag.r->key = 'r';
    flag.r->description = _("Remove existing color table");
    flag.r->guisection = _("Remove");

    flag.w = G_define_flag();
    flag.w->key = 'w';
    flag.w->description =
        _("Only write new color table if it does not already exist");

    flag.l = G_define_flag();
    flag.l->key = 'l';
    flag.l->description = _("List available rules then exit");
    flag.l->suppress_required = YES;
    flag.l->guisection = _("Print");

    flag.n = G_define_flag();
    flag.n->key = 'n';
    flag.n->description = _("Invert colors");
    flag.n->guisection = _("Define");

    flag.g = G_define_flag();
    flag.g->key = 'g';
    flag.g->description = _("Logarithmic scaling");
    flag.g->guisection = _("Define");

    flag.a = G_define_flag();
    flag.a->key = 'a';
    flag.a->description = _("Logarithmic-absolute scaling");
    flag.a->guisection = _("Define");

    flag.c = G_define_flag();
    flag.c->key = 'c';
    flag.c->label = _("Convert color rules from RGB values to color table");
    flag.c->description = _("Option 'rgb_column' with valid RGB values required");
	
    /* TODO ?
    flag.e = G_define_flag();
    flag.e->key = 'e';
    flag.e->description = _("Histogram equalization");
    flag.e->guisection = _("Define");
    */
    if (G_parser(argc, argv))
	exit(EXIT_FAILURE);

    if (flag.l->answer) {
	G_list_color_rules(stdout);
	return EXIT_SUCCESS;
    }

    overwrite = !flag.w->answer;
    remove = flag.r->answer;
    name = opt.map->answer;
    style = opt.colr->answer;
    rules = opt.rules->answer;
    attrcolumn = opt.attrcol->answer;
    rgbcolumn = opt.rgbcol->answer;
    convert = flag.c->answer;
    use = USE_CAT;
    if (opt.use->answer) {
        switch (opt.use->answer[0]) {
        case 'a':
            use = USE_ATTR;
            break;
        case 'c':
            use = USE_CAT;
            break;
        case 'z':
            use = USE_Z;
            break;
        default:
            break;
        }
    }
    G_debug(1, "use=%d", use);
    
    if (!name)
        G_fatal_error(_("No vector map specified"));

    if (use == USE_ATTR && !attrcolumn)
        G_fatal_error(_("Option <%s> required"), opt.attrcol->key); 
    if (use != USE_ATTR && attrcolumn) {
        G_important_message(_("Option <%s> given, assuming <use=attr>..."), opt.attrcol->key);
        use = USE_ATTR;
    }

    if (opt.rast->answer && opt.volume->answer)
        G_fatal_error(_("%s= and %s= are mutually exclusive"),
		      opt.rast->key, opt.volume->key);

    cmap = NULL;
    if (opt.rast->answer)
        cmap = opt.rast->answer;
    if (opt.volume->answer)
        cmap = opt.volume->answer;
    
    if (!cmap && !style && !rules && !remove && !convert)
        G_fatal_error(_("One of -%c, -%c or %s=, %s= or %s= "
			"must be specified"), flag.r->key, flag.c->key, 
		      opt.colr->key, opt.rast->key, opt.rules->key);
    
    if (!!style + !!cmap + !!rules > 1)
        G_fatal_error(_("%s=, %s= and %s= are mutually exclusive"),
			opt.colr->key, opt.rules->key, opt.rast->key);

    if (flag.g->answer && flag.a->answer)
        G_fatal_error(_("-%c and -%c are mutually exclusive"),
		      flag.g->key, flag.a->key);

    if (flag.c->answer && !rgbcolumn) 
	G_fatal_error(_("%s= required for -%c"),
		      opt.rgbcol->key, flag.c->key);

    is_from_stdin = rules && strcmp(rules, "-") == 0;
    if (is_from_stdin)
        G_fatal_error(_("Reading rules from standard input is not implemented yet, please provide path to rules file instead."));

    mapset = G_find_vector(name, "");
    if (!mapset)
	G_fatal_error(_("Vector map <%s> not found"), name);
    
    stat = -1;
    if (remove) {
	stat = Vect_remove_colors(name, mapset);
        if (stat < 0)
            G_fatal_error(_("Unable to remove color table of vector map <%s>"), name);
        if (stat == 0)
            G_warning(_("Color table of vector map <%s> not found"), name);
        return EXIT_SUCCESS;
    }

    G_suppress_warnings(TRUE);
    have_colors = Vect_read_colors(name, mapset, NULL);

    if (have_colors > 0 && !overwrite) {
        G_fatal_error(_("Color table exists. Exiting."));
    }

    G_suppress_warnings(FALSE);

    /* open map and get min/max values */
    Vect_set_open_level(1); /* no topology required */
    if (Vect_open_old2(&Map, name, mapset, opt.field->answer) < 0)
	G_fatal_error(_("Unable to open vector map <%s>"), name);

    Vect_set_error_handler_io(&Map, NULL);
    if (use == USE_Z && !Vect_is_3d(&Map))
        G_fatal_error(_("Vector map <%s> is not 3D"), Vect_get_full_name(&Map));
    
    layer = Vect_get_field_number(&Map, opt.field->answer);
    if (layer < 1)
	G_fatal_error(_("Layer <%s> not found"), opt.field->answer);
    
    if (opt.range->answer) {
	range.min = atof(opt.range->answers[0]);
	range.max = atof(opt.range->answers[1]);
	if (range.min > range.max)
	    G_fatal_error(_("Option <%s>: min must be greater or equal to max"),
			  opt.range->key);
    }

    Rast_init_colors(&colors);
    if (is_from_stdin) {
        G_fatal_error(_("Reading color rules from standard input is currently not supported"));
	/*
        if (!read_color_rules(stdin, &colors, min, max, fp))
            exit(EXIT_FAILURE);
	*/
    } else if (style || rules) {	
	if (style && !G_find_color_rule(style))
	    G_fatal_error(_("Color table <%s> not found"), style);
	
	if (use == USE_CAT) {
	    scan_cats(&Map, layer, style, rules,
		      opt.range->answer ? &range : NULL,
		      &colors);
        }
        else if (use == USE_Z) {
	    scan_z(&Map, layer, style, rules,
		      opt.range->answer ? &range : NULL,
		      &colors);
        }
        else {
	    scan_attr(&Map, layer, attrcolumn, style, rules,
		      opt.range->answer ? &range : NULL,
		      &colors);
	}
    }
    else {
	/* use color from another map (cmap) */
	if (opt.rast->answer) {
            cmapset = G_find_raster2(cmap, "");
            if (!cmapset)
                G_fatal_error(_("Raster map <%s> not found"), cmap);

            if (Rast_read_colors(cmap, cmapset, &colors) < 0)
                G_fatal_error(_("Unable to read color table for raster map <%s>"), cmap);
        } else if (opt.volume->answer) {
            cmapset = G_find_raster3d(cmap, "");
            if (!cmapset)
                G_fatal_error(_("3D raster map <%s> not found"), cmap);

            if (Rast3d_read_colors(cmap, cmapset, &colors) < 0)
                G_fatal_error(_("Unable to read color table for 3D raster map <%s>"), cmap);
        }
    }

    if (flag.n->answer)
        Rast_invert_colors(&colors);

    /* TODO ?
    if (flag.e->answer) {
    if (!have_stats)
    have_stats = get_stats(name, mapset, &statf);
    Rast_histogram_eq_colors(&colors_tmp, &colors, &statf);
    colors = colors_tmp;
    }
    */
    if (flag.g->answer) {
        Rast_log_colors(&colors_tmp, &colors, 100);
        colors = colors_tmp;
    }

    if (flag.a->answer) {
        Rast_abs_log_colors(&colors_tmp, &colors, 100);
        colors = colors_tmp;
    }

    G_important_message(_("Writing color rules..."));
    
    if (style || rules || opt.rast->answer || opt.volume->answer) {
	if (rgbcolumn)
	    write_rgb_values(&Map, layer, rgbcolumn, &colors);
	else
	    Vect_write_colors(name, mapset, &colors);
    }
    
    if (convert) {
	/* convert RGB values to color tables */
	rgb2colr(&Map, layer, rgbcolumn, &colors);
	Vect_write_colors(name, mapset, &colors);
    }
    Vect_close(&Map);
    
    G_message(_("Color table for vector map <%s> set to '%s'"), 
	      G_fully_qualified_name(name, mapset), 
              is_from_stdin || convert ? "rules" : style ? style : rules ? rules :
              cmap);
    
    exit(EXIT_SUCCESS);
}
Example #15
0
int main(int argc, char *argv[])
{
    char *p;
    int method;
    int in_fd;
    int selection_fd;
    int out_fd;
    DCELL *result;
    char *selection;
    RASTER_MAP_TYPE map_type;
    int row, col;
    int readrow;
    int nrows, ncols;
    int n;
    int copycolr;
    int half;
    stat_func *newvalue;
    stat_func_w *newvalue_w;
    ifunc cat_names;
    double quantile;
    const void *closure;
    struct Colors colr;
    struct Cell_head cellhd;
    struct Cell_head window;
    struct History history;
    struct GModule *module;
    struct
    {
	struct Option *input, *output, *selection;
	struct Option *method, *size;
	struct Option *title;
	struct Option *weight;
	struct Option *gauss;
	struct Option *quantile;
    } parm;
    struct
    {
	struct Flag *align, *circle;
    } flag;

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

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

    G_gisinit(argv[0]);

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

    parm.input = G_define_standard_option(G_OPT_R_INPUT);

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

    parm.output = G_define_standard_option(G_OPT_R_OUTPUT);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

    Rast_close(out_fd);
    Rast_close(in_fd);

    if (selection)
        Rast_close(selection_fd);

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

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

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

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


    exit(EXIT_SUCCESS);
}
Example #16
0
int exec_rectify(char *extension, char *interp_method, char *angle_map)
{
    char *name;
    char *mapset;
    char *result;
    char *type = "raster";
    int n;
    struct Colors colr;
    struct Categories cats;
    struct History hist;
    int colr_ok, cats_ok;
    long start_time, rectify_time;
    double aver_z;
    int elevfd;
    struct cache *ebuffer;

    G_debug(1, "Open elevation raster: ");

    /* open elevation raster */
    select_target_env();
    G_set_window(&target_window);
    G_debug(1, "target window: rs=%d cs=%d n=%f s=%f w=%f e=%f\n",
	    target_window.rows, target_window.cols, target_window.north,
	    target_window.south, target_window.west, target_window.east);

    elevfd = Rast_open_old(elev_name, elev_mapset);
    if (elevfd < 0) {
	G_fatal_error(_("Could not open elevation raster"));
	return 1;
    }
    ebuffer = readcell(elevfd, seg_mb_elev, 1);
    select_target_env();
    Rast_close(elevfd);

    /* get an average elevation of the control points */
    /* this is used only if target cells have no elevation */
    get_aver_elev(&group.control_points, &aver_z);

    G_message("-----------------------------------------------");

    /* rectify each file */
    for (n = 0; n < group.group_ref.nfiles; n++) {
	if (!ref_list[n])
	    continue;

	name = group.group_ref.file[n].name;
	mapset = group.group_ref.file[n].mapset;
	result =
	    G_malloc(strlen(group.group_ref.file[n].name) + strlen(extension) + 1);
	strcpy(result, group.group_ref.file[n].name);
	strcat(result, extension);

	G_debug(2, "ORTHO RECTIFYING:");
	G_debug(2, "NAME %s", name);
	G_debug(2, "MAPSET %s", mapset);
	G_debug(2, "RESULT %s", result);
	G_debug(2, "select_current_env...");

	select_current_env();

	cats_ok = Rast_read_cats(name, mapset, &cats) >= 0;
	colr_ok = Rast_read_colors(name, mapset, &colr) > 0;

	/* Initialze History */
	if (Rast_read_history(name, mapset, &hist) < 0)
	    Rast_short_history(result, type, &hist);
	G_debug(2, "reading was fine...");

	time(&start_time);

	G_debug(2, "Starting the rectification...");

	if (rectify(name, mapset, ebuffer, aver_z, result, interp_method)) {
	    G_debug(2, "Done. Writing results...");
	    select_target_env();
	    if (cats_ok) {
		Rast_write_cats(result, &cats);
		Rast_free_cats(&cats);
	    }
	    if (colr_ok) {
		Rast_write_colors(result, G_mapset(), &colr);
		Rast_free_colors(&colr);
	    }
	    /* Write out History */
	    Rast_command_history(&hist);
	    Rast_write_history(result, &hist);

	    select_current_env();
	    time(&rectify_time);
	    report(rectify_time - start_time, 1);
	}
	else
	    report((long)0, 0);

	G_free(result);
    }
    
    close(ebuffer->fd);
    release_cache(ebuffer);

    if (angle_map) {
	camera_angle(angle_map);
    }
    
    return 0;
}
Example #17
0
File: main.c Project: caomw/grass
int main(int argc, char **argv)
{
    struct GModule *module;
    struct Option *opt_out;
    struct Option *opt_lev;
    struct Flag *flg_d;
    struct Flag *flg_c;
    int dither;
    char *out_name;
    int out_file;
    CELL *out_array;
    struct Colors out_colors;
    int levels;
    int atrow, atcol;
    struct Cell_head window;
    unsigned char *dummy, *nulls;
    int i, j;
    struct History history;

    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("raster"));
    G_add_keyword(_("composite"));
    G_add_keyword("RGB");
    module->description =
	_("Combines red, green and blue raster maps into "
	  "a single composite raster map.");

    for (i = 0; i < 3; i++) {
	struct Option *opt;
	char buff[80];

	B[i].opt_name = opt = G_define_standard_option(G_OPT_R_INPUT);

	sprintf(buff, "%s", color_names[i]);
	opt->key = G_store(buff);

	opt->answer = NULL;

	sprintf(buff, _("Name of raster map to be used for <%s>"),
		color_names[i]);
	opt->description = G_store(buff);
    }

    opt_lev = G_define_option();
    opt_lev->key = "levels";
    opt_lev->type = TYPE_INTEGER;
    opt_lev->required = NO;
    opt_lev->options = "1-256";
    opt_lev->answer = "32";
    opt_lev->description =
	_("Number of levels to be used for each component");
    opt_lev->guisection = _("Levels");

    for (i = 0; i < 3; i++) {
	struct Option *opt;
	char buff[80];

	B[i].opt_levels = opt = G_define_option();

	sprintf(buff, "lev_%s", color_names[i]);
	opt->key = G_store(buff);

	opt->type = TYPE_INTEGER;
	opt->required = NO;
	opt->options = "1-256";

	sprintf(buff, _("Number of levels to be used for <%s>"),
		color_names[i]);
	opt->description = G_store(buff);
	opt->guisection = _("Levels");
    }

    opt_out = G_define_standard_option(G_OPT_R_OUTPUT);

    flg_d = G_define_flag();
    flg_d->key = 'd';
    flg_d->description = _("Dither");

    flg_c = G_define_flag();
    flg_c->key = 'c';
    flg_c->description = _("Use closest color");

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

    levels = atoi(opt_lev->answer);

    dither = flg_d->answer;
    closest = flg_c->answer;

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

    dummy = G_malloc(window.cols);

    nulls = G_malloc(window.cols);

    for (i = 0; i < 3; i++) {
	struct band *b = &B[i];

	/* Get name of layer to be used */
	b->name = b->opt_name->answer;

	/* Make sure map is available */
	b->file = Rast_open_old(b->name, "");

	b->type = Rast_get_map_type(b->file);

	b->size = Rast_cell_size(b->type);

	/* Reading color lookup table */
	if (Rast_read_colors(b->name, "", &b->colors) == -1)
	    G_fatal_error(_("Unable to read color file of raster map <%s>"), b->name);

	for (j = 0; j < 3; j++)
	    b->array[j] = (i == j)
		? G_malloc(window.cols)
		: dummy;

	b->levels = b->opt_levels->answer ? atoi(b->opt_levels->answer)
	    : levels;
	b->maxlev = b->levels - 1;
	b->offset = 128 / b->maxlev;

	if (dither)
	    for (j = 0; j < 2; j++)
		b->floyd[j] = G_calloc(window.cols + 2, sizeof(short));
    }

    /* open output files */
    out_name = opt_out->answer;

    out_file = Rast_open_c_new(out_name);

    out_array = Rast_allocate_c_buf();

    /* Make color table */
    make_color_cube(&out_colors);

    G_message(_("Writing raster map <%s>..."), out_name);

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

	for (i = 0; i < 3; i++) {
	    struct band *b = &B[i];

	    Rast_get_row_colors(b->file, atrow, &b->colors,
				b->array[0],
				b->array[1], b->array[2], nulls);

	    if (dither) {
		short *tmp = b->floyd[0];

		b->floyd[0] = b->floyd[1];
		for (atcol = 0; atcol < window.cols + 2; atcol++)
		    tmp[atcol] = 0;
		b->floyd[1] = tmp;
	    }
	}

	for (atcol = 0; atcol < window.cols; atcol++) {
	    int val[3];

	    if (nulls[atcol]) {
		Rast_set_c_null_value(&out_array[atcol], 1);
		continue;
	    }

	    for (i = 0; i < 3; i++) {
		struct band *b = &B[i];
		int v = b->array[i][atcol];

		if (dither) {
		    int r, w, d;

		    v += b->floyd[0][atcol + 1] / 16;
		    v = (v < 0) ? 0 : (v > 255) ? 255 : v;
		    r = quantize(i, v);
		    w = r * 255 / b->maxlev;
		    d = v - w;
		    b->floyd[0][atcol + 2] += 7 * d;
		    b->floyd[1][atcol + 0] += 3 * d;
		    b->floyd[1][atcol + 1] += 5 * d;
		    b->floyd[1][atcol + 2] += 1 * d;
		    val[i] = r;
		}
		else
		    val[i] = quantize(i, v);
	    }

	    out_array[atcol] = (CELL)
		(val[2] * B[1].levels + val[1]) * B[0].levels + val[0];
	}

	Rast_put_row(out_file, out_array, CELL_TYPE);
    }
    G_percent(window.rows, window.rows, 1);

    /* Close the input files */
    for (i = 0; i < 3; i++)
	Rast_close(B[i].file);

    /* Close the output file */
    Rast_close(out_file);
    Rast_write_colors(out_name, G_mapset(), &out_colors);
    Rast_short_history(out_name, "raster", &history);
    Rast_command_history(&history);
    Rast_write_history(out_name, &history);

    G_done_msg(_("Raster map <%s> created."), out_name);

    exit(EXIT_SUCCESS);
}
Example #18
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;
}
Example #19
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);
}
Example #20
0
File: main.c Project: caomw/grass
int main(int argc, char *argv[])
{
    char *name, *outfile;
    const char *unit;
    int unit_id;
    double factor;
    int fd, projection;
    FILE *fp, *coor_fp;
    double res;
    char *null_string;
    char ebuf[256], nbuf[256], label[512], formatbuff[256];
    char b1[100], b2[100];
    int n;
    int havefirst = FALSE;
    int coords = 0, i, k = -1;
    double e1, e2, n1, n2;
    RASTER_MAP_TYPE data_type;
    struct Cell_head window;
    struct
    {
	struct Option *opt1, *profile, *res, *output, *null_str, *coord_file, *units;
	struct Flag *g, *c, *m;
    }
    parm;
    struct GModule *module;

    G_gisinit(argv[0]);

    /* Set description */
    module = G_define_module();
    G_add_keyword(_("raster"));
    G_add_keyword(_("profile"));
    module->description =
	_("Outputs the raster map layer values lying on user-defined line(s).");

    parm.opt1 = G_define_standard_option(G_OPT_R_INPUT);

    parm.output = G_define_standard_option(G_OPT_F_OUTPUT);
    parm.output->required = NO;
    parm.output->answer = "-";
    parm.output->description =
	_("Name of file for output (use output=- for stdout)");

    parm.profile = G_define_standard_option(G_OPT_M_COORDS);
    parm.profile->required = NO;
    parm.profile->multiple = YES;
    parm.profile->description = _("Profile coordinate pairs");

    parm.coord_file = G_define_standard_option(G_OPT_F_INPUT);
    parm.coord_file->key = "file";
    parm.coord_file->required = NO;
    parm.coord_file->label =
	_("Name of input file containing coordinate pairs");
    parm.coord_file->description =
	_("Use instead of the 'coordinates' option. "
	  "\"-\" reads from stdin.");

    parm.res = G_define_option();
    parm.res->key = "resolution";
    parm.res->type = TYPE_DOUBLE;
    parm.res->required = NO;
    parm.res->description =
	_("Resolution along profile (default = current region resolution)");

    parm.null_str = G_define_option();
    parm.null_str->key = "null";
    parm.null_str->type = TYPE_STRING;
    parm.null_str->required = NO;
    parm.null_str->answer = "*";
    parm.null_str->description = _("Character to represent no data cell");

    parm.g = G_define_flag();
    parm.g->key = 'g';
    parm.g->description =
	_("Output easting and northing in first two columns of four column output");

    parm.c = G_define_flag();
    parm.c->key = 'c';
    parm.c->description =
	_("Output RRR:GGG:BBB color values for each profile point");

    parm.units = G_define_standard_option(G_OPT_M_UNITS);
    parm.units->options = "meters,kilometers,feet,miles";
    parm.units->label = parm.units->description;
    parm.units->description = _("If units are not specified, current location units are used. "
                                "Meters are used by default in geographic (latlon) locations.");

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

    clr = 0;
    if (parm.c->answer)
	clr = 1;		/* color output */

    null_string = parm.null_str->answer;

    if ((parm.profile->answer && parm.coord_file->answer) ||
	(!parm.profile->answer && !parm.coord_file->answer))
	G_fatal_error(_("Either use profile option or coordinate_file "
			" option, but not both"));

    G_get_window(&window);
    projection = G_projection();

    /* get conversion factor and units name */
    if (parm.units->answer) {
        unit_id = G_units(parm.units->answer);
        factor = 1. / G_meters_to_units_factor(unit_id);
        unit = G_get_units_name(unit_id, 1, 0);
    }
    /* keep meters in case of latlon */
    else if (projection == PROJECTION_LL) {
        factor = 1;
        unit = "meters";
    } 
    else {
        /* get conversion factor to current units */
        unit = G_database_unit_name(1);
        factor = G_database_units_to_meters_factor();
    }

    if (parm.res->answer) {
	res = atof(parm.res->answer);
	/* Catch bad resolution ? */
	if (res <= 0)
	    G_fatal_error(_("Illegal resolution %g [%s]"), res / factor, unit);
    }
    else {
	/* Do average of EW and NS res */
	res = (window.ew_res + window.ns_res) / 2;
    }

    G_message(_("Using resolution: %g [%s]"), res / factor, unit);

    G_begin_distance_calculations();

    /* Open Input File for reading */
    /* Get Input Name */
    name = parm.opt1->answer;
    if (parm.g->answer)
	coords = 1;

    /* Open Raster File */
    fd = Rast_open_old(name, "");

    /* initialize color structure */
    if (clr)
	Rast_read_colors(name, "", &colors);

    /* Open ASCII file for output or stdout */
    outfile = parm.output->answer;

    if ((strcmp("-", outfile)) == 0) {
	fp = stdout;
    }
    else if (NULL == (fp = fopen(outfile, "w")))
	G_fatal_error(_("Unable to open file <%s>"), outfile);

    /* Get Raster Type */
    data_type = Rast_get_map_type(fd);
    /* Done with file */

    /* Show message giving output format */
    G_message(_("Output columns:"));
    if (coords == 1)
	sprintf(formatbuff,
		_("Easting, Northing, Along track dist. [%s], Elevation"), unit);
    else
	sprintf(formatbuff, _("Along track dist. [%s], Elevation"), unit);
    if (clr)
	strcat(formatbuff, _(" RGB color"));
    G_message(formatbuff);

    /* Get Profile Start Coords */
    if (parm.coord_file->answer) {
	if (strcmp("-", parm.coord_file->answer) == 0)
	    coor_fp = stdin;
	else
	    coor_fp = fopen(parm.coord_file->answer, "r");

	if (coor_fp == NULL)
	    G_fatal_error(_("Could not open <%s>"), parm.coord_file->answer);


	for (n = 1; input(b1, ebuf, b2, nbuf, label, coor_fp); n++) {
	    G_debug(4, "stdin line %d: ebuf=[%s]  nbuf=[%s]", n, ebuf, nbuf);
	    if (!G_scan_easting(ebuf, &e2, G_projection()) ||
		!G_scan_northing(nbuf, &n2, G_projection()))
		G_fatal_error(_("Invalid coordinates %s %s"), ebuf, nbuf);

	    if (havefirst)
		do_profile(e1, e2, n1, n2, coords, res, fd, data_type,
			   fp, null_string, unit, factor);
	    e1 = e2;
	    n1 = n2;
	    havefirst = TRUE;
	}

	if (coor_fp != stdin)
	    fclose(coor_fp);
    }
    else {
	/* Coords given on the Command Line using the profile= option */
	for (i = 0; parm.profile->answers[i]; i += 2) {
	    /* Test for number coordinate pairs */
	    k = i;
	}

	if (k == 0) {
	    /* Only one coordinate pair supplied */
	    G_scan_easting(parm.profile->answers[0], &e1, G_projection());
	    G_scan_northing(parm.profile->answers[1], &n1, G_projection());
	    e2 = e1;
	    n2 = n1;

	    /* Get profile info */
	    do_profile(e1, e2, n1, n2, coords, res, fd, data_type, fp,
		       null_string, unit, factor);
	}
	else {
	    for (i = 0; i <= k - 2; i += 2) {
		G_scan_easting(parm.profile->answers[i], &e1, G_projection());
		G_scan_northing(parm.profile->answers[i + 1], &n1,
				G_projection());
		G_scan_easting(parm.profile->answers[i + 2], &e2,
			       G_projection());
		G_scan_northing(parm.profile->answers[i + 3], &n2,
				G_projection());

		/* Get profile info */
		do_profile(e1, e2, n1, n2, coords, res, fd, data_type,
			   fp, null_string, unit, factor);

	    }
	}
    }

    Rast_close(fd);
    fclose(fp);

    if (clr)
	Rast_free_colors(&colors);

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

    G_gisinit(argv[0]);

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

    opt.basemap = G_define_standard_option(G_OPT_R_BASE);

    opt.covermap = G_define_standard_option(G_OPT_R_COVER);

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

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

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

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

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

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

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

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

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

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

    method = menu[i].val;

    base_fd = Rast_open_old(basemap, "");

    cover_fd = Rast_open_old(covermap, "");

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

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

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

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

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

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

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

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

    G_message(_("First pass"));

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

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

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

	    n = base_buf[col] - mincat;

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

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

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

	G_percent(row, rows, 2);
    }

    G_percent(row, rows, 2);

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

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

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

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

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

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

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

		n = base_buf[col] - mincat;

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

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

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

	    G_percent(row, rows, 2);
	}

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

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

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

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

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

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

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

	fclose(fp);

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

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

	out_fd = Rast_open_fp_new(output);

	out_buf = Rast_allocate_d_buf();

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

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

	    Rast_put_d_row(out_fd, out_buf);

	    G_percent(row, rows, 2);
	}

	G_percent(row, rows, 2);

	Rast_close(out_fd);

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

    return 0;
}
Example #22
0
int main(int argc, char *argv[])
{
    char *name, *outfile;
    int fd, projection;
    FILE *fp;
    double res;
    char *null_string;
    char ebuf[256], nbuf[256], label[512], formatbuff[256];
    char b1[100], b2[100];
    int n;
    int havefirst = FALSE;
    int coords = 0, i, k = -1;
    double e1, e2, n1, n2;
    RASTER_MAP_TYPE data_type;
    struct Cell_head window;
    struct
    {
	struct Option *opt1, *profile, *res, *output, *null_str;
	struct Flag *g, *c;
    }
    parm;
    struct GModule *module;

    G_gisinit(argv[0]);

    /* Set description */
    module = G_define_module();
    G_add_keyword(_("raster"));
    G_add_keyword(_("profile"));
    module->description =
	_("Outputs the raster map layer values lying on user-defined line(s).");

    parm.opt1 = G_define_standard_option(G_OPT_R_INPUT);

    parm.output = G_define_option();
    parm.output->key = "output";
    parm.output->type = TYPE_STRING;
    parm.output->required = NO;
    parm.output->answer = "-";
    parm.output->gisprompt = "new_file,file,output";
    parm.output->description =
	_("Name of file for output (use output=- for stdout)");

    parm.profile = G_define_option();
    parm.profile->key = "profile";
    parm.profile->type = TYPE_STRING;
    parm.profile->required = NO;
    parm.profile->multiple = YES;
    parm.profile->key_desc = "east,north";
    parm.profile->description = _("Profile coordinate pairs");

    parm.res = G_define_option();
    parm.res->key = "res";
    parm.res->type = TYPE_DOUBLE;
    parm.res->required = NO;
    parm.res->description =
	_("Resolution along profile (default = current region resolution)");

    parm.null_str = G_define_option();
    parm.null_str->key = "null";
    parm.null_str->type = TYPE_STRING;
    parm.null_str->required = NO;
    parm.null_str->answer = "*";
    parm.null_str->description = _("Character to represent no data cell");

    parm.g = G_define_flag();
    parm.g->key = 'g';
    parm.g->description =
	_("Output easting and northing in first two columns of four column output");

    parm.c = G_define_flag();
    parm.c->key = 'c';
    parm.c->description =
	_("Output RRR:GGG:BBB color values for each profile point");


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


    clr = 0;
    if (parm.c->answer)
	clr = 1;		/* color output */

    null_string = parm.null_str->answer;

    G_get_window(&window);
    projection = G_projection();
    if (parm.res->answer) {
	res = atof(parm.res->answer);
	/* Catch bad resolution ? */
	if (res <= 0)
	    G_fatal_error(_("Illegal resolution! [%g]"), res);
    }
    else {
	/* Do average of EW and NS res */
	res = (window.ew_res + window.ns_res) / 2;
    }

    G_message(_("Using resolution [%g]"), res);

    G_begin_distance_calculations();

    /* Open Input File for reading */
    /* Get Input Name */
    name = parm.opt1->answer;
    if (parm.g->answer)
	coords = 1;

    /* Open Raster File */
    fd = Rast_open_old(name, "");

    /* initialize color structure */
    if (clr)
	Rast_read_colors(name, "", &colors);

    /* Open ASCII file for output or stdout */
    outfile = parm.output->answer;

    if ((strcmp("-", outfile)) == 0) {
	fp = stdout;
    }
    else if (NULL == (fp = fopen(outfile, "w")))
	G_fatal_error(_("Unable to open file <%s>"), outfile);

    /* Get Raster Type */
    data_type = Rast_get_map_type(fd);
    /* Done with file */

    /* Show message giving output format */
    G_message(_("Output Format:"));
    if (coords == 1)
	sprintf(formatbuff,
		_("[Easting] [Northing] [Along Track Dist.(m)] [Elevation]"));
    else
	sprintf(formatbuff, _("[Along Track Dist.(m)] [Elevation]"));
    if (clr)
	strcat(formatbuff, _(" [RGB Color]"));
    G_message(formatbuff);

    /* Get Profile Start Coords */
    if (!parm.profile->answer) {
	/* Assume input from stdin */
	for (n = 1; input(b1, ebuf, b2, nbuf, label); n++) {
	    G_debug(4, "stdin line %d: ebuf=[%s]  nbuf=[%s]", n, ebuf, nbuf);
	    if (!G_scan_easting(ebuf, &e2, G_projection()) ||
		!G_scan_northing(nbuf, &n2, G_projection()))
		G_fatal_error(_("Invalid coordinates %s %s"), ebuf, nbuf);

	    if (havefirst)
		do_profile(e1, e2, n1, n2, name, coords, res, fd, data_type,
			   fp, null_string);
	    e1 = e2;
	    n1 = n2;
	    havefirst = TRUE;
	}
    }
    else {
	/* Coords from Command Line */
	for (i = 0; parm.profile->answers[i]; i += 2) {
	    /* Test for number coordinate pairs */
	    k = i;
	}

	if (k == 0) {
	    /* Only one coordinate pair supplied */
	    G_scan_easting(parm.profile->answers[0], &e1, G_projection());
	    G_scan_northing(parm.profile->answers[1], &n1, G_projection());
	    e2 = e1;
	    n2 = n1;

	    /* Get profile info */
	    do_profile(e1, e2, n1, n2, name, coords, res, fd, data_type, fp,
		       null_string);
	}
	else {
	    for (i = 0; i <= k - 2; i += 2) {
		G_scan_easting(parm.profile->answers[i], &e1, G_projection());
		G_scan_northing(parm.profile->answers[i + 1], &n1,
				G_projection());
		G_scan_easting(parm.profile->answers[i + 2], &e2,
			       G_projection());
		G_scan_northing(parm.profile->answers[i + 3], &n2,
				G_projection());

		/* Get profile info */
		do_profile(e1, e2, n1, n2, name, coords, res, fd, data_type,
			   fp, null_string);

	    }
	}
    }

    Rast_close(fd);
    fclose(fp);

    if (clr)
	Rast_free_colors(&colors);

    exit(EXIT_SUCCESS);
}				/* Done with main */
Example #23
0
int main(int argc, char **argv)
{
    char *map_name;
    int maptype;
    int color;
    int i;
    int thin, lines, steps;
    int fp;
    int label_indent;
    int hide_catnum, hide_catstr, show_ticks, show_bg, hide_nodata, do_smooth;
    struct Categories cats;
    struct Colors colors;
    struct GModule *module;
    struct Option *opt_rast2d, *opt_rast3d, *opt_color, *opt_lines,
        *opt_thin, *opt_labelnum, *opt_at, *opt_use, *opt_range,
        *opt_font, *opt_path, *opt_charset, *opt_fontsize, *opt_title,
        *opt_ticks, *opt_tstep, *opt_brdcolor, *opt_bgcolor,
        *opt_tit_fontsize, *opt_digits, *opt_units;
    struct Flag *hidestr, *hidenum, *hidenodata, *smooth, *flipit, *histo,
        *showtick, *showbg, *log_sc;
    double X0, X1, Y0, Y1;
    int flip, UserRange;
    double UserRangeMin, UserRangeMax, UserRangeTemp;
    double *catlist;
    int catlistCount, use_catlist, ticksCount;
    double fontsize;
    char *title;
    char *units;
    double *tick_values;
    double t_step;
    int colorb, colorbg;
    double tit_fontsize;
    int log_scale, digits;

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

    module = G_define_module();
    G_add_keyword(_("display"));
    G_add_keyword(_("cartography"));
    G_add_keyword(_("legend"));
    module->description =
        _("Displays a legend for a 2D or 3D raster map in the active frame "
          "of the graphics monitor.");

    opt_rast2d = G_define_standard_option(G_OPT_R_MAP);
    opt_rast2d->key = "raster";
    opt_rast2d->required = NO;
    opt_rast2d->guisection = _("Input");

    opt_rast3d = G_define_standard_option(G_OPT_R3_MAP);
    opt_rast3d->key = "raster_3d";
    opt_rast3d->required = NO;
    opt_rast3d->guisection = _("Input");

    opt_title = G_define_option();
    opt_title->key = "title";
    opt_title->type = TYPE_STRING;
    opt_title->required = NO;
    opt_title->description = _("Legend title");
    opt_title->guisection = _("Title");

    opt_tit_fontsize = G_define_option();
    opt_tit_fontsize->key = "title_fontsize";
    opt_tit_fontsize->type = TYPE_DOUBLE;
    opt_tit_fontsize->required = NO;
    opt_tit_fontsize->options = "1-360";
    opt_tit_fontsize->label = _("Title font size");
    opt_tit_fontsize->description = _("Default: Same as fontsize");
    opt_tit_fontsize->guisection = _("Title");

    opt_lines = G_define_option();
    opt_lines->key = "lines";
    opt_lines->type = TYPE_INTEGER;
    opt_lines->answer = "0";
    opt_lines->options = "0-1000";
    opt_lines->description =
        _("Number of text lines (useful for truncating long legends)");
    opt_lines->guisection = _("Advanced");

    opt_thin = G_define_option();
    opt_thin->key = "thin";
    opt_thin->type = TYPE_INTEGER;
    opt_thin->required = NO;
    opt_thin->answer = "1";
    opt_thin->options = "1-1000";
    opt_thin->description =
        _("Thinning factor (thin=10 gives cats 0,10,20...)");
    opt_thin->guisection = _("Advanced");

    opt_units = G_define_option();
    opt_units->key = "units";
    opt_units->type = TYPE_STRING;
    opt_units->required = NO;
    opt_units->description =
            _("Units to display after labels (e.g. meters)");
    opt_units->guisection = _("Advanced");

    opt_labelnum = G_define_option();
    opt_labelnum->key = "labelnum";
    opt_labelnum->type = TYPE_INTEGER;
    opt_labelnum->answer = "5";
    opt_labelnum->options = "2-100";
    opt_labelnum->description =
        _("Number of text labels for smooth gradient legend");
    opt_labelnum->guisection = _("Gradient");

    opt_ticks = G_define_option();
    opt_ticks->key = "label_values";
    opt_ticks->type = TYPE_DOUBLE;
    opt_ticks->required = NO;
    opt_ticks->description = _("Specific values to draw ticks");
    opt_ticks->required = NO;
    opt_ticks->multiple = YES;
    opt_ticks->guisection = _("Gradient");

    opt_tstep = G_define_option();
    opt_tstep->key = "label_step";
    opt_tstep->type = TYPE_DOUBLE;
    opt_tstep->required = NO;
    opt_tstep->description = _("Display label every step");
    opt_tstep->guisection = _("Gradient");

    opt_digits = G_define_option();
    opt_digits->key = "digits";
    opt_digits->type = TYPE_INTEGER;
    opt_digits->required = NO;
    opt_digits->description = _("Number of digits after decimal point");
    opt_digits->guisection = _("Advanced");
    opt_digits->answer = NULL;
    opt_digits->options = "0-6";

    opt_at = G_define_option();
    opt_at->key = "at";
    opt_at->key_desc = "bottom,top,left,right";
    opt_at->type = TYPE_DOUBLE; /* needs to be TYPE_DOUBLE to get past options check */
    opt_at->required = NO;
    opt_at->options = "0-100";
    opt_at->label =
        _("Size and placement as percentage of screen coordinates "
          "(0,0 is lower left)");
    opt_at->description = opt_at->key_desc;
    opt_at->answer = NULL;

    opt_use = G_define_option();
    opt_use->key = "use";
    opt_use->type = TYPE_DOUBLE;        /* string as it is fed through the parser? */
    opt_use->required = NO;
    opt_use->description =
        _("List of discrete category numbers/values for legend");
    opt_use->multiple = YES;
    opt_use->guisection = _("Subset");

    opt_range = G_define_option();
    opt_range->key = "range";
    opt_range->key_desc = "min,max";
    opt_range->type = TYPE_DOUBLE;      /* should it be type_double or _string ?? */
    opt_range->required = NO;
    opt_range->description =
        _("Use a subset of the map range for the legend (min,max)");
    opt_range->guisection = _("Subset");

    opt_color = G_define_standard_option(G_OPT_C);
    opt_color->label = _("Text color");
    opt_color->guisection = _("Font settings");

    opt_font = G_define_option();
    opt_font->key = "font";
    opt_font->type = TYPE_STRING;
    opt_font->required = NO;
    opt_font->description = _("Font name");
    opt_font->guisection = _("Font settings");

    opt_fontsize = G_define_option();
    opt_fontsize->key = "fontsize";
    opt_fontsize->type = TYPE_DOUBLE;
    opt_fontsize->required = NO;
    opt_fontsize->options = "1-360";
    opt_fontsize->label = _("Font size");
    opt_fontsize->description = _("Default: Auto-scaled");
    opt_fontsize->guisection = _("Font settings");

    opt_path = G_define_standard_option(G_OPT_F_INPUT);
    opt_path->key = "path";
    opt_path->required = NO;
    opt_path->description = _("Path to font file");
    opt_path->gisprompt = "old_file,font,file";
    opt_path->guisection = _("Font settings");

    opt_charset = G_define_option();
    opt_charset->key = "charset";
    opt_charset->type = TYPE_STRING;
    opt_charset->required = NO;
    opt_charset->description =
        _("Text encoding (only applicable to TrueType fonts)");
    opt_charset->guisection = _("Font settings");

    opt_brdcolor = G_define_standard_option(G_OPT_CN);
    opt_brdcolor->key = "border_color";
    opt_brdcolor->answer = "black";
    opt_brdcolor->label = _("Border color");
    opt_brdcolor->guisection = _("Background");

    opt_bgcolor = G_define_standard_option(G_OPT_CN);
    opt_bgcolor->key = "bgcolor";
    opt_bgcolor->answer = "white";
    opt_bgcolor->label = _("Background color");
    opt_bgcolor->guisection = _("Background");


    hidestr = G_define_flag();
    hidestr->key = 'v';
    hidestr->description = _("Do not show category labels");
    hidestr->guisection = _("Advanced");

    hidenum = G_define_flag();
    hidenum->key = 'c';
    hidenum->description = _("Do not show category numbers");
    hidenum->guisection = _("Advanced");

    showtick = G_define_flag();
    showtick->key = 't';
    showtick->description = _("Draw legend ticks for labels");
    showtick->guisection = _("Gradient");

    hidenodata = G_define_flag();
    hidenodata->key = 'n';
    hidenodata->description = _("Skip categories with no label");
    hidenodata->guisection = _("Advanced");

    smooth = G_define_flag();
    smooth->key = 's';
    smooth->description = _("Draw smooth gradient");
    smooth->guisection = _("Gradient");

    flipit = G_define_flag();
    flipit->key = 'f';
    flipit->description = _("Flip legend");
    flipit->guisection = _("Advanced");

    histo = G_define_flag();
    histo->key = 'd';
    histo->description = _("Add histogram to smoothed legend");
    histo->guisection = _("Gradient");

    showbg = G_define_flag();
    showbg->key = 'b';
    showbg->description = _("Show background");
    showbg->guisection = _("Background");

    log_sc = G_define_flag();
    log_sc->key = 'l';
    log_sc->description = _("Use logarithmic scale");
    log_sc->guisection = _("Advanced");

    G_option_required(opt_rast2d, opt_rast3d, NULL);
    G_option_exclusive(opt_rast2d, opt_rast3d, NULL);
    G_option_exclusive(hidenum, opt_ticks, NULL);
    G_option_exclusive(hidenum, opt_tstep, NULL);

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

    if (opt_rast2d->answer) {
        map_name = opt_rast2d->answer;
        maptype = MAP_TYPE_RASTER2D;
    }
    else {
        map_name = opt_rast3d->answer;
        maptype = MAP_TYPE_RASTER3D;
    }

    if (opt_title->answer)
        title = opt_title->answer;
    else
        title = "";

    if (opt_units->answer) {
        units = opt_units->answer;
    }
    else
        units = "";

    hide_catstr = hidestr->answer;      /* note hide_catstr gets changed and re-read below */
    hide_catnum = hidenum->answer;
    show_ticks = showtick->answer;
    hide_nodata = hidenodata->answer;
    do_smooth = smooth->answer;
    flip = flipit->answer;
    show_bg = showbg->answer;
    log_scale = log_sc->answer;

    if (showtick->answer) {
        label_indent = 12;
    }
    else
        label_indent = 6;

    if (opt_digits->answer != NULL)
        sscanf(opt_digits->answer, "%d", &digits);
    else
        digits = -1;

    color = D_parse_color(opt_color->answer, TRUE);

    if (opt_lines->answer != NULL)
        sscanf(opt_lines->answer, "%d", &lines);

    thin = 1;
    if (opt_thin->answer != NULL)
        sscanf(opt_thin->answer, "%d", &thin);
    if (!thin)
        thin = 1;

    if (opt_labelnum->answer != NULL)
        sscanf(opt_labelnum->answer, "%d", &steps);

    if ((opt_tstep->answer) || (opt_ticks->answer))
        steps = 0;

    if (opt_tstep->answer != NULL)
        t_step = atof(opt_tstep->answer);

    ticksCount = 0;
    if (opt_ticks->answer != NULL) {
        tick_values = (double *)G_calloc(100 + 1, sizeof(double));
        for (i = 0; i < 100; i++)       /* fill with dummy values */
            tick_values[i] = 1.0 * (i + 1);
        tick_values[i] = 0;

        for (i = 0; (opt_ticks->answers[i] != NULL) && i < 100; i++)
            tick_values[i] = atof(opt_ticks->answers[i]);
        ticksCount = i;
    }

    catlistCount = 0;
    if (opt_use->answer != NULL) {      /* should this be answerS ? */
        use_catlist = TRUE;

        catlist = (double *)G_calloc(100 + 1, sizeof(double));
        for (i = 0; i < 100; i++)       /* fill with dummy values */
            catlist[i] = 1.0 * (i + 1);
        catlist[i] = 0;

        for (i = 0; (opt_use->answers[i] != NULL) && i < 100; i++)
            catlist[i] = atof(opt_use->answers[i]);

        catlistCount = i;
    }
    else
        use_catlist = FALSE;


    UserRange = FALSE;
    if (opt_range->answer != NULL) {    /* should this be answerS ? */
        sscanf(opt_range->answers[0], "%lf", &UserRangeMin);
        sscanf(opt_range->answers[1], "%lf", &UserRangeMax);
        UserRange = TRUE;
        if (UserRangeMin > UserRangeMax) {
            UserRangeTemp = UserRangeMax;
            UserRangeMax = UserRangeMin;
            UserRangeMin = UserRangeTemp;
            flip = !flip;
        }
    }

    if (maptype == MAP_TYPE_RASTER2D) {
        if (Rast_read_colors(map_name, "", &colors) == -1)
            G_fatal_error(_("Color file for <%s> not available"), map_name);

        fp = Rast_map_is_fp(map_name, "");

        Rast_read_cats(map_name, "", &cats);
    }
    else {
        if (Rast3d_read_colors(map_name, "", &colors) == -1)
            G_fatal_error(_("Color file for <%s> not available"), map_name);

        fp = TRUE;              /* currently raster 3D is always floating point */

        Rast3d_read_cats(map_name, "", &cats);
    }

    if (fp && !use_catlist) {
        do_smooth = TRUE;
        /* fprintf(stderr, "FP map found - switching gradient legend on\n"); */
        flip = !flip;
    }

    D_open_driver();

    /* Parse and select background color */
    colorb = D_parse_color(opt_brdcolor->answer, TRUE);
    colorbg = D_parse_color(opt_bgcolor->answer, TRUE);

    if (opt_font->answer)
        D_font(opt_font->answer);
    else if (opt_path->answer)
        D_font(opt_path->answer);

    if (opt_fontsize->answer != NULL)
        fontsize = atof(opt_fontsize->answer);
    else
        fontsize = 12;          /* dummy placeholder, should never be called */

    if (opt_charset->answer)
        D_encoding(opt_charset->answer);

    if (opt_tit_fontsize->answer != NULL)
        tit_fontsize = atof(opt_tit_fontsize->answer);
    else
        tit_fontsize = 0;

    if (opt_at->answer != NULL) {
        sscanf(opt_at->answers[0], "%lf", &Y1);
        sscanf(opt_at->answers[1], "%lf", &Y0);
        sscanf(opt_at->answers[2], "%lf", &X0);
        sscanf(opt_at->answers[3], "%lf", &X1);
    }
    else {                      /* default */
        Y1 = 12;
        Y0 = 88;
        X0 = 3;
        X1 = 7;

        if (histo->answer) {
            X0 += 5;
            X1 += 5;
        }
    }

    if (show_bg)
        draw(map_name, maptype, color, thin, lines, steps, fp, label_indent,
             hide_catnum, hide_catstr, show_ticks, hide_nodata, do_smooth,
             cats, colors, X0, X1, Y0, Y1, flip, UserRange, UserRangeMin,
             UserRangeMax, catlist, catlistCount, use_catlist, ticksCount,
             fontsize, tit_fontsize, title, tick_values, t_step, colorb,
             colorbg, opt_use, opt_at, opt_fontsize, opt_tstep,
             opt_range, histo, hidestr, log_scale, 0, digits, units);

    draw(map_name, maptype, color, thin, lines, steps, fp, label_indent,
         hide_catnum, hide_catstr, show_ticks, hide_nodata, do_smooth, cats,
         colors, X0, X1, Y0, Y1, flip, UserRange, UserRangeMin, UserRangeMax,
         catlist, catlistCount, use_catlist, ticksCount, fontsize,
         tit_fontsize, title, tick_values, t_step, colorb, colorbg, opt_use,
         opt_at, opt_fontsize, opt_tstep, opt_range, histo,
         hidestr, log_scale, 1, digits, units);

    D_close_driver();

    exit(EXIT_SUCCESS);
}
Example #24
0
int main(int argc, char **argv)
{
    char *map_name;
    int color;
    int lines;
    int cols;

    struct FPRange fp_range;
    struct Colors colors;
    double ratio;
    DCELL dmin, dmax, dval;
    int cats_num;
    int cur_dot_row, cur_dot_col;
    int dots_per_line, dots_per_col;
    int atcat;
    int white, black;
    int atcol, atline;
    int count, offset;
    double t, b, l, r;
    int fp, new_colr;
    double x_box[5], y_box[5];

    struct GModule *module;
    struct Option *opt1, *opt2, *opt3, *opt4;
    struct Flag *skip_null;

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

    module = G_define_module();
    G_add_keyword(_("display"));
    G_add_keyword(_("raster"));
    module->description =
	_("Displays the color table associated with a raster map layer.");

    opt1 = G_define_standard_option(G_OPT_R_MAP);
    opt1->description =
	_("Name of raster map whose color table is to be displayed");

    opt2 = G_define_option();
    opt2->key = "color";
    opt2->type = TYPE_STRING;
    opt2->answer = DEFAULT_BG_COLOR;
    opt2->gisprompt = "old_color,color,color";
    opt2->description =
	_("Color of lines separating the colors of the color table");

    opt3 = G_define_option();
    opt3->key = "lines";
    opt3->type = TYPE_INTEGER;
    opt3->options = "1-1000";
    opt3->description = _("Number of lines to appear in the color table");

    opt4 = G_define_option();
    opt4->key = "cols";
    opt4->type = TYPE_INTEGER;
    opt4->options = "1-1000";
    opt4->description = _("Number of columns to appear in the color table");

    skip_null = G_define_flag();
    skip_null->key = 'n';
    skip_null->description =
	_("Don't draw a collar showing the NULL color in FP maps");

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


    map_name = opt1->answer;
    fp = Rast_map_is_fp(map_name, "");

    if (opt2->answer != NULL) {
	new_colr = D_translate_color(opt2->answer);
	color = new_colr;
    }

    if (fp)
	lines = 1;
    else
	lines = 0;

    if (opt3->answer != NULL) {
	if (fp)
	    G_warning(_("<%s> is floating-point; "
			"ignoring [lines] and drawing continuous color ramp"),
		      map_name);
	else
	    sscanf(opt3->answer, "%d", &lines);
    }

    if (fp)
	cols = 1;
    else
	cols = 0;

    if (opt4->answer) {
	if (fp)
	    G_warning(_("<%s> is floating-point; "
			"ignoring [cols] and drawing continuous color ramp"),
		      map_name);
	else
	    sscanf(opt4->answer, "%d", &cols);
    }

    /* Make sure map is available */
    if (Rast_read_colors(map_name, "", &colors) == -1)
	G_fatal_error(_("Color file for <%s> not available"), map_name);
    if (Rast_read_fp_range(map_name, "", &fp_range) == -1)
	G_fatal_error(_("Range file for <%s> not available"), map_name);
    if (D_open_driver() != 0)
	G_fatal_error(_("No graphics device selected. "
			"Use d.mon to select graphics device."));

    D_setup_unity(0);
    D_get_src(&t, &b, &l, &r);

    Rast_get_fp_range_min_max(&fp_range, &dmin, &dmax);
    if (Rast_is_d_null_value(&dmin) || Rast_is_d_null_value(&dmax))
	G_fatal_error(_("Data range is empty"));

    cats_num = (int)dmax - (int)dmin + 1;

    if (lines <= 0 && cols <= 0) {
	double dx, dy;

	dy = (double)(b - t);
	dx = (double)(r - l);
	ratio = dy / dx;
	cols = 1 + sqrt((dmax - dmin + 1.) / ratio);
	lines = 1 + cats_num / cols;
    }
    else if (lines > 0 && cols <= 0) {
	cols = 1 + cats_num / lines;
    }
    else if (cols > 0 && lines <= 0) {
	lines = 1 + cats_num / cols;
    }
    /* otherwise, accept without complaint what the user requests
     * It is possible that the number of lines and cols is not
     * sufficient for the number of categories.
     */

    dots_per_line = (b - t) / lines;
    dots_per_col = (r - l) / cols;

    x_box[0] = 0;			y_box[0] = 0;
    x_box[1] = 0;			y_box[1] = (6 - dots_per_line);
    x_box[2] = (dots_per_col - 6);	y_box[2] = 0;
    x_box[3] = 0;			y_box[3] = (dots_per_line - 6);
    x_box[4] = (6 - dots_per_col);	y_box[4] = 0;

    white = D_translate_color("white");
    black = D_translate_color("black");
    Rast_set_c_null_value(&atcat, 1);

    if (!fp) {
	for (atcol = 0; atcol < cols; atcol++) {
	    cur_dot_row = t;
	    cur_dot_col = l + atcol * dots_per_col;
	    count = 0;
	    for (atline = 0; atline < lines; atline++) {
		cur_dot_row += dots_per_line;
		/* Draw outer border box */
		D_use_color(color);
		D_begin();
		D_move_abs(cur_dot_col + 2, (cur_dot_row - 1));
		D_cont_rel(0, (2 - dots_per_line));
		D_cont_rel((dots_per_col - 2), 0);
		D_cont_rel(0, (dots_per_line - 2));
		D_cont_rel((2 - dots_per_col), 0);
		D_end();
		D_stroke();
		/* Draw black box */
		D_use_color(black);
		D_begin();
		D_move_abs(cur_dot_col + 3, (cur_dot_row - 2));
		D_cont_rel(0, (4 - dots_per_line));
		D_cont_rel((dots_per_col - 4), 0);
		D_cont_rel(0, (dots_per_line - 4));
		D_cont_rel((4 - dots_per_col), 0);
		D_end();
		D_stroke();
		/* Color box */
		D_color((CELL) atcat, &colors);
		D_pos_abs(cur_dot_col + 4, (cur_dot_row - 3));
		D_polygon_rel(x_box, y_box, 5);

		count++;
		/* first cat number is null value */
		if (count == 1)
		    atcat = (int)dmin;
		else if (++atcat > (int)dmax)
		    break;
	    }
	    if (atcat > (int)dmax)
		break;
	} /* col loop */
    } /* int map */

    else {
	/*** draw continuous color ramp for fp map ***/

	cur_dot_row = t + dots_per_line;
	cur_dot_col = l;
	/* Draw outer border box */
	D_use_color(color);
	D_begin();
	D_move_abs(cur_dot_col + 1, (cur_dot_row - 1));
	D_cont_rel(0, (2 - dots_per_line));
	D_cont_rel((dots_per_col - 2), 0);
	D_cont_rel(0, (dots_per_line - 2));
	D_cont_rel((2 - dots_per_col), 0);
	D_end();
	D_stroke();
	/* Draw black box */
	D_use_color(black);
	D_begin();
	D_move_abs(cur_dot_col + 2, (cur_dot_row - 2));
	D_cont_rel(0, (4 - dots_per_line));
	D_cont_rel((dots_per_col - 4), 0);
	D_cont_rel(0, (dots_per_line - 4));
	D_cont_rel((4 - dots_per_col), 0);
	D_end();
	D_stroke();

	/* Color ramp box */
	  /* get separate color for each pixel */
	  /* fisrt 5 pixels draw null color */
	y_box[1] = -1;
	y_box[3] = 1;
	x_box[2] = (dots_per_col - 6);
	x_box[4] = (6 - dots_per_col);

	G_debug(1, "dots_per_line: %d  dmin=%.2f dmax=%.2f",
		dots_per_line, dmin, dmax);

	if (skip_null->answer)
	    offset = 1;
	else
	    offset = 4;

	for (r = 0; r < dots_per_line - 6; r++) {
	    if ((r <= 4) && !skip_null->answer)
		Rast_set_d_null_value(&dval, 1);
	    else
		dval =
		    dmin +  r*(dmax - dmin) / (dots_per_line - 6 - offset);

	    D_d_color(dval, &colors);
	    D_pos_abs(cur_dot_col + 3, (cur_dot_row - 3) - r);
	    D_polygon_rel(x_box, y_box, 5);
	}
    }
    
    D_save_command(G_recreate_command());
    D_close_driver();

    exit(EXIT_SUCCESS);
}
Example #25
0
int main(int argc, char **argv)
{
    char *mapname,		/* ptr to name of output layer  */
     *setname,			/* ptr to name of input mapset  */
     *ipolname;			/* name of interpolation method */

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

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

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

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

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

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

    struct GModule *module;

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

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


    G_gisinit(argv[0]);

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    Rast_set_input_window(&incellhd);

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

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

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


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

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

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

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

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

	exit(EXIT_SUCCESS);
    }


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

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

    Rast_set_input_window(&incellhd);

    /* And switch back to original location */

    G__switch_env();

    /* Adjust borders of output map */

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

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

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

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

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

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

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

    G__switch_env();
    Rast_set_output_window(&outcellhd);

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

    cell_size = Rast_cell_size(cell_type);

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

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

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

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

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

	Rast_put_row(fdo, obuffer, cell_type);

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

    Rast_close(fdo);

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

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

    G_done_msg(NULL);
    exit(EXIT_SUCCESS);
}
Example #26
0
void set_map(char *name, char *name1, char *name2, struct Cell_head window,
	     int top, int bot, int left, int right)
{
    char cmd[30], cmd1[30], cmd2[30], **sel;
    int i, j, btn, d, class, top0, bot0, right0, left0, paint = 0, method;
    double msc[2], dtmp;


    /* VARIABLES
       IN:
       name = raster map name to be set up
       name1 = overlay vector map name
       name2 = overlay site map name
     */

    colors_old = (struct Colors *)G_malloc(1 * sizeof(struct Colors));
    Rast_init_colors(colors_old);
    Rast_read_colors(name, G_mapset(), colors_old);

    G_system("clear");
    paint_map(name, name1, name2);
    paint = 1;

    /* setup the screen to raster map 
       coordinate conversion system */

    scr_cell(&window, top, bot, left, right, msc);

    top0 = top;
    bot0 = bot;
    left0 = left;
    right0 = right;

    /* display the menu and instructions */
  again:
    if (!paint) {
	if (G_yes
	    ("\n    Refresh the screen before choosing more setup?  ", 1))
	    paint_map(name, name1, name2);
    }
    else
	G_system("clear");

    fprintf(stderr, "\n\n    CHOOSE THE SETUP OPTION:\n\n");
    fprintf(stderr, "       Draw sampling regions                1\n");
    fprintf(stderr, "       Setup a sampling frame               2\n");
    fprintf(stderr, "       Setup sampling units                 3\n");
    fprintf(stderr, "       Setup a moving window                4\n");
    fprintf(stderr, "       Setup group or class limits          5\n");
    fprintf(stderr, "       Change the raster map color table    6\n");
    fprintf(stderr, "       Exit and save setup                  7\n");

    do {
	fprintf(stderr, "\n                                Which Number?   ");
	dtmp = 5.0;
	numtrap(1, &dtmp);
	if ((method = fabs(dtmp)) > 7 || method < 1) {
	    fprintf(stderr, "\n    Choice must between 1-7; try again");
	}
    }
    while (method > 7 || method < 1);

    /* setup regions */
    if (method == 1)
	set_rgn(msc, name, name1, name2);

    /* setup the sampling frame */
    else if (method == 2) {
	top = top0;
	bot = bot0;
	right = right0;
	left = left0;
	set_frame(msc, &top, &bot, &left, &right);
    }

    /* setup sampling units */

    else if (method == 3) {
	sample(top, bot, left, right, name, name1, name2, msc);
    }

    /* setup the moving window */

    else if (method == 4) {
	mov_wind(top, bot, left, right, name, name1, name2, msc);
    }

    /* setup group/class limits */

    else if (method == 5) {

	/* setup the buffer to store the user's input */

	sel = (char **)G_malloc(10 * sizeof(char *));
	for (i = 0; i < 9; i++)
	    sel[i] = (char *)G_calloc(2, sizeof(char));

      back:
	ask_group(sel);

	/* check for no input */

	if (sel[0][0] != 'x' && sel[1][0] != 'x' && sel[2][0] != 'x' &&
	    sel[3][0] != 'x' && sel[4][0] != 'x' && sel[5][0] != 'x' &&
	    sel[6][0] != 'x' && sel[7][0] != 'x' && sel[8][0] != 'x') {
	    G_system("clear");
	    fprintf(stderr,
		    "    Did you mean to not make any attribute group");
	    if (!G_yes("\n    or index class setup choices?   ", 1))
		goto back;
	}

	/* if there is input, then invoke the
	   group/class setup module and then free
	   the memory allocated for selections */

	else {
	    get_group_drv(sel);
	    for (i = 0; i < 9; i++)
		G_free(sel[i]);
	    G_free(sel);
	}
    }

    /* change color tables */

    else if (method == 6)
	change_color(name, name1, name2);

    /* reset the colortable and exit */

    else if (method == 7) {
	Rast_write_colors(name, G_mapset(), colors_old);
	Rast_free_colors(colors_old);
	/*     R_close_driver(); */
	G_system("d.frame -e");
	exit(0);
    }
    paint = 0;
    goto again;
    return;
}
Example #27
0
File: main.c Project: caomw/grass
static int load_files(void)
{
    void *voidc;
    int rtype;
    register int i, rowoff, row, col, vxoff, vyoff, offset;
    int cnt, fd, size, tsiz, coff;
    int vnum;
    int y_rows, y_cols;
    char *pr, *pg, *pb;
    unsigned char *tr, *tg, *tb, *tset;
    char *mpfilename, *name;
    char *yfiles[MAXIMAGES];
    struct Colors colors;
    int ret;

    size = nrows * ncols;

    pr = G_malloc(size);
    pg = G_malloc(size);
    pb = G_malloc(size);

    tsiz = Rast_window_cols();

    tr = (unsigned char *)G_malloc(tsiz);
    tg = (unsigned char *)G_malloc(tsiz);
    tb = (unsigned char *)G_malloc(tsiz);
    tset = (unsigned char *)G_malloc(tsiz);

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

	for (i = 0; i < size; i++)
	    pr[i] = pg[i] = pb[i] = 0;

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

	    name = vfiles[vnum][cnt];

	    G_message(_("Reading raster map <%s>..."), name);

	    fd = Rast_open_old(name, "");

	    if (Rast_read_colors(name, "", &colors) < 0)
		G_fatal_error(_("Unable to read color table for <%s>"), name);

	    rtype = Rast_get_map_type(fd);
	    voidc = Rast_allocate_buf(rtype);

	    for (row = 0; row < vrows; row++) {
		Rast_get_row(fd, voidc, (int)(row / vscale), rtype);

		rowoff = (vyoff + row) * ncols;
		Rast_lookup_colors(voidc, tr, tg, tb,
				       tset, tsiz, &colors, rtype);

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

		    if (!tset[coff])
			pr[offset] = pg[offset] = pb[offset] = (char)255;
		    else {
			pr[offset] = (char)tr[coff];
			pg[offset] = (char)tg[coff];
			pb[offset] = (char)tb[coff];
		    }
		}
	    }

	    Rast_close(fd);
	}

	yfiles[cnt] = G_tempfile();

#ifdef USE_PPM
	write_ppm(pr, pg, pb, nrows, ncols, &y_rows, &y_cols, yfiles[cnt]);
#else
	write_ycc(pr, pg, pb, nrows, ncols, &y_rows, &y_cols, yfiles[cnt]);
#endif
    }

    mpfilename = G_tempfile();
    write_params(mpfilename, yfiles, outfile, cnt, quality, y_rows, y_cols, 0);

    if (G_verbose() <= G_verbose_min())
	ret = G_spawn(encoder, encoder, mpfilename,
		      SF_REDIRECT_FILE, SF_STDOUT, SF_MODE_OUT, G_DEV_NULL,
		      SF_REDIRECT_FILE, SF_STDERR, SF_MODE_OUT, G_DEV_NULL,
		      NULL);
    else
	ret = G_spawn(encoder, encoder, mpfilename, NULL);

    if (ret != 0)
	G_warning(_("mpeg_encode ERROR"));

    clean_files(mpfilename, yfiles, cnt);

    G_free(voidc);
    G_free(tset);
    G_free(tr);
    G_free(tg);
    G_free(tb);
    G_free(pr);
    G_free(pg);
    G_free(pb);

    return (cnt);
}
Example #28
0
/* *************************************************************** */
int main(int argc, char *argv[])
{
    int i, j;
    int nfiles;
    int fd[NFILES];
    struct Categories cats[NFILES];
    struct Cell_head window;
    struct Colors ncolor[NFILES];
    struct Colors colors;
    RASTER_MAP_TYPE out_type[NFILES];
    CELL *cell[NFILES];
    DCELL *dcell[NFILES];

    /*   int row, col; */
    double drow, dcol;
    int row_in_window, in_window;
    double east, north;
    int line;
    char buffer[1024];
    char **ptr;
    struct Option *opt1, *opt2, *opt3, *opt4, *opt_fs;
    struct Flag *label_flag, *cache_flag, *int_flag, *color_flag, *header_flag;
    char fs;
    int Cache_size;
    int done = FALSE;
    int point, point_cnt;
    struct order *cache;
    int cur_row;
    int projection;
    int cache_hit = 0, cache_miss = 0;
    int cache_hit_tot = 0, cache_miss_tot = 0;
    int pass = 0;
    int cache_report = FALSE;
    char tmp_buf[500], *null_str;
    int red, green, blue;
    struct GModule *module;


    G_gisinit(argv[0]);

    /* Set description */
    module = G_define_module();
    G_add_keyword(_("raster"));
    G_add_keyword(_("position"));
    G_add_keyword(_("querying"));
    module->description =
	_("Queries raster map layers on their category values and category labels.");

    opt1 = G_define_option();
    opt1->key = "input";
    opt1->type = TYPE_STRING;
    opt1->required = YES;
    opt1->multiple = YES;
    opt1->gisprompt = "old,cell,raster";
    opt1->description = _("Name of existing raster map(s) to query");

    opt2 = G_define_option();
    opt2->key = "cache";
    opt2->type = TYPE_INTEGER;
    opt2->required = NO;
    opt2->multiple = NO;
    opt2->description = _("Size of point cache");
    opt2->answer = "500";
    opt2->guisection = _("Advanced");

    opt3 = G_define_option();
    opt3->key = "null";
    opt3->type = TYPE_STRING;
    opt3->required = NO;
    opt3->answer = "*";
    opt3->description = _("Char string to represent no data cell");

    opt_fs = G_define_standard_option(G_OPT_F_SEP);

    opt4 = G_define_option();
    opt4->key = "east_north";
    opt4->type = TYPE_DOUBLE;
    opt4->key_desc = "east,north";
    opt4->required = NO;
    opt4->multiple = YES;
    opt4->description = _("Coordinates for query");

    header_flag = G_define_flag();
    header_flag->key = 'n';
    header_flag->description = _("Output header row");

    label_flag = G_define_flag();
    label_flag->key = 'f';
    label_flag->description = _("Show the category labels of the grid cell(s)");

    color_flag = G_define_flag();
    color_flag->key = 'r';
    color_flag->description = _("Output color values as RRR:GGG:BBB");

    int_flag = G_define_flag();
    int_flag->key = 'i';
    int_flag->description = _("Output integer category values, not cell values");

    cache_flag = G_define_flag();
    cache_flag->key = 'c';
    cache_flag->description = _("Turn on cache reporting");
    cache_flag->guisection = _("Advanced");

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


    tty = isatty(0);

    projection = G_projection();

    /* see v.in.ascii for a better solution */
    if (opt_fs->answer != NULL) {
	if (strcmp(opt_fs->answer, "space") == 0)
	    fs = ' ';
	else if (strcmp(opt_fs->answer, "tab") == 0)
	    fs = '\t';
	else if (strcmp(opt_fs->answer, "\\t") == 0)
	    fs = '\t';
	else
	    fs = opt_fs->answer[0];
    }

    null_str = opt3->answer;


    if (tty)
	Cache_size = 1;
    else
	Cache_size = atoi(opt2->answer);

    if (Cache_size < 1)
	Cache_size = 1;

    cache = (struct order *)G_malloc(sizeof(struct order) * Cache_size);

    /*enable cache report */
    if (cache_flag->answer)
	cache_report = TRUE;


    ptr = opt1->answers;
    nfiles = 0;
    for (; *ptr != NULL; ptr++) {
	char name[GNAME_MAX];

	if (nfiles >= NFILES)
	    G_fatal_error(_("can only do up to %d raster maps"),
			  NFILES);

	strcpy(name, *ptr);
	fd[nfiles] = Rast_open_old(name, "");

	out_type[nfiles] = Rast_get_map_type(fd[nfiles]);
	if (int_flag->answer)
	    out_type[nfiles] = CELL_TYPE;

	if (color_flag->answer) {
	    Rast_read_colors(name, "", &colors);
	    ncolor[nfiles] = colors;
	}

	if (label_flag->answer && Rast_read_cats(name, "", &cats[nfiles]) < 0)
	    G_fatal_error(_("Unable to read category file for <%s>"), name);

	nfiles++;
    }

    for (i = 0; i < nfiles; i++) {
	if (int_flag->answer)
	    out_type[i] = CELL_TYPE;

	cell[i] = Rast_allocate_c_buf();
	if (out_type[i] != CELL_TYPE)
	    dcell[i] = Rast_allocate_d_buf();
    }

    G_get_window(&window);


    if(header_flag->answer) {
	fprintf(stdout, "easting%cnorthing%csite_name", fs, fs);

	ptr = opt1->answers;
	for (; *ptr != NULL; ptr++) {
	    char name[GNAME_MAX];
	    strcpy(name, *ptr);

	    fprintf(stdout, "%c%s", fs, name);

	    if (label_flag->answer)
		fprintf(stdout, "%c%s_label", fs, name);
	    if (color_flag->answer)
		fprintf(stdout, "%c%s_color", fs, name);
	}

	fprintf(stdout, "\n");
    }

    line = 0;
    if (!opt4->answers && tty)
	fprintf(stderr, "enter points, \"end\" to quit\n");

    j = 0;
    done = FALSE;
    while (!done) {
	pass++;
	if (cache_report & !tty)
	    fprintf(stderr, "Pass %3d  Line %6d   - ", pass, line);

	cache_hit = cache_miss = 0;

	if (!opt4->answers && tty) {
	    fprintf(stderr, "\neast north [label] >  ");
	    Cache_size = 1;
	}
	{
	    point_cnt = 0;
	    for (i = 0; i < Cache_size; i++) {
		if (!opt4->answers && fgets(buffer, 1000, stdin) == NULL)
		    done = TRUE;
		else {
		    line++;
		    if ((!opt4->answers &&
			 (strncmp(buffer, "end\n", 4) == 0 ||
			  strncmp(buffer, "exit\n", 5) == 0)) ||
			(opt4->answers && !opt4->answers[j]))
			done = TRUE;
		    else {
			*(cache[point_cnt].lab_buf) =
			    *(cache[point_cnt].east_buf) =
			    *(cache[point_cnt].north_buf) = 0;
			if (!opt4->answers)
			    sscanf(buffer, "%s %s %[^\n]",
				   cache[point_cnt].east_buf,
				   cache[point_cnt].north_buf,
				   cache[point_cnt].lab_buf);
			else {
			    strcpy(cache[point_cnt].east_buf,
				   opt4->answers[j++]);
			    strcpy(cache[point_cnt].north_buf,
				   opt4->answers[j++]);
			}
			if (*(cache[point_cnt].east_buf) == 0)
			    continue;	/* skip blank lines */

			if (*(cache[point_cnt].north_buf) == 0) {
			    oops(line, buffer,
				 "two coordinates (east north) required");
			    continue;
			}
			if (!G_scan_northing
			    (cache[point_cnt].north_buf, &north, window.proj)
			    || !G_scan_easting(cache[point_cnt].east_buf,
					       &east, window.proj)) {
			    oops(line, buffer, "invalid coordinate(s)");
			    continue;
			}

			/* convert north, east to row and col */
			drow = Rast_northing_to_row(north, &window);
			dcol = Rast_easting_to_col(east, &window);

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

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

	if (Cache_size > 1)
	    qsort(cache, point_cnt, sizeof(struct order), by_row);

	/* extract data from files and store in cache */

	cur_row = -99;

	for (point = 0; point < point_cnt; point++) {
	    row_in_window = 1;
	    in_window = 1;
	    if (cache[point].row < 0 || cache[point].row >= window.rows)
		row_in_window = in_window = 0;
	    if (cache[point].col < 0 || cache[point].col >= window.cols)
		in_window = 0;

	    if (!in_window) {
		if (tty)
		    fprintf(stderr,
			    "** note ** %s %s is outside your current window\n",
			    cache[point].east_buf, cache[point].north_buf);
	    }

	    if (cur_row != cache[point].row) {
		cache_miss++;
		if (row_in_window)
		    for (i = 0; i < nfiles; i++) {
			Rast_get_c_row(fd[i], cell[i], cache[point].row);

			if (out_type[i] != CELL_TYPE)
			    Rast_get_d_row(fd[i], dcell[i], cache[point].row);
		    }

		cur_row = cache[point].row;
	    }
	    else
		cache_hit++;

	    for (i = 0; i < nfiles; i++) {
		if (in_window)
		    cache[point].value[i] = cell[i][cache[point].col];
		else
		    Rast_set_c_null_value(&(cache[point].value[i]), 1);

		if (out_type[i] != CELL_TYPE) {
		    if (in_window)
			cache[point].dvalue[i] = dcell[i][cache[point].col];
		    else
			Rast_set_d_null_value(&(cache[point].dvalue[i]), 1);
		}
		if (color_flag->answer) {
		    if (out_type[i] == CELL_TYPE)
			Rast_get_c_color(&cell[i][cache[point].col],
					     &red, &green, &blue, &ncolor[i]);
		    else
			Rast_get_d_color(&dcell[i][cache[point].col],
					     &red, &green, &blue, &ncolor[i]);

		    sprintf(cache[point].clr_buf[i], "%03d:%03d:%03d", red,
			    green, blue);
		}

	    }
	}			/* point loop */

	if (Cache_size > 1)
	    qsort(cache, point_cnt, sizeof(struct order), by_point);

	/* report data from re-ordered cache */

	for (point = 0; point < point_cnt; point++) {

	    G_debug(1, "%s|%s at col %d, row %d\n",
		    cache[point].east_buf, cache[point].north_buf,
		    cache[point].col, cache[point].row);


	    fprintf(stdout, "%s%c%s%c%s", cache[point].east_buf, fs,
		    cache[point].north_buf, fs, cache[point].lab_buf);

	    for (i = 0; i < nfiles; i++) {
		if (out_type[i] == CELL_TYPE) {
		    if (Rast_is_c_null_value(&cache[point].value[i])) {
			fprintf(stdout, "%c%s", fs, null_str);
			if (label_flag->answer)
			    fprintf(stdout, "%c", fs);
			if (color_flag->answer)
			    fprintf(stdout, "%c", fs);
			continue;
		    }
		    fprintf(stdout, "%c%ld", fs, (long)cache[point].value[i]);
		}
		else {		/* FCELL or DCELL */

		    if (Rast_is_d_null_value(&cache[point].dvalue[i])) {
			fprintf(stdout, "%c%s", fs, null_str);
			if (label_flag->answer)
			    fprintf(stdout, "%c", fs);
			if (color_flag->answer)
			    fprintf(stdout, "%c", fs);
			continue;
		    }
		    if (out_type[i] == FCELL_TYPE)
			sprintf(tmp_buf, "%.7g", cache[point].dvalue[i]);
		    else /* DCELL */
			sprintf(tmp_buf, "%.15g", cache[point].dvalue[i]);
		    G_trim_decimal(tmp_buf); /* not needed with %g? */
		    fprintf(stdout, "%c%s", fs, tmp_buf);
		}
		if (label_flag->answer)
		    fprintf(stdout, "%c%s", fs,
			    Rast_get_c_cat(&(cache[point].value[i]), &cats[i]));
		if (color_flag->answer)
		    fprintf(stdout, "%c%s", fs, cache[point].clr_buf[i]);
	    }
	    fprintf(stdout, "\n");
	}

	if (cache_report & !tty)
	    fprintf(stderr, "Cache  Hit: %6d  Miss: %6d\n",
		    cache_hit, cache_miss);

	cache_hit_tot += cache_hit;
	cache_miss_tot += cache_miss;
	cache_hit = cache_miss = 0;
    }

    if (!opt4->answers && tty)
	fprintf(stderr, "\n");
    if (cache_report & !tty)
	fprintf(stderr, "Total:    Cache  Hit: %6d  Miss: %6d\n",
		cache_hit_tot, cache_miss_tot);

    exit(EXIT_SUCCESS);
}