コード例 #1
0
ファイル: main.c プロジェクト: rashadkm/grass_cmake
static void do_reclass(const char *basemap, char **outputs)
{
    const char *tempfile = G_tempfile();
    char *input_arg = G_malloc(strlen(basemap) + 7);
    char *rules_arg = G_malloc(strlen(tempfile) + 7);
    int quant;

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

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

    for (quant = 0; quant < num_quants; quant++) {
	const char *output = outputs[quant];
	char *output_arg = G_malloc(strlen(output) + 8);
	FILE *fp;
	int cat;

	sprintf(output_arg, "output=%s", output);

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

	for (cat = 0; cat < num_cats; cat++)
	    fprintf(fp, "%d = %d %f\n", min + cat, min + cat, basecats[cat].quants[quant]);

	fclose(fp);

	G_spawn("r.reclass", "r.reclass", input_arg, output_arg, rules_arg, NULL);
    }

    remove(tempfile);
}
コード例 #2
0
char* Create_segment_file (int nrows, int fract, RASTER_MAP_TYPE data_type)
{
    int seg_fd;
    char* seg_name;
    int ncols;
    int submatrix_rows, submatrix_cols; 
    int length_data_item = 0;
    int seg_error;

    ncols = G_window_cols ();
	if (data_type == CELL_TYPE) length_data_item = sizeof (CELL);
	if (data_type == FCELL_TYPE) length_data_item = sizeof (FCELL);
	if (data_type == DCELL_TYPE) length_data_item = sizeof (DCELL);	
    submatrix_rows = nrows/fract + 1;
    submatrix_cols = ncols/fract + 1;
    seg_name = G_tempfile ();
    seg_fd = creat (seg_name, 0666);
	
	/* create a new segment file on disk */
	/* size of data items (CELL, DCELL, FCELL ...) is stored in the file header */
    seg_error = segment_format (seg_fd, nrows, ncols,
		    submatrix_rows, submatrix_cols, length_data_item); 
	
	if ( seg_error != 1 ) {
		G_fatal_error ("Cannot create segment file(s).\nCheck available diskspace and access rights.");
	}
    close (seg_fd);
	
    return seg_name;
}
コード例 #3
0
ファイル: ls_cameras.c プロジェクト: AsherBond/MondocosmOS
int I_list_cameras(int full)
{
    char *element;
    char buf[1024];
    char title[50];
    FILE *ls, *temp;
    int any;

    if (tempfile == NULL)
	tempfile = G_tempfile();

    element = "camera";
    G__make_mapset_element(element);

    temp = fopen(tempfile, "w");
    if (temp == NULL)
	G_fatal_error("can't open any temp files");
    fprintf(temp, "Available cameras\n");
    fprintf(temp, "---------------------------------\n");

    any = 0;
    strcpy(buf, "cd ");
    G_file_name(buf + strlen(buf), element, "", G_mapset());
    strcat(buf, ";ls");
    if (!full)
	strcat(buf, " -C");
    if (ls = popen(buf, "r")) {
	while (G_getl(buf, sizeof buf, ls)) {
	    any = 1;
	    fprintf(temp, "%s", buf);
	    if (full) {
		I_get_cam_title(buf, title, sizeof title);
		if (*title)
		    fprintf(temp, " (%s)", title);
		fprintf(temp, "\n");
	    }
	    else
		fprintf(temp, "\n");
	}
	pclose(ls);
    }
    if (!any)
	fprintf(temp, "no camera files available\n");
    fprintf(temp, "---------------------------------\n");
    fclose(temp);
    sprintf(buf, "$GRASS_PAGER %s", tempfile);
    G_system(buf);
    unlink(tempfile);
    fprintf(stderr, "hit RETURN to continue -->");
    G_gets(buf);

    return 0;
}
コード例 #4
0
ファイル: dseg_open.c プロジェクト: GRASS-GIS/grass-ci
int dseg_open(DSEG * dseg, int srows, int scols, int nsegs_in_memory)
{
    char *filename;
    int errflag;
    int fd;

    dseg->filename = NULL;
    dseg->fd = -1;
    dseg->name = NULL;
    dseg->mapset = NULL;

    filename = G_tempfile();
    if (-1 == (fd = creat(filename, 0666))) {
	G_warning("dseg_open(): unable to create segment file");
	return -2;
    }
    if (0 >
	(errflag =
	 Segment_format(fd, Rast_window_rows(), Rast_window_cols(), srows, scols,
			sizeof(double)))) {
	close(fd);
	unlink(filename);
	if (errflag == -1) {
	    G_warning("dseg_open(): could not write segment file");
	    return -1;
	}
	else {
	    G_warning("dseg_open(): illegal configuration parameter(s)");
	    return -3;
	}
    }
    close(fd);
    if (-1 == (fd = open(filename, 2))) {
	unlink(filename);
	G_warning("dseg_open(): unable to re-open segment file");
	return -4;
    }
    if (0 > (errflag = Segment_init(&(dseg->seg), fd, nsegs_in_memory))) {
	close(fd);
	unlink(filename);
	if (errflag == -1) {
	    G_warning("dseg_open(): could not read segment file");
	    return -5;
	}
	else {
	    G_warning("dseg_open(): out of memory");
	    return -6;
	}
    }
    dseg->filename = filename;
    dseg->fd = fd;
    return 0;
}
コード例 #5
0
ファイル: sseg_open.c プロジェクト: AsherBond/MondocosmOS
int
seg_open(SSEG * sseg, int nrows, int ncols, int row_in_seg, int col_in_seg,
	 int nsegs_in_memory, int size_struct)
{
    char *filename;
    int errflag;
    int fd;

    sseg->filename = NULL;
    sseg->fd = -1;

    filename = G_tempfile();
    if (-1 == (fd = creat(filename, 0666))) {
	G_warning("seg_open(): unable to create segment file");
	return -2;
    }
    if (0 > (errflag = segment_format(fd, nrows, ncols,
				      row_in_seg, col_in_seg, size_struct))) {
	close(fd);
	unlink(filename);
	if (errflag == -1) {
	    G_warning("seg_open(): could not write segment file");
	    return -1;
	}
	else {
	    G_warning("seg_open(): illegal configuration parameter(s)");
	    return -3;
	}
    }
    close(fd);
    if (-1 == (fd = open(filename, 2))) {
	unlink(filename);
	G_warning("seg_open(): unable to re-open segment file");
	return -4;
    }
    if (0 > (errflag = segment_init(&(sseg->seg), fd, nsegs_in_memory))) {
	close(fd);
	unlink(filename);
	if (errflag == -1) {
	    G_warning("seg_open(): could not read segment file");
	    return -5;
	}
	else {
	    G_warning("seg_open(): out of memory");
	    return -6;
	}
    }
    sseg->filename = filename;
    sseg->fd = fd;
    return 0;
}
コード例 #6
0
ファイル: ls_elev.c プロジェクト: imincik/pkg-grass
int I_list_elev(int full)
{
    char *element;
    char buf[1024];
    FILE *ls, *temp;
    int any;

    if (tempfile == NULL)
	tempfile = G_tempfile();

    element = "cell";
    G__make_mapset_element(element);

    temp = fopen(tempfile, "w");
    if (temp == NULL)
	G_fatal_error("can't open any temp files");
    fprintf(temp, "Available raster maps:\n");
    fprintf(temp, "---------------------------------\n");

    any = 0;
    strcpy(buf, "cd ");
    G__file_name(buf + strlen(buf), element, " ", " ");
    strcat(buf, ";ls");
    strcat(buf, " -C");
    if ((ls = popen(buf, "r"))) {
	while (G_getl(buf, sizeof buf, ls)) {
	    any = 1;
	    fprintf(temp, "%s", buf);
	    fprintf(temp, "\n");
	}
	pclose(ls);
    }
    if (!any)
	fprintf(temp, "no raster maps available\n");
    fprintf(temp, "---------------------------------\n");
    fclose(temp);
    sprintf(buf, "$GRASS_PAGER %s", tempfile);
    G_system(buf);
    unlink(tempfile);
    fprintf(stderr, "hit RETURN to continue -->");
    G_gets(buf);

/******/
    G_list_element("cell", "cell", G_mapset(), NULL);


    return 0;
}
コード例 #7
0
int accept(void)
{
    if (sessionfile == NULL) {
        *cur = 0;
        sessionfile = G_tempfile();
        fd = fopen(sessionfile, "w");
        if (fd == NULL) {
            error("session file", "", "can't open");
            return 1;
        }
    }
    if (fd != NULL && *cur) {
        fprintf(fd, "%s\n", cur);
        fflush(fd);
        *cur = 0;
    }

    return 0;
}
コード例 #8
0
ファイル: r_plt.c プロジェクト: AsherBond/MondocosmOS
int add_to_plfile(char *buf)
{
    FILE *fd;

    if (PS.plfile == NULL) {
	PS.plfile = G_tempfile();
	fd = fopen(PS.plfile, "w");
    }
    else
	fd = fopen(PS.plfile, "a");
    if (fd != NULL) {
	fprintf(fd, "%s\n", buf);
	fclose(fd);
    }
    else
	error("point/line file", "", "can't open");

    return 0;
}
コード例 #9
0
ファイル: rast_segment.c プロジェクト: rkrug/grass-ci
void rast_segment_open(SEGMENT * segment, const char *name,
                       RASTER_MAP_TYPE * map_type)
{
    /* TODO: check if not passing the mapset is OK */
    int rowio = Rast_open_old(name, "");

    *map_type = Rast_get_map_type(rowio);
    int segment_rows = 64;

    /* we use long segments because this is how the values a binned */
    int segment_cols = Rast_input_window_cols();
    int segments_in_memory = 4;

    if (Segment_open(segment, G_tempfile(), Rast_input_window_rows(),
                     Rast_input_window_cols(), segment_rows, segment_cols,
                     Rast_cell_size(*map_type), segments_in_memory) != 1)
        G_fatal_error(_("Cannot create temporary file with segments of a raster map"));
    rast_segment_load(segment, rowio, *map_type);
    Rast_close(rowio);          /* we won't need the raster again */
}
コード例 #10
0
ファイル: main.c プロジェクト: caomw/grass
static int use_r_out(void)
{
    char *mpfilename;
    int ret;

    mpfilename = G_tempfile();
    write_params(mpfilename, vfiles[0], outfile, frames, quality, 0, 0, 1);

    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, NULL, 0);

    return (1);
}
コード例 #11
0
ファイル: main.c プロジェクト: AsherBond/MondocosmOS
static FILE *create_temp_file(const char *name, char **tmpname)
{
    FILE *fp;
    char *tmp;
    int i;

    if (!name)
	return NULL;

    *tmpname = tmp = G_tempfile();
    fp = fopen(tmp, "w+");
    if (!fp)
	G_fatal_error(_("Unable to open temporary file <%s>"), *tmpname);

    for (i = 0; i < nsizr; i++) {
	if (fwrite(zero_array_cell, sizeof(FCELL), nsizc, fp) != nsizc) {
	    clean();
	    G_fatal_error(_("Error writing temporary file <%s>"), *tmpname);
	}
    }

    return fp;
}
コード例 #12
0
ファイル: main.c プロジェクト: 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;
}
コード例 #13
0
ファイル: io.c プロジェクト: AsherBond/MondocosmOS
int open_file(char *name)
{
    int cell_file, buf_len;
    int i, row;
    CELL *buf;

    /* open raster map */
    cell_file = Rast_open_old(name, "");
    
    if (Rast_get_map_type(cell_file) != CELL_TYPE) {
	Rast_close(cell_file);
	G_fatal_error(_("Input raster must be of type CELL."));
    }

    n_rows = Rast_window_rows();
    n_cols = Rast_window_cols();
    G_message(_("File %s -- %d rows X %d columns"), name, n_rows, n_cols);
    n_cols += (PAD << 1);

    /* copy raster map into our read/write file */
    work_file_name = G_tempfile();

    /* create the file and then open it for read and write */
    close(creat(work_file_name, 0666));
    if ((work_file = open(work_file_name, 2)) < 0) {
	unlink(work_file_name);
	G_fatal_error(_("%s: Unable to create temporary file <%s> -- errno = %d"),
		      error_prefix, work_file_name, errno);
    }
    buf_len = n_cols * sizeof(CELL);
    buf = (CELL *) G_malloc(buf_len);
    Rast_set_c_null_value(buf, n_cols);
    for (i = 0; i < PAD; i++) {
	if (write(work_file, buf, buf_len) != buf_len) {
	    unlink(work_file_name);
	    G_fatal_error(_("%s: Error writing temporary file"),
			  error_prefix);
	}
    }
    for (row = 0; row < n_rows; row++) {
	Rast_get_c_row(cell_file, buf + PAD, row);
	if (write(work_file, buf, buf_len) != buf_len) {
	    unlink(work_file_name);
	    G_fatal_error(_("%s: Error writing temporary file"),
			  error_prefix);
	}
    }

    Rast_set_c_null_value(buf, n_cols);

    for (i = 0; i < PAD; i++) {
	if (write(work_file, buf, buf_len) != buf_len) {
	    unlink(work_file_name);
	    G_fatal_error(_("%s: Error writing temporary file"),
			  error_prefix);
	}
    }
    n_rows += (PAD << 1);
    G_free(buf);
    Rast_close(cell_file);
    Rowio_setup(&row_io, work_file, MAX_ROW, n_cols * sizeof(CELL), read_row,
		write_row);

    return 0;
}
コード例 #14
0
ファイル: main.c プロジェクト: AsherBond/MondocosmOS
int main(int argc, char **argv)
{
    int fe, fd, fm;
    int i, j, type;
    int new_id;
    int nrows, ncols, nbasins;
    int map_id, dir_id, bas_id;
    char map_name[GNAME_MAX], new_map_name[GNAME_MAX];
    const char *tempfile1, *tempfile2, *tempfile3;
    char dir_name[GNAME_MAX];
    char bas_name[GNAME_MAX];

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    in_buf = get_buf();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	Rast_close(bas_id);
	close(fm);
    }

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

	read(fd, out_buf, bufsz);

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

	Rast_put_row(dir_id, out_buf, CELL_TYPE);

    }

    Rast_close(new_id);
    close(fe);

    Rast_close(dir_id);
    close(fd);

    G_free(in_buf);
    G_free(out_buf);

    exit(EXIT_SUCCESS);
}
コード例 #15
0
ファイル: open.c プロジェクト: AsherBond/MondocosmOS
void *Rast3d_open_cell_new(const char *name, int typeIntern, int cache,
		      RASTER3D_Region * region)
{
    RASTER3D_Map *map;
    int nofHeaderBytes, dummy = 0, compression, precision;
    long ldummy = 0;
    char xname[GNAME_MAX], xmapset[GMAPSET_MAX];

    Rast3d_init_defaults();
    if (!Rast3d_mask_open_old()) {
	Rast3d_error(_("Rast3d_open_cell_new: error in Rast3d_mask_open_old"));
	return (void *)NULL;
    }

    compression = g3d_do_compression;
    precision = g3d_precision;

    map = Rast3d_malloc(sizeof(RASTER3D_Map));
    if (map == NULL) {
	Rast3d_error(_("Rast3d_open_cell_new: error in Rast3d_malloc"));
	return (void *)NULL;
    }

    if (G_unqualified_name(name, G_mapset(), xname, xmapset) < 0) {
	G_warning(_("map <%s> is not in the current mapset"), name);
	return (void *)NULL;
    }

    map->fileName = G_store(xname);
    map->mapset = G_store(xmapset);

    map->tempName = G_tempfile();
    map->data_fd = open(map->tempName, O_RDWR | O_CREAT | O_TRUNC, 0666);
    if (map->data_fd < 0) {
	Rast3d_error(_("Rast3d_open_cell_new: could not open file"));
	return (void *)NULL;
    }

    Rast3d_make_mapset_map_directory(map->fileName);

    map->useXdr = RASTER3D_USE_XDR;

    if (g3d_file_type == FCELL_TYPE) {
	if (precision > 23)
	    precision = 23;	/* 32 - 8 - 1 */
	else if (precision < -1)
	    precision = 0;
    }
    else if (precision > 52)
	precision = 52;		/* 64 - 11 - 1 */
    else if (precision < -1)
	precision = 0;

    /* no need to write trailing zeros */
    if ((typeIntern == FCELL_TYPE) && (g3d_file_type == DCELL_TYPE)) {
	if (precision == -1)
	    precision = 23;
	else
	    precision = RASTER3D_MIN(precision, 23);
    }

    if (compression == RASTER3D_NO_COMPRESSION)
	precision = RASTER3D_MAX_PRECISION;
    if (compression == RASTER3D_COMPRESSION)
	map->useXdr = RASTER3D_USE_XDR;

    if (RASTER3D_HAS_INDEX) {
	map->indexLongNbytes = sizeof(long);

	/* at the beginning of the file write */
	/*      nof bytes of "long" */
	/*      max nof bytes used for index */
	/*      position of index in file */
	/* the index is appended at the end of the file at closing time. since */
	/* we do not know this position yet we write dummy values */

	if ((!Rast3d_write_ints(map->data_fd, map->useXdr,
			    &(map->indexLongNbytes), 1)) ||
	    (!Rast3d_write_ints(map->data_fd, map->useXdr, &dummy, 1))) {
	    Rast3d_error(_("Rast3d_open_cell_new: can't write header"));
	    return (void *)NULL;
	}
	if (write(map->data_fd, &ldummy, map->indexLongNbytes) !=
	    map->indexLongNbytes) {
	    Rast3d_error(_("Rast3d_open_cell_new: can't write header"));
	    return (void *)NULL;
	}
    }

    /* can't use a constant since this depends on sizeof (long) */
    nofHeaderBytes = lseek(map->data_fd, (long)0, SEEK_CUR);

    Rast3d_range_init(map);
    Rast3d_adjust_region(region);

    if (!Rast3d_fill_header(map, RASTER3D_WRITE_DATA, compression,
			g3d_do_rle_compression, g3d_do_lzw_compression,
			g3d_file_type, precision, cache, RASTER3D_HAS_INDEX,
			map->useXdr, typeIntern, nofHeaderBytes,
			g3d_tile_dimension[0], g3d_tile_dimension[1],
			g3d_tile_dimension[2],
			region->proj, region->zone,
			region->north, region->south, region->east,
			region->west, region->top, region->bottom,
			region->rows, region->cols, region->depths,
			region->ew_res, region->ns_res, region->tb_res,
			g3d_unit_default)) {
	Rast3d_error(_("Rast3d_open_cell_new: error in Rast3d_fill_header"));
	return (void *)NULL;
    }

    /*Set the map window to the map region */
    Rast3d_region_copy(&(map->window), region);
    /*Set the resampling function to nearest neighbor for data access */
    Rast3d_get_nearest_neighbor_fun_ptr(&(map->resampleFun));

    Rast3d_mask_off(map);

    return (void *)map;
}
コード例 #16
0
ファイル: main.c プロジェクト: 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);
}
コード例 #17
0
ファイル: break_polygons.c プロジェクト: GRASS-GIS/grass-ci
/* break polygons using a file-based search index */
void Vect_break_polygons_file(struct Map_info *Map, int type, struct Map_info *Err)
{
    struct line_pnts *BPoints, *Points;
    struct line_cats *Cats, *ErrCats;
    int i, j, k, ret, ltype, broken, last, nlines;
    int nbreaks;
    struct RTree *RTree;
    int npoints, nallpoints, nmarks;
    XPNT2 XPnt;
    double dx, dy, a1 = 0, a2 = 0;
    int closed, last_point;
    char cross;
    int fd, xpntfd;
    char *filename;
    static struct RTree_Rect rect;
    static int rect_init = 0;

    if (!rect_init) {
	rect.boundary = G_malloc(6 * sizeof(RectReal));
	rect_init = 6;
    }
    
    G_debug(1, "File-based version of Vect_break_polygons()");

    filename = G_tempfile();
    fd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
    RTree = RTreeCreateTree(fd, 0, 2);
    remove(filename);

    filename = G_tempfile();
    xpntfd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
    remove(filename);

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

    nlines = Vect_get_num_lines(Map);

    G_debug(3, "nlines =  %d", nlines);
    /* Go through all lines in vector, and add each point to structure of points,
     * if such point already exists check angles of segments and if differ mark for break */

    nmarks = 0;
    npoints = 1;		/* index starts from 1 ! */
    nallpoints = 0;
    XPnt.used = 0;

    G_message(_("Breaking polygons (pass 1: select break points)..."));

    for (i = 1; i <= nlines; i++) {
	G_percent(i, nlines, 1);
	G_debug(3, "i =  %d", i);
	if (!Vect_line_alive(Map, i))
	    continue;

	ltype = Vect_read_line(Map, Points, Cats, i);
	if (!(ltype & type))
	    continue;

	/* This would be confused by duplicate coordinates (angle cannot be calculated) ->
	 * prune line first */
	Vect_line_prune(Points);

	/* If first and last point are identical it is close polygon, we don't need to register last point
	 * and we can calculate angle for first.
	 * If first and last point are not identical we have to mark for break both */
	last_point = Points->n_points - 1;
	if (Points->x[0] == Points->x[last_point] &&
	    Points->y[0] == Points->y[last_point])
	    closed = 1;
	else
	    closed = 0;

	for (j = 0; j < Points->n_points; j++) {
	    G_debug(3, "j =  %d", j);
	    nallpoints++;

	    if (j == last_point && closed)
		continue;	/* do not register last of close polygon */

	    /* Box */
	    rect.boundary[0] = Points->x[j];
	    rect.boundary[3] = Points->x[j];
	    rect.boundary[1] = Points->y[j];
	    rect.boundary[4] = Points->y[j];
	    rect.boundary[2] = 0;
	    rect.boundary[5] = 0;

	    /* Already in DB? */
	    fpoint = -1;
	    RTreeSearch(RTree, &rect, (void *)srch, NULL);
	    G_debug(3, "fpoint =  %d", fpoint);

	    if (Points->n_points <= 2 ||
		(!closed && (j == 0 || j == last_point))) {
		cross = 1;	/* mark for cross in any case */
	    }
	    else {		/* calculate angles */
		cross = 0;
		if (j == 0 && closed) {	/* closed polygon */
		    dx = Points->x[last_point] - Points->x[0];
		    dy = Points->y[last_point] - Points->y[0];
		    a1 = atan2(dy, dx);
		    dx = Points->x[1] - Points->x[0];
		    dy = Points->y[1] - Points->y[0];
		    a2 = atan2(dy, dx);
		}
		else {
		    dx = Points->x[j - 1] - Points->x[j];
		    dy = Points->y[j - 1] - Points->y[j];
		    a1 = atan2(dy, dx);
		    dx = Points->x[j + 1] - Points->x[j];
		    dy = Points->y[j + 1] - Points->y[j];
		    a2 = atan2(dy, dx);
		}
	    }

	    if (fpoint > 0) {	/* Found */
		/* read point */
		lseek(xpntfd, (off_t) (fpoint - 1) * sizeof(XPNT2), SEEK_SET);
		read(xpntfd, &XPnt, sizeof(XPNT2));
		if (XPnt.cross == 1)
		    continue;	/* already marked */

		/* Check angles */
		if (cross) {
		    XPnt.cross = 1;
		    nmarks++;
		    /* write point */
		    lseek(xpntfd, (off_t) (fpoint - 1) * sizeof(XPNT2), SEEK_SET);
		    write(xpntfd, &XPnt, sizeof(XPNT2));
		}
		else {
		    G_debug(3, "a1 = %f xa1 = %f a2 = %f xa2 = %f", a1,
			    XPnt.a1, a2, XPnt.a2);
		    if ((a1 == XPnt.a1 && a2 == XPnt.a2) ||
		        (a1 == XPnt.a2 && a2 == XPnt.a1)) {	/* identical */

		    }
		    else {
			XPnt.cross = 1;
			nmarks++;
			/* write point */
			lseek(xpntfd, (off_t) (fpoint - 1) * sizeof(XPNT2), SEEK_SET);
			write(xpntfd, &XPnt, sizeof(XPNT2));
		    }
		}
	    }
	    else {
		/* Add to tree and to structure */
		RTreeInsertRect(&rect, npoints, RTree);
		if (j == 0 || j == (Points->n_points - 1) ||
		    Points->n_points < 3) {
		    XPnt.a1 = 0;
		    XPnt.a2 = 0;
		    XPnt.cross = 1;
		    nmarks++;
		}
		else {
		    XPnt.a1 = a1;
		    XPnt.a2 = a2;
		    XPnt.cross = 0;
		}
		/* write point */
		lseek(xpntfd, (off_t) (npoints - 1) * sizeof(XPNT2), SEEK_SET);
		write(xpntfd, &XPnt, sizeof(XPNT2));

		npoints++;
	    }
	}
    }

    nbreaks = 0;

    /* Second loop through lines (existing when loop is started, no need to process lines written again)
     * and break at points marked for break */

    G_message(_("Breaking polygons (pass 2: break at selected points)..."));

    for (i = 1; i <= nlines; i++) {
	int n_orig_points;

	G_percent(i, nlines, 1);
	G_debug(3, "i =  %d", i);
	if (!Vect_line_alive(Map, i))
	    continue;

	ltype = Vect_read_line(Map, Points, Cats, i);
	if (!(ltype & type))
	    continue;
	if (!(ltype & GV_LINES))
	    continue;		/* Nonsense to break points */

	/* Duplicates would result in zero length lines -> prune line first */
	n_orig_points = Points->n_points;
	Vect_line_prune(Points);

	broken = 0;
	last = 0;
	G_debug(3, "n_points =  %d", Points->n_points);
	for (j = 1; j < Points->n_points; j++) {
	    G_debug(3, "j =  %d", j);
	    nallpoints++;

	    /* Box */
	    rect.boundary[0] = Points->x[j];
	    rect.boundary[3] = Points->x[j];
	    rect.boundary[1] = Points->y[j];
	    rect.boundary[4] = Points->y[j];
	    rect.boundary[2] = 0;
	    rect.boundary[5] = 0;

	    if (Points->n_points <= 1 ||
		(j == (Points->n_points - 1) && !broken))
		break;
	    /* One point only or 
	     * last point and line is not broken, do nothing */

	    RTreeSearch(RTree, &rect, (void *)srch, 0);
	    G_debug(3, "fpoint =  %d", fpoint);

	    /* read point */
	    lseek(xpntfd, (off_t) (fpoint - 1) * sizeof(XPNT2), SEEK_SET);
	    read(xpntfd, &XPnt, sizeof(XPNT2));

	    /* break or write last segment of broken line */
	    if ((j == (Points->n_points - 1) && broken) ||
		XPnt.cross) {
		Vect_reset_line(BPoints);
		for (k = last; k <= j; k++) {
		    Vect_append_point(BPoints, Points->x[k], Points->y[k],
				      Points->z[k]);
		}

		/* Result may collapse to one point */
		Vect_line_prune(BPoints);
		if (BPoints->n_points > 1) {
		    ret = Vect_write_line(Map, ltype, BPoints, Cats);
		    G_debug(3,
			    "Line %d written j = %d n_points(orig,pruned) = %d n_points(new) = %d",
			    ret, j, Points->n_points, BPoints->n_points);
		}

		if (!broken)
		    Vect_delete_line(Map, i);	/* not yet deleted */

		/* Write points on breaks */
		if (Err) {
		    if (XPnt.cross && !XPnt.used) {
			Vect_reset_line(BPoints);
			Vect_append_point(BPoints, Points->x[j], Points->y[j], 0);
			Vect_write_line(Err, GV_POINT, BPoints, ErrCats);
		    }
		    if (!XPnt.used) {
			XPnt.used = 1;
			/* write point */
			lseek(xpntfd, (off_t) (fpoint - 1) * sizeof(XPNT2), SEEK_SET);
			write(xpntfd, &XPnt, sizeof(XPNT2));
		    }
		}

		last = j;
		broken = 1;
		nbreaks++;
	    }
	}
	if (!broken && n_orig_points > Points->n_points) {	/* was pruned before -> rewrite */
	    if (Points->n_points > 1) {
		Vect_rewrite_line(Map, i, ltype, Points, Cats);
		G_debug(3, "Line %d pruned, npoints = %d", i,
			Points->n_points);
	    }
	    else {
		Vect_delete_line(Map, i);
		G_debug(3, "Line %d was deleted", i);
	    }
	}
	else {
	    G_debug(3, "Line %d was not changed", i);
	}
    }

    close(RTree->fd);
    RTreeDestroyTree(RTree);
    close(xpntfd);
    Vect_destroy_line_struct(Points);
    Vect_destroy_line_struct(BPoints);
    Vect_destroy_cats_struct(Cats);
    Vect_destroy_cats_struct(ErrCats);
    G_verbose_message(_("Breaks: %d"), nbreaks);
}
コード例 #18
0
ファイル: get_stats.c プロジェクト: GRASS-GIS/grass-ci
/* linked list of stats */
void get_stats(const char *mapname, struct stat_list *dist_stats, int nsteps,
               int map_type)
{
    char buf[1024];             /* input buffer for reading stats */
    int done = FALSE;
    char *tempfile;             /* temp file name */
    FILE *fd;                   /* temp file pointer */

    /*
       int is_fp;
       struct FPRange fp_range;
     */
    long int cat;               /* a category value */
    long int stat;              /* a category stat value */
    struct stat_node *ptr = NULL;
    int first;

    /* write stats to a temp file */
    tempfile = G_tempfile();
    /*
       is_fp = Rast_map_is_fp(mapname, "");
       if (is_fp) {
       if (Rast_read_fp_range(mapname, "", &fp_range) <= 0)
       G_fatal_error("Can't read frange file");
       }
     */
    run_stats(mapname, nsteps, tempfile, map_type);

    /* open temp file and read the stats into a linked list */
    fd = fopen(tempfile, "r");
    if (fd == NULL) {
        perror("opening r.stats output file");
        G_fatal_error("unable to continue.");
    }
    dist_stats->ptr = NULL;
    dist_stats->count = 0;
    dist_stats->sumstat = 0;

    first = TRUE;

    while (!done) {
        if (fgets(buf, sizeof(buf), fd) != NULL) {
            /* WARNING!!!!!!
             * this will be very wrong if type!=COUNT
             * since the stat prodcued by r.stats will be a floating point value
             * possibly less than 1 (shapiro)
             */
            if (sscanf(buf, "* %ld", &stat) == 1) {
                dist_stats->null_stat = stat;
                /*
                   if (stat > dist_stats->maxstat && nodata)
                   dist_stats->maxstat = stat;
                   if (stat < dist_stats->minstat && nodata)
                   dist_stats->minstat = stat;
                   if (nodata)
                   dist_stats->sumstat += stat;
                 */
            }
            else if (sscanf(buf, "%ld %ld", &cat, &stat) == 2) {
                /* count stats */
                dist_stats->count++;

                /* sum stats */
                dist_stats->sumstat += stat;

                /* a max or a min stat? */
                if (first) {
                    dist_stats->maxstat = stat;
                    dist_stats->minstat = stat;
                    dist_stats->maxcat = cat;
                    dist_stats->mincat = cat;
                    first = FALSE;
                }
                if (stat > dist_stats->maxstat)
                    dist_stats->maxstat = stat;
                if (stat < dist_stats->minstat)
                    dist_stats->minstat = stat;

                /* a max or a min cat? */
                if (cat > dist_stats->maxcat)
                    dist_stats->maxcat = cat;
                if (cat < dist_stats->mincat)
                    dist_stats->mincat = cat;

                /* put it in the list */
                if (dist_stats->ptr == NULL) {
                    /* first in list */
                    dist_stats->ptr = (struct stat_node *)
                        G_malloc(sizeof(struct stat_node));
                    dist_stats->ptr->cat = cat;
                    dist_stats->ptr->stat = stat;
                    dist_stats->ptr->next = NULL;
                    ptr = dist_stats->ptr;
                }
                else {
                    ptr->next = (struct stat_node *)
                        G_malloc(sizeof(struct stat_node));
                    ptr->next->cat = cat;
                    ptr->next->stat = stat;
                    ptr->next->next = NULL;     /* mod: shapiro */
                    ptr = ptr->next;
                }
            }
        }
        else
            done = TRUE;
    }
    fclose(fd);
    unlink(tempfile);
}
コード例 #19
0
ファイル: r_text.c プロジェクト: imincik/pkg-grass
int read_text(char *east, char *north, char *text)
{
    PSCOLOR color, hcolor, background, border;
    int r, g, b;
    int ret;
    int xoffset;
    int yoffset;
    float size;
    int fontsize;
    double width;
    double hwidth;
    double rotate;
    int xref, yref;
    int opaque;
    char t1[128];
    char buf[1024];
    char *key, *data;
    FILE *fd;
    char fontname[128];

    set_color(&color, 0, 0, 0);	/* black */
    unset_color(&hcolor);
    unset_color(&background);
    unset_color(&border);
    opaque = TRUE;
    size = 0.0;
    fontsize = 0;
    xoffset = 0;
    yoffset = 0;
    width = 1.;
    hwidth = 0.;
    rotate = 0.0;
    xref = CENTER;
    yref = CENTER;
    G_strcpy(fontname, "Helvetica");

    while (*text == ' ' || *text == '\t')
	text++;
    if (*text == '\\')
	text++;
    if (*text == 0) {
	error("text", "", "no text given");
	gobble_input();
	return 0;
    }

    while (input(2, buf, help)) {
	if (!key_data(buf, &key, &data))
	    continue;

	if (KEY("font")) {
	    get_font(data);
	    strcpy(fontname, data);
	    continue;
	}

	if (KEY("color")) {
	    ret = G_str_to_color(data, &r, &g, &b);
	    if (ret == 1)
		set_color(&color, r, g, b);
	    else if (ret == 2)
		error(key, data, "primary color cannot be \"none\"");
	    else
		error(key, data, "illegal color request");

	    continue;
	}

	if (KEY("hcolor")) {
	    ret = G_str_to_color(data, &r, &g, &b);
	    if (ret == 1)
		set_color(&hcolor, r, g, b);
	    else if (ret == 2)
		unset_color(&hcolor);
	    else
		error(key, data, "illegal hcolor request");

	    if (color_none(&hcolor) || hwidth <= 0.)
		hwidth = 0.;
	    continue;
	}

	if (KEY("background")) {
	    ret = G_str_to_color(data, &r, &g, &b);
	    if (ret == 1)
		set_color(&background, r, g, b);
	    else if (ret == 2) {
		unset_color(&background);
		opaque = FALSE;
	    }
	    else
		error(key, data, "illegal background color request");

	    continue;
	}

	if (KEY("border")) {
	    ret = G_str_to_color(data, &r, &g, &b);
	    if (ret == 1)
		set_color(&border, r, g, b);
	    else if (ret == 2)
		unset_color(&border);
	    else
		error(key, data, "illegal border color request");

	    continue;
	}

	if (KEY("opaque")) {
	    opaque = yesno(key, data);
	    continue;
	}

	if (KEY("width")) {
	    width = -1.;
	    *t1 = 0;
	    if (sscanf(data, "%lf%1s", &width, t1) < 1 || width < 0.) {
		width = 1.;
		error(key, data, "illegal width request");
	    }
	    if (t1 && t1[0] == 'i')
		width = width / 72.0;
	    continue;
	}

	if (KEY("hwidth")) {
	    hwidth = -1.;
	    *t1 = 0;
	    if (sscanf(data, "%lf%1s", &hwidth, t1) < 1 || hwidth < 0.) {
		hwidth = 0.;
		error(key, data, "illegal width request");
	    }
	    if (t1 && t1[0] == 'i')
		hwidth = hwidth / 72.0;
	    continue;
	}

	if (KEY("size")) {
	    double x;

	    if (!scan_resolution(data, &x)) {
		size = 0.0;
		error(key, data, "illegal size request");
	    }
	    else
		size = x;
	    continue;
	}

	if (KEY("fontsize")) {
	    if (sscanf(data, "%d", &fontsize) != 1 || fontsize <= 0) {
		error(key, data, "illegal fontsize request");
	    }
	    else
		continue;
	}

	if (KEY("xoffset")) {
	    *t1 = 0;
	    if (sscanf(data, "%d%1s", &xoffset, t1) != 1 || *t1) {
		xoffset = 0;
		error(key, data, "illegal request (text)");
	    }
	    continue;
	}

	if (KEY("yoffset")) {
	    *t1 = 0;
	    if (sscanf(data, "%d%1s", &yoffset, t1) != 1 || *t1) {
		yoffset = 0;
		error(key, data, "illegal request (text)");
	    }
	    continue;
	}

	if (KEY("rotate")) {
	    if (sscanf(data, "%lf", &rotate) != 1) {
		rotate = 0.0;
		error(key, data, "illegal rotate request");
	    }
	    continue;
	}

	if (KEY("ref")) {
	    if (!scan_ref(data, &xref, &yref)) {
		xref = CENTER;
		yref = CENTER;
		error(key, data, "illegal ref request");
	    }
	    continue;
	}

	error(key, data, "illegal request (text)");
    }

    /* if file doesn't exist create it and close it */
    if (labels.other == NULL) {
	labels.other = G_tempfile();
	if ((fd = fopen(labels.other, "w")) != NULL)
	    fclose(fd);
    }

    /* open file in append mode */
    fd = fopen(labels.other, "a");
    if (fd == NULL) {
	error("misc labels file", "", "can't open");
	return 1;
    }

    /* write the file */
    fprintf(fd, "font: %s\n", fontname);
    fprintf(fd, "east: %s\n", east);
    fprintf(fd, "north: %s\n", north);
    fprintf(fd, "xoffset: %d\n", xoffset);
    fprintf(fd, "yoffset: %d\n", yoffset);
    fprintf(fd, "width: %f\n", width);
    fprintf(fd, "hwidth: %f\n", hwidth);
    fprintf(fd, "size: %f\n", size);
    fprintf(fd, "fontsize: %d\n", fontsize);
    fprintf(fd, "opaque: %s\n", opaque ? "yes" : "no");
    if (rotate != 0)
	fprintf(fd, "rotate: %f\n", rotate);

    fprintf(fd, "color: ");
    if (!color_none(&color))
	fprintf(fd, "%d:%d:%d\n", color.r, color.g, color.b);
    else
	fprintf(fd, "black\n");

    fprintf(fd, "hcolor: ");
    if (!color_none(&hcolor))
	fprintf(fd, "%d:%d:%d\n", hcolor.r, hcolor.g, hcolor.b);
    else
	fprintf(fd, "none\n");

    fprintf(fd, "background: ");
    if (!color_none(&background))
	fprintf(fd, "%d:%d:%d\n", background.r, background.g, background.b);
    else
	fprintf(fd, "none\n");


    fprintf(fd, "border: ");
    if (!color_none(&border))
	fprintf(fd, "%d:%d:%d\n", border.r, border.g, border.b);
    else
	fprintf(fd, "none\n");

    fprintf(fd, "ref: ");
    switch (yref) {
    case UPPER:
	fprintf(fd, "upper");
	break;
    case LOWER:
	fprintf(fd, "lower");
	break;
    case CENTER:
	fprintf(fd, "center");
	break;
    }
    switch (xref) {
    case LEFT:
	fprintf(fd, " left");
	break;
    case RIGHT:
	fprintf(fd, " right");
	break;
    case CENTER:
	fprintf(fd, "%s", (xref == CENTER) ? "" : " center");
	break;
    }
    fprintf(fd, "\n");
    fprintf(fd, "text:%s\n\n", text);
    fclose(fd);

    return 0;
}
コード例 #20
0
ファイル: main.c プロジェクト: AsherBond/MondocosmOS
int main(int argc, char **argv)
{
    int n, verbose = 1,
	backrow, backcol,
	col, row,
	len, flag,
	srows, scols,
	backrow_fd, backcol_fd, path_fd, in_row_fd, in_col_fd, out_fd;
    const char *current_mapset,
	*search_mapset,
	*path_mapset,
	*backrow_mapset,
	*backcol_mapset, *in_row_file, *in_col_file, *out_file;
    CELL *cell;
    POINT *PRES_PT, *PRESENT_PT, *OLD_PT;
    struct Cell_head window;
    double east, north;
    struct Option *opt1, *opt2, *opt3, *opt4;
    struct Flag *flag1;
    struct GModule *module;

    G_gisinit(argv[0]);

    /* Set description */
    module = G_define_module();
    G_add_keyword(_("raster"));
    G_add_keyword(_("fire"));
    G_add_keyword(_("cumulative costs"));
    module->description =
	_("Recursively traces the least cost path backwards to "
	  "cells from which the cumulative cost was determined.");

    opt1 = G_define_option();
    opt1->key = "x_input";
    opt1->type = TYPE_STRING;
    opt1->required = YES;
    opt1->gisprompt = "old,cell,raster";
    opt1->description =
	_("Name of raster map containing back-path easting information");

    opt2 = G_define_option();
    opt2->key = "y_input";
    opt2->type = TYPE_STRING;
    opt2->required = YES;
    opt2->gisprompt = "old,cell,raster";
    opt2->description =
	_("Name of raster map containing back-path northing information");

    opt3 = G_define_option();
    opt3->key = "coordinate";
    opt3->type = TYPE_STRING;
    opt3->multiple = YES;
    opt3->key_desc = "x,y";
    opt3->description =
	_("The map E and N grid coordinates of starting points");

    opt4 = G_define_option();
    opt4->key = "output";
    opt4->type = TYPE_STRING;
    opt4->required = YES;
    opt4->gisprompt = "new,cell,raster";
    opt4->description = _("Name of spread path raster map");

    flag1 = G_define_flag();
    flag1->key = 'v';
    flag1->description = _("Run verbosely");

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

    current_mapset = G_mapset();
    in_row_file = G_tempfile();
    in_col_file = G_tempfile();
    out_file = G_tempfile();

    /*  Get database window parameters      */
    G_get_window(&window);

    verbose = flag1->answer;

    /*  Check if backrow layer exists in data base  */
    search_mapset = "";

    strcpy(backrow_layer, opt2->answer);
    strcpy(backcol_layer, opt1->answer);

    backrow_mapset = G_find_raster(backrow_layer, search_mapset);
    backcol_mapset = G_find_raster(backcol_layer, search_mapset);

    if (backrow_mapset == NULL)
	G_fatal_error("%s - not found", backrow_layer);

    if (backcol_mapset == NULL)
	G_fatal_error("%s - not found", backcol_layer);

    search_mapset = "";

    strcpy(path_layer, opt4->answer);

    path_mapset = G_find_raster(path_layer, search_mapset);

    /*  find number of rows and cols in window    */
    nrows = Rast_window_rows();
    ncols = Rast_window_cols();

    cell = Rast_allocate_c_buf();

    /*  Open back cell layers for reading  */
    backrow_fd = Rast_open_old(backrow_layer, backrow_mapset);
    backcol_fd = Rast_open_old(backcol_layer, backcol_mapset);

    /*   Parameters for map submatrices   */
    len = sizeof(CELL);

    srows = nrows / 4 + 1;
    scols = ncols / 4 + 1;

    if (verbose)
	G_message
	    ("\nReading the input map -%s- and -%s- and creating some temporary files...",
	     backrow_layer, backcol_layer);

    /* Create segmented files for back cell and output layers  */
    in_row_fd = creat(in_row_file, 0666);
    segment_format(in_row_fd, nrows, ncols, srows, scols, len);
    close(in_row_fd);
    in_col_fd = creat(in_col_file, 0666);
    segment_format(in_col_fd, nrows, ncols, srows, scols, len);
    close(in_col_fd);

    out_fd = creat(out_file, 0666);
    segment_format(out_fd, nrows, ncols, srows, scols, len);
    close(out_fd);

    /*   Open initialize and segment all files  */
    in_row_fd = open(in_row_file, 2);
    segment_init(&in_row_seg, in_row_fd, 4);
    in_col_fd = open(in_col_file, 2);
    segment_init(&in_col_seg, in_col_fd, 4);

    out_fd = open(out_file, 2);
    segment_init(&out_seg, out_fd, 4);

    /*   Write the back cell layers in the segmented files, and  
     *   Change UTM coordinates to ROWs and COLUMNs */
    for (row = 0; row < nrows; row++) {
	Rast_get_c_row(backrow_fd, cell, row);

	for (col = 0; col < ncols; col++)
	    if (cell[col] > 0)
		cell[col] =
		    (window.north - cell[col]) / window.ns_res /* - 0.5 */ ;
	    else
		cell[col] = -1;
	segment_put_row(&in_row_seg, cell, row);
	Rast_get_c_row(backcol_fd, cell, row);

	for (col = 0; col < ncols; col++)
	    if (cell[col] > 0)
		cell[col] =
		    (cell[col] - window.west) / window.ew_res /* - 0.5 */ ;
	segment_put_row(&in_col_seg, cell, row);
    }

    /* Convert easting and northing from the command line to row and col */
    if (opt3->answer) {
	for (n = 0; opt3->answers[n] != NULL; n += 2) {
	    G_scan_easting(opt3->answers[n], &east, G_projection());
	    G_scan_northing(opt3->answers[n + 1], &north, G_projection());
	    row = (window.north - north) / window.ns_res;
	    col = (east - window.west) / window.ew_res;
	    /* ignore pt outside window */
	    if (east < window.west || east > window.east ||
		north < window.south || north > window.north) {
		G_warning("Ignoring point outside window: ");
		G_warning("   %.4f,%.4f", east, north);
		continue;
	    }

	    value = (char *)&backrow;
	    segment_get(&in_row_seg, value, row, col);
	    /* ignore pt in no-data area */
	    if (backrow < 0) {
		G_warning("Ignoring point in NO-DATA area :");
		G_warning("   %.4f,%.4f", east, north);
		continue;
	    }
	    value = (char *)&backcol;
	    segment_get(&in_col_seg, value, row, col);

	    insert(&PRESENT_PT, row, col, backrow, backcol);
	}
    }

    /*  Set flag according to input */
    if (path_mapset != NULL) {
	if (head_start_pt == NULL)
	    /*output layer exists and start pts are not given on cmd line */
	    flag = 1;

	/* output layer exists and starting pts are given on cmd line */
	else
	    flag = 2;
    }
    else
	flag = 3;		/* output layer does not previously exist */

    /* If the output layer containing the starting positions */
    /* create a linked list of of them  */
    if (flag == 1) {
	path_fd = Rast_open_old(path_layer, path_mapset);

	/*  Search for the marked starting pts and make list    */
	for (row = 0; row < nrows; row++) {
	    Rast_get_c_row(path_fd, cell, row);

	    for (col = 0; col < ncols; col++) {
		if (cell[col] > 0) {
		    value = (char *)&backrow;
		    segment_get(&in_row_seg, value, row, col);
		    /* ignore pt in no-data area */
		    if (backrow < 0) {
			G_warning("Ignoring point in NO-DATA area:");
			G_warning("   %.4f,%.4f\n",
				  window.west + window.ew_res * (col + 0.5),
				  window.north - window.ns_res * (row + 0.5));
			continue;
		    }
		    value = (char *)&backcol;
		    segment_get(&in_col_seg, value, row, col);
		    insert(&PRESENT_PT, row, col, backrow, backcol);
		}
	    }			/* loop over cols */
	}			/* loop over rows */

	Rast_close(path_fd);
    }

    /* loop over the starting points to find the least cost paths */
    if (verbose)
	G_message("\nFinding the least cost paths ...");

    PRES_PT = head_start_pt;
    while (PRES_PT != NULL) {
	path_finder(PRES_PT->row, PRES_PT->col, PRES_PT->backrow,
		    PRES_PT->backcol);

	OLD_PT = PRES_PT;
	PRES_PT = NEXT_PT;
	G_free(OLD_PT);
    }

    /* Write pending updates by segment_put() to outputmap */
    segment_flush(&out_seg);

    if (verbose)
	G_message("\nWriting the output map  -%s-...", path_layer);

    path_fd = Rast_open_c_new(path_layer);
    for (row = 0; row < nrows; row++) {
	segment_get_row(&out_seg, cell, row);
	Rast_put_row(path_fd, cell, CELL_TYPE);
    }

    if (verbose)
	G_message("finished.");

    segment_release(&in_row_seg);	/* release memory  */
    segment_release(&in_col_seg);
    segment_release(&out_seg);

    close(in_row_fd);		/* close all files */
    close(in_col_fd);
    close(out_fd);

    Rast_close(path_fd);
    Rast_close(backrow_fd);
    Rast_close(backcol_fd);

    unlink(in_row_file);	/* remove submatrix files  */
    unlink(in_col_file);
    unlink(out_file);

    exit(EXIT_SUCCESS);
}
コード例 #21
0
ファイル: main.c プロジェクト: rkrug/grass-ci
/*--------------------------------------------------------------------*/
int main(int argc, char *argv[])
{
    /* Variable declarations */
    int nsply, nsplx, nrows, ncols, nsplx_adj, nsply_adj;
    int nsubregion_col, nsubregion_row, subregion_row, subregion_col;
    int subregion = 0, nsubregions = 0;
    int last_row, last_column, grid, bilin, ext, flag_auxiliar, cross;	/* booleans */
    double stepN, stepE, lambda, mean;
    double N_extension, E_extension, edgeE, edgeN;

    const char *mapset, *drv, *db, *vector, *map;
    char table_name[GNAME_MAX], title[64];
    char xname[GNAME_MAX], xmapset[GMAPSET_MAX];

    int dim_vect, nparameters, BW;
    int *lineVect;		/* Vector restoring primitive's ID */
    double *TN, *Q, *parVect;	/* Interpolating and least-square vectors */
    double **N, **obsVect;	/* Interpolation and least-square matrix */

    SEGMENT out_seg, mask_seg;
    const char *out_file, *mask_file;
    int out_fd, mask_fd;
    double seg_size;
    int seg_mb, segments_in_memory;
    int have_mask;

    /* Structs declarations */
    int raster;
    struct Map_info In, In_ext, Out;
    struct History history;

    struct GModule *module;
    struct Option *in_opt, *in_ext_opt, *out_opt, *out_map_opt, *stepE_opt,
               *stepN_opt, *lambda_f_opt, *type_opt, *dfield_opt, *col_opt, *mask_opt,
               *memory_opt, *solver, *error, *iter;
    struct Flag *cross_corr_flag, *spline_step_flag;

    struct Reg_dimens dims;
    struct Cell_head elaboration_reg, original_reg;
    struct bound_box general_box, overlap_box, original_box;

    struct Point *observ;
    struct line_cats *Cats;
    dbCatValArray cvarr;

    int with_z;
    int nrec, ctype = 0;
    struct field_info *Fi;
    dbDriver *driver, *driver_cats;

    /*----------------------------------------------------------------*/
    /* Options declarations */
    module = G_define_module();
    G_add_keyword(_("vector"));
    G_add_keyword(_("surface"));
    G_add_keyword(_("interpolation"));
    G_add_keyword(_("LIDAR"));
    module->description =
        _("Performs bicubic or bilinear spline interpolation with Tykhonov regularization.");

    cross_corr_flag = G_define_flag();
    cross_corr_flag->key = 'c';
    cross_corr_flag->description =
        _("Find the best Tykhonov regularizing parameter using a \"leave-one-out\" cross validation method");

    spline_step_flag = G_define_flag();
    spline_step_flag->key = 'e';
    spline_step_flag->label = _("Estimate point density and distance");
    spline_step_flag->description =
        _("Estimate point density and distance for the input vector points within the current region extends and quit");

    in_opt = G_define_standard_option(G_OPT_V_INPUT);
    in_opt->label = _("Name of input vector point map");

    dfield_opt = G_define_standard_option(G_OPT_V_FIELD);
    dfield_opt->guisection = _("Settings");

    col_opt = G_define_standard_option(G_OPT_DB_COLUMN);
    col_opt->required = NO;
    col_opt->label =
        _("Name of the attribute column with values to be used for approximation");
    col_opt->description = _("If not given and input is 3D vector map then z-coordinates are used.");
    col_opt->guisection = _("Settings");

    in_ext_opt = G_define_standard_option(G_OPT_V_INPUT);
    in_ext_opt->key = "sparse_input";
    in_ext_opt->required = NO;
    in_ext_opt->label =
        _("Name of input vector map with sparse points");

    out_opt = G_define_standard_option(G_OPT_V_OUTPUT);
    out_opt->required = NO;
    out_opt->guisection = _("Outputs");

    out_map_opt = G_define_standard_option(G_OPT_R_OUTPUT);
    out_map_opt->key = "raster_output";
    out_map_opt->required = NO;
    out_map_opt->guisection = _("Outputs");

    mask_opt = G_define_standard_option(G_OPT_R_INPUT);
    mask_opt->key = "mask";
    mask_opt->label = _("Raster map to use for masking (applies to raster output only)");
    mask_opt->description = _("Only cells that are not NULL and not zero are interpolated");
    mask_opt->required = NO;

    stepE_opt = G_define_option();
    stepE_opt->key = "ew_step";
    stepE_opt->type = TYPE_DOUBLE;
    stepE_opt->required = NO;
    stepE_opt->answer = "4";
    stepE_opt->description =
        _("Length of each spline step in the east-west direction");
    stepE_opt->guisection = _("Settings");

    stepN_opt = G_define_option();
    stepN_opt->key = "ns_step";
    stepN_opt->type = TYPE_DOUBLE;
    stepN_opt->required = NO;
    stepN_opt->answer = "4";
    stepN_opt->description =
        _("Length of each spline step in the north-south direction");
    stepN_opt->guisection = _("Settings");

    type_opt = G_define_option();
    type_opt->key = "method";
    type_opt->description = _("Spline interpolation algorithm");
    type_opt->type = TYPE_STRING;
    type_opt->options = "bilinear,bicubic";
    type_opt->answer = "bilinear";
    type_opt->guisection = _("Settings");
    G_asprintf((char **) &(type_opt->descriptions),
               "bilinear;%s;bicubic;%s",
               _("Bilinear interpolation"),
               _("Bicubic interpolation"));

    lambda_f_opt = G_define_option();
    lambda_f_opt->key = "lambda_i";
    lambda_f_opt->type = TYPE_DOUBLE;
    lambda_f_opt->required = NO;
    lambda_f_opt->description = _("Tykhonov regularization parameter (affects smoothing)");
    lambda_f_opt->answer = "0.01";
    lambda_f_opt->guisection = _("Settings");

    solver = N_define_standard_option(N_OPT_SOLVER_SYMM);
    solver->options = "cholesky,cg";
    solver->answer = "cholesky";

    iter = N_define_standard_option(N_OPT_MAX_ITERATIONS);

    error = N_define_standard_option(N_OPT_ITERATION_ERROR);

    memory_opt = G_define_option();
    memory_opt->key = "memory";
    memory_opt->type = TYPE_INTEGER;
    memory_opt->required = NO;
    memory_opt->answer = "300";
    memory_opt->label = _("Maximum memory to be used (in MB)");
    memory_opt->description = _("Cache size for raster rows");

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

    vector = out_opt->answer;
    map = out_map_opt->answer;

    if (vector && map)
        G_fatal_error(_("Choose either vector or raster output, not both"));

    if (!vector && !map && !cross_corr_flag->answer)
        G_fatal_error(_("No raster or vector or cross-validation output"));

    if (!strcmp(type_opt->answer, "linear"))
        bilin = P_BILINEAR;
    else
        bilin = P_BICUBIC;

    stepN = atof(stepN_opt->answer);
    stepE = atof(stepE_opt->answer);
    lambda = atof(lambda_f_opt->answer);

    flag_auxiliar = FALSE;

    drv = db_get_default_driver_name();
    if (!drv) {
        if (db_set_default_connection() != DB_OK)
            G_fatal_error(_("Unable to set default DB connection"));
        drv = db_get_default_driver_name();
    }
    db = db_get_default_database_name();
    if (!db)
        G_fatal_error(_("No default DB defined"));

    /* Set auxiliary table's name */
    if (vector) {
        if (G_name_is_fully_qualified(out_opt->answer, xname, xmapset)) {
            sprintf(table_name, "%s_aux", xname);
        }
        else
            sprintf(table_name, "%s_aux", out_opt->answer);
    }

    /* Something went wrong in a previous v.surf.bspline execution */
    if (db_table_exists(drv, db, table_name)) {
        /* Start driver and open db */
        driver = db_start_driver_open_database(drv, db);
        if (driver == NULL)
            G_fatal_error(_("No database connection for driver <%s> is defined. Run db.connect."),
                          drv);
        db_set_error_handler_driver(driver);

        if (P_Drop_Aux_Table(driver, table_name) != DB_OK)
            G_fatal_error(_("Old auxiliary table could not be dropped"));
        db_close_database_shutdown_driver(driver);
    }

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

    Vect_set_open_level(1);	/* WITHOUT TOPOLOGY */
    if (1 > Vect_open_old(&In, in_opt->answer, mapset))
        G_fatal_error(_("Unable to open vector map <%s> at the topological level"),
                      in_opt->answer);

    bspline_field = 0; /* assume 3D input */
    bspline_column = col_opt->answer;

    with_z = !bspline_column && Vect_is_3d(&In);

    if (Vect_is_3d(&In)) {
        if (!with_z)
            G_verbose_message(_("Input is 3D: using attribute values instead of z-coordinates for approximation"));
        else
            G_verbose_message(_("Input is 3D: using z-coordinates for approximation"));
    }
    else { /* 2D */
        if (!bspline_column)
            G_fatal_error(_("Input vector map is 2D. Parameter <%s> required."), col_opt->key);
    }

    if (!with_z) {
        bspline_field = Vect_get_field_number(&In, dfield_opt->answer);
    }

    /* Estimate point density and mean distance for current region */
    if (spline_step_flag->answer) {
        double dens, dist;
        if (P_estimate_splinestep(&In, &dens, &dist) == 0) {
            fprintf(stdout, _("Estimated point density: %.4g"), dens);
            fprintf(stdout, _("Estimated mean distance between points: %.4g"), dist);
        }
        else {
            fprintf(stdout, _("No points in current region"));
        }

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

    /*----------------------------------------------------------------*/
    /* Cross-correlation begins */
    if (cross_corr_flag->answer) {
        G_debug(1, "CrossCorrelation()");
        cross = cross_correlation(&In, stepE, stepN);

        if (cross != TRUE)
            G_fatal_error(_("Cross validation didn't finish correctly"));
        else {
            G_debug(1, "Cross validation finished correctly");

            Vect_close(&In);

            G_done_msg(_("Cross validation finished for ew_step = %f and ns_step = %f"), stepE, stepN);
            exit(EXIT_SUCCESS);
        }
    }

    /* Open input ext vector */
    ext = FALSE;
    if (in_ext_opt->answer) {
        ext = TRUE;
        G_message(_("Vector map <%s> of sparse points will be interpolated"),
                  in_ext_opt->answer);

        if ((mapset = G_find_vector2(in_ext_opt->answer, "")) == NULL)
            G_fatal_error(_("Vector map <%s> not found"), in_ext_opt->answer);

        Vect_set_open_level(1);	/* WITHOUT TOPOLOGY */
        if (1 > Vect_open_old(&In_ext, in_ext_opt->answer, mapset))
            G_fatal_error(_("Unable to open vector map <%s> at the topological level"),
                          in_opt->answer);
    }

    /* Open output map */
    /* vector output */
    if (vector && !map) {
        if (strcmp(drv, "dbf") == 0)
            G_fatal_error(_("Sorry, the <%s> driver is not compatible with "
                            "the vector output of this module. "
                            "Try with raster output or another driver."), drv);

        Vect_check_input_output_name(in_opt->answer, out_opt->answer,
                                     G_FATAL_EXIT);
        grid = FALSE;

        if (0 > Vect_open_new(&Out, out_opt->answer, WITH_Z))
            G_fatal_error(_("Unable to create vector map <%s>"),
                          out_opt->answer);

        /* Copy vector Head File */
        if (ext == FALSE) {
            Vect_copy_head_data(&In, &Out);
            Vect_hist_copy(&In, &Out);
        }
        else {
            Vect_copy_head_data(&In_ext, &Out);
            Vect_hist_copy(&In_ext, &Out);
        }
        Vect_hist_command(&Out);

        G_verbose_message(_("Points in input vector map <%s> will be interpolated"),
                          vector);
    }


    /* read z values from attribute table */
    if (bspline_field > 0) {
        G_message(_("Reading values from attribute table..."));
        db_CatValArray_init(&cvarr);
        Fi = Vect_get_field(&In, bspline_field);
        if (Fi == NULL)
            G_fatal_error(_("Cannot read layer info"));

        driver_cats = db_start_driver_open_database(Fi->driver, Fi->database);
        /*G_debug (0, _("driver=%s db=%s"), Fi->driver, Fi->database); */

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

        nrec =
            db_select_CatValArray(driver_cats, Fi->table, Fi->key,
                                  col_opt->answer, NULL, &cvarr);
        G_debug(3, "nrec = %d", nrec);

        ctype = cvarr.ctype;
        if (ctype != DB_C_TYPE_INT && ctype != DB_C_TYPE_DOUBLE)
            G_fatal_error(_("Column type not supported"));

        if (nrec < 0)
            G_fatal_error(_("Unable to select data from table"));

        G_verbose_message(_("%d records selected from table"), nrec);

        db_close_database_shutdown_driver(driver_cats);
    }

    /*----------------------------------------------------------------*/
    /* Interpolation begins */
    G_debug(1, "Interpolation()");

    /* Open driver and database */
    driver = db_start_driver_open_database(drv, db);
    if (driver == NULL)
        G_fatal_error(_("No database connection for driver <%s> is defined. "
                        "Run db.connect."), drv);
    db_set_error_handler_driver(driver);

    /* Create auxiliary table */
    if (vector) {
        if ((flag_auxiliar = P_Create_Aux4_Table(driver, table_name)) == FALSE) {
            P_Drop_Aux_Table(driver, table_name);
            G_fatal_error(_("Interpolation: Creating table: "
                            "It was impossible to create table <%s>."),
                          table_name);
        }
        /* db_create_index2(driver, table_name, "ID"); */
        /* sqlite likes that ??? */
        db_close_database_shutdown_driver(driver);
        driver = db_start_driver_open_database(drv, db);
    }

    /* raster output */
    raster = -1;
    Rast_set_fp_type(DCELL_TYPE);
    if (!vector && map) {
        grid = TRUE;
        raster = Rast_open_fp_new(out_map_opt->answer);

        G_verbose_message(_("Cells for raster map <%s> will be interpolated"),
                          map);
    }

    /* Setting regions and boxes */
    G_debug(1, "Interpolation: Setting regions and boxes");
    G_get_window(&original_reg);
    G_get_window(&elaboration_reg);
    Vect_region_box(&original_reg, &original_box);
    Vect_region_box(&elaboration_reg, &overlap_box);
    Vect_region_box(&elaboration_reg, &general_box);

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

    /* Alloc raster matrix */
    have_mask = 0;
    out_file = mask_file = NULL;
    out_fd = mask_fd = -1;
    if (grid == TRUE) {
        int row;
        DCELL *drastbuf;

        seg_mb = atoi(memory_opt->answer);
        if (seg_mb < 3)
            G_fatal_error(_("Memory in MB must be >= 3"));

        if (mask_opt->answer)
            seg_size = sizeof(double) + sizeof(char);
        else
            seg_size = sizeof(double);

        seg_size = (seg_size * SEGSIZE * SEGSIZE) / (1 << 20);
        segments_in_memory = seg_mb / seg_size + 0.5;
        G_debug(1, "%d %dx%d segments held in memory", segments_in_memory, SEGSIZE, SEGSIZE);

        out_file = G_tempfile();
        out_fd = creat(out_file, 0666);
        if (Segment_format(out_fd, nrows, ncols, SEGSIZE, SEGSIZE, sizeof(double)) != 1)
            G_fatal_error(_("Can not create temporary file"));
        close(out_fd);

        out_fd = open(out_file, 2);
        if (Segment_init(&out_seg, out_fd, segments_in_memory) != 1)
            G_fatal_error(_("Can not initialize temporary file"));

        /* initialize output */
        G_message(_("Initializing output..."));

        drastbuf = Rast_allocate_buf(DCELL_TYPE);
        Rast_set_d_null_value(drastbuf, ncols);
        for (row = 0; row < nrows; row++) {
            G_percent(row, nrows, 2);
            Segment_put_row(&out_seg, drastbuf, row);
        }
        G_percent(row, nrows, 2);

        if (mask_opt->answer) {
            int row, col, maskfd;
            DCELL dval, *drastbuf;
            char mask_val;

            G_message(_("Load masking map"));

            mask_file = G_tempfile();
            mask_fd = creat(mask_file, 0666);
            if (Segment_format(mask_fd, nrows, ncols, SEGSIZE, SEGSIZE, sizeof(char)) != 1)
                G_fatal_error(_("Can not create temporary file"));
            close(mask_fd);

            mask_fd = open(mask_file, 2);
            if (Segment_init(&mask_seg, mask_fd, segments_in_memory) != 1)
                G_fatal_error(_("Can not initialize temporary file"));

            maskfd = Rast_open_old(mask_opt->answer, "");
            drastbuf = Rast_allocate_buf(DCELL_TYPE);

            for (row = 0; row < nrows; row++) {
                G_percent(row, nrows, 2);
                Rast_get_d_row(maskfd, drastbuf, row);
                for (col = 0; col < ncols; col++) {
                    dval = drastbuf[col];
                    if (Rast_is_d_null_value(&dval) || dval == 0)
                        mask_val = 0;
                    else
                        mask_val = 1;

                    Segment_put(&mask_seg, &mask_val, row, col);
                }
            }

            G_percent(row, nrows, 2);
            G_free(drastbuf);
            Rast_close(maskfd);

            have_mask = 1;
        }
    }

    /*------------------------------------------------------------------
      | Subdividing and working with tiles:
      | Each original region will be divided into several subregions.
      | Each one will be overlaped by its neighbouring subregions.
      | The overlapping is calculated as a fixed OVERLAP_SIZE times
      | the largest spline step plus 2 * edge
      ----------------------------------------------------------------*/

    /* Fixing parameters of the elaboration region */
    P_zero_dim(&dims);		/* Set dim struct to zero */

    nsplx_adj = NSPLX_MAX;
    nsply_adj = NSPLY_MAX;
    if (stepN > stepE)
        dims.overlap = OVERLAP_SIZE * stepN;
    else
        dims.overlap = OVERLAP_SIZE * stepE;
    P_get_edge(bilin, &dims, stepE, stepN);
    P_set_dim(&dims, stepE, stepN, &nsplx_adj, &nsply_adj);

    G_verbose_message(_("Adjusted EW splines %d"), nsplx_adj);
    G_verbose_message(_("Adjusted NS splines %d"), nsply_adj);

    /* calculate number of subregions */
    edgeE = dims.ew_size - dims.overlap - 2 * dims.edge_v;
    edgeN = dims.sn_size - dims.overlap - 2 * dims.edge_h;

    N_extension = original_reg.north - original_reg.south;
    E_extension = original_reg.east - original_reg.west;

    nsubregion_col = ceil(E_extension / edgeE) + 0.5;
    nsubregion_row = ceil(N_extension / edgeN) + 0.5;

    if (nsubregion_col < 0)
        nsubregion_col = 0;
    if (nsubregion_row < 0)
        nsubregion_row = 0;

    nsubregions = nsubregion_row * nsubregion_col;

    /* Creating line and categories structs */
    Cats = Vect_new_cats_struct();
    Vect_cat_set(Cats, 1, 0);

    subregion_row = 0;
    elaboration_reg.south = original_reg.north;
    last_row = FALSE;

    while (last_row == FALSE) {	/* For each subregion row */
        subregion_row++;
        P_set_regions(&elaboration_reg, &general_box, &overlap_box, dims,
                      GENERAL_ROW);

        if (elaboration_reg.north > original_reg.north) {	/* First row */

            P_set_regions(&elaboration_reg, &general_box, &overlap_box, dims,
                          FIRST_ROW);
        }

        if (elaboration_reg.south <= original_reg.south) {	/* Last row */

            P_set_regions(&elaboration_reg, &general_box, &overlap_box, dims,
                          LAST_ROW);
            last_row = TRUE;
        }

        nsply =
            ceil((elaboration_reg.north -
                  elaboration_reg.south) / stepN) + 0.5;
        G_debug(1, "Interpolation: nsply = %d", nsply);
        /*
        if (nsply > NSPLY_MAX)
            nsply = NSPLY_MAX;
        */
        elaboration_reg.east = original_reg.west;
        last_column = FALSE;
        subregion_col = 0;

        /* TODO: process each subregion using its own thread (via OpenMP or pthreads) */
        /*     I'm not sure about pthreads, but you can tell OpenMP to start all at the
        	same time and it will keep num_workers supplied with the next job as free
        	cpus become available */
        while (last_column == FALSE) {	/* For each subregion column */
            int npoints = 0;
            /* needed for sparse points interpolation */
            int npoints_ext, *lineVect_ext = NULL;
            double **obsVect_ext;	/*, mean_ext = .0; */
            struct Point *observ_ext;

            subregion_col++;
            subregion++;
            if (nsubregions > 1)
                G_message(_("Processing subregion %d of %d..."), subregion, nsubregions);

            P_set_regions(&elaboration_reg, &general_box, &overlap_box, dims,
                          GENERAL_COLUMN);

            if (elaboration_reg.west < original_reg.west) {	/* First column */

                P_set_regions(&elaboration_reg, &general_box, &overlap_box,
                              dims, FIRST_COLUMN);
            }

            if (elaboration_reg.east >= original_reg.east) {	/* Last column */

                P_set_regions(&elaboration_reg, &general_box, &overlap_box,
                              dims, LAST_COLUMN);
                last_column = TRUE;
            }
            nsplx =
                ceil((elaboration_reg.east -
                      elaboration_reg.west) / stepE) + 0.5;
            G_debug(1, "Interpolation: nsplx = %d", nsplx);
            /*
            if (nsplx > NSPLX_MAX)
            nsplx = NSPLX_MAX;
            */
            G_debug(1, "Interpolation: (%d,%d): subregion bounds",
                    subregion_row, subregion_col);
            G_debug(1, "Interpolation: \t\tNORTH:%.2f\t",
                    elaboration_reg.north);
            G_debug(1, "Interpolation: WEST:%.2f\t\tEAST:%.2f",
                    elaboration_reg.west, elaboration_reg.east);
            G_debug(1, "Interpolation: \t\tSOUTH:%.2f",
                    elaboration_reg.south);

#ifdef DEBUG_SUBREGIONS
            fprintf(stdout, "B 5\n");
            fprintf(stdout, " %.11g %.11g\n", elaboration_reg.east, elaboration_reg.north);
            fprintf(stdout, " %.11g %.11g\n", elaboration_reg.west, elaboration_reg.north);
            fprintf(stdout, " %.11g %.11g\n", elaboration_reg.west, elaboration_reg.south);
            fprintf(stdout, " %.11g %.11g\n", elaboration_reg.east, elaboration_reg.south);
            fprintf(stdout, " %.11g %.11g\n", elaboration_reg.east, elaboration_reg.north);
            fprintf(stdout, "C 1 1\n");
            fprintf(stdout, " %.11g %.11g\n", (elaboration_reg.west + elaboration_reg.east) / 2,
                    (elaboration_reg.south + elaboration_reg.north) / 2);
            fprintf(stdout, " 1 %d\n", subregion);
#endif



            /* reading points in interpolation region */
            dim_vect = nsplx * nsply;
            observ_ext = NULL;
            if (grid == FALSE && ext == TRUE) {
                observ_ext =
                    P_Read_Vector_Region_Map(&In_ext,
                                             &elaboration_reg,
                                             &npoints_ext, dim_vect,
                                             1);
            }
            else
                npoints_ext = 1;

            if (grid == TRUE && have_mask) {
                /* any unmasked cells in general region ? */
                mean = 0;
                observ_ext =
                    P_Read_Raster_Region_masked(&mask_seg, &original_reg,
                                                original_box, general_box,
                                                &npoints_ext, dim_vect, mean);
            }

            observ = NULL;
            if (npoints_ext > 0) {
                observ =
                    P_Read_Vector_Region_Map(&In, &elaboration_reg, &npoints,
                                             dim_vect, bspline_field);
            }
            else
                npoints = 1;

            G_debug(1,
                    "Interpolation: (%d,%d): Number of points in <elaboration_box> is %d",
                    subregion_row, subregion_col, npoints);
            if (npoints > 0)
                G_verbose_message(_("%d points found in this subregion"), npoints);
            /* only interpolate if there are any points in current subregion */
            if (npoints > 0 && npoints_ext > 0) {
                int i;

                nparameters = nsplx * nsply;
                BW = P_get_BandWidth(bilin, nsply);

                /* Least Squares system */
                N = G_alloc_matrix(nparameters, BW);	/* Normal matrix */
                TN = G_alloc_vector(nparameters);	/* vector */
                parVect = G_alloc_vector(nparameters);	/* Parameters vector */
                obsVect = G_alloc_matrix(npoints, 3);	/* Observation vector */
                Q = G_alloc_vector(npoints);	/* "a priori" var-cov matrix */
                lineVect = G_alloc_ivector(npoints);	/*  */

                for (i = 0; i < npoints; i++) {	/* Setting obsVect vector & Q matrix */
                    double dval;

                    Q[i] = 1;	/* Q=I */
                    lineVect[i] = observ[i].lineID;
                    obsVect[i][0] = observ[i].coordX;
                    obsVect[i][1] = observ[i].coordY;

                    /* read z coordinates from attribute table */
                    if (bspline_field > 0) {
                        int cat, ival, ret;

                        cat = observ[i].cat;
                        if (cat < 0)
                            continue;

                        if (ctype == DB_C_TYPE_INT) {
                            ret =
                                db_CatValArray_get_value_int(&cvarr, cat,
                                                             &ival);
                            obsVect[i][2] = ival;
                            observ[i].coordZ = ival;
                        }
                        else {	/* DB_C_TYPE_DOUBLE */
                            ret =
                                db_CatValArray_get_value_double(&cvarr, cat,
                                                                &dval);
                            obsVect[i][2] = dval;
                            observ[i].coordZ = dval;
                        }
                        if (ret != DB_OK) {
                            G_warning(_("Interpolation: (%d,%d): No record for point (cat = %d)"),
                                      subregion_row, subregion_col, cat);
                            continue;
                        }
                    }
                    /* use z coordinates of 3D vector */
                    else {
                        obsVect[i][2] = observ[i].coordZ;
                    }
                }

                /* Mean calculation for every point */
                mean = P_Mean_Calc(&elaboration_reg, observ, npoints);

                G_debug(1, "Interpolation: (%d,%d): mean=%lf",
                        subregion_row, subregion_col, mean);

                G_free(observ);

                for (i = 0; i < npoints; i++)
                    obsVect[i][2] -= mean;

                /* Bilinear interpolation */
                if (bilin) {
                    G_debug(1,
                            "Interpolation: (%d,%d): Bilinear interpolation...",
                            subregion_row, subregion_col);
                    normalDefBilin(N, TN, Q, obsVect, stepE, stepN, nsplx,
                                   nsply, elaboration_reg.west,
                                   elaboration_reg.south, npoints,
                                   nparameters, BW);
                    nCorrectGrad(N, lambda, nsplx, nsply, stepE, stepN);
                }
                /* Bicubic interpolation */
                else {
                    G_debug(1,
                            "Interpolation: (%d,%d): Bicubic interpolation...",
                            subregion_row, subregion_col);
                    normalDefBicubic(N, TN, Q, obsVect, stepE, stepN, nsplx,
                                     nsply, elaboration_reg.west,
                                     elaboration_reg.south, npoints,
                                     nparameters, BW);
                    nCorrectGrad(N, lambda, nsplx, nsply, stepE, stepN);
                }

                if(G_strncasecmp(solver->answer, "cg", 2) == 0)
                    G_math_solver_cg_sband(N, parVect, TN, nparameters, BW, atoi(iter->answer), atof(error->answer));
                else
                    G_math_solver_cholesky_sband(N, parVect, TN, nparameters, BW);


                G_free_matrix(N);
                G_free_vector(TN);
                G_free_vector(Q);

                if (grid == TRUE) {	/* GRID INTERPOLATION ==> INTERPOLATION INTO A RASTER */
                    G_debug(1, "Interpolation: (%d,%d): Regular_Points...",
                            subregion_row, subregion_col);

                    if (!have_mask) {
                        P_Regular_Points(&elaboration_reg, &original_reg, general_box,
                                         overlap_box, &out_seg, parVect,
                                         stepN, stepE, dims.overlap, mean,
                                         nsplx, nsply, nrows, ncols, bilin);
                    }
                    else {
                        P_Sparse_Raster_Points(&out_seg,
                                               &elaboration_reg, &original_reg,
                                               general_box, overlap_box,
                                               observ_ext, parVect,
                                               stepE, stepN,
                                               dims.overlap, nsplx, nsply,
                                               npoints_ext, bilin, mean);
                    }
                }
                else {		/* OBSERVATION POINTS INTERPOLATION */
                    if (ext == FALSE) {
                        G_debug(1, "Interpolation: (%d,%d): Sparse_Points...",
                                subregion_row, subregion_col);
                        P_Sparse_Points(&Out, &elaboration_reg, general_box,
                                        overlap_box, obsVect, parVect,
                                        lineVect, stepE, stepN,
                                        dims.overlap, nsplx, nsply, npoints,
                                        bilin, Cats, driver, mean,
                                        table_name);
                    }
                    else {	/* FLAG_EXT == TRUE */

                        /* done that earlier */
                        /*
                        int npoints_ext, *lineVect_ext = NULL;
                        double **obsVect_ext;
                        struct Point *observ_ext;

                        observ_ext =
                            P_Read_Vector_Region_Map(&In_ext,
                        			     &elaboration_reg,
                        			     &npoints_ext, dim_vect,
                        			     1);
                        */

                        obsVect_ext = G_alloc_matrix(npoints_ext, 3);	/* Observation vector_ext */
                        lineVect_ext = G_alloc_ivector(npoints_ext);

                        for (i = 0; i < npoints_ext; i++) {	/* Setting obsVect_ext vector & Q matrix */
                            obsVect_ext[i][0] = observ_ext[i].coordX;
                            obsVect_ext[i][1] = observ_ext[i].coordY;
                            obsVect_ext[i][2] = observ_ext[i].coordZ - mean;
                            lineVect_ext[i] = observ_ext[i].lineID;
                        }

                        G_free(observ_ext);

                        G_debug(1, "Interpolation: (%d,%d): Sparse_Points...",
                                subregion_row, subregion_col);
                        P_Sparse_Points(&Out, &elaboration_reg, general_box,
                                        overlap_box, obsVect_ext, parVect,
                                        lineVect_ext, stepE, stepN,
                                        dims.overlap, nsplx, nsply,
                                        npoints_ext, bilin, Cats, driver,
                                        mean, table_name);

                        G_free_matrix(obsVect_ext);
                        G_free_ivector(lineVect_ext);
                    }		/* END FLAG_EXT == TRUE */
                }		/* END GRID == FALSE */
                G_free_vector(parVect);
                G_free_matrix(obsVect);
                G_free_ivector(lineVect);
            }
            else {
                if (observ)
                    G_free(observ);
                if (observ_ext)
                    G_free(observ_ext);
                if (npoints == 0)
                    G_warning(_("No data within this subregion. "
                                "Consider increasing spline step values."));
            }
        }			/*! END WHILE; last_column = TRUE */
    }				/*! END WHILE; last_row = TRUE */

    G_verbose_message(_("Writing output..."));
    /* Writing the output raster map */
    if (grid == TRUE) {
        int row, col;
        DCELL *drastbuf, dval;


        if (have_mask) {
            Segment_release(&mask_seg);	/* release memory  */
            close(mask_fd);
            unlink(mask_file);
        }

        drastbuf = Rast_allocate_buf(DCELL_TYPE);
        for (row = 0; row < nrows; row++) {
            G_percent(row, nrows, 2);
            for (col = 0; col < ncols; col++) {
                Segment_get(&out_seg, &dval, row, col);
                drastbuf[col] = dval;
            }
            Rast_put_d_row(raster, drastbuf);
        }

        Rast_close(raster);

        Segment_release(&out_seg);	/* release memory  */
        close(out_fd);
        unlink(out_file);
        /* set map title */
        sprintf(title, "%s interpolation with Tykhonov regularization",
                type_opt->answer);
        Rast_put_cell_title(out_map_opt->answer, title);
        /* write map history */
        Rast_short_history(out_map_opt->answer, "raster", &history);
        Rast_command_history(&history);
        Rast_write_history(out_map_opt->answer, &history);
    }
    /* Writing to the output vector map the points from the overlapping zones */
    else if (flag_auxiliar == TRUE) {
        if (ext == FALSE)
            P_Aux_to_Vector(&In, &Out, driver, table_name);
        else
            P_Aux_to_Vector(&In_ext, &Out, driver, table_name);

        /* Drop auxiliary table */
        G_debug(1, "%s: Dropping <%s>", argv[0], table_name);
        if (P_Drop_Aux_Table(driver, table_name) != DB_OK)
            G_fatal_error(_("Auxiliary table could not be dropped"));
    }

    db_close_database_shutdown_driver(driver);

    Vect_close(&In);
    if (ext != FALSE)
        Vect_close(&In_ext);
    if (vector)
        Vect_close(&Out);

    G_done_msg(" ");

    exit(EXIT_SUCCESS);
}				/*END MAIN */
コード例 #22
0
ファイル: start.c プロジェクト: AsherBond/MondocosmOS
int start_mon(const char *name, const char *output, int select,
	      const char *width, const char *height, const char *bgcolor,
	      int truecolor)
{
    const char *curr_mon;
    char *env_name, *env_value, *cmd_value;
    char *tempfile, buf[1024];
    int env_fd;
    
    curr_mon = G__getenv("MONITOR");
    if (curr_mon && strcmp(curr_mon, name) == 0 && check_mon(curr_mon))
	G_fatal_error(_("Monitor <%s> already running"), name);
    
    tempfile = G_tempfile();

    env_name = env_value = NULL;
    G_asprintf(&env_name, "MONITOR_%s_ENVFILE", name);
    G_asprintf(&env_value, "%s.env", tempfile);
    G_setenv(env_name, env_value);
    env_fd = creat(env_value, 0666);
    if (env_fd < 0)
	G_fatal_error(_("Unable to create file '%s'"), env_value);
    if (width) {
	sprintf(buf, "GRASS_WIDTH=%s\n", width);
	write(env_fd, buf, strlen(buf));
    }
    if (height) {
	sprintf(buf, "GRASS_HEIGHT=%s\n", height);
	write(env_fd, buf, strlen(buf));
    }
    if (bgcolor) {
	if (strcmp(bgcolor, "none") == 0)
	    sprintf(buf, "GRASS_TRANSPARENT=TRUE\n");
	else
	    sprintf(buf, "GRASS_BACKGROUNDCOLOR=%s\n", bgcolor);
	write(env_fd, buf, strlen(buf));
    }
    if (truecolor) {
	sprintf(buf, "GRASS_TRUECOLOR=TRUE\n");
	write(env_fd, buf, strlen(buf));
    }
    close(env_fd);

    cmd_value = NULL;
    G_asprintf(&env_name, "MONITOR_%s_CMDFILE", name);
    G_asprintf(&cmd_value, "%s.cmd", tempfile);
    G_setenv(env_name, cmd_value);
    close(creat(cmd_value, 0666));

    G_verbose_message(_("Staring monitor <%s> with env file '%s'"), name, env_value);
    
    G_debug(1, "start: name=%s ", name);
    G_debug(3, "       envfile = %s", env_value);
    G_debug(3, "       cmdfile = %s", cmd_value);
    
    if (select)
	G_setenv("MONITOR", name);
    
    if (strncmp(name, "wx", 2) == 0) /* use G_strncasecmp() instead */
	start_wx(name, tempfile, env_value, cmd_value, 
		 width, height);
    else
	start(name, output);
    
    return 0;
}
コード例 #23
0
ファイル: open_files.c プロジェクト: felipebetancur/grass-ci
int open_files(struct globals *globals)
{
    struct Ref Ref;		/* group reference list */
    int *in_fd, bounds_fd, is_null;
    int n, row, col, srows, scols, inlen, outlen, nseg;
    DCELL **inbuf;		/* buffers to store lines from each of the imagery group rasters */
    CELL *boundsbuf, bounds_val;
    int have_bounds = 0;
    CELL s, id;
    struct Range range;	/* min/max values of bounds map */
    struct FPRange *fp_range;	/* min/max values of each input raster */
    DCELL *min, *max;
    struct ngbr_stats Ri, Rk;

    /*allocate memory for flags */
    globals->null_flag = flag_create(globals->nrows, globals->ncols);
    globals->candidate_flag = flag_create(globals->nrows, globals->ncols);

    flag_clear_all(globals->null_flag);
    flag_clear_all(globals->candidate_flag);

    G_debug(1, "Checking image group...");

    /* ****** open the input rasters ******* */

    if (!I_get_group_ref(globals->image_group, &Ref))
	G_fatal_error(_("Group <%s> not found in the current mapset"),
		      globals->image_group);

    if (Ref.nfiles <= 0)
	G_fatal_error(_("Group <%s> contains no raster maps"),
		      globals->image_group);

    /* Read Imagery Group */

    in_fd = G_malloc(Ref.nfiles * sizeof(int));
    inbuf = (DCELL **) G_malloc(Ref.nfiles * sizeof(DCELL *));
    fp_range = G_malloc(Ref.nfiles * sizeof(struct FPRange));
    min = G_malloc(Ref.nfiles * sizeof(DCELL));
    max = G_malloc(Ref.nfiles * sizeof(DCELL));

    G_debug(1, "Opening input rasters...");
    for (n = 0; n < Ref.nfiles; n++) {
	inbuf[n] = Rast_allocate_d_buf();
	in_fd[n] = Rast_open_old(Ref.file[n].name, Ref.file[n].mapset);
    }

    /* Get min/max values of each input raster for scaling */

    globals->max_diff = 0.;
    globals->nbands = Ref.nfiles;

    for (n = 0; n < Ref.nfiles; n++) {
	/* returns -1 on error, 2 on empty range, quitting either way. */
	if (Rast_read_fp_range(Ref.file[n].name, Ref.file[n].mapset, &fp_range[n]) != 1)
	    G_fatal_error(_("No min/max found in raster map <%s>"),
			  Ref.file[n].name);
	Rast_get_fp_range_min_max(&(fp_range[n]), &min[n], &max[n]);

	G_debug(1, "Range for layer %d: min = %f, max = %f",
		    n, min[n], max[n]);
	
    }
    if (globals->weighted == FALSE)
	globals->max_diff = Ref.nfiles;
    else {
	/* max difference with selected similarity method */
	Ri.mean = max;
	Rk.mean = min;
	globals->max_diff = 1;
	globals->max_diff = (*globals->calculate_similarity) (&Ri, &Rk, globals);
    }

    /* ********** find out file segmentation size ************ */
    G_debug(1, "Calculate temp file sizes...");

    /* size of each element to be stored */

    inlen = sizeof(DCELL) * Ref.nfiles;
    outlen = sizeof(CELL);
    G_debug(1, "data element size, in: %d , out: %d ", inlen, outlen);
    globals->datasize = sizeof(double) * globals->nbands;

    /* count non-null cells */
    globals->notnullcells = (long)globals->nrows * globals->ncols;
    for (row = 0; row < globals->nrows; row++) {
	for (n = 0; n < Ref.nfiles; n++) {
	    Rast_get_d_row(in_fd[n], inbuf[n], row);
	}
	for (col = 0; col < globals->ncols; col++) {

	    is_null = 0;	/*Assume there is data */
	    for (n = 0; n < Ref.nfiles; n++) {
		if (Rast_is_d_null_value(&inbuf[n][col])) {
		    is_null = 1;
		}
	    }
	    if (is_null) {
		globals->notnullcells--;
		FLAG_SET(globals->null_flag, row, col);
	    }
	}
    }
    G_verbose_message(_("Non-NULL cells: %ld"), globals->notnullcells);
    if (globals->notnullcells < 2)
	G_fatal_error(_("Insufficient number of non-NULL cells in current region"));

    /* segment lib segment size */
    srows = 64;
    scols = 64;

    nseg = manage_memory(srows, scols, globals);

    /* create segment structures */
    if (Segment_open
	(&globals->bands_seg, G_tempfile(), globals->nrows, globals->ncols, srows,
	 scols, inlen, nseg) != 1)
	G_fatal_error("Unable to create input temporary files");

    if (Segment_open
	(&globals->rid_seg, G_tempfile(), globals->nrows, globals->ncols, srows,
	 scols, outlen, nseg * 2) != 1)
	G_fatal_error("Unable to create input temporary files");

    /* load input bands to segment structure */
    if (Ref.nfiles > 1)
	G_message(_("Loading input bands..."));
    else
	G_message(_("Loading input band..."));

    globals->bands_val = (double *)G_malloc(inlen);
    globals->second_val = (double *)G_malloc(inlen);
    /* initial segment ID */
    s = 1;

    globals->row_min = globals->nrows;
    globals->row_max = 0;
    globals->col_min = globals->ncols;
    globals->col_max = 0;
    for (row = 0; row < globals->nrows; row++) {
	G_percent(row, globals->nrows, 4);
	for (n = 0; n < Ref.nfiles; n++) {
	    Rast_get_d_row(in_fd[n], inbuf[n], row);
	}
	for (col = 0; col < globals->ncols; col++) {

	    is_null = 0;	/*Assume there is data */
	    for (n = 0; n < Ref.nfiles; n++) {
		globals->bands_val[n] = inbuf[n][col];
		if (Rast_is_d_null_value(&inbuf[n][col])) {
		    is_null = 1;
		}
		else {
		    if (globals->weighted == FALSE)
		    	/* scaled version */
			globals->bands_val[n] = (inbuf[n][col] - min[n]) / (max[n] - min[n]);
		}
	    }
	    if (Segment_put(&globals->bands_seg,
	                    (void *)globals->bands_val, row, col) != 1)
		G_fatal_error(_("Unable to write to temporary file"));

	    if (!is_null) {
		if (!globals->seeds) {
		    /* sequentially number all cells with a unique segment ID */
		    id = s;
		    s++;
		}

		/* get min/max row/col to narrow the processing window */
		if (globals->row_min > row)
		    globals->row_min = row;
		if (globals->row_max < row)
		    globals->row_max = row;
		if (globals->col_min > col)
		    globals->col_min = col;
		if (globals->col_max < col)
		    globals->col_max = col;
	    }
	    else {
		/* all input bands NULL */
		Rast_set_c_null_value(&id, 1);
		FLAG_SET(globals->null_flag, row, col);
	    }
	    if (!globals->seeds || is_null) {
		if (Segment_put(&globals->rid_seg,
		                (void *)&id, row, col) != 1)
		    G_fatal_error(_("Unable to write to temporary file"));
	    }
	}
    }
    G_percent(1, 1, 1);
    G_debug(1, "nrows: %d, min row: %d, max row %d",
	       globals->nrows, globals->row_min, globals->row_max);
    G_debug(1, "ncols: %d, min col: %d, max col %d",
               globals->ncols, globals->col_min, globals->col_max);
    
    globals->row_max++;
    globals->col_max++;
    globals->ncells = (long)(globals->row_max - globals->row_min) *
			    (globals->col_max - globals->col_min);

    /* bounds/constraints */

    Rast_set_c_null_value(&globals->upper_bound, 1);
    Rast_set_c_null_value(&globals->lower_bound, 1);

    if (globals->bounds_map != NULL) {
	if (Segment_open
	    (&globals->bounds_seg, G_tempfile(), globals->nrows, globals->ncols,
	     srows, scols, sizeof(CELL), nseg) != TRUE)
	    G_fatal_error("Unable to create bounds temporary files");

	if (Rast_read_range(globals->bounds_map, globals->bounds_mapset, &range) != 1)
	    G_fatal_error(_("No min/max found in raster map <%s>"),
			  globals->bounds_map);
	Rast_get_range_min_max(&range, &globals->upper_bound,
				       &globals->lower_bound);

	if (Rast_is_c_null_value(&globals->upper_bound) ||
	    Rast_is_c_null_value(&globals->lower_bound)) {
	    
	    G_fatal_error(_("No min/max found in raster map <%s>"),
	                  globals->bounds_map);
	}

	bounds_fd = Rast_open_old(globals->bounds_map, globals->bounds_mapset);
	boundsbuf = Rast_allocate_c_buf();

	for (row = 0; row < globals->nrows; row++) {
	    Rast_get_c_row(bounds_fd, boundsbuf, row);
	    for (col = 0; col < globals->ncols; col++) {
		bounds_val = boundsbuf[col];
		if (FLAG_GET(globals->null_flag, row, col)) {
		    Rast_set_c_null_value(&bounds_val, 1);
		}
		else {
		    if (!Rast_is_c_null_value(&bounds_val)) {
			have_bounds = 1;
			if (globals->lower_bound > bounds_val)
			    globals->lower_bound = bounds_val;
			if (globals->upper_bound < bounds_val)
			    globals->upper_bound = bounds_val;
		    }
		}
		if (Segment_put(&globals->bounds_seg, &bounds_val, row, col) != 1)
		    G_fatal_error(_("Unable to write to temporary file"));
	    }
	}
	Rast_close(bounds_fd);
	G_free(boundsbuf);

	if (!have_bounds) {
	    G_warning(_("There are no boundary constraints in '%s'"), globals->bounds_map);
	    Rast_set_c_null_value(&globals->upper_bound, 1);
	    Rast_set_c_null_value(&globals->lower_bound, 1);
	    Segment_close(&globals->bounds_seg);
	    globals->bounds_map = NULL;
	    globals->bounds_mapset = NULL;
	}
    }
    else {
	G_debug(1, "no boundary constraint supplied.");
    }

    /* other info */
    globals->candidate_count = 0;	/* counter for remaining candidate pixels */

    /* Free memory */

    for (n = 0; n < Ref.nfiles; n++) {
	G_free(inbuf[n]);
	Rast_close(in_fd[n]);
    }

    globals->rs.sum = G_malloc(globals->datasize);
    globals->rs.mean = G_malloc(globals->datasize);

    globals->reg_tree = rgtree_create(globals->nbands, globals->datasize);
    globals->n_regions = s - 1;

    if (globals->seeds) {
	load_seeds(globals, srows, scols, nseg);
    }

    G_debug(1, "Number of initial regions: %d", globals->n_regions);

    G_free(inbuf);
    G_free(in_fd);
    G_free(fp_range);
    G_free(min);
    G_free(max);

    return TRUE;
}
コード例 #24
0
ファイル: main.c プロジェクト: imincik/pkg-grass
int main(int argc, char *argv[])
{
    char *input;
    char *output;
    char *title;
    FILE *fd;
    int cf;
    struct Cell_head cellhd;
    CELL *cell;
    FCELL *fcell;
    DCELL *dcell;
    int row, col;
    int nrows, ncols;
    static int missingval;
    int rtype;
    double mult_fact;
    double x;
    struct GModule *module;
    struct History history;
    struct
    {
	struct Option *input, *output, *type, *title, *mult;
    } parm;


    G_gisinit(argv[0]);

    module = G_define_module();
    module->keywords = _("raster, import");
    module->description =
	_("Converts an ESRI ARC/INFO ascii raster file (GRID) "
	  "into a (binary) raster map layer.");

    parm.input = G_define_option();
    parm.input->key = "input";
    parm.input->type = TYPE_STRING;
    parm.input->required = YES;
    parm.input->description =
	_("ARC/INFO ASCII raster file (GRID) to be imported");
    parm.input->gisprompt = "old_file,file,input";

    parm.output = G_define_standard_option(G_OPT_R_OUTPUT);

    parm.type = G_define_option();
    parm.type->key = "type";
    parm.type->type = TYPE_STRING;
    parm.type->required = NO;
    parm.type->options = "CELL,FCELL,DCELL";
    parm.type->answer = "FCELL";
    parm.type->description = _("Storage type for resultant raster map");

    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 for resultant raster map");

    parm.mult = G_define_option();
    parm.mult->key = "mult";
    parm.mult->type = TYPE_DOUBLE;
    parm.mult->answer = "1.0";
    parm.mult->required = NO;
    parm.mult->description = _("Multiplier for ASCII data");

    if (G_parser(argc, argv))
	exit(EXIT_FAILURE);
    input = parm.input->answer;
    output = parm.output->answer;
    if (title = parm.title->answer)
	G_strip(title);

    sscanf(parm.mult->answer, "%lf", &mult_fact);
    if (strcmp("CELL", parm.type->answer) == 0)
	rtype = CELL_TYPE;
    else if (strcmp("DCELL", parm.type->answer) == 0)
	rtype = DCELL_TYPE;
    else
	rtype = FCELL_TYPE;

    if (strcmp("-", input) == 0) {
	Tmp_file = G_tempfile();
	if (NULL == (Tmp_fd = fopen(Tmp_file, "w+")))
	    G_fatal_error(_("Unable to open temporary file <%s>"), Tmp_file);
	unlink(Tmp_file);
	if (0 > file_cpy(stdin, Tmp_fd))
	    exit(EXIT_FAILURE);
	fd = Tmp_fd;
    }
    else
	fd = fopen(input, "r");

    if (fd == NULL)
	G_fatal_error(_("Unable to open input file <%s>"), input);

    if (!gethead(fd, &cellhd, &missingval))
	G_fatal_error(_("Can't get cell header"));

    nrows = cellhd.rows;
    ncols = cellhd.cols;
    if (G_set_window(&cellhd) < 0)
	G_fatal_error(_("Can't set window"));

    if (nrows != G_window_rows())
	G_fatal_error(_("OOPS: rows changed from %d to %d"), nrows,
		      G_window_rows());
    if (ncols != G_window_cols())
	G_fatal_error(_("OOPS: cols changed from %d to %d"), ncols,
		      G_window_cols());

    switch (rtype) {
    case CELL_TYPE:
	cell = G_allocate_c_raster_buf();
	break;
    case FCELL_TYPE:
	fcell = G_allocate_f_raster_buf();
	break;
    case DCELL_TYPE:
	dcell = G_allocate_d_raster_buf();
	break;
    }
    cf = G_open_raster_new(output, rtype);
    if (cf < 0)
	G_fatal_error(_("Unable to create raster map <%s>"), output);

    for (row = 0; row < nrows; row++) {
	G_percent(row, nrows, 5);
	for (col = 0; col < ncols; col++) {
	    if (fscanf(fd, "%lf", &x) != 1) {
		G_unopen_cell(cf);
		G_fatal_error(_("Data conversion failed at row %d, col %d"),
			      row + 1, col + 1);
	    }
	    switch (rtype) {
	    case CELL_TYPE:
		if ((int)x == missingval)
		    G_set_c_null_value(cell + col, 1);
		else
		    cell[col] = (CELL) x *mult_fact;

		break;
	    case FCELL_TYPE:
		if ((int)x == missingval)
		    G_set_f_null_value(fcell + col, 1);
		else
		    fcell[col] = (FCELL) x *mult_fact;

		break;
	    case DCELL_TYPE:
		if ((int)x == missingval)
		    G_set_d_null_value(dcell + col, 1);
		else
		    dcell[col] = (DCELL) x *mult_fact;

		break;
	    }
	}
	switch (rtype) {
	case CELL_TYPE:
	    G_put_c_raster_row(cf, cell);
	    break;
	case FCELL_TYPE:
	    G_put_f_raster_row(cf, fcell);
	    break;
	case DCELL_TYPE:
	    G_put_d_raster_row(cf, dcell);
	    break;
	}
    }
    /* G_message(_("CREATING SUPPORT FILES FOR %s"), output); */
    G_close_cell(cf);
    if (title)
	G_put_cell_title(output, title);
    G_short_history(output, "raster", &history);
    G_command_history(&history);
    G_write_history(output, &history);


    exit(EXIT_SUCCESS);
}
コード例 #25
0
ファイル: clump.c プロジェクト: caomw/grass
CELL clump(int in_fd, int out_fd, int diag, int print)
{
    register int col;
    register int n;
    CELL NEW, OLD;
    CELL *temp_cell, *temp_clump;
    CELL *prev_in, *cur_in, *out_cell;
    CELL *prev_clump, *cur_clump;
    CELL X, LEFT;
    CELL *index, *renumber;
    CELL label;
    int nrows, ncols;
    int row;
    int len;
    int nalloc;
    long cur_time;
    char *cname;
    int cfd, csize;
    CELL cat;

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

    /* allocate clump index */
    nalloc = INCR;
    index = (CELL *) G_malloc(nalloc * sizeof(CELL));
    index[0] = 0;
    renumber = NULL;

    /* allocate CELL buffers two columns larger than current window */
    len = (ncols + 2) * sizeof(CELL);
    prev_in = (CELL *) G_malloc(len);
    cur_in = (CELL *) G_malloc(len);
    prev_clump = (CELL *) G_malloc(len);
    cur_clump = (CELL *) G_malloc(len);
    out_cell = (CELL *) G_malloc(len);

    /* temp file for initial clump IDs */
    cname = G_tempfile();
    if ((cfd = open(cname, O_RDWR | O_CREAT | O_EXCL, 0600)) < 0)
	G_fatal_error(_("Unable to open temp file"));
    csize = ncols * sizeof(CELL);

    time(&cur_time);

    /* fake a previous row which is all NULL */
    Rast_set_c_null_value(prev_in, ncols + 2);

    /* set left and right edge to NULL */
    Rast_set_c_null_value(&cur_in[0], 1);
    Rast_set_c_null_value(&cur_in[ncols + 1], 1);

    /* initialize clump labels */
    G_zero(cur_clump, len);
    G_zero(prev_clump, len);
    label = 0;

    /****************************************************
     *                      PASS 1                      *
     * pass thru the input, create initial clump labels *
     ****************************************************/

    G_message(_("Pass 1 of 2..."));
    for (row = 0; row < nrows; row++) {
	Rast_get_c_row(in_fd, cur_in + 1, row);

	G_percent(row, nrows, 4);
	Rast_set_c_null_value(&X, 1);
	for (col = 1; col <= ncols; col++) {
	    LEFT = X;
	    X = cur_in[col];
	    if (Rast_is_c_null_value(&X)) {	/* don't clump NULL data */
		cur_clump[col] = 0;
		continue;
	    }

	    /*
	     * if the cell value is different to the left and above
	     * (diagonal: and above left and above right)
	     * then we must start a new clump
	     *
	     * this new clump may eventually collide with another
	     * clump and will have to be merged
	     */

	    /* try to connect the current cell to an existing clump */
	    OLD = NEW = 0;
	    /* same clump as to the left */
	    if (X == LEFT) {
		OLD = cur_clump[col] = cur_clump[col - 1];
	    }

	    if (diag) {
		/* check above right, center, left, in that order */
		n = 2;
		temp_clump = prev_clump + col + 1;
		temp_cell = prev_in + col + 1;
		do {
		    if (X == *temp_cell) {
			cur_clump[col] = *temp_clump;
			if (OLD == 0) {
			    OLD = *temp_clump;
			    }
			else {
			    NEW = *temp_clump;
			    break;
			}
		    }
		    temp_cell--;
		    temp_clump--;
		} while (n-- > 0);
	    }
	    else {
		/* check above */
		if (X == prev_in[col]) {
		    temp_clump = prev_clump + col;
		    cur_clump[col] = *temp_clump;
		    if (OLD == 0) {
			OLD = *temp_clump;
			}
		    else {
			NEW = *temp_clump;
		    }
		}
	    }

	    if (NEW == 0 || OLD == NEW) {	/* ok */
		if (OLD == 0) {
		    /* start a new clump */
		    label++;
		    cur_clump[col] = label;
		    if (label >= nalloc) {
			nalloc += INCR;
			index =
			    (CELL *) G_realloc(index,
					       nalloc * sizeof(CELL));
		    }
		    index[label] = label;
		}
		continue;
	    }

	    /* conflict! preserve NEW clump ID and change OLD clump ID.
	     * Must go back to the left in the current row and to the right
	     * in the previous row to change all the clump values as well.
	     */

	    /* left of the current row from 1 to col - 1 */
	    temp_clump = cur_clump;
	    n = col - 1;
	    while (n-- > 0) {
		temp_clump++;	/* skip left edge */
		if (*temp_clump == OLD)
		    *temp_clump = NEW;
	    }

	    /* right of previous row from col + 1 to ncols */
	    temp_clump = prev_clump;
	    temp_clump += col;
	    n = ncols - col;
	    while (n-- > 0) {
		temp_clump++;	/* skip col */
		if (*temp_clump == OLD)
		    *temp_clump = NEW;
	    }

	    /* modify the OLD index */
	    index[OLD] = NEW;
	}

	/* write initial clump IDs */
	/* this works also with writing out cur_clump, but only 
	 * prev_clump is complete and will not change any more */
	if (row > 0) {
	    if (write(cfd, prev_clump + 1, csize) != csize)
		G_fatal_error(_("Unable to write to temp file"));
	}

	/* switch the buffers so that the current buffer becomes the previous */
	temp_cell = cur_in;
	cur_in = prev_in;
	prev_in = temp_cell;

	temp_clump = cur_clump;
	cur_clump = prev_clump;
	prev_clump = temp_clump;
    }
    /* write last row with initial clump IDs */
    if (write(cfd, prev_clump + 1, csize) != csize)
	G_fatal_error(_("Unable to write to temp file"));
    G_percent(1, 1, 1);

    /* generate a renumbering scheme */
    G_message(_("Generating renumbering scheme..."));
    G_debug(1, "%d initial labels", label);
    /* allocate final clump ID */
    renumber = (CELL *) G_malloc((label + 1) * sizeof(CELL));
    renumber[0] = 0;
    cat = 1;
    G_percent(0, label, 1);
    for (n = 1; n <= label; n++) {
	G_percent(n, label, 1);
	OLD = n;
	NEW = index[n];
	if (OLD != NEW) {
	    renumber[n] = 0;
	    /* find valid clump ID */
	    while (OLD != NEW) {
		OLD = NEW;
		NEW = index[OLD];
	    }
	    index[n] = NEW;
	}
	else
	    /* set final clump id */
	    renumber[n] = cat++;
    }
    
    /* rewind temp file */
    lseek(cfd, 0, SEEK_SET);

    if (print) {
	fprintf(stdout, "clumps=%d\n", cat - 1);
    }
    else {
	/****************************************************
	 *                      PASS 2                      *
	 * apply renumbering scheme to initial clump labels *
	 ****************************************************/

	/* the input raster is no longer needed, 
	 * using instead the temp file with initial clump labels */

	G_message(_("Pass 2 of 2..."));
	for (row = 0; row < nrows; row++) {

	    G_percent(row, nrows, 4);
	
	    if (read(cfd, cur_clump, csize) != csize)
		G_fatal_error(_("Unable to read from temp file"));

	    temp_clump = cur_clump;
	    temp_cell = out_cell;

	    for (col = 0; col < ncols; col++) {
		*temp_cell = renumber[index[*temp_clump]];
		if (*temp_cell == 0)
		    Rast_set_c_null_value(temp_cell, 1);
		temp_clump++;
		temp_cell++;
	    }
	    Rast_put_row(out_fd, out_cell, CELL_TYPE);
	}
	G_percent(1, 1, 1);
    }

    close(cfd);
    unlink(cname);

    print_time(&cur_time);

    return 0;
}
コード例 #26
0
ファイル: put_title.c プロジェクト: cran/GRASS
int G_put_cell_title (char *name, char *title)
{
    char *mapset;
    FILE *in, *out;
    char *tempfile;
    int line ;
    char buf[300];

    mapset = G_mapset() ;
    in = out = 0 ;
    in = G_fopen_old ("cats", name, mapset);
    if (!in)
    {
	sprintf (buf, "category information for [%s] in [%s] missing or invalid", name, mapset);
	G_warning (buf);
	return -1;
    }

    tempfile = G_tempfile();
    out = fopen (tempfile, "w");
    if (!out)
    {
	fclose (in);
        sprintf (buf, "G_put_title - can't create a temp file");
        G_warning (buf);
	return -1;
    }

    for (line = 0; G_getl (buf, sizeof buf, in); line++)
    {
	if (line == 1)
	{
	    strcpy (buf, title);
	    G_strip (buf);
	}
	fprintf (out, "%s\n", buf);
    }
    fclose (in);
    fclose (out);

/* must be #cats line, title line, and label for cat 0 */
    if (line < 3)
    {
	sprintf (buf, "category information for [%s] in [%s] invalid", name, mapset);
	G_warning (buf);
	return -1;
    }

    in = fopen (tempfile, "r");
    if (!in)
    {
	sprintf (buf, "G_put_title - can't reopen temp file");
	G_warning (buf);
	return -1;
    }

    out = G_fopen_new ("cats", name);
    if (!out)
    {
	fclose (in);
        sprintf (buf, "can't write category information for [%s] in [%s]", name, mapset);
        G_warning (buf);
	return -1;
    }

    while (fgets(buf, sizeof buf, in))
	fprintf (out, "%s", buf);

    fclose (in);
    fclose (out);

    return 1;
}
コード例 #27
0
ファイル: map.c プロジェクト: AsherBond/MondocosmOS
/*!
   \brief Delete vector map including attribute tables

   \param map vector map name

   \return -1 error
   \return 0 success
 */
int Vect_delete(const char *map)
{
    int i, n, ret;
    struct Map_info Map;
    struct field_info *Fi;
    char buf[GPATH_MAX];
    DIR *dir;
    struct dirent *ent;
    const char *tmp;
    char xname[GNAME_MAX], xmapset[GMAPSET_MAX];

    G_debug(3, "Delete vector '%s'", map);

    /* remove mapset from fully qualified name */
    if (G_name_is_fully_qualified(map, xname, xmapset)) {
	map = xname;
    }

    if (map == NULL || strlen(map) == 0) {
	G_warning(_("Invalid vector map name <%s>"), map ? map : "null");
	return -1;
    }

    sprintf(buf, "%s/%s/%s/%s/%s/%s", G_gisdbase(), G_location(),
	    G_mapset(), GV_DIRECTORY, map, GV_DBLN_ELEMENT);

    G_debug(1, "dbln file: %s", buf);

    if (access(buf, F_OK) == 0) {
	/* Open input */
	Vect_set_open_level(1);	/* Topo not needed */
	ret = Vect_open_old_head(&Map, map, G_mapset());
	if (ret < 1) {
	    G_warning(_("Unable to open header file for vector map <%s>"),
		      map);
	    return -1;
	}

	/* Delete all tables, NOT external (OGR) */
	if (Map.format == GV_FORMAT_NATIVE) {

	    n = Vect_get_num_dblinks(&Map);
	    for (i = 0; i < n; i++) {
		Fi = Vect_get_dblink(&Map, i);
		if (Fi == NULL) {
		    G_warning(_("Database connection not defined for layer %d"),
			      Map.dblnk->field[i].number);
		    Vect_close(&Map);
		    return -1;
		}
		G_debug(3, "Delete drv:db:table '%s:%s:%s'", Fi->driver,
			Fi->database, Fi->table);

		ret = db_table_exists(Fi->driver, Fi->database, Fi->table);
		if (ret == -1) {
		    G_warning(_("Unable to find table <%s> linked to vector map <%s>"),
			      Fi->table, map);
		    Vect_close(&Map);
		    return -1;
		}

		if (ret == 1) {
		    ret =
			db_delete_table(Fi->driver, Fi->database, Fi->table);
		    if (ret == DB_FAILED) {
			G_warning(_("Unable to delete table <%s>"),
				  Fi->table);
			Vect_close(&Map);
			return -1;
		    }
		}
		else {
		    G_warning(_("Table <%s> linked to vector map <%s> does not exist"),
			      Fi->table, map);
		}
	    }
	}
	Vect_close(&Map);
    }

    /* Delete all files from vector/name directory */
    sprintf(buf, "%s/%s/vector/%s", G_location_path(), G_mapset(), map);
    G_debug(3, "opendir '%s'", buf);
    dir = opendir(buf);
    if (dir == NULL) {
	G_warning(_("Unable to open directory '%s'"), buf);
	return -1;
    }

    while ((ent = readdir(dir))) {
	G_debug(3, "file = '%s'", ent->d_name);
	if ((strcmp(ent->d_name, ".") == 0) ||
	    (strcmp(ent->d_name, "..") == 0))
	    continue;
	sprintf(buf, "%s/%s/vector/%s/%s", G_location_path(), G_mapset(), map,
		ent->d_name);
	G_debug(3, "delete file '%s'", buf);
	ret = unlink(buf);
	if (ret == -1) {
	    G_warning(_("Unable to delete file '%s'"), buf);
	    closedir(dir);
	    return -1;
	}
    }
    closedir(dir);

    /* NFS can create .nfsxxxxxxxx files for those deleted 
     *  -> we have to move the directory to ./tmp before it is deleted */
    sprintf(buf, "%s/%s/vector/%s", G_location_path(), G_mapset(), map);

    tmp = G_tempfile();

    G_debug(3, "rename '%s' to '%s'", buf, tmp);
    ret = rename(buf, tmp);

    if (ret == -1) {
	G_warning(_("Unable to rename directory '%s' to '%s'"), buf, tmp);
	return -1;
    }

    G_debug(3, "remove directory '%s'", tmp);
    /* Warning: remove() fails on Windows */
    ret = rmdir(tmp);
    if (ret == -1) {
	G_warning(_("Unable to remove directory '%s'"), tmp);
	return -1;
    }

    return 0;
}
コード例 #28
0
ファイル: setup.c プロジェクト: AsherBond/MondocosmOS
static void set_rgn(double *msc, char *name, char *name1, char *name2)
{
    char reg_name[20];
    int x0, y0, xp, yp, *x, *y, xstart, ystart, btn, d, method, meth;
    static int pts, rgn_cnt = 0;
    double dtmp, etmp;
    FILE *tmp;
    char *tempfile;

    /* get the name of the regions map */

    if (!G_ask_cell_new("    ENTER THE NEW REGION MAP NAME:", reg_name))
	return;

    /* allocate memory for storing the
       points along the boundary of each
       region */

    x = (int *)G_malloc(100 * sizeof(int));
    y = (int *)G_malloc(100 * sizeof(int));

    tempfile = G_tempfile();
    tmp = fopen(tempfile, "w");

  back2:
    G_system("clear");
    fprintf(stderr, "\n\n    CHOOSE AN OPTION:\n\n");
    fprintf(stderr, "       Draw a region                     1\n");
    fprintf(stderr, "       Quit drawing regions and return");
    fprintf(stderr, "\n          to setup options menu          2\n");
    fprintf(stderr, "       Change the color for drawing      3\n\n");

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

    if (meth == 2)
	return;
    if (meth == 3) {
	R_open_driver();
	change_draw();
    }
    if (meth == 1) {
	R_open_driver();
	rgn_cnt = 0;
    }

    /* ask the user to outline a region */

  back:
    G_system("clear");
    ppoint(NULL, 0, 0, -1);
    fprintf(stderr, "\n    PLEASE OUTLINE REGION # %d\n", (++rgn_cnt));
    pbutton(0);
    pts = 0;
    x0 = 0;
    y0 = 0;

    /* get the points along the boundary
       of the region as they are drawn */

    do {
	btn = 0;
	R_get_location_with_line(x0, y0, &xp, &yp, &btn);
	if (btn == 1)
	    ppoint(msc, xp, yp, 0);
	else if (btn == 2) {
	    if (!pts) {
		pbutton(1);
		R_move_abs(xp, yp);
		xstart = xp;
		ystart = yp;
	    }
	    x[pts] = xp * msc[0];
	    y[pts] = yp * msc[1];
	    ppoint(msc, xp, yp, (++pts));
	    x0 = xp;
	    y0 = yp;
	    R_cont_abs(x0, y0);
	}
	else if (btn == 3 && pts < 3) {
	    fprintf(stderr,
		    "\n\n    Please digitize more than 2 boundary points\n\n");
	}
    }
    while (btn != 3 || pts < 3);

    R_cont_abs(xstart, ystart);
    R_close_driver();
    R_open_driver();
    x[pts] = x[0];
    y[pts] = y[0];
    pts++;

    /* redisplay the menu and find out what
       to do next */
  back1:
    G_system("clear");
    fprintf(stderr, "\n\n    CHOOSE AN OPTION:\n\n");
    fprintf(stderr,
	    "       Draw another region                          1\n");
    fprintf(stderr,
	    "       Start over drawing regions                   2\n");
    fprintf(stderr,
	    "       Quit drawing and save the region map         3\n");
    fprintf(stderr,
	    "       Quit drawing and don't save the region map   4\n");
    fprintf(stderr,
	    "       Change the color for drawing                 5\n\n");
    do {
	fprintf(stderr,
		"                                        Which Number?  ");
	numtrap(1, &dtmp);
	if ((method = fabs(dtmp)) > 5 || method < 1) {
	    fprintf(stderr, "\n    Choice must between 1-5; try again");
	}
    }
    while (method > 5 || method < 1);


    /* save the region and draw another */

    if (method == 1) {
	save_rgn(reg_name, tempfile, tmp, x, y, pts, rgn_cnt, 1);
	goto back;
    }

    /* start over */

    else if (method == 2) {
	fclose(tmp);
	if (!(tmp = fopen(tempfile, "w")))
	    G_fatal_error
		("Can't open temporary file for storing region info\n");
	rgn_cnt = 0;
	R_close_driver();
	paint_map(name, name1, name2);
	goto back2;
    }

    /* save the region and exit */

    else if (method == 3)
	save_rgn(reg_name, tempfile, tmp, x, y, pts, rgn_cnt, 2);


    /* change the color for drawing */

    else if (method == 5) {
	change_draw();
	goto back1;
    }

    R_close_driver();
    G_free(x);
    G_free(y);
    unlink(tempfile);
    return;

}
コード例 #29
0
ファイル: main.c プロジェクト: AsherBond/MondocosmOS
int main(int argc, char **argv)
{
    struct Cell_head window;
    struct Categories cats;
    struct GModule *module;
    struct Option *opt1, *opt2, *opt3;
    struct Flag *fancy_mode, *simple_mode, *draw;
    char *tmpfile;
    FILE *fp;

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

    module = G_define_module();
    G_add_keyword(_("display"));
    G_add_keyword(_("cartography"));
    module->description =
	_("Create a TITLE for a raster map in a form suitable "
	  "for display with d.text.");

    opt1 = G_define_standard_option(G_OPT_R_MAP);

    opt2 = G_define_option();
    opt2->key = "color";
    opt2->type = TYPE_STRING;
    opt2->answer = DEFAULT_FG_COLOR;
    opt2->required = NO;
    opt2->gisprompt = "old_color,color,color";
    opt2->description = _("Sets the text color");

    opt3 = G_define_option();
    opt3->key = "size";
    opt3->type = TYPE_DOUBLE;
    opt3->answer = "4.0";
    opt3->options = "0-100";
    opt3->description =
	_("Sets the text size as percentage of the frame's height");

    draw = G_define_flag();
    draw->key = 'd';
    draw->description = _("Draw title on current display");

    fancy_mode = G_define_flag();
    fancy_mode->key = 'f';
    fancy_mode->description = _("Do a fancier title");

    /* currently just title, but it doesn't have to be /that/ simple */
    simple_mode = G_define_flag();
    simple_mode->key = 's';
    simple_mode->description = _("Do a simple title");


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


    map_name = opt1->answer;

    color = opt2->answer;

    if (opt3->answer != NULL)
	sscanf(opt3->answer, "%f", &size);

    type = fancy_mode->answer ? FANCY : NORMAL;

    if (fancy_mode->answer && simple_mode->answer)
	G_fatal_error(_("Title can be fancy or simple, not both"));

    if (!strlen(map_name))
	G_fatal_error(_("No map name given"));

    Rast_get_cellhd(map_name, "", &window);

    if (Rast_read_cats(map_name, "", &cats) == -1)
	G_fatal_error(_("Unable to read category file of raster map <%s>"),
		      map_name);


    if (draw->answer) {
	tmpfile = G_convert_dirseps_to_host(G_tempfile());
	if (!(fp = fopen(tmpfile, "w")))
	    G_fatal_error(_("Unable to open temporary file <%s>"), tmpfile);
    }
    else
	fp = stdout;


    if (type == NORMAL)
	normal(&window, &cats, simple_mode->answer, fp);
    else
	fancy(&window, &cats, fp);


    if (draw->answer) {
	char inarg[GPATH_MAX];
	fclose(fp);
	sprintf(inarg, "input=%s", tmpfile);
	G_spawn("d.text", "d.text", inarg, NULL);
	unlink(tmpfile);
	/* note a tmp file will remain, created by d.text so it can survive d.redraw */
    }

    exit(EXIT_SUCCESS);
}
コード例 #30
0
ファイル: open_files.c プロジェクト: felipebetancur/grass-ci
static int load_seeds(struct globals *globals, int srows, int scols, int nseg)
{
    int row, col;
    SEGMENT seeds_seg;
    CELL *seeds_buf, seeds_val;
    int seeds_fd;
    int spos, sneg, have_seeds;
    struct rc Ri;

    G_debug(1, "load_seeds()");
    
    G_message(_("Loading seeds from raster map <%s>..."), globals->seeds);

    if (Segment_open
	(&seeds_seg, G_tempfile(), globals->nrows, globals->ncols,
	 srows, scols, sizeof(CELL), nseg) != TRUE)
	G_fatal_error("Unable to create bounds temporary files");

    seeds_fd = Rast_open_old(globals->seeds, "");
    seeds_buf = Rast_allocate_c_buf();
    
    have_seeds = 0;

    /* load seeds map to segment structure */
    for (row = 0; row < globals->nrows; row++) {
	Rast_get_c_row(seeds_fd, seeds_buf, row);
	for (col = 0; col < globals->ncols; col++) {
	    if (FLAG_GET(globals->null_flag, row, col)) {
		Rast_set_c_null_value(&seeds_val, 1);
	    }
	    else {
		seeds_val = seeds_buf[col];
		if (!Rast_is_c_null_value(&seeds_val))
		    have_seeds = 1;
	    }
	    if (Segment_put(&seeds_seg, &seeds_val, row, col) != 1)
		G_fatal_error(_("Unable to write to temporary file"));
	}
    }

    if (!have_seeds) {
	G_warning(_("No seeds found in '%s'!"), globals->seeds);
	G_free(seeds_buf);
	Rast_close(seeds_fd);
	Segment_close(&seeds_seg);
	return 0;
    }

    spos = 1;
    sneg = -1;

    /* convert seeds to regions */
    G_debug(1, "convert seeds to regions");
    Rast_set_c_null_value(&seeds_val, 1);
    for (row = 0; row < globals->nrows; row++) {
	Rast_get_c_row(seeds_fd, seeds_buf, row);
	for (col = 0; col < globals->ncols; col++) {
	    if (!(FLAG_GET(globals->null_flag, row, col)) && 
	        !(FLAG_GET(globals->candidate_flag, row, col))) {

		if (Rast_is_c_null_value(&(seeds_buf[col]))) {
		    if (Segment_put(&globals->rid_seg, &sneg, row, col) != 1)
			G_fatal_error(_("Unable to write to temporary file"));
		    sneg--;
		    globals->n_regions--;
		}
		else {
		    Ri.row = row;
		    Ri.col = col;
		    read_seed(globals, &seeds_seg, &Ri, spos);
		    spos++;
		}
	    }
	}
    }

    G_free(seeds_buf);
    Rast_close(seeds_fd);
    Segment_close(&seeds_seg);

    globals->n_regions = spos - 1;
    
    flag_clear_all(globals->candidate_flag);
    
    return 1;
}