Example #1
0
static void do_reclass_int(int fd, void *cell, int null_is_zero)
{
    struct fileinfo *fcb = &R__.fileinfo[fd];
    CELL *c = cell;
    CELL *reclass_table = fcb->reclass.table;
    CELL min = fcb->reclass.min;
    CELL max = fcb->reclass.max;
    int i;

    for (i = 0; i < R__.rd_window.cols; i++) {
	if (Rast_is_c_null_value(&c[i])) {
	    if (null_is_zero)
		c[i] = 0;
	    continue;
	}

	if (c[i] < min || c[i] > max) {
	    if (null_is_zero)
		c[i] = 0;
	    else
		Rast_set_c_null_value(&c[i], 1);
	    continue;
	}

	c[i] = reclass_table[c[i] - min];

	if (null_is_zero && Rast_is_c_null_value(&c[i]))
	    c[i] = 0;
    }
}
Example #2
0
int read_range(void)
{
    struct FPRange drange;
    struct Range range;
    CELL tmp_min, tmp_max;
    DCELL tmp_dmin, tmp_dmax;
    char buff[1024];
    int i;

    /* read the fpranges and ranges of all input maps */
    for (i = 0; i < noi; i++) {
        if (Rast_read_fp_range(name[i], G_mapset(), &drange) <= 0) {
            sprintf(buff, "Can't read f_range for map %s", name[i]);
            G_fatal_error("%s", buff);
        }
        Rast_get_fp_range_min_max(&drange, &tmp_dmin, &tmp_dmax);

        if (Rast_read_range(name[i], G_mapset(), &range) <= 0) {
            sprintf(buff, "Can't read range for map %s", name[i]);
            G_fatal_error("%s", buff);
        }
        Rast_get_range_min_max(&range, &tmp_min, &tmp_max);
        if (!i || tmp_max > old_max || Rast_is_c_null_value(&old_max))
            old_max = tmp_max;
        if (!i || tmp_min < old_min || Rast_is_c_null_value(&old_min))
            old_min = tmp_min;
        if (!i || tmp_dmax > old_dmax || Rast_is_d_null_value(&old_dmax))
            old_dmax = tmp_dmax;
        if (!i || tmp_dmin < old_dmin || Rast_is_d_null_value(&old_dmin))
            old_dmin = tmp_dmin;
    }				/* for loop */

    return 0;
}
Example #3
0
/*!
 * \brief Add data to cell stats
 *
 * The <i>n</i> CELL values in the <i>data</i> array are inserted (and
 * counted) in the Cell_stats structure.
 *
 * Look for NULLs and update the NULL-value count.
 *
 * \param cell raster values
 * \param n number of values
 * \param s pointer to Cell_stats structure which holds cell stats info
 *
 * \return 1 on failure
 * \return 0 on success
 */
int Rast_update_cell_stats(const CELL * cell, int n, struct Cell_stats *s)
{
    CELL cat;
    int p, q;
    int idx, offset;
    int N;
    NODE *node, *pnode;
    NODE *new_node;

    if (n <= 0)
	return 1;

    node = s->node;

    /* first non-null node is special case */
    if ((N = s->N) == 0) {
	cat = *cell++;
	while (Rast_is_c_null_value(&cat)) {
	    s->null_data_count++;
	    cat = *cell++;
	    n--;
	}
	if (n > 0) {		/* if there are some non-null cells */
	    N = 1;
	    if (cat < 0) {
		idx = -((-cat) >> SHIFT) - 1;
		offset = cat + ((-idx) << SHIFT) - 1;
	    }
Example #4
0
File: range.c Project: caomw/grass
/*!
 * \brief Get range min and max
 *
 * The mininum and maximum CELL values are extracted from the
 * <i>range</i> structure.
 *
 * If the range structure has no defined min/max (first!=0) there will
 * not be a valid range. In this case the min and max returned must be
 * the NULL-value.
 *
 * \param range pointer to Range structure which holds range info
 * \param[out] min minimum value
 * \param[out] max maximum value
 */
void Rast_get_range_min_max(const struct Range *range, CELL * min, CELL * max)
{
    if (range->first_time) {
	Rast_set_c_null_value(min, 1);
	Rast_set_c_null_value(max, 1);
    }
    else {
	if (Rast_is_c_null_value(&(range->min)))
	    Rast_set_c_null_value(min, 1);
	else
	    *min = range->min;

	if (Rast_is_c_null_value(&(range->max)))
	    Rast_set_c_null_value(max, 1);
	else
	    *max = range->max;
    }
}
Example #5
0
int pval(void *rast, int i)
{
    void *ptr = (void *)((CELL *) rast + i);

    if (Rast_is_c_null_value(ptr))
        return 0;
    else
        return (int)((CELL *) rast)[i];
}
Example #6
0
void new_stats(const char *name, struct Reclass *reclass)
{
    struct Histogram histo, histo2;
    struct Range range;
    CELL cat, cat2;
    int i;
    CELL min, max;

    min = reclass->min;
    max = reclass->max;

    /* read histogram for original file */
    G_suppress_warnings(1);
    i = Rast_read_histogram(reclass->name, reclass->mapset, &histo);
    G_suppress_warnings(0);
    if (i <= 0)
	return;

    /* compute data rage for reclass */
    Rast_init_range(&range);

    for (i = 0; i < histo.num; i++) {
	cat = histo.list[i].cat;
	if (cat < min || cat > max)
	    continue;
	cat2 = reclass->table[cat - min];
	Rast_update_range(cat2, &range);
    }
    Rast_write_range(name, &range);

    /* now generate a histogram from the original */

    /* allocate histogram list */
    histo2.num += range.max - range.min + 1;

    histo2.list = (LIST *) G_calloc(histo2.num, sizeof(LIST));

    /* set all counts to 0 */
    i = 0;
    for (cat = range.min; cat <= range.max; cat++) {
	histo2.list[i].cat = cat;
	histo2.list[i++].count = 0;
    }

    /* go thru original histogram and add into histo2 */
    for (i = 0; i < histo.num; i++) {
	cat = histo.list[i].cat;
	if (cat < min || cat > max)
	    Rast_set_c_null_value(&cat, 1);
	else
	    cat2 = reclass->table[cat - min];
	if (!Rast_is_c_null_value(&cat))
	    histo2.list[cat2 - range.min].count += histo.list[i].count;
    }
    Rast_write_histogram(name, &histo2);
}
Example #7
0
int recurse_cell(CELL flag, int i, int j, int nl, int ns,
                 struct whereandwhat bas[], struct whereandwhat dir[])
{
    CELL edge;
    int rc = 0;

    if (j == 0 && j >= ns - 1)
        return rc;

    if (bas[i].p[j] != flag) {
        rc = 1;
        bas[i].p[j] = flag;
    }

    if (i > 0) {
        edge = dir[i - 1].p[j - 1];
        if (bas[i - 1].p[j - 1] == -1 && !Rast_is_c_null_value(&edge) &&
                edge == 4)
            rc += recurse_cell(flag, i - 1, j - 1, nl, ns, bas, dir);
        edge = dir[i - 1].p[j];
        if (bas[i - 1].p[j] == -1 && !Rast_is_c_null_value(&edge) && edge == 8)
            rc += recurse_cell(flag, i - 1, j, nl, ns, bas, dir);
        edge = dir[i - 1].p[j + 1];
        if (bas[i - 1].p[j + 1] == -1 && !Rast_is_c_null_value(&edge) &&
                edge == 16)
            rc += recurse_cell(flag, i - 1, j + 1, nl, ns, bas, dir);

    }

    edge = dir[i].p[j - 1];
    if (bas[i].p[j - 1] == -1 && !Rast_is_c_null_value(&edge) && edge == 2)
        rc += recurse_cell(flag, i, j - 1, nl, ns, bas, dir);

    edge = dir[i].p[j + 1];
    if (bas[i].p[j + 1] == -1 && !Rast_is_c_null_value(&edge) && edge == 32)
        rc += recurse_cell(flag, i, j + 1, nl, ns, bas, dir);

    if (i < nl - 1) {
        edge = dir[i + 1].p[j - 1];
        if (bas[i + 1].p[j - 1] == -1 && !Rast_is_c_null_value(&edge) &&
                edge == 1)
            rc += recurse_cell(flag, i + 1, j - 1, nl, ns, bas, dir);
        edge = dir[i + 1].p[j];
        if (bas[i + 1].p[j] == -1 && !Rast_is_c_null_value(&edge) && edge == 128)
            rc += recurse_cell(flag, i + 1, j, nl, ns, bas, dir);
        edge = dir[i + 1].p[j + 1];
        if (bas[i + 1].p[j + 1] == -1 && !Rast_is_c_null_value(&edge) &&
                edge == 64)
            rc += recurse_cell(flag, i + 1, j + 1, nl, ns, bas, dir);
    }
    return rc;
}
Example #8
0
int report_range(void)
{
    char buff[300], buff2[300];

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

    return 0;
}
Example #9
0
/*!
   \brief Get number of categories

   \param name raster map name
   \param mapset mapset name

   \return -1 on error
   \return number of cats
 */
CELL Rast_get_max_c_cat(const char *name, const char *mapset)
{
    struct Range range;
    CELL min, max;

    /* return the max category number */
    if (Rast_read_range(name, mapset, &range) < 0)
	return -1;
    Rast_get_range_min_max(&range, &min, &max);
    if (Rast_is_c_null_value(&max))
	max = 0;
    return max;
}
Example #10
0
static void convert_and_write_id(int fd, const void *vbuf)
{
    const CELL *buf = vbuf;
    struct fileinfo *fcb = &R__.fileinfo[fd];
    DCELL *p = (DCELL *) fcb->data;
    int i;

    for (i = 0; i < fcb->cellhd.cols; i++)
	if (Rast_is_c_null_value(&buf[i]))
	    Rast_set_d_null_value(&p[i], 1);
	else
	    p[i] = (DCELL) buf[i];

    Rast_put_d_row(fd, p);
}
Example #11
0
File: range.c Project: caomw/grass
/*!
 * \brief Update range structure (CELL)
 *
 * Compares the <i>cat</i> value with the minimum and maximum values
 * in the <i>range</i> structure, modifying the range if <i>cat</i>
 * extends the range.
 *
 * NULL-values must be detected and ignored.
 *
 * \param cat raster value
 * \param range pointer to Range structure which holds range info
 */
void Rast_update_range(CELL cat, struct Range *range)
{
    if (!Rast_is_c_null_value(&cat)) {
	if (range->first_time) {
	    range->first_time = 0;
	    range->min = cat;
	    range->max = cat;
	    return;
	}
	if (cat < range->min)
	    range->min = cat;
	if (cat > range->max)
	    range->max = cat;
    }
}
Example #12
0
int report_range(void)
{
    struct FPRange drange;
    struct Range range;
    char buff[1024], buff2[300];
    RASTER_MAP_TYPE inp_type;

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

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

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

    return 0;
}
Example #13
0
int is_null_value(struct RASTER_MAP_PTR buf, int col)
{
    switch (buf.type) {
    case CELL_TYPE:
	return Rast_is_c_null_value(&buf.data.c[col]);
	break;
    case FCELL_TYPE:
	return Rast_is_f_null_value(&buf.data.f[col]);
	break;
    case DCELL_TYPE:
	return Rast_is_d_null_value(&buf.data.d[col]);
	break;
    }

    return -1;
}
Example #14
0
/*!
   \brief Read or simulate null value row

   Read or simulate null value row and set the cells corresponding 
   to null value to 1. The masked out cells are set to null when the
   mask exists. (the MASK is taken care of by null values
   (if the null file doesn't exist for this map, then the null row
   is simulated by assuming that all zeros in raster map are nulls.
   Also all masked out cells become nulls.

   \param fd file descriptor for the opened map
   \param buf buffer for the row to be placed into
   \param flags
   \param row data row desired

   \return void
 */
void Rast_get_null_value_row(int fd, char *flags, int row)
{
    struct fileinfo *fcb = &R__.fileinfo[fd];

    if (!fcb->reclass_flag)
	get_null_value_row(fd, flags, row, 1);
    else {
	CELL *buf = G_alloca(R__.rd_window.cols * sizeof(CELL));
	int i;

	Rast_get_c_row(fd, buf, row);
	for (i = 0; i < R__.rd_window.cols; i++)
	    flags[i] = Rast_is_c_null_value(&buf[i]) ? 1 : 0;

	G_freea(buf);
    }
}
Example #15
0
File: Gs3.c Project: caomw/grass
/*!
   \brief Load raster map as integer map

   Calling function must have already allocated space in buff for
   struct BM of wind->rows & wind->cols.

   This routine simply loads the map into the bitmap by repetitve calls
   to get_map_row.  Any value other than 0 in the map will set the bitmap.
   (may want to change later to allow specific value to set)

   Changed to use null.

   \param wind current window
   \param map_name raster map name
   \param[out] buff data buffer

   \returns 1 on success
   \return -1 on failure
 */
int Gs_loadmap_as_bitmap(struct Cell_head *wind, const char *map_name,
			 struct BM *buff)
{
    FILEDESC cellfile;
    const char *map_set;
    int *tmp_buf;
    int row, col;

    G_debug(3, "Gs_loadmap_as_bitmap");

    map_set = G_find_raster2(map_name, "");
    if (!map_set) {
	G_warning(_("Raster map <%s> not found"), map_name);
	return -1;
    }

    cellfile = Rast_open_old(map_name, map_set);

    tmp_buf = (int *)G_malloc(wind->cols * sizeof(int));	/* G_fatal_error */
    if (!tmp_buf) {
	return -1;
    }

    G_message(_("Loading raster map <%s>..."),
	      G_fully_qualified_name(map_name, map_set));

    for (row = 0; row < wind->rows; row++) {
	Rast_get_c_row(cellfile, tmp_buf, row);

	for (col = 0; col < wind->cols; col++) {
	    if (Rast_is_c_null_value(&tmp_buf[col])) {
		/* no data */
		BM_set(buff, col, row, 1);
	    }
	    else {
		BM_set(buff, col, row, 0);
	    }
	}
    }

    Rast_close(cellfile);

    G_free(tmp_buf);

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

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

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

	out_fd[quant] = Rast_open_fp_new(output);
    }

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

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

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

	    Rast_put_d_row(out_fd[quant], out_buf);
	}

	G_percent(row, rows, 2);
    }

    G_percent(row, rows, 2);

    for (quant = 0; quant < num_quants; quant++) {
	Rast_close(out_fd[quant]);
	if (have_colors)
	    Rast_write_colors(outputs[quant], mapset, &colors);
    }
}
Example #17
0
/*!
 * \brief Looks up the category label for each raster value (DCELL).
 * 
 * Looks up the category label for each raster value in the
 * <i>rast_row</i> and updates the marks for labels found.
 *
 * <b>Note:</b> Non-zero mark for i-th label stores the number of of
 * raster cells read so far which are labeled with i-th label and fall
 * into i-th data range.
 *
 * \param rast_row raster row to update stats
 * \param ncols number of columns
 * \param pcats pointer to Categories structure
 *
 * \return -1 on error
 * \return 1 on success
 */
int Rast_mark_cats(const void *rast_row,
		   int ncols, struct Categories *pcats,
		   RASTER_MAP_TYPE data_type)
{
    size_t size = Rast_cell_size(data_type);
    CELL i;

    while (ncols-- > 0) {
	i = Rast_quant_get_cell_value(&pcats->q,
				      Rast_get_d_value(rast_row, data_type));
	if (Rast_is_c_null_value(&i))
	    continue;
	if (i > pcats->ncats)
	    return -1;
	pcats->marks[i]++;
	rast_row = G_incr_void_ptr(rast_row, size);
    }
    return 1;
}
Example #18
0
static void fill_bins(int basefile, int coverfile)
{
    CELL *basebuf = Rast_allocate_c_buf();
    DCELL *coverbuf = Rast_allocate_d_buf();
    int row, col;

    G_message(_("Binning data"));

    for (row = 0; row < rows; row++) {
	Rast_get_c_row(basefile, basebuf, row);
	Rast_get_d_row(coverfile, coverbuf, row);

	for (col = 0; col < cols; col++) {
	    struct basecat *bc;
	    int i, bin;
	    struct bin *b;

	    if (Rast_is_c_null_value(&basebuf[col]))
		continue;

	    if (Rast_is_d_null_value(&coverbuf[col]))
		continue;

	    i = get_slot(coverbuf[col]);
	    bc = &basecats[basebuf[col] - min];
	    if (!bc->slot_bins[i])
		continue;

	    bin = bc->slot_bins[i] - 1;
	    b = &bc->bins[bin];

	    bc->values[b->base + b->count++] = coverbuf[col];
	}

	G_percent(row, rows, 2);
    }

    G_percent(rows, rows, 2);
    G_free(basebuf);
    G_free(coverbuf);
}
Example #19
0
static void convert_int(unsigned char *wk, char *null_buf, const CELL * rast,
			int n, int len, int zeros_r_nulls)
{
    int i;

    /* transform CELL data into non-machine dependent multi-byte format */

    for (i = 0; i < n; i++) {
	CELL v = rast[i];
	int neg;
	int k;

	/* substitute embeded null vals by 0's */
	if (Rast_is_c_null_value(&v)) {
	    v = 0;
	    null_buf[i] = 1;
	}
	else if (zeros_r_nulls && !v)
	    null_buf[i] = 1;

	/* negatives */
	if (v < 0) {
	    neg = 1;
	    v = -v;
	}
	else
	    neg = 0;

	/* copy byte by byte */
	for (k = len - 1; k >= 0; k--) {
	    wk[k] = v & 0xff;
	    v >>= 8;
	}

	/* set negative bit in first byte */
	if (neg)
	    wk[0] |= 0x80;

	wk += len;
    }
}
Example #20
0
File: range.c Project: caomw/grass
/*!
 * \brief Update range structure based on raster row
 *
 * Note: for internal use only.
 *
 * \param cell raster values
 * \param n number of values
 * \param range pointer to Range structure which holds range info
 * \param ignore_zeros ignore zeros
 */
void Rast__row_update_range(const CELL * cell, int n,
			    struct Range *range, int ignore_zeros)
{
    CELL cat;

    while (n-- > 0) {
	cat = *cell++;
	if (Rast_is_c_null_value(&cat) || (ignore_zeros && !cat))
	    continue;
	if (range->first_time) {
	    range->first_time = 0;
	    range->min = cat;
	    range->max = cat;
	    continue;
	}
	if (cat < range->min)
	    range->min = cat;
	if (cat > range->max)
	    range->max = cat;
    }
}
Example #21
0
/* 0 on out of region or NULL, 1 on success */
int rast_segment_get_value_xy(SEGMENT * base_segment,
                              struct Cell_head *input_region,
                              RASTER_MAP_TYPE rtype, double x, double y,
                              double *value)
{
    /* Rast gives double, Segment needs off_t */
    off_t base_row = Rast_northing_to_row(y, input_region);
    off_t base_col = Rast_easting_to_col(x, input_region);

    /* skip points which are outside the base raster
     * (null propagation) */
    if (base_row < 0 || base_col < 0 ||
            base_row >= input_region->rows || base_col >= input_region->cols)
        return 0;
    if (rtype == DCELL_TYPE) {
        DCELL tmp;

        Segment_get(base_segment, &tmp, base_row, base_col);
        if (Rast_is_d_null_value(&tmp))
            return 0;
        *value = (double)tmp;
    }
    else if (rtype == FCELL_TYPE) {
        FCELL tmp;

        Segment_get(base_segment, &tmp, base_row, base_col);
        if (Rast_is_f_null_value(&tmp))
            return 0;
        *value = (double)tmp;
    }
    else {
        CELL tmp;

        Segment_get(base_segment, &tmp, base_row, base_col);
        if (Rast_is_c_null_value(&tmp))
            return 0;
        *value = (double)tmp;
    }
    return 1;
}
Example #22
0
static void get_slot_counts(int basefile, int coverfile)
{
    CELL *basebuf = Rast_allocate_c_buf();
    DCELL *coverbuf = Rast_allocate_d_buf();
    int row, col;

    G_message(_("Computing histograms"));

    for (row = 0; row < rows; row++) {
	Rast_get_c_row(basefile, basebuf, row);
	Rast_get_d_row(coverfile, coverbuf, row);

	for (col = 0; col < cols; col++) {
	    struct basecat *bc;
	    int i;

	    if (Rast_is_c_null_value(&basebuf[col]))
		continue;

	    if (Rast_is_d_null_value(&coverbuf[col]))
		continue;

	    i = get_slot(coverbuf[col]);
	    bc = &basecats[basebuf[col] - min];

	    bc->slots[i]++;
	    bc->total++;
	}

	G_percent(row, rows, 2);
    }

    G_percent(rows, rows, 2);
    G_free(basebuf);
    G_free(coverbuf);
}
Example #23
0
static void embed_mask(char *flags, int row)
{
    CELL *mask_buf = G_alloca(R__.rd_window.cols * sizeof(CELL));
    int i;

    if (R__.auto_mask <= 0)
	return;

    if (get_map_row_nomask(R__.mask_fd, mask_buf, row, CELL_TYPE) < 0) {
	G_freea(mask_buf);
	return;
    }

    if (R__.fileinfo[R__.mask_fd].reclass_flag) {
	embed_nulls(R__.mask_fd, mask_buf, row, CELL_TYPE, 0, 0);
	do_reclass_int(R__.mask_fd, mask_buf, 1);
    }

    for (i = 0; i < R__.rd_window.cols; i++)
	if (mask_buf[i] == 0 || Rast_is_c_null_value(&mask_buf[i]))
	    flags[i] = 1;

    G_freea(mask_buf);
}
Example #24
0
int renumber(int in, int out)
{
    CELL *cell, *c;
    int row, col;

    cell = Rast_allocate_c_buf();

    G_message(_("%s: STEP 3 ... "), G_program_name());
    for (row = 0; row < nrows; row++) {
	G_percent(row, nrows, 5);
	Rast_get_c_row(in, c = cell, row);
	col = ncols;
	while (col-- > 0) {
	    if (!Rast_is_c_null_value(c))
		*c = table[*c];
	    c++;
	}
	Rast_put_row(out, cell, CELL_TYPE);
    }
    G_percent(row, nrows, 10);
    G_free(cell);

    return 0;
}
Example #25
0
int read_input_map(char *input, char *mapset, int ZEROFLAG)
{
    int fd;
    int row;
    int hit;
    register int col;
    register CELL *cell;
    register MAPTYPE *ptr;

    map = (MAPTYPE *) G_malloc((size_t) window.rows * window.cols * sizeof(MAPTYPE));

    fd = Rast_open_old(input, mapset);

    cell = Rast_allocate_c_buf();

    ptr = map;

    minrow = -1;
    maxrow = -1;
    mincol = window.cols;
    maxcol = 0;

    G_message(_("Reading input raster map <%s>..."),
	      G_fully_qualified_name(input, mapset));

    count_rows_with_data = 0;

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

	Rast_get_c_row(fd, cell, row);

	for (col = 0; col < window.cols; col++) {
	    if (ZEROFLAG) {
		if ((*ptr++ = (*cell++ != 0))) {
		    if (minrow < 0)
			minrow = row;
		    maxrow = row;
		    if (col < mincol)
			mincol = col;
		    if (col > maxcol)
			maxcol = col;
		    if (!hit) {
			count_rows_with_data++;
			hit = 1;
		    }
		}
	    }
	    else {		/* use NULL */

		if ((*ptr++ = !Rast_is_c_null_value(cell++))) {
		    if (minrow < 0)
			minrow = row;
		    maxrow = row;
		    if (col < mincol)
			mincol = col;
		    if (col > maxcol)
			maxcol = col;
		    if (!hit) {
			count_rows_with_data++;
			hit = 1;
		    }
		}
	    }
	}
	cell -= window.cols;
    }
    G_percent(row, window.rows, 2);
    Rast_close(fd);
    G_free(cell);

    return 0;
}
Example #26
0
int init_search(int depr_fd)
{
    int r, c, r_nbr, c_nbr, ct_dir;
    CELL *depr_buf, ele_value;
    int nextdr[8] = { 1, -1, 0, 0, -1, 1, 1, -1 };
    int nextdc[8] = { 0, 0, -1, 1, 1, -1, 1, -1 };
    char asp_value, is_null;
    WAT_ALT wa;
    ASP_FLAG af, af_nbr;
    GW_LARGE_INT n_depr_cells = 0;

    nxt_avail_pt = heap_size = 0;

    /* load edge cells and real depressions to A* heap */
    if (depr_fd >= 0)
	depr_buf = Rast_allocate_buf(CELL_TYPE);
    else
	depr_buf = NULL;

    G_message(_("Initializing A* search..."));
    for (r = 0; r < nrows; r++) {
	G_percent(r, nrows, 2);

	if (depr_fd >= 0) {
	    Rast_get_row(depr_fd, depr_buf, r, CELL_TYPE);
	}

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

	    seg_get(&aspflag, (char *)&af, r, c);
	    is_null = FLAG_GET(af.flag, NULLFLAG);

	    if (is_null)
		continue;

	    asp_value = 0;
	    if (r == 0 || r == nrows - 1 || c == 0 || c == ncols - 1) {

		if (r == 0 && c == 0)
		    asp_value = -7;
		else if (r == 0 && c == ncols - 1)
		    asp_value = -5;
		else if (r == nrows - 1 && c == 0)
		    asp_value = -1;
		else if (r == nrows - 1 && c == ncols - 1)
		    asp_value = -3;
		else if (r == 0)
		    asp_value = -2;
		else if (c == 0)
		    asp_value = -4;
		else if (r == nrows - 1)
		    asp_value = -6;
		else if (c == ncols - 1)
		    asp_value = -8;

		seg_get(&watalt, (char *)&wa, r, c);
		ele_value = wa.ele;
		heap_add(r, c, ele_value);
		FLAG_SET(af.flag, INLISTFLAG);
		FLAG_SET(af.flag, EDGEFLAG);
		af.asp = asp_value;
		seg_put(&aspflag, (char *)&af, r, c);
		continue;
	    }

	    /* any neighbour NULL ? */
	    for (ct_dir = 0; ct_dir < sides; ct_dir++) {
		/* get r, c (r_nbr, c_nbr) for neighbours */
		r_nbr = r + nextdr[ct_dir];
		c_nbr = c + nextdc[ct_dir];

		seg_get(&aspflag, (char *)&af_nbr, r_nbr, c_nbr);
		is_null = FLAG_GET(af_nbr.flag, NULLFLAG);

		if (is_null) {
		    asp_value = -1 * drain[r - r_nbr + 1][c - c_nbr + 1];
		    seg_get(&watalt, (char *)&wa, r, c);
		    ele_value = wa.ele;
		    heap_add(r, c, ele_value);
		    FLAG_SET(af.flag, INLISTFLAG);
		    FLAG_SET(af.flag, EDGEFLAG);
		    af.asp = asp_value;
		    seg_put(&aspflag, (char *)&af, r, c);

		    break;
		}
	    }
	    if (asp_value) /* some neighbour was NULL, point added to list */
		continue;
	    
	    /* real depression ? */
	    if (depr_fd >= 0) {
		if (!Rast_is_c_null_value(&depr_buf[c]) && depr_buf[c] != 0) {
		    seg_get(&watalt, (char *)&wa, r, c);
		    ele_value = wa.ele;
		    heap_add(r, c, ele_value);
		    FLAG_SET(af.flag, INLISTFLAG);
		    FLAG_SET(af.flag, DEPRFLAG);
		    af.asp = asp_value;
		    seg_put(&aspflag, (char *)&af, r, c);
		    n_depr_cells++;
		}
	    }
	}
    }
    G_percent(nrows, nrows, 2);	/* finish it */

    if (depr_fd >= 0) {
	Rast_close(depr_fd);
	G_free(depr_buf);
    }

    G_debug(1, "%lld edge cells", heap_size - n_depr_cells);
    if (n_depr_cells)
	G_debug(1, "%lld cells in depressions", n_depr_cells);

    return 1;
}
Example #27
0
/*!
 * \brief Get a raster category label
 *
 * This routine looks up category <i>rast</i> in the <i>pcats</i>
 * structure and returns a pointer to a string which is the label for
 * the category. A legal pointer is always returned. If the category
 * does not exist in <i>pcats</i>, then a pointer to the empty string
 * "" is returned.
 *
 * <b>Warning:</b> The pointer that is returned points to a hidden
 * static buffer. Successive calls to Rast_get_c_cat() overwrite this
 * buffer.
 *
 * \param rast cell value
 * \param pcats pointer to Categories structure
 * \param data_type map type (CELL, FCELL, DCELL)
 *
 * \return pointer to category label
 * \return "" if category is not found
 */
char *Rast_get_cat(void *rast,
		   struct Categories *pcats, RASTER_MAP_TYPE data_type)
{
    static char label[1024];
    char *f, *l, *v;
    CELL i;
    DCELL val;
    float a[2];
    char fmt[30], value_str[30];

    if (Rast_is_null_value(rast, data_type)) {
	sprintf(label, "no data");
	return label;
    }

    /* first search the list of labels */
    *label = 0;
    val = Rast_get_d_value(rast, data_type);
    i = Rast_quant_get_cell_value(&pcats->q, val);

    G_debug(5, "Rast_get_cat(): val %lf found i %d", val, i);

    if (!Rast_is_c_null_value(&i) && i < pcats->ncats) {
	if (pcats->labels[i] != NULL)
	    return pcats->labels[i];
	return label;
    }

    /* generate the label */
    if ((f = pcats->fmt) == NULL)
	return label;

    a[0] = (float)val *pcats->m1 + pcats->a1;
    a[1] = (float)val *pcats->m2 + pcats->a2;

    l = label;
    while (*f) {
	if (*f == '$') {
	    f++;
	    if (*f == '$')
		*l++ = *f++;
	    else if (*f == '?') {
		f++;
		get_cond(&f, v = value_str, val);
		while (*v)
		    *l++ = *v++;
	    }
	    else if (get_fmt(&f, fmt, &i)) {
		sprintf(v = value_str, fmt, a[i]);
		while (*v)
		    *l++ = *v++;
	    }
	    else
		*l++ = '$';
	}
	else {
	    *l++ = *f++;
	}
    }
    *l = 0;
    return label;
}
Example #28
0
int main(int argc, char *argv[])
{
    int i, j, nlines, type, field, cat;
    int fd;

    /* struct Categories RCats; *//* TODO */
    struct Cell_head window;
    RASTER_MAP_TYPE out_type;
    CELL *cell;
    DCELL *dcell;
    double drow, dcol;
    char buf[2000];
    struct Option *vect_opt, *rast_opt, *field_opt, *col_opt, *where_opt;
    int Cache_size;
    struct order *cache;
    int cur_row;
    struct GModule *module;

    struct Map_info Map;
    struct line_pnts *Points;
    struct line_cats *Cats;
    int point;
    int point_cnt;		/* number of points in cache */
    int outside_cnt;		/* points outside region */
    int nocat_cnt;		/* points inside region but without category */
    int dupl_cnt;		/* duplicate categories */
    struct bound_box box;

    int *catexst, *cex;
    struct field_info *Fi;
    dbString stmt;
    dbDriver *driver;
    int select, norec_cnt, update_cnt, upderr_cnt, col_type;

    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("vector"));
    G_add_keyword(_("raster"));
    G_add_keyword(_("position"));
    G_add_keyword(_("querying"));
    G_add_keyword(_("attribute table"));
    module->description =
	_("Uploads raster values at positions of vector points to the table.");

    vect_opt = G_define_standard_option(G_OPT_V_INPUT);
    vect_opt->key = "vector";
    vect_opt->description =
	_("Name of input vector points map for which to edit attribute table");

    rast_opt = G_define_standard_option(G_OPT_R_INPUT);
    rast_opt->key = "raster";
    rast_opt->description = _("Name of existing raster map to be queried");

    field_opt = G_define_standard_option(G_OPT_V_FIELD);

    col_opt = G_define_option();
    col_opt->key = "column";
    col_opt->type = TYPE_STRING;
    col_opt->required = YES;
    col_opt->description =
	_("Column name (will be updated by raster values)");

    where_opt = G_define_standard_option(G_OPT_DB_WHERE);

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


    field = atoi(field_opt->answer);

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

    G_get_window(&window);
    Vect_region_box(&window, &box);	/* T and B set to +/- PORT_DOUBLE_MAX */

    /* Open vector */
    Vect_set_open_level(2);
    Vect_open_old(&Map, vect_opt->answer, "");

    Fi = Vect_get_field(&Map, field);
    if (Fi == NULL)
	G_fatal_error(_("Database connection not defined for layer %d"),
		      field);

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

    /* Open raster */
    fd = Rast_open_old(rast_opt->answer, "");

    out_type = Rast_get_map_type(fd);

    /* TODO: Later possibly category labels */
    /* 
       if ( Rast_read_cats (name, "", &RCats) < 0 )
       G_fatal_error ( "Cannot read category file");
     */

    /* Check column type */
    col_type = db_column_Ctype(driver, Fi->table, col_opt->answer);

    if (col_type == -1)
	G_fatal_error(_("Column <%s> not found"), col_opt->answer);

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

    if (out_type == CELL_TYPE && col_type == DB_C_TYPE_DOUBLE)
	G_warning(_("Raster type is integer and column type is float"));

    if (out_type != CELL_TYPE && col_type == DB_C_TYPE_INT)
	G_warning(_("Raster type is float and column type is integer, some data lost!!"));

    /* Read vector points to cache */
    Cache_size = Vect_get_num_primitives(&Map, GV_POINT);
    /* Note: Some space may be wasted (outside region or no category) */

    cache = (struct order *)G_calloc(Cache_size, sizeof(struct order));

    point_cnt = outside_cnt = nocat_cnt = 0;

    nlines = Vect_get_num_lines(&Map);

    G_debug(1, "Reading %d vector features fom map", nlines);

    for (i = 1; i <= nlines; i++) {
	type = Vect_read_line(&Map, Points, Cats, i);
	G_debug(4, "line = %d type = %d", i, type);

	/* check type */
	if (!(type & GV_POINT))
	    continue;		/* Points only */

	/* check region */
	if (!Vect_point_in_box(Points->x[0], Points->y[0], 0.0, &box)) {
	    outside_cnt++;
	    continue;
	}

	Vect_cat_get(Cats, field, &cat);
	if (cat < 0) {		/* no category of given field */
	    nocat_cnt++;
	    continue;
	}

	G_debug(4, "    cat = %d", cat);

	/* Add point to cache */
	drow = Rast_northing_to_row(Points->y[0], &window);
	dcol = Rast_easting_to_col(Points->x[0], &window);

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

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

    Vect_set_db_updated(&Map);
    Vect_hist_command(&Map);
    Vect_close(&Map);

    G_debug(1, "Read %d vector points", point_cnt);
    /* Cache may contain duplicate categories, sort by cat, find and remove duplicates 
     * and recalc count and decrease point_cnt  */
    qsort(cache, point_cnt, sizeof(struct order), by_cat);

    G_debug(1, "Points are sorted, starting duplicate removal loop");

    for (i = 0, j = 1; j < point_cnt; j++)
	if (cache[i].cat != cache[j].cat)
	    cache[++i] = cache[j];
	else
	    cache[i].count++;
    point_cnt = i + 1;

    G_debug(1, "%d vector points left after removal of duplicates",
	    point_cnt);

    /* Report number of points not used */
    if (outside_cnt)
	G_warning(_("%d points outside current region were skipped"),
		  outside_cnt);

    if (nocat_cnt)
	G_warning(_("%d points without category were skipped"), nocat_cnt);

    /* Sort cache by current region row */
    qsort(cache, point_cnt, sizeof(struct order), by_row);

    /* Allocate space for raster row */
    if (out_type == CELL_TYPE)
	cell = Rast_allocate_c_buf();
    else
	dcell = Rast_allocate_d_buf();

    /* Extract raster values from file and store in cache */
    G_debug(1, "Extracting raster values");

    cur_row = -1;

    for (point = 0; point < point_cnt; point++) {
	if (cache[point].count > 1)
	    continue;		/* duplicate cats */

	if (cur_row != cache[point].row) {
	    if (out_type == CELL_TYPE)
		Rast_get_c_row(fd, cell, cache[point].row);
	    else
		Rast_get_d_row(fd, dcell, cache[point].row);
	}
	cur_row = cache[point].row;

	if (out_type == CELL_TYPE) {
	    cache[point].value = cell[cache[point].col];
	}
	else {
	    cache[point].dvalue = dcell[cache[point].col];
	}
    }				/* point loop */

    /* Update table from cache */
    G_debug(1, "Updating db table");

    /* select existing categories to array (array is sorted) */
    select = db_select_int(driver, Fi->table, Fi->key, NULL, &catexst);

    db_begin_transaction(driver);

    norec_cnt = update_cnt = upderr_cnt = dupl_cnt = 0;

    for (point = 0; point < point_cnt; point++) {
	if (cache[point].count > 1) {
	    G_warning(_("More points (%d) of category %d, value set to 'NULL'"),
		      cache[point].count, cache[point].cat);
	    dupl_cnt++;
	}

	/* category exist in DB ? */
	cex =
	    (int *)bsearch((void *)&(cache[point].cat), catexst, select,
			   sizeof(int), srch_cat);
	if (cex == NULL) {	/* cat does not exist in DB */
	    norec_cnt++;
	    G_warning(_("No record for category %d in table <%s>"),
		      cache[point].cat, Fi->table);
	    continue;
	}

	sprintf(buf, "update %s set %s = ", Fi->table, col_opt->answer);

	db_set_string(&stmt, buf);

	if (out_type == CELL_TYPE) {
	    if (cache[point].count > 1 ||
		Rast_is_c_null_value(&cache[point].value)) {
		sprintf(buf, "NULL");
	    }
	    else {
		sprintf(buf, "%d ", cache[point].value);
	    }
	}
	else {			/* FCELL or DCELL */
	    if (cache[point].count > 1 ||
		Rast_is_d_null_value(&cache[point].dvalue)) {
		sprintf(buf, "NULL");
	    }
	    else {
		sprintf(buf, "%.10f", cache[point].dvalue);
	    }
	}
	db_append_string(&stmt, buf);

	sprintf(buf, " where %s = %d", Fi->key, cache[point].cat);
	db_append_string(&stmt, buf);
	/* user provides where condition: */
	if (where_opt->answer) {
	    sprintf(buf, " AND %s", where_opt->answer);
	    db_append_string(&stmt, buf);
	}
	G_debug(3, db_get_string(&stmt));

	/* Update table */
	if (db_execute_immediate(driver, &stmt) == DB_OK) {
	    update_cnt++;
	}
	else {
	    upderr_cnt++;
	}
    }

    G_debug(1, "Committing DB transaction");
    db_commit_transaction(driver);
    G_free(catexst);
    db_close_database_shutdown_driver(driver);
    db_free_string(&stmt);

    /* Report */
    G_message(_("%d categories loaded from table"), select);
    G_message(_("%d categories loaded from vector"), point_cnt);
    G_message(_("%d categories from vector missing in table"), norec_cnt);
    G_message(_("%d duplicate categories in vector"), dupl_cnt);
    if (!where_opt->answer)
	G_message(_("%d records updated"), update_cnt);
    G_message(_("%d update errors"), upderr_cnt);

    exit(EXIT_SUCCESS);
}
Example #29
0
int dopolys(int fd, int fm, int nl, int ns)
{
    int cnt, i, j, found, flag;
    int bufsz, cellsz;
    int *cells;
    int *dir;

    bufsz = ns * sizeof(int);
    dir = (int *)G_calloc(ns, sizeof(int));
    cellsz = 3 * ns;
    cells = (int *)G_malloc(cellsz * sizeof(int));

    found = 0;

    lseek(fd, bufsz, SEEK_SET);
    for (i = 1; i < nl - 1; i += 1) {
	read(fd, dir, bufsz);
	for (j = 1; j < ns - 1; j += 1) {
	    if (Rast_is_c_null_value(&dir[j]) || dir[j] >= 0)
		continue;
	    cells[found++] = i;
	    cells[found++] = j;
	    cells[found++] = 0;

	    if (found >= cellsz) {
		cellsz += 3 * ns;
		cells = (int *)G_realloc(cells, cellsz * sizeof(int));
	    }
	}
    }
    if (found == 0)
	return 0;

    /* Loop through the list, assigning polygon numbers to unassigned entries
       and carrying the same assignment over to adjacent cells.  Repeat
       recursively */

    flag = 0;
    for (i = 0; i < found; i += 3) {
	if (cells[i + 2] == 0) {
	    flag += 1;
	    recurse_list(flag, cells, found, i);
	}
    }
    G_message(_("Found %d unresolved areas"), flag);

    /* Compose a new raster map to contain the resulting assignments */
    lseek(fm, 0, SEEK_SET);
    cnt = 0;
    for (i = 0; i < nl; i += 1) {
	for (j = 0; j < ns; j += 1)
	    dir[j] = -1;
	while (cells[cnt] == i) {
	    dir[cells[cnt + 1]] = cells[cnt + 2];
	    cnt += 3;
	}
	write(fm, dir, bufsz);
    }

    G_free(cells);
    G_free(dir);

    return flag;
}
Example #30
0
int create_isegs(struct globals *globals)
{
    int row, col;
    int successflag = 1;
    int have_bound, rid;
    CELL current_bound, bounds_val;

    if (globals->bounds_map == NULL) {
	/* just one time through loop */
	successflag = globals->method_fn(globals);
    }
    else {
	/* outer processing loop for polygon constraints */
	for (current_bound = globals->lower_bound;
	     current_bound <= globals->upper_bound; current_bound++) {

	    G_debug(1, "current_bound = %d", current_bound);

	    have_bound = 0;

	    /* get min/max row/col to narrow the processing window */
	    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++) {
		for (col = 0; col < globals->ncols; col++) {
		    FLAG_SET(globals->null_flag, row, col);
		    Segment_get(&globals->bounds_seg, &bounds_val,
				row, col);

		    if (!Rast_is_c_null_value(&bounds_val)
		        && bounds_val == current_bound) {

			Segment_get(&globals->rid_seg, &rid, row, col);
			if (!Rast_is_c_null_value(&rid)) {
			    have_bound = 1;

			    FLAG_UNSET(globals->null_flag, row, col);

			    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;
			}
		    }
		}
	    }
	    globals->row_max++;
	    globals->col_max++;

	    if (have_bound)
		successflag = globals->method_fn(globals);
	}    /* end outer loop for processing polygons */

	/* restore NULL flag */
	flag_clear_all(globals->null_flag);
	for (row = 0; row < globals->nrows; row++) {
	    for (col = 0; col < globals->ncols; col++) {
		Segment_get(&globals->rid_seg, &rid, row, col);
		if (Rast_is_c_null_value(&rid))
		    FLAG_SET(globals->null_flag, row, col);
	    }
	}
    }

    return successflag;
}