示例#1
0
static void write_cats(const char *element, const char *name,
		       struct Categories *cats)
{
    FILE *fd;
    int i, fp_map;
    char *descr;
    DCELL val1, val2;
    char str1[100], str2[100];

    fd = G_fopen_new(element, name);
    if (!fd)
	G_fatal_error(_("Unable to open %s file for map <%s>"), element, name);

    /* write # cats - note # indicate 3.0 or later */
    fprintf(fd, "# %ld categories\n", (long)cats->num);

    /* title */
    fprintf(fd, "%s\n", cats->title != NULL ? cats->title : "");

    /* write format and coefficients */
    fprintf(fd, "%s\n", cats->fmt != NULL ? cats->fmt : "");
    fprintf(fd, "%.2f %.2f %.2f %.2f\n",
	    cats->m1, cats->a1, cats->m2, cats->a2);

    /* if the map is integer or if this is a vector map, sort labels */
    if (strncmp(element, "dig", 3) == 0)
	fp_map = 0;
    else
	fp_map = Rast_map_is_fp(name, G_mapset());
    if (!fp_map)
	Rast_sort_cats(cats);

    /* write the cat numbers:label */
    for (i = 0; i < Rast_quant_nof_rules(&cats->q); i++) {
	descr = Rast_get_ith_d_cat(cats, i, &val1, &val2);
	if ((cats->fmt && cats->fmt[0])
	    || (descr && descr[0])) {
	    if (val1 == val2) {
		sprintf(str1, "%.10f", val1);
		G_trim_decimal(str1);
		fprintf(fd, "%s:%s\n", str1, descr != NULL ? descr : "");
	    }
	    else {
		sprintf(str1, "%.10f", val1);
		G_trim_decimal(str1);
		sprintf(str2, "%.10f", val2);
		G_trim_decimal(str2);
		fprintf(fd, "%s:%s:%s\n", str1, str2,
			descr != NULL ? descr : "");
	    }
	}
    }
    fclose(fd);
}
示例#2
0
static void format(char *buf, int d, int m, double s, char h)
{
    char temp[50];
    double ss;

    sprintf(temp, "%f", s);
    sscanf(temp, "%lf", &ss);
    if (ss >= 60) {
	ss = 0;			/* force it to zero */
	if (++m >= 60) {
	    m = 0;
	    d++;
	}
    }

    if (ss < 10.0)
	sprintf(temp, "0%f", ss);
    else
	sprintf(temp, "%f", ss);
    G_trim_decimal(temp);
    if (strcmp(temp, "00") != 0 && strcmp(temp, "0") != 0)
	sprintf(buf, "%d:%02d:%s%c", d, m, temp, h);
    else if (m > 0)
	sprintf(buf, "%d:%02d%c", d, m, h);
    else if (d > 0)
	sprintf(buf, "%d%c", d, h);
    else
	sprintf(buf, "0");
}
示例#3
0
/*!
   \fn 
   \brief 
   \return 
   \param 
 */
int
db_convert_value_to_string(dbValue * value, int sqltype, dbString * string)
{
    char buf[64];
    const char *bp = buf;

    if (db_test_value_isnull(value)) {
	*buf = 0;
    }
    else {
	switch (db_sqltype_to_Ctype(sqltype)) {
	case DB_C_TYPE_INT:
	    sprintf(buf, "%d", db_get_value_int(value));
	    break;
	case DB_C_TYPE_DOUBLE:
	    sprintf(buf, "%.15g", db_get_value_double(value));
	    G_trim_decimal(buf);
	    break;
	case DB_C_TYPE_STRING:
	    bp = db_get_value_string(value);
	    break;
	case DB_C_TYPE_DATETIME:
	    return db_convert_value_datetime_into_string(value, sqltype,
							 string);
	default:
	    db_error
		("db_convert_value_into_string(): unrecongized sqltype-type");
	    return DB_FAILED;
	}
    }
    return db_set_string(string, bp);
}
示例#4
0
int Rast3d_write_cats(const char *name, struct Categories *cats)
 /* adapted from Rast_write_cats */
{
    FILE *fd;
    int i;
    const char *descr;
    DCELL val1, val2;
    char str1[100], str2[100];

    fd = G_fopen_new_misc(RASTER3D_DIRECTORY, RASTER3D_CATS_ELEMENT, name);
    if (!fd)
	return -1;

    /* write # cats - note # indicate 3.0 or later */
    fprintf(fd, "# %ld categories\n", (long)cats->num);

    /* title */
    fprintf(fd, "%s\n", cats->title != NULL ? cats->title : "");

    /* write format and coefficients */
    fprintf(fd, "%s\n", cats->fmt != NULL ? cats->fmt : "");
    fprintf(fd, "%.2f %.2f %.2f %.2f\n",
	    cats->m1, cats->a1, cats->m2, cats->a2);

    /* write the cat numbers:label */
    for (i = 0; i < Rast_quant_nof_rules(&cats->q); i++) {
	descr = Rast_get_ith_d_cat(cats, i, &val1, &val2);
	if ((cats->fmt && cats->fmt[0]) || (descr && descr[0])) {
	    if (val1 == val2) {
		sprintf(str1, "%.10f", val1);
		G_trim_decimal(str1);
		fprintf(fd, "%s:%s\n", str1, descr != NULL ? descr : "");
	    }
	    else {
		sprintf(str1, "%.10f", val1);
		G_trim_decimal(str1);
		sprintf(str2, "%.10f", val2);
		G_trim_decimal(str2);
		fprintf(fd, "%s:%s:%s\n", str1, str2,
			descr != NULL ? descr : "");
	    }
	}
    }
    fclose(fd);
    return 1;
}
示例#5
0
static int format_double(double value, char *buf)
{
    int G_trim_decimal();

    sprintf(buf, "%.8f", value);
    G_trim_decimal(buf);
    return 0;
}
示例#6
0
static void format_max(char *str, double dval)
{
    double dtmp;

    sprintf(str, "%.15g", dval);
    G_trim_decimal(str);
    sscanf(str, "%lf", &dtmp);
    if (dtmp != dval) {  /* if  no zeros after decimal point were trimmed */
	sprintf(str, "%.15g", dval + GRASS_EPSILON);
    }
}
示例#7
0
int report_range(void)
{
    char buff[300], buff2[300];

    if (Rast_is_d_null_value(&old_dmin) || Rast_is_d_null_value(&old_dmax))
        G_message(_("Old data range is empty"));
    else {
        sprintf(buff, "%.15g", old_dmin);
        sprintf(buff2, "%.15g", old_dmax);
        G_trim_decimal(buff);
        G_trim_decimal(buff2);
        G_message(_("Old data range is %s to %s"), buff, buff2);
    }
    if (Rast_is_c_null_value(&old_min) || Rast_is_c_null_value(&old_max))
        G_message(_("Old integer data range is empty"));
    else
        G_message(_("Old integer data range is %d to %d"),
                  (int)old_min, (int)old_max);

    return 0;
}
示例#8
0
文件: main.c 项目: caomw/grass
int print_d_label(double x)
{
    char *label, tmp[40];
    DCELL dtmp;

    dtmp = x;
    G_squeeze(label = Rast_get_d_cat(&dtmp, &cats));
    sprintf(tmp, "%.10f", x);
    G_trim_decimal(tmp);
    fprintf(stdout, "%s%s%s\n", tmp, fs, label);

    return 0;
}
示例#9
0
static void sum_out(FILE *fp, long cat, double sum1)
{
    char buf[64];

    if (cat == 0)
	*buf = 0;
    else {
	sprintf(buf, "%.10lf", sum1);
	G_trim_decimal(buf);
    }

    fprintf(fp, "%ld = %ld %s\n", cat, cat, buf);
}
示例#10
0
/* overall min and max data values in color table */
static void write_rules(FILE * fd, struct _Color_Rule_ *crules, DCELL dmin,
			DCELL dmax)
{
    struct _Color_Rule_ *rule;
    char str[100];

    /* find the end of the rules list */
    rule = crules;
    while (rule->next)
	rule = rule->next;

    /* write out the rules in reverse order */
    for (; rule; rule = rule->prev) {
	if (rule->low.value == dmin)
	    format_min(str, (double)rule->low.value);
	else {
	    sprintf(str, "%.15g", (double)rule->low.value);
	    G_trim_decimal(str);
	}
	fprintf(fd, "%s:%d", str, (int)rule->low.red);
	if (rule->low.red != rule->low.grn || rule->low.red != rule->low.blu)
	    fprintf(fd, ":%d:%d", rule->low.grn, rule->low.blu);
	/* even if low==high, write second end when the high is dmax */
	if (rule->high.value == dmax || rule->low.value != rule->high.value) {
	    if (rule->high.value == dmax)
		format_max(str, (double)rule->high.value);
	    else {
		sprintf(str, "%.15g", (double)rule->high.value);
		G_trim_decimal(str);
	    }
	    fprintf(fd, " %s:%d", str, (int)rule->high.red);
	    if (rule->high.red != rule->high.grn ||
		rule->high.red != rule->high.blu)
		fprintf(fd, ":%d:%d", rule->high.grn, rule->high.blu);
	}
	fprintf(fd, "\n");
    }
}
示例#11
0
int report_range(void)
{
    struct FPRange drange;
    struct Range range;
    char buff[1024], buff2[300];
    RASTER_MAP_TYPE inp_type;

    inp_type = Rast_map_type(name, "");
    if (inp_type != CELL_TYPE) {
	if (Rast_read_fp_range(name, "", &drange) <= 0)
	    G_fatal_error(_("Unable to read f_range for map %s"), name);

	Rast_get_fp_range_min_max(&drange, &old_dmin, &old_dmax);
	if (Rast_is_d_null_value(&old_dmin) || Rast_is_d_null_value(&old_dmax))
	    G_message(_("Data range is empty"));
	else {
	    sprintf(buff, "%.10f", old_dmin);
	    sprintf(buff2, "%.10f", old_dmax);
	    G_trim_decimal(buff);
	    G_trim_decimal(buff2);
	    G_message(_("Data range of %s is %s to %s (entire map)"), name,
		      buff, buff2);
	}
    }
    if (Rast_read_range(name, "", &range) <= 0)
	G_fatal_error(_("Unable to read range for map <%s>"), name);

    Rast_get_range_min_max(&range, &old_min, &old_max);
    if (Rast_is_c_null_value(&old_min) || Rast_is_c_null_value(&old_max))
	G_message(_("Integer data range of %s is empty"), name);
    else
	G_message(_("Integer data range of %s is %d to %d"),
		  name, (int)old_min, (int)old_max);

    return 0;
}
示例#12
0
static void write_new_colors(FILE * fd, struct Colors *colors)
{
    char str1[100], str2[100];

    format_min(str1, (double)colors->cmin);
    format_max(str2, (double)colors->cmax);
    fprintf(fd, "%% %s %s\n", str1, str2);

    if (colors->shift) {
	sprintf(str2, "%.15g", (double)colors->shift);
	G_trim_decimal(str2);
	fprintf(fd, "shift:%s\n", str2);
    }
    if (colors->invert)
	fprintf(fd, "invert\n");

    if (colors->null_set) {
	fprintf(fd, "nv:%d", colors->null_red);
	if (colors->null_red != colors->null_grn || colors->null_red
	    != colors->null_blu)
	    fprintf(fd, ":%d:%d", colors->null_grn, colors->null_blu);
	fprintf(fd, "\n");
    }
    if (colors->undef_set) {
	fprintf(fd, "*:%d", colors->undef_red);
	if (colors->undef_red != colors->undef_grn || colors->undef_red
	    != colors->undef_blu)
	    fprintf(fd, ":%d:%d", colors->undef_grn, colors->undef_blu);
	fprintf(fd, "\n");
    }
    if (colors->modular.rules) {
	fprintf(fd, "%s\n", "%%");
	write_rules(fd, colors->modular.rules, colors->cmin, colors->cmax);
	fprintf(fd, "%s\n", "%%");
    }
    if (colors->fixed.rules)
	write_rules(fd, colors->fixed.rules, colors->cmin, colors->cmax);
}
示例#13
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);
}
示例#14
0
/*!
  \brief Write data to GRASS ASCII vector format

  Prints message if some features without category are skipped.

  \param[out] ascii  pointer to the output ASCII file
  \param[out] att    att file (< version 5 only)
  \param Map    pointer to Map_info structure
  \param ver    version number 4 or 5
  \param format format GV_ASCII_FORMAT_POINT or GV_ASCII_FORMAT_STD
  \param dp     number of significant digits
  \param fs     field separator
  \param region_flag check region
  \param type   feature type filter
  \param field  field number
  \param Clist  list of categories to filter features or NULL
  \param where  SQL select where statement to filter features or NULL
  \param column_names array of columns to be included to the output or NULL
                 "*" as the first item in the array indicates all columns
  \param header TRUE to print also header

  \return number of written features
  \return -1 on error
*/
int Vect_write_ascii(FILE *ascii,
		     FILE *att, struct Map_info *Map, int ver,
		     int format, int dp, char *fs, int region_flag, int type,
		     int field, const struct cat_list *Clist, const char* where,
		     const char **column_names, int header)
{
    int ltype, ctype, i, cat, line, left, right, found;
    double *xptr, *yptr, *zptr, x, y;
    static struct line_pnts *Points;
    struct line_cats *Cats, *ACats;
    char *xstring, *ystring, *zstring;
    size_t xsize, ysize, zsize;
    struct Cell_head window;
    struct ilist *fcats;
    int count, n_skipped;

    /* where || columns */
    struct field_info *Fi;
    dbDriver *driver;
    dbValue value;
    dbHandle handle;
    int *cats, ncats, more;
    dbTable *Table;
    dbString dbstring;
    dbColumn *Column;
    dbValue *Value;
    char *buf;
    size_t bufsize;
    dbCursor cursor;
    /* columns */
    char **columns;
    int *coltypes;
    char *all_columns;
    
    Fi = NULL;
    driver = NULL;
    columns = NULL;
    coltypes = NULL;
    all_columns = NULL;
    
    G_zero(&value, sizeof(dbValue));
    db_init_string(&dbstring);

    xstring = NULL;
    ystring = NULL;
    zstring = NULL;
    xsize = 0;
    ysize = 0;
    zsize = 0;
    buf = NULL;
    bufsize = 0;

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

    count = ncats = 0;
    xstring = ystring = zstring = NULL;
    cats = NULL;
    
    if (field > 0 && (where || column_names)) {
	Fi = Vect_get_field(Map, field);
	if (!Fi) {
	    G_fatal_error(_("Database connection not defined for layer %d"),
			  field);
	}

	driver = db_start_driver(Fi->driver);
	if (!driver)
	    G_fatal_error(_("Unable to start driver <%s>"), Fi->driver);
	
	db_init_handle(&handle);
	db_set_handle(&handle, Fi->database, NULL);
	
	if (db_open_database(driver, &handle) != DB_OK)
	    G_fatal_error(_("Unable to open database <%s> by driver <%s>"),
			  Fi->database, Fi->driver);
	
	/* select cats (sorted array) */
	ncats = db_select_int(driver, Fi->table, Fi->key, where, &cats);
	G_debug(3, "%d categories selected from table <%s>", ncats, Fi->table);

	if (!column_names) {
	    db_close_database(driver);
	    db_shutdown_driver(driver);
	}
	else {
	    int icol, ncols;
	    const char *col_name;
            int len_all = 0;
            
	    db_set_string(&dbstring, Fi->table);
	    if (db_describe_table(driver, &dbstring, &Table) != DB_OK) {
		G_warning(_("Unable to describe table <%s>"), Fi->table);
		return -1;
	    }
	    
	    ncols = db_get_table_number_of_columns(Table);
	    columns = (char **) G_malloc((ncols + 1) * sizeof(char *));

            if (column_names[0] && strcmp(column_names[0], "*") == 0) {
                
                /* all columns */
                icol = 0;
                for (i = 0; i < ncols; i++) {
                    col_name = db_get_column_name(db_get_table_column(Table, i));
		    /* key column skipped */
                    if (strcmp(Fi->key, col_name) != 0)
			columns[icol++] = G_store(col_name);
                }
                columns[icol] = NULL;
            }
            else {
		int j;

		icol = 0;
		i = 0;
		while (column_names[i]) {
		    /* key column skipped */
                    if (strcmp(Fi->key, column_names[i]) != 0) {
			found = 0;
			for (j = 0; j < ncols; j++) {
			    col_name = db_get_column_name(db_get_table_column(Table, j));
			    if (strcmp(col_name, column_names[i]) == 0) {
				columns[icol++] = G_store(col_name);
				found = 1;
				break;
			    }
			}
			if (!found) {
			    G_warning(_("Column <%s> does not exist"),
				      column_names[i]);
			    G_important_message(_("Available columns:"));
			    for (j = 0; j < ncols; j++) {
				col_name = db_get_column_name(db_get_table_column(Table, j));
				G_important_message("%s", col_name);
			    }
			    G_warning(_("Export cancelled"));
			    db_close_database(driver);
			    db_shutdown_driver(driver);
			    return -1;
			}
		    }
		    i++;
                }
                columns[icol] = NULL;
            }

	    db_zero_string(&dbstring);
	    db_free_table(Table);
	    Table = NULL;
            
	    if (columns[0]) {
		/* selected columns only */
		i = 0;
		while (columns[i])
		    len_all += strlen(columns[i++]);
		
		coltypes = G_malloc(i * sizeof(int));
		
		all_columns = G_malloc(len_all + i + 2);

		i = 0;
		strcpy(all_columns, columns[0]);
		while (columns[i]) {
		    /* get column types */
		    coltypes[i] = db_column_Ctype(driver, Fi->table, columns[i]);
		    if (coltypes[i] < 0) {
			db_close_database(driver);
			db_shutdown_driver(driver);
			G_warning(_("Unknown type of column <%s>, export cancelled"),
				  columns[i]);
			return -1;
		    }
		    if (i > 0) {
			strcat(all_columns, ",");
			strcat(all_columns, columns[i]);
		    }
		    i++;
		}
	    }
	    else {
		/* no column or only key column selected */
		G_free(columns);
		columns = NULL;

		db_close_database(driver);
		db_shutdown_driver(driver);
	    }
	}
    }

    if (format == GV_ASCII_FORMAT_POINT && header) {

	/* print header */
	if (Map->head.with_z)
	    fprintf(ascii, "east%snorth%sheight%scat", fs, fs, fs);
	else
	    fprintf(ascii, "east%snorth%scat", fs, fs);
	if (columns) {
	    for (i = 0; columns[i]; i++) {
		if (db_select_value
		    (driver, Fi->table, Fi->key, cat,
		     columns[i], &value) < 0)
		    G_fatal_error(_("Unable to select record from table <%s> (key %s, column %s)"),
				  Fi->table, Fi->key, columns[i]);
		if (columns[i])
		    fprintf(ascii, "%s%s", fs, columns[i]);
		else
		    fprintf(ascii, "%s", columns[i]); /* can not happen */
	    }
	}
	fprintf(ascii, "%s", HOST_NEWLINE);
    }

    Points = Vect_new_line_struct();
    Cats = Vect_new_cats_struct();
    ACats = Vect_new_cats_struct();
    fcats = Vect_new_list();

    /* by default, read_next_line will NOT read Dead lines */
    /* but we can override that (in Level I only) by specifying */
    /* the type  -1, which means match all line types */

    Vect_rewind(Map);

    count = n_skipped = line = 0;
    while (TRUE) {
	ltype = Vect_read_next_line(Map, Points, Cats);
	if (ltype == -1 ) {      /* failure */
	    if (columns) {
		db_close_database(driver);
		db_shutdown_driver(driver);

                free_col_arrays(coltypes, all_columns,
                                column_names && strcmp(column_names[0], "*") == 0 ? columns : NULL);
	    }
	    
	    return -1;
	}

	if (ltype == -2)	{	/* EOF */
	    if (columns) {
		db_close_database(driver);
		db_shutdown_driver(driver);
                
                free_col_arrays(coltypes, all_columns,
                                column_names && strcmp(column_names[0], "*") == 0 ? columns : NULL);
	    }
	    break;
	}

	line++;

	if (!(ltype & type))
	    continue;

	if (format == GV_ASCII_FORMAT_POINT && !(ltype & GV_POINTS))
	    continue;

	found = get_cat(Cats, Clist, cats, ncats, field, &cat);

	if (!found && field > 0 && ltype == GV_BOUNDARY &&
	    type & GV_AREA && Vect_level(Map) > 1) {
	    Vect_get_line_areas(Map, line, &left, &right);
	    if (left < 0)
		left = Vect_get_isle_area(Map, abs(left));
	    if (left > 0) {
		Vect_get_area_cats(Map, left, ACats);
		found = get_cat(ACats, Clist, cats, ncats, field, &cat);
	    }
	    if (right < 0)
		right = Vect_get_isle_area(Map, abs(right));
	    if (!found && right > 0) {
		Vect_get_area_cats(Map, right, ACats);
		found = get_cat(ACats, Clist, cats, ncats, field, &cat);
	    }
	}
	
	if (!found) {
            if (Cats->n_cats < 1)
                n_skipped++;
            
	    continue;
	}

	if (ver < 5) {
	    Vect_cat_get(Cats, 1, &cat);
	}

	switch (ltype) {
	case GV_BOUNDARY:
	    if (ver == 5)
		ctype = 'B';
	    else
		ctype = 'A';
	    break;
	case GV_CENTROID:
	    if (ver < 5) {
		if (att != NULL) {
		    if (cat > 0) {
			G_rasprintf(&xstring, &xsize, "%.*f", dp, Points->x[0]);
			G_trim_decimal(xstring);
			G_rasprintf(&ystring, &ysize, "%.*f", dp, Points->y[0]);
			G_trim_decimal(ystring);
			fprintf(att, "A %s %s %d%s", xstring, ystring, cat, HOST_NEWLINE);
		    }
		}
		continue;
	    }
	    ctype = 'C';
	    break;
	case GV_LINE:
	    ctype = 'L';
	    break;
	case GV_POINT:
	    ctype = 'P';
	    break;
	case GV_FACE:
	    ctype = 'F';
	    break;
	case GV_KERNEL:
	    ctype = 'K';
	    break;
	default:
	    ctype = 'X';
	    G_warning(_("Unknown feature type %d"), (int)ltype);
	    break;
	}

	if (format == GV_ASCII_FORMAT_POINT) {
	    if (region_flag) {
		if ((window.east < Points->x[0]) ||
		    (window.west > Points->x[0]))
		    continue;
	    }
	    G_rasprintf(&xstring, &xsize, "%.*f", dp, Points->x[0]);
	    G_trim_decimal(xstring);

	    if (region_flag) {
		if ((window.north < Points->y[0]) ||
		    (window.south > Points->y[0]))
		    continue;
	    }
	    G_rasprintf(&ystring, &ysize, "%.*f", dp, Points->y[0]);
	    G_trim_decimal(ystring);

	    Vect_field_cat_get(Cats, field, fcats);

	    if (Map->head.with_z && ver == 5) {
		if (region_flag) {
		    if ((window.top < Points->z[0]) ||
			(window.bottom > Points->z[0]))
			continue;
		}
		G_rasprintf(&zstring, &zsize, "%.*f", dp, Points->z[0]);
		G_trim_decimal(zstring);
		fprintf(ascii, "%s%s%s%s%s", xstring, fs, ystring, fs,
			zstring);
	    }
	    else {
		fprintf(ascii, "%s%s%s", xstring, fs, ystring);
	    }

	    if (fcats->n_values > 0 && cat > -1) {
		if (fcats->n_values > 1) {
		    G_warning(_("Feature has more categories. Only one category (%d) "
				"is exported."), cat);
		}
		fprintf(ascii, "%s%d", fs, cat);
		
		/* print attributes */
		if (columns) {

		    G_rasprintf(&buf, &bufsize, "SELECT %s FROM %s WHERE %s = %d",
			    all_columns, Fi->table, Fi->key, cat);
		    G_debug(2, "SQL: %s", buf);
		    db_set_string(&dbstring, buf);

		    if (db_open_select_cursor
				    (driver, &dbstring, &cursor, DB_SEQUENTIAL) != DB_OK) {
			db_close_database(driver);
			db_shutdown_driver(driver);
			G_fatal_error(_("Cannot select attributes for cat = %d"),
			  cat);
		    }
		    if (db_fetch(&cursor, DB_NEXT, &more) != DB_OK) {
			db_close_database(driver);
			db_shutdown_driver(driver);
			G_fatal_error(_("Unable to fetch data from table"));
		    }

		    Table = db_get_cursor_table(&cursor);


		    for (i = 0; columns[i]; i++) {
			Column = db_get_table_column(Table, i);
			Value = db_get_column_value(Column);

			if (db_test_value_isnull(Value)) {
			    fprintf(ascii, "%s", fs);
			}
			else {
			    switch(coltypes[i])
			    {
			    case DB_C_TYPE_INT: {
				fprintf(ascii, "%s%d", fs, db_get_value_int(Value));
				break;
			    }
			    case DB_C_TYPE_DOUBLE: {
				fprintf(ascii, "%s%.*f", fs, dp, db_get_value_double(Value));
				break;
			    }
			    case DB_C_TYPE_STRING: {
				fprintf(ascii, "%s%s", fs, db_get_value_string(Value));
				break;
			    }
			    case DB_C_TYPE_DATETIME: {
				break;
			    }
			    case -1:
				G_fatal_error(_("Column <%s> not found in table <%s>"),
					      columns[i], Fi->table);
			    default: G_fatal_error(_("Column <%s>: unsupported data type"),
						   columns[i]);
			    }
			}
		    }
		    db_close_cursor(&cursor);
		}
	    }

	    fprintf(ascii, "%s", HOST_NEWLINE);
	}
	else if (format == GV_ASCII_FORMAT_STD) {
	    /* FORMAT_STANDARD */
	    if (ver == 5 && Cats->n_cats > 0)
		fprintf(ascii, "%c  %d %d%s", ctype, Points->n_points,
			Cats->n_cats, HOST_NEWLINE);
	    else
              fprintf(ascii, "%c  %d%s", ctype, Points->n_points, HOST_NEWLINE);

	    xptr = Points->x;
	    yptr = Points->y;
	    zptr = Points->z;

	    while (Points->n_points--) {

		G_rasprintf(&xstring, &xsize, "%.*f", dp, *xptr++);
		G_trim_decimal(xstring);
		G_rasprintf(&ystring, &ysize, "%.*f", dp, *yptr++);
		G_trim_decimal(ystring);

		if (ver == 5) {
		    if (Map->head.with_z) {
			G_rasprintf(&zstring, &zsize, "%.*f", dp, *zptr++);
			G_trim_decimal(zstring);
			fprintf(ascii, " %-12s %-12s %-12s%s", xstring,
				ystring, zstring, HOST_NEWLINE);
		    }
		    else {
                      fprintf(ascii, " %-12s %-12s%s", xstring, ystring, HOST_NEWLINE);
		    }
		}		/*Version 4 */
		else {
                    fprintf(ascii, " %-12s %-12s%s", ystring, xstring, HOST_NEWLINE);
		}
	    }

	    if (ver == 5) {
		for (i = 0; i < Cats->n_cats; i++) {
		    fprintf(ascii, " %-5d %-10d%s", Cats->field[i],
			    Cats->cat[i], HOST_NEWLINE);
		}
	    }
	    else {
		if (cat > -1) {
		    if (ltype == GV_POINT) {
			G_rasprintf(&xstring, &xsize, "%.*f", dp, Points->x[0]);
			G_trim_decimal(xstring);
			G_rasprintf(&ystring, &ysize, "%.*f", dp, Points->y[0]);
			G_trim_decimal(ystring);
			fprintf(att, "P %s %s %d%s", xstring, ystring, cat, HOST_NEWLINE);
		    }
		    else {
			x = (Points->x[1] + Points->x[0]) / 2;
			y = (Points->y[1] + Points->y[0]) / 2;

			G_rasprintf(&xstring, &xsize, "%.*f", dp, x);
			G_trim_decimal(xstring);
			G_rasprintf(&ystring, &ysize, "%.*f", dp, y);
			G_trim_decimal(ystring);
			fprintf(att, "L %s %s %d%s", xstring, ystring, cat, HOST_NEWLINE);
		    }
		}
	    }
	}
	else if (format == GV_ASCII_FORMAT_WKT) {
	    if (ltype & (GV_BOUNDARY | GV_CENTROID | GV_FACE | GV_KERNEL))
		continue;
	    /* Well-Known Text */
	    Vect_sfa_line_astext(Points, ltype, Vect_is_3d(Map), dp, ascii);
	    count++;
	}
	else {
	    G_fatal_error(_("Unknown format"));
	}
	count++;
    }

    if (format == GV_ASCII_FORMAT_WKT) {
	/* process areas - topology required */
	int i, area, nareas, isle, nisles;

	if (Vect_level(Map) < 2) {
	    G_warning(_("Topology not available, unable to process areas"));
	    nareas = 0;
	}
	else {
	    nareas = Vect_get_num_areas(Map);
	}
	for (area = 1; area <= nareas; area++) {
	    if (!Vect_area_alive(Map, area)) /* skip dead areas */
		continue;
	    if (Vect_get_area_cat(Map, area, field) < 0)
		continue;
	    /* get boundary -> linearring */
	    if (Vect_get_area_points(Map, area, Points) < 0) {
		G_warning(_("Unable to get boundary of area id %d"), area);
		continue;
	    }
	    fprintf(ascii, "POLYGON(");
	    /* write outter ring */
	    Vect_sfa_line_astext(Points, GV_BOUNDARY, 0, dp, ascii); /* boundary is always 2D */
	    /* get isles (holes) -> inner rings */
	    nisles = Vect_get_area_num_isles(Map, area);
	    for (i = 0; i < nisles; i++) {
		/* get isle boundary -> linearring */
		isle = Vect_get_area_isle(Map, area, i);
		if (Vect_get_isle_points(Map, isle, Points) < 0) {
		    G_warning(_("Unable to get boundary of isle id %d (area id %d)"), isle, area);
		    continue;
		}
		fprintf(ascii, ", ");
		/* write inner ring */
		Vect_sfa_line_astext(Points, GV_BOUNDARY, 0, dp, ascii); /* boundary is always 2D */
	    }
	    fprintf(ascii, ")%s", HOST_NEWLINE);
	    
	    count++;
	}
    }

    if (n_skipped > 0)
        G_important_message(_("%d features without category skipped. To export also "
                              "features without category use '%s=-1'."), n_skipped, "layer");
    
    Vect_destroy_line_struct(Points);
    Vect_destroy_cats_struct(Cats);
    Vect_destroy_cats_struct(ACats);
    
    return count;
}
示例#15
0
int main(int argc, char *argv[])
{
    void *raster, *ptr;

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

    G_gisinit(argv[0]);

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

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

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

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

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

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

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

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


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

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

    sprintf(null_str, "-9999");

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

    map_type = Rast_get_map_type(fd);
    out_type = map_type;

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

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

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

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

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

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

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

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

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

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

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

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

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

    Rast_close(fd);
    fclose(fp);

    exit(EXIT_SUCCESS);
}
示例#16
0
/* cloned from lib/gis/wind_format.c */
void format_double(double value, char *buf)
{
    sprintf(buf, "%.8f", value);
    G_trim_decimal(buf);
}
示例#17
0
文件: stats.c 项目: imincik/pkg-grass
int print_stats_table(univar_stat * stats)
{
    unsigned int i;
    int z, n_zones = zone_info.n_zones;

    if (n_zones == 0)
	n_zones = 1;

    /* print column headers */

    if (zone_info.n_zones) {
	fprintf(stdout, "zone%s", zone_info.sep);
	fprintf(stdout, "label%s", zone_info.sep);
    }
    fprintf(stdout, "non_null_cells%s", zone_info.sep);
    fprintf(stdout, "null_cells%s", zone_info.sep);
    fprintf(stdout, "min%s", zone_info.sep);
    fprintf(stdout, "max%s", zone_info.sep);
    fprintf(stdout, "range%s", zone_info.sep);
    fprintf(stdout, "mean%s", zone_info.sep);
    fprintf(stdout, "mean_of_abs%s", zone_info.sep);
    fprintf(stdout, "stddev%s", zone_info.sep);
    fprintf(stdout, "variance%s", zone_info.sep);
    fprintf(stdout, "coeff_var%s", zone_info.sep);
    fprintf(stdout, "sum%s", zone_info.sep);
    fprintf(stdout, "sum_abs");

    if (param.extended->answer) {
	fprintf(stdout, "%sfirst_quart", zone_info.sep);
	fprintf(stdout, "%smedian", zone_info.sep);
	fprintf(stdout, "%sthird_quart", zone_info.sep);
	for (i = 0; i < stats[0].n_perc; i++) {

	    if (stats[0].perc[i] == (int)stats[0].perc[i]) {
		/* percentile is an exact integer */
		fprintf(stdout, "%sperc_%d", zone_info.sep, (int)stats[0].perc[i]);
	    }
	    else {
		/* percentile is not an exact integer */

		char buf[24];
		sprintf(buf, "%.15g", stats[0].perc[i]);
		G_strchg(buf, '.', '_');
		fprintf(stdout, "%sperc_%s", zone_info.sep, buf);
	    }
	}
    }
    fprintf(stdout, "\n");

    /* print stats */

    for (z = 0; z < n_zones; z++) {
	char sum_str[100];
	double mean, variance, stdev, var_coef;

	/* for extendet stats */
	double quartile_25 = 0.0, quartile_75 = 0.0, *quartile_perc;
	double median = 0.0;
	int qpos_25, qpos_75, *qpos_perc;

	/* stats collected for this zone? */
	if (stats[z].n == 0)
	    continue;

	i = 0;

	/* all these calculations get promoted to doubles, so any DIV0 becomes nan */
	mean = stats[z].sum / stats[z].n;
	variance = (stats[z].sumsq - stats[z].sum * stats[z].sum / stats[z].n) / stats[z].n;
	if (variance < GRASS_EPSILON)
	    variance = 0.0;
	stdev = sqrt(variance);
	var_coef = (stdev / mean) * 100.;	/* perhaps stdev/fabs(mean) ? */

	if (zone_info.n_zones) {
	    /* zone number */
	    fprintf(stdout, "%d%s", z + zone_info.min, zone_info.sep);
	    /* zone label */
	    fprintf(stdout,"%s%s", G_get_cat(z + zone_info.min, &(zone_info.cats)), zone_info.sep);
	}

	/* non-null cells cells */
	fprintf(stdout, "%d%s", stats[z].n, zone_info.sep);
	/* null cells */
	fprintf(stdout, "%d%s", stats[z].size - stats[z].n, zone_info.sep);
	/* min */
	fprintf(stdout, "%.15g%s", stats[z].min, zone_info.sep);
	/* max */
	fprintf(stdout, "%.15g%s", stats[z].max, zone_info.sep);
	/* range */
	fprintf(stdout, "%.15g%s", stats[z].max - stats[z].min, zone_info.sep);
	/* mean */
	fprintf(stdout, "%.15g%s", mean, zone_info.sep);
	/* mean of abs */
	fprintf(stdout, "%.15g%s", stats[z].sum_abs / stats[z].n, zone_info.sep);
	/* stddev */
	fprintf(stdout, "%.15g%s", stdev, zone_info.sep);
	/* variance */
	fprintf(stdout, "%.15g%s", variance, zone_info.sep);
	/* coefficient of variance */
	fprintf(stdout, "%.15g%s", var_coef, zone_info.sep);
	/* sum */
	sprintf(sum_str, "%.15g", stats[z].sum);
	G_trim_decimal(sum_str);
	fprintf(stdout, "%s%s", sum_str, zone_info.sep);
	/* absolute sum */
	sprintf(sum_str, "%.15g", stats[z].sum_abs);
	G_trim_decimal(sum_str);
	fprintf(stdout, "%s", sum_str);

	/* TODO: mode, skewness, kurtosis */
	if (param.extended->answer) {
	    qpos_perc = (int *)G_calloc(stats[z].n_perc, sizeof(int));
	    quartile_perc = (double *)G_calloc(stats[z].n_perc, sizeof(double));
	    for (i = 0; i < stats[z].n_perc; i++) {
		qpos_perc[i] = (int)(stats[z].n * 1e-2 * stats[z].perc[i] - 0.5);
	    }
	    qpos_25 = (int)(stats[z].n * 0.25 - 0.5);
	    qpos_75 = (int)(stats[z].n * 0.75 - 0.5);

	    switch (stats[z].map_type) {
	    case CELL_TYPE:
		heapsort_int(stats[z].cell_array, stats[z].n);

		quartile_25 = (double)stats[z].cell_array[qpos_25];
		if (stats[z].n % 2)	/* odd */
		    median = (double)stats[z].cell_array[(int)(stats[z].n / 2)];
		else		/* even */
		    median =
			(double)(stats[z].cell_array[stats[z].n / 2 - 1] +
				 stats[z].cell_array[stats[z].n / 2]) / 2.0;
		quartile_75 = (double)stats[z].cell_array[qpos_75];
		for (i = 0; i < stats[z].n_perc; i++) {
		    quartile_perc[i] = (double)stats[z].cell_array[qpos_perc[i]];
		}
		break;

	    case FCELL_TYPE:
		heapsort_float(stats[z].fcell_array, stats[z].n);

		quartile_25 = (double)stats[z].fcell_array[qpos_25];
		if (stats[z].n % 2)	/* odd */
		    median = (double)stats[z].fcell_array[(int)(stats[z].n / 2)];
		else		/* even */
		    median =
			(double)(stats[z].fcell_array[stats[z].n / 2 - 1] +
				 stats[z].fcell_array[stats[z].n / 2]) / 2.0;
		quartile_75 = (double)stats[z].fcell_array[qpos_75];
		for (i = 0; i < stats[z].n_perc; i++) {
		    quartile_perc[i] = (double)stats[z].fcell_array[qpos_perc[i]];
		}
		break;

	    case DCELL_TYPE:
		heapsort_double(stats[z].dcell_array, stats[z].n);

		quartile_25 = stats[z].dcell_array[qpos_25];
		if (stats[z].n % 2)	/* odd */
		    median = stats[z].dcell_array[(int)(stats[z].n / 2)];
		else		/* even */
		    median =
			(stats[z].dcell_array[stats[z].n / 2 - 1] +
			 stats[z].dcell_array[stats[z].n / 2]) / 2.0;
		quartile_75 = stats[z].dcell_array[qpos_75];
		for (i = 0; i < stats[z].n_perc; i++) {
		    quartile_perc[i] = stats[z].dcell_array[qpos_perc[i]];
		}
		break;

	    default:
		break;
	    }

	    /* first quartile */
	    fprintf(stdout, "%s%g", zone_info.sep, quartile_25);
	    /* median */
	    fprintf(stdout, "%s%g", zone_info.sep, median);
	    /* third quartile */
	    fprintf(stdout, "%s%g", zone_info.sep, quartile_75);
	    /* percentiles */
	    for (i = 0; i < stats[z].n_perc; i++) {
		fprintf(stdout, "%s%g", zone_info.sep , 
			quartile_perc[i]);
	    }

	    G_free((void *)quartile_perc);
	    G_free((void *)qpos_perc);
	}

	fprintf(stdout, "\n");

	/* zone z finished */

    }

    return 1;
}
示例#18
0
文件: stats.c 项目: imincik/pkg-grass
/* *************************************************************** */
int print_stats(univar_stat * stats)
{
    int z, n_zones = zone_info.n_zones;

    if (n_zones == 0)
	n_zones = 1;

    for (z = 0; z < n_zones; z++) {
	char sum_str[100];
	double mean, variance, stdev, var_coef;

	/* for extendet stats */
	double quartile_25 = 0.0, quartile_75 = 0.0, *quartile_perc;
	double median = 0.0;
	unsigned int i;
	int qpos_25, qpos_75, *qpos_perc;

	/* stats collected for this zone? */
	if (stats[z].n == 0)
	    continue;

	/* all these calculations get promoted to doubles, so any DIV0 becomes nan */
	mean = stats[z].sum / stats[z].n;
	variance = (stats[z].sumsq - stats[z].sum * stats[z].sum / stats[z].n) / stats[z].n;
	if (variance < GRASS_EPSILON)
	    variance = 0.0;
	stdev = sqrt(variance);
	var_coef = (stdev / mean) * 100.;	/* perhaps stdev/fabs(mean) ? */

	sprintf(sum_str, "%.15g", stats[z].sum);
	G_trim_decimal(sum_str);

	if (zone_info.n_zones)
	    fprintf(stdout, "\nzone %d %s\n\n", z + zone_info.min, G_get_cat(z + zone_info.min, &(zone_info.cats)));

	if (!param.shell_style->answer) {
	    fprintf(stdout, "total null and non-null cells: %d\n", stats[z].size);
	    fprintf(stdout, "total null cells: %d\n\n", stats[z].size - stats[z].n);
	    fprintf(stdout, "Of the non-null cells:\n----------------------\n");
	}

	if (param.shell_style->answer) {
	    fprintf(stdout, "n=%d\n", stats[z].n);
	    fprintf(stdout, "null_cells=%d\n", stats[z].size - stats[z].n);
	    fprintf(stdout, "cells=%d\n", stats->size);
	    fprintf(stdout, "min=%.15g\n", stats[z].min);
	    fprintf(stdout, "max=%.15g\n", stats[z].max);
	    fprintf(stdout, "range=%.15g\n", stats[z].max - stats[z].min);
	    fprintf(stdout, "mean=%.15g\n", mean);
	    fprintf(stdout, "mean_of_abs=%.15g\n", stats[z].sum_abs / stats[z].n);
	    fprintf(stdout, "stddev=%.15g\n", stdev);
	    fprintf(stdout, "variance=%.15g\n", variance);
	    fprintf(stdout, "coeff_var=%.15g\n", var_coef);
	    fprintf(stdout, "sum=%s\n", sum_str);
	}
	else {
	    fprintf(stdout, "n: %d\n", stats[z].n);
	    fprintf(stdout, "minimum: %g\n", stats[z].min);
	    fprintf(stdout, "maximum: %g\n", stats[z].max);
	    fprintf(stdout, "range: %g\n", stats[z].max - stats[z].min);
	    fprintf(stdout, "mean: %g\n", mean);
	    fprintf(stdout, "mean of absolute values: %g\n",
		    stats[z].sum_abs / stats[z].n);
	    fprintf(stdout, "standard deviation: %g\n", stdev);
	    fprintf(stdout, "variance: %g\n", variance);
	    fprintf(stdout, "variation coefficient: %g %%\n", var_coef);
	    fprintf(stdout, "sum: %s\n", sum_str);
	}


	/* TODO: mode, skewness, kurtosis */
	if (param.extended->answer) {
	    qpos_perc = (int *)G_calloc(stats[z].n_perc, sizeof(int));
	    quartile_perc = (double *)G_calloc(stats[z].n_perc, sizeof(double));
	    for (i = 0; i < stats[z].n_perc; i++) {
		qpos_perc[i] = (int)(stats[z].n * 1e-2 * stats[z].perc[i] - 0.5);
	    }
	    qpos_25 = (int)(stats[z].n * 0.25 - 0.5);
	    qpos_75 = (int)(stats[z].n * 0.75 - 0.5);

	    switch (stats[z].map_type) {
	    case CELL_TYPE:
		heapsort_int(stats[z].cell_array, stats[z].n);

		quartile_25 = (double)stats[z].cell_array[qpos_25];
		if (stats[z].n % 2)	/* odd */
		    median = (double)stats[z].cell_array[(int)(stats[z].n / 2)];
		else		/* even */
		    median =
			(double)(stats[z].cell_array[stats[z].n / 2 - 1] +
				 stats[z].cell_array[stats[z].n / 2]) / 2.0;
		quartile_75 = (double)stats[z].cell_array[qpos_75];
		for (i = 0; i < stats[z].n_perc; i++) {
		    quartile_perc[i] = (double)stats[z].cell_array[qpos_perc[i]];
		}
		break;

	    case FCELL_TYPE:
		heapsort_float(stats[z].fcell_array, stats[z].n);

		quartile_25 = (double)stats[z].fcell_array[qpos_25];
		if (stats[z].n % 2)	/* odd */
		    median = (double)stats[z].fcell_array[(int)(stats[z].n / 2)];
		else		/* even */
		    median =
			(double)(stats[z].fcell_array[stats[z].n / 2 - 1] +
				 stats[z].fcell_array[stats[z].n / 2]) / 2.0;
		quartile_75 = (double)stats[z].fcell_array[qpos_75];
		for (i = 0; i < stats[z].n_perc; i++) {
		    quartile_perc[i] = (double)stats[z].fcell_array[qpos_perc[i]];
		}
		break;

	    case DCELL_TYPE:
		heapsort_double(stats[z].dcell_array, stats[z].n);

		quartile_25 = stats[z].dcell_array[qpos_25];
		if (stats[z].n % 2)	/* odd */
		    median = stats[z].dcell_array[(int)(stats[z].n / 2)];
		else		/* even */
		    median =
			(stats[z].dcell_array[stats[z].n / 2 - 1] +
			 stats[z].dcell_array[stats[z].n / 2]) / 2.0;
		quartile_75 = stats[z].dcell_array[qpos_75];
		for (i = 0; i < stats[z].n_perc; i++) {
		    quartile_perc[i] = stats[z].dcell_array[qpos_perc[i]];
		}
		break;

	    default:
		break;
	    }

	    if (param.shell_style->answer) {
		fprintf(stdout, "first_quartile=%g\n", quartile_25);
		fprintf(stdout, "median=%g\n", median);
		fprintf(stdout, "third_quartile=%g\n", quartile_75);
		for (i = 0; i < stats[z].n_perc; i++) {
		    char buf[24];
		    sprintf(buf, "%.15g", stats[z].perc[i]);
		    G_strchg(buf, '.', '_');
		    fprintf(stdout, "percentile_%s=%g\n", buf, quartile_perc[i]);
		}
	    }
	    else {
		fprintf(stdout, "1st quartile: %g\n", quartile_25);
		if (stats[z].n % 2)
		    fprintf(stdout, "median (odd number of cells): %g\n", median);
		else
		    fprintf(stdout, "median (even number of cells): %g\n",
			    median);
		fprintf(stdout, "3rd quartile: %g\n", quartile_75);


		for (i = 0; i < stats[z].n_perc; i++) {
		    if (stats[z].perc[i] == (int)stats[z].perc[i]) {
			/* percentile is an exact integer */
			if ((int)stats[z].perc[i] % 10 == 1 && (int)stats[z].perc[i] != 11)
			    fprintf(stdout, "%dst percentile: %g\n", (int)stats[z].perc[i],
				    quartile_perc[i]);
			else if ((int)stats[z].perc[i] % 10 == 2 && (int)stats[z].perc[i] != 12)
			    fprintf(stdout, "%dnd percentile: %g\n", (int)stats[z].perc[i],
				    quartile_perc[i]);
			else if ((int)stats[z].perc[i] % 10 == 3 && (int)stats[z].perc[i] != 13)
			    fprintf(stdout, "%drd percentile: %g\n", (int)stats[z].perc[i],
				    quartile_perc[i]);
			else
			    fprintf(stdout, "%dth percentile: %g\n", (int)stats[z].perc[i],
				    quartile_perc[i]);
		    }
		    else {
			/* percentile is not an exact integer */
			fprintf(stdout, "%.15g percentile: %g\n", stats[z].perc[i],
				quartile_perc[i]);
		    }
		}
	    }
	    G_free((void *)quartile_perc);
	    G_free((void *)qpos_perc);
	}

	/* G_message() prints to stderr not stdout: disabled. this \n is printed above with zone */
	/* if (!(param.shell_style->answer))
	    G_message("\n"); */
    }

    return 1;
}