Beispiel #1
0
int G_read_colors(const char *name, const char *mapset, struct Colors *colors)
{
    int fp;
    char buf[GNAME_MAX];
    char *err;
    char xname[GNAME_MAX];
    struct Range range;
    struct FPRange drange;
    CELL min, max;
    DCELL dmin, dmax;

    fp = G_raster_map_is_fp(name, mapset);
    G_init_colors(colors);

    strcpy(xname, name);
    mapset = G_find_cell(xname, mapset);
    name = xname;

    if (fp)
	G_mark_colors_as_fp(colors);

    /* first look for secondary color table in current mapset */
    sprintf(buf, "colr2/%s", mapset);
    if (read_colors(buf, name, G_mapset(), colors) >= 0)
	return 1;

    /* now look for the regular color table */
    switch (read_colors("colr", name, mapset, colors)) {
    case -2:
	if (!fp) {
	    if (G_read_range(name, mapset, &range) >= 0) {
		G_get_range_min_max(&range, &min, &max);
		if (!G_is_c_null_value(&min) && !G_is_c_null_value(&max))
		    G_make_rainbow_colors(colors, min, max);
		return 0;
	    }
	}
	else {
	    if (G_read_fp_range(name, mapset, &drange) >= 0) {
		G_get_fp_range_min_max(&drange, &dmin, &dmax);
		if (!G_is_d_null_value(&dmin) && !G_is_d_null_value(&dmax))
		    G_make_rainbow_fp_colors(colors, dmin, dmax);
		return 0;
	    }
	}
	err = "missing";
	break;
    case -1:
	err = "invalid";
	break;
    default:
	return 1;
    }

    G_warning(_("color support for [%s] in mapset [%s] %s"), name, mapset,
	      err);
    return -1;
}
Beispiel #2
0
int G3d_isNullValueNum(const void *n, int type)
{
    if (type == FCELL_TYPE)
	return G_is_f_null_value(n);
    else
	return G_is_d_null_value(n);
}
Beispiel #3
0
int G_set_d_color(DCELL val, int r, int g, int b, struct Colors *colors)
{
    DCELL tmp = val;

    if (G_is_d_null_value(&tmp))
	return G_set_null_value_color(r, g, b, colors);
    return G_add_d_raster_color_rule(&val, r, g, b, &val, r, g, b, colors);
}
Beispiel #4
0
/**************************************************************
 * apply_filter: apply the filter to a single neighborhood
 *
 *  filter:    filter to be applied
 *  input:     input buffers
 **************************************************************/
DCELL apply_filter(FILTER * filter, DCELL ** input)
{
    int size = filter->size;
    double **matrix = filter->matrix;
    double divisor = filter->divisor;
    int r, c;
    DCELL v;

    v = 0;

    if (divisor == 0) {
	int have_result = 0;

	for (r = 0; r < size; r++)
	    for (c = 0; c < size; c++) {
		if (G_is_d_null_value(&input[r][c]))
		    continue;
		v += input[r][c] * matrix[r][c];
		divisor += filter->dmatrix[r][c];
		have_result = 1;
	    }

	if (have_result)
	    v /= divisor;
	else
	    G_set_d_null_value(&v, 1);
    }
    else {
	for (r = 0; r < size; r++)
	    for (c = 0; c < size; c++) {
		if (G_is_d_null_value(&input[r][c])) {
		    G_set_d_null_value(&v, 1);
		    return v;
		}
		v += input[r][c] * matrix[r][c];
	    }

	v /= divisor;
    }

    return v;
}
Beispiel #5
0
static double loglike(DCELL * x, struct SubSig *SubSig, int nbands)
{
    int b1, b2;
    double diff1, diff2;
    double sum;

    sum = 0;
    for (b1 = 0; b1 < nbands; b1++)
	for (b2 = 0; b2 < nbands; b2++) {
	    if (G_is_d_null_value(&x[b1])
		|| G_is_d_null_value(&x[b2]))
		continue;
	    diff1 = x[b1] - SubSig->means[b1];
	    diff2 = x[b2] - SubSig->means[b2];
	    sum += diff1 * diff2 * SubSig->Rinv[b1][b2];
	}

    sum = -0.5 * sum + SubSig->cnst;
    return (sum);
}
Beispiel #6
0
void w_kurt(DCELL * result, DCELL(*values)[2], int n, const void *closure)
{
    DCELL sum, ave, sumsq, sumqt, var;
    int count;
    int i;

    sum = 0.0;
    count = 0;

    for (i = 0; i < n; i++) {
	if (G_is_d_null_value(&values[i][0]))
	    continue;

	sum += values[i][0] * values[i][1];
	count += values[i][1];
    }

    if (count == 0) {
	G_set_d_null_value(result, 1);
	return;
    }

    ave = sum / count;

    sumsq = 0;

    for (i = 0; i < n; i++) {
	DCELL d;

	if (G_is_d_null_value(&values[i][0]))
	    continue;

	d = values[i][0] - ave;
	sumsq += d * d * values[i][1];
	sumqt += d * d * d * values[i][1];
    }

    var = sumsq / count;

    *result = sumqt / (count * var * var) - 3;
}
Beispiel #7
0
void w_skew(DCELL * result, DCELL(*values)[2], int n, const void *closure)
{
    DCELL sum, ave, sumsq, sumcb, sdev;
    int count;
    int i;

    sum = 0.0;
    count = 0;

    for (i = 0; i < n; i++) {
	if (G_is_d_null_value(&values[i][0]))
	    continue;

	sum += values[i][0] * values[i][1];
	count += values[i][1];
    }

    if (count == 0) {
	G_set_d_null_value(result, 1);
	return;
    }

    ave = sum / count;

    sumsq = 0;

    for (i = 0; i < n; i++) {
	DCELL d;

	if (G_is_d_null_value(&values[i][0]))
	    continue;

	d = values[i][0] - ave;
	sumsq += d * d * values[i][1];
	sumcb += d * d * d * values[i][1];
    }

    sdev = sqrt(sumsq / count);

    *result = sumcb / (count * sdev * sdev * sdev);
}
Beispiel #8
0
int G_quantize_fp_map(const char *name, const char *mapset,
		      CELL min, CELL max)
{
    char buf[300];
    DCELL d_min, d_max;
    struct FPRange fp_range;

    if (G_read_fp_range(name, mapset, &fp_range) < 0) {
	sprintf(buf, "G_quantize_fp_map: can't read fp range for map %s",
		name);
	G_warning(buf);
	return -1;
    }
    G_get_fp_range_min_max(&fp_range, &d_min, &d_max);
    if (G_is_d_null_value(&d_min) || G_is_d_null_value(&d_max)) {
	sprintf(buf, "G_quantize_fp_map: raster map %s is empty", name);
	G_warning(buf);
	return -1;
    }
    return G_quantize_fp_map_range(name, mapset, d_min, d_max, min, max);
}
int QgsGrassGisLib::putRasterRow( int fd, const void *buf, RASTER_MAP_TYPE data_type )
{
    Raster rast = mRasters.value( fd );
    if ( rast.row < 0 || rast.row >= mRows )
    {
        QgsDebugMsg( QString( "row %1 out of range 0 - %2" ).arg( rast.row ).arg( mRows ) );
        return -1;
    }

    QGis::DataType inputType = qgisRasterType( data_type );
    //QgsDebugMsg( QString("data_type = %1").arg(data_type) );
    //QgsDebugMsg( QString("inputType = %1").arg(inputType) );
    //QgsDebugMsg( QString("provider->dataType = %1").arg( rast.provider->dataType( rast.band ) ) );

    //double noDataValue = rast.provider->noDataValue( rast.band );
    QgsRasterBlock block( inputType, mColumns, 1, rast.noDataValue );

    memcpy( block.bits( 0 ), buf, QgsRasterBlock::typeSize( inputType )*mColumns );
    block.convert( rast.provider->dataType( rast.band ) );

    // Set no data after converting to output type
    for ( int i = 0; i < mColumns; i++ )
    {
        bool isNoData = false;
        switch ( data_type )
        {
        case CELL_TYPE:
            isNoData = G_is_c_null_value( &(( CELL * ) buf )[i] ) != 0;
            break;
        case FCELL_TYPE:
            isNoData = G_is_f_null_value( &(( FCELL * ) buf )[i] ) != 0;
            break;
        case DCELL_TYPE:
            isNoData = G_is_d_null_value( &(( DCELL * ) buf )[i] ) != 0;
            break;
        default:
            break;
        }
        if ( isNoData )
        {
            block.setIsNoData( i );
        }
    }

    if ( !rast.provider->write( block.bits( 0 ), rast.band, mColumns, 1, 0, rast.row ) )
    {
        fatal( "Cannot write block" );
    }
    mRasters[fd].row++;

    return 1;
}
Beispiel #10
0
void p_cubic_f(struct cache *ibuffer,	/* input buffer                  */
		void *obufptr,	/* ptr in output buffer          */
		int cell_type,	/* raster map type of obufptr    */
		double *row_idx,	/* row index                     */
		double *col_idx,	/* column index          */
	    struct Cell_head *cellhd	/* cell header of input layer    */
    )
{
    /* start nearest neighbor to do some basic tests */
    int row, col;		/* row/col of nearest neighbor   */
    DCELL *cellp, cell;

    /* cut indices to integer */
    row = (int)floor(*row_idx);
    col = (int)floor(*col_idx);

    /* check for out of bounds - if out of bounds set NULL value     */
    if (row < 0 || row >= cellhd->rows || col < 0 || col >= cellhd->cols) {
        G_set_null_value(obufptr, 1, cell_type);
        return;
    }

    cellp = CPTR(ibuffer, row, col);
    /* if nearest is null, all the other interps will be null */
    if (G_is_d_null_value(cellp)) {
        G_set_null_value(obufptr, 1, cell_type);
        return;
    }
    cell = *cellp;
    
    p_cubic(ibuffer, obufptr, cell_type, row_idx, col_idx, cellhd);
    /* fallback to bilinear if cubic is null */
    if (G_is_d_null_value(obufptr)) {
        p_bilinear(ibuffer, obufptr, cell_type, row_idx, col_idx, cellhd);
        /* fallback to nearest if bilinear is null */
	if (G_is_d_null_value(obufptr))
	    G_set_raster_value_d(obufptr, cell, cell_type);
    }
}
Beispiel #11
0
int mask_match_d_interval(DCELL x, d_Interval * I)
{
    if (G_is_d_null_value(&x))
	return 0;

    if (I->inf < 0)
	return x <= I->low;

    if (I->inf > 0)
	return x >= I->high;

    return x >= I->low && x <= I->high;
}
Beispiel #12
0
void p_cubic(struct cache *ibuffer,	/* input buffer                  */
	     void *obufptr,	/* ptr in output buffer          */
	     int cell_type,	/* raster map type of obufptr    */
	     double *row_idx,	/* row index (decimal)           */
	     double *col_idx,	/* column index (decimal)        */
	     struct Cell_head *cellhd	/* information of output map     */
    )
{
    int row;			/* row indices for interp        */
    int col;			/* column indices for interp     */
    int i, j;
    DCELL t, u;			/* intermediate slope            */
    DCELL result;		/* result of interpolation       */
    DCELL val[4];		/* buffer for temporary values   */
    DCELL cell[4][4];

    /* cut indices to integer */
    row = (int)floor(*row_idx - 0.5);
    col = (int)floor(*col_idx - 0.5);

    /* check for out of bounds of map - if out of bounds set NULL value     */
    if (row - 1 < 0 || row + 2 >= cellhd->rows ||
	col - 1 < 0 || col + 2 >= cellhd->cols) {
	G_set_null_value(obufptr, 1, cell_type);
	return;
    }

    for (i = 0; i < 4; i++)
	for (j = 0; j < 4; j++) {
	    const DCELL *cellp = CPTR(ibuffer, row - 1 + i, col - 1 + j);
	    if (G_is_d_null_value(cellp)) {
		G_set_null_value(obufptr, 1, cell_type);
		return;
	    }
	    cell[i][j] = *cellp;
	}

    /* do the interpolation  */
    t = *col_idx - 0.5 - col;
    u = *row_idx - 0.5 - row;

    for (i = 0; i < 4; i++) {
	val[i] = G_interp_cubic(t, cell[i][0], cell[i][1], cell[i][2], cell[i][3]);
    }

    result = G_interp_cubic(u, val[0], val[1], val[2], val[3]);

    G_set_raster_value_d(obufptr, result, cell_type);
}
Beispiel #13
0
/* THIS IS CALLED IF ONLY THE TARGET POINT UNDER CURRENT CONSIDERATION IS TO
   BE RAISED BY 'OFFSETB' AMOUNT */
double find_inclination2(int x, int y, double viewpt_elev, 
			SEGMENT *seg_in_p,
			int row_viewpt, int col_viewpt, RASTER_MAP_TYPE data_type)
{
    double del_x, del_y,dist,atan(),sqrt();
    int abs();
    double dest_elev = 0.0;
    extern struct Cell_head window;
    void *value = NULL;	
	/* these vars can store one data value from the elevation input map, */
	/* which could be CELL, DCELL or FCELL type. */
    CELL c_value;
    FCELL f_value;
    DCELL d_value;
    
    del_x = abs(x) ;
    del_y = abs(y) ;
        
    dist=sqrt(del_x * del_x + del_y * del_y)*window.ns_res;
    
    	/* this takes care, that target elevation has the right format, 
	   depending on type of input DEM */
    	
	if (data_type == CELL_TYPE) {
		value = (CELL*) &c_value;
	}
	if (data_type == FCELL_TYPE) {
		value = (FCELL*) &f_value;
	}
	if (data_type == DCELL_TYPE) {
		value = (DCELL*) &d_value;
	}
	
    /* read value from elevation input map, convert to appropriate */
	/* map type */
    segment_get(seg_in_p,value,row_viewpt-y,x+col_viewpt);

	if (data_type == CELL_TYPE) {	
	  if ( G_is_c_null_value (&c_value) ) {
	  	return (NULLPT);
	  } else {
	  	dest_elev = c_value + OFFSETB;
	  }
	}

	if (data_type == FCELL_TYPE) {
	  if ( G_is_f_null_value (&f_value) ) {
	  	return (NULLPT);
	  } else {
	  	dest_elev = f_value + OFFSETB;
	  }
	}

	if (data_type == DCELL_TYPE) {
	  if ( G_is_d_null_value (&d_value) ) {
	  	return (NULLPT);
	  } else {
	  	dest_elev = d_value + OFFSETB;	
	  }
	}


	/* CURVATURE CORRECTION */
	/* decrease height of target point */
	if (DIST_CC > 0.0) {
		if (dist >= DIST_CC) {
			dest_elev = dest_elev - ((dist*dist) / (2 * Re));
		}
	}
        	
    return(atan((dest_elev - viewpt_elev) / dist));
}
Beispiel #14
0
/* This function is for floating point maps */
void do_report_DCELL ( char *map, char *mapset, char *sites,
					int precision, int null_flag, int uncat_flag,
					int all_flag, int quiet_flag, int skip_flag,
				  	char *logfile, int background, int gain, int show_progress) {
    	DCELL *dcellbuf;
	DCELL dvalue;
	CELL value;
	struct Cell_head region;
	struct Categories categories;
	GT_Row_cache_t *cache;
	unsigned long row_idx, col_idx;	
	short error;
	int fd;
	unsigned long i,j,k;
	unsigned long no_sites;
	FILE *lp;	
	unsigned long nrows, ncols;
	unsigned long *share_smp = NULL; /* array that keeps percentage of sites */
	double total = 0;
	double map_total = 0;
	double kvamme_gain;
	long null_count = 0; /* keeps count of sites on NULL cells */
	long nocat_count = 0; /* sites on cells outside category range */
	/* category counts and descriptions */
	int cats;
	char **cats_description; /* category labels */
	long *cat_count; /* category counts */
	long null_count_map; /* number of NULL cells in input map */
	long nocat_count_map; /* number of cells that do not fall into the category range [0 .. n] */		
	
	int debug_mode = 0;		/* 1 to enable writing additional output to logfile */
	time_t systime;

	char errmsg [200];
	struct Map_info in_vect_map;
  	struct line_pnts *vect_points;
	double x,y,z;
	int n_points = 1;
	int cur_type;


	/* get current region */
	G_get_window (&region);
	nrows = G_window_rows ();
	ncols = G_window_cols ();	
	
	/* check logfile */
	if (logfile != NULL) {
		debug_mode = 1;	
		if ( !G_legal_filename (logfile) ) {
			delete_tmpfile (map);
			G_fatal_error ("Please specify a legal filename for the logfile.\n");
		}
		/* attempt to write to logfile */
		if ( (lp = fopen ( logfile, "w+" ) ) == NULL )	{
			delete_tmpfile (map);
			G_fatal_error ("Could not create logfile.\n");
		}
		/* we want unbuffered output for the logfile */
		setvbuf (lp,NULL,_IONBF,0);	
		fprintf (lp,"This is s.report, version %.2f\n",PROGVERSION);
		systime = time (NULL);
		fprintf (lp,"Started on %s",ctime(&systime));
		fprintf (lp,"\tlocation    = %s\n",G_location());
		fprintf (lp,"\tmapset      = %s\n",G_mapset());
		fprintf (lp,"\tinput map   = %s\n",map);
		fprintf (lp,"\tsample file = %s\n",sites);
	} else {		
		/* log output to stderr by default */
		lp = stderr;
	}

  	if (1 > Vect_open_old (&in_vect_map, sites, "")) {
    		sprintf (errmsg, "Could not open input map %s.\n", sites);
		delete_tmpfile (map);	
    		G_fatal_error (errmsg);
  	}

	vect_points = Vect_new_line_struct ();

	if (all_flag != 1) {
		Vect_set_constraint_region (&in_vect_map, region.north, region.south, 
			region.east, region.west, 0.0, 0.0);
	}
		
	/* get total number of sampling points */
	i = 0;	
	while ((cur_type = Vect_read_next_line (&in_vect_map, vect_points, NULL) > 0)) {
		i ++;
	}
	no_sites = i; /* store this for later use */
			
	/* open raster map */
	fd = G_open_cell_old (map, G_find_cell (map, ""));
	if (fd < 0)
	{
		delete_tmpfile (map);
		G_fatal_error ("Could not open raster map for reading!\n");
	}
	/* allocate a cache and a raster buffer */
	cache = (GT_Row_cache_t *) G_malloc (sizeof (GT_Row_cache_t));
	GT_RC_open (cache, CACHESIZE, fd, DCELL_TYPE);
	dcellbuf = G_allocate_raster_buf (DCELL_TYPE);			
	
	cats = GT_get_stats (map,mapset,&null_count_map, &nocat_count_map, show_progress);
	if ( cats < 2 ) {
		delete_tmpfile (map);
		G_fatal_error ("Input map must have at least two categories.");
	}
	
	/* get category labels and counts */
	cats_description = GT_get_labels (map,mapset);
	if (cats_description == NULL) {
		delete_tmpfile (map);
		G_fatal_error ("Could not read category labels from input map.");
	}	
	cat_count = GT_get_f_counts (map,mapset, show_progress);
	if (cat_count == NULL) {
		delete_tmpfile (map);
		G_fatal_error ("Could not count categories in input map.");
	}

	/* now read category structure of input map*/
	G_init_cats (0, "", &categories);
	error = G_read_cats (map, mapset, &categories);
	if (error != 0) {	/* no categories found */
		delete_tmpfile (map);		
		G_fatal_error ("Could not read category information of input map.");
	}
	
	/* allocate a double array to hold statistics */
	share_smp = (unsigned long *) G_malloc ((signed) (cats * sizeof (unsigned long)));
	for (i = 0; i < cats; i++)
	{
		share_smp[i] = 0;		
	}	
	
	/* count raster values under sites */
	/* re-open sites file with samples */
	i = 0;
	k = 0; /* progress counter for status display */

	Vect_rewind (&in_vect_map);

	if ( !quiet_flag ) {
		fprintf (stdout, "Counting sample: \n");
		fflush (stdout);	
	}
	
	/* we MUST not set constraints so that no raster values outside the current region are
	   accessed, which would give an "illegal cache request" error */
	Vect_set_constraint_region (&in_vect_map, region.north, region.south, 
				     region.east, region.west, 0.0, 0.0);
		
	while ((cur_type = Vect_read_next_line (&in_vect_map, vect_points, NULL) > 0)) {
		Vect_copy_pnts_to_xyz (vect_points, &x, &y, &z, &n_points);		
		k ++;
		if ( !quiet_flag ) {
			G_percent ((signed) k, (signed) no_sites, 1);
		}
		/* get raster row with same northing as sample and perform
		 * quantification */
		row_idx = (long) G_northing_to_row (y, &region);
		col_idx = (long) G_easting_to_col (x, &region);				
				
		dcellbuf = GT_RC_get (cache, (signed) row_idx);
		/* now read the raster value under the current site */
		if (G_is_d_null_value (&dcellbuf[col_idx]) == 0) {	
			dvalue = dcellbuf[col_idx];
			value = G_quant_get_cell_value (&categories.q, dvalue);
			if ( ! (( value < 0 ) || ( value > cats -1)) ) {
				share_smp [value] ++;
				i ++;
			} else {
				if ( uncat_flag ) {
					/* also keep count of sites on uncategorised cells? */
					i ++;
					nocat_count++;
				}
			}							
		}
		if (G_is_d_null_value (&dcellbuf[col_idx]) == 1) { 
			/* got a NULL value under this site */
			if (null_flag) { /* only count this, if null flag is set */
				null_count ++;
				i ++;
			}
		}
	}

	Vect_close (&in_vect_map);		
	
	fprintf (lp,"\n");
	if ( background ) {
		fprintf (lp,"Distribution of categories under %lu points (%lu in region) and in input map:\n",i,no_sites);	
	} else {
		fprintf (lp,"Distribution of categories under %lu points (%lu in region):\n",i,no_sites);	
	}
	/* determine starting value for total of sites analysed */
	total = 0;
	for ( j=0; j < cats; j ++) {
		total = total + share_smp[j];
		map_total = map_total + cat_count[j];
	}
	if (null_flag) { /* add NULL values to total */	
		total = total + null_count;
		map_total = map_total + null_count_map;
	}
	if (uncat_flag) { /* add uncategorised cells to total */
		total = total + nocat_count;
		map_total = map_total + nocat_count_map;
		
	}
	/* Now display those values which the user has chosen */
	if ( (background) && (gain) ) {	
		fprintf (lp,"Cat.\tPts.\t(%%)\tMap\t(%%)\tGain\tDescription\n");				
	}
	if ( (background) && (!gain) ) {	
		fprintf (lp,"Cat.\tPts.\t(%%)\tMap\t(%%)\tDescription\n");		
	}
	if ( (!background) && (gain) ) {	
		fprintf (lp,"Cat.\tPts.\t(%%)\tGain\tDescription\n");
	}
	if ( (!background) && (!gain) ) {	
		fprintf (lp,"Cat.\tPts.\t(%%)\tDescription\n");
	}	
	for ( j = 0; j < cats; j ++) {
		/* if skip_flag is not set: only show categories that have count > 0 */
		if ((skip_flag == 1) || ((skip_flag == 0) && (share_smp[j] > 0))) {
			if ( (background) && (gain) ) {
				/* Kvamme's Gain = 1 - (%area/%sites) */
				kvamme_gain = gstats_gain_K(((double) share_smp[j]*(100/total)),
							    ((double) cat_count[j]*(100/map_total)));							    				
				fprintf (lp, "%lu\t%6lu\t%6.2f\t%8lu %6.2f\t%6.2f\t%s\n", j, share_smp[j], (float) share_smp[j]*(100/total),
						cat_count[j], (float) cat_count[j]*(100/map_total),
						kvamme_gain, cats_description[j]);
			} 
			if ( (background) && (!gain) ) {
				fprintf (lp, "%lu\t%6lu\t%6.2f\t%8lu %6.2f\t%s\n", j, share_smp[j], (float) share_smp[j]*(100/total),
						cat_count[j], (float) cat_count[j]*(100/map_total),
						cats_description[j]);
				
			} 			
			if ( (!background) && (gain) ) {
				kvamme_gain = 1 - ( ((float) cat_count[j]*(100/map_total)) / ((float) share_smp[j]*(100/total)) );
				fprintf (lp, "%lu\t%6lu\t%6.2f\t%6.2f\t%s\n", j, share_smp[j], (float) share_smp[j]*(100/total),						
						kvamme_gain, cats_description[j]);				
			} 			
			if ( (!background) && (!gain) ) {
				fprintf (lp, "%lu\t%6lu\t%6.2f\t%s\n", j, share_smp[j], (float) share_smp[j]*(100/total),
						cats_description[j]);
			} 									
		}
	}
	if (null_flag) {		
		if ( background ) {
			fprintf (lp,"NULL\t%6lu\t%6.2f\t%8lu %6.2f\n",null_count, (float) null_count * 100 / total
						,null_count_map, (float) null_count_map * 100 / map_total);
		} else {
			fprintf (lp,"NULL\t%6lu\t%6.2f\n",null_count, (float) null_count * 100 / total);
		}
	}
	if (uncat_flag) {
		if ( background ) {
			fprintf (lp,"NOCAT\t%6lu\t%6.2f\t%8lu %6.2f\n",nocat_count, (float) nocat_count * 100 / total
						,nocat_count_map, (float) nocat_count_map * 100 / map_total);
		} else {
			fprintf (lp,"NOCAT\t%6lu\t%6.2f\n",nocat_count, (float) nocat_count * 100 / total);
		}		
	}
	if ( background) {
		fprintf (lp,"TOTAL\t%6lu\t%6.2f\t%8lu %6.2f\n",(long) total, (float) 100, (long) map_total, (float) 100);
	} else {
		fprintf (lp,"TOTAL\t%6lu\t%6.2f\n",(long) total, (float) 100);
	}
	
	/* close cache and sites file; free buffers. */
	GT_RC_close (cache);
	G_free (dcellbuf);
	G_free (cache);	
}
Beispiel #15
0
static void seed(struct ClassSig *Sig, int nbands)
{
    int i, b1, b2;
    double period;
    double *mean, **R;

    /* Compute the mean of variance for each band */
    mean = G_alloc_vector(nbands);
    R = G_alloc_matrix(nbands, nbands);
    n_nulls = (int *)G_calloc(nbands, sizeof(int));

    total_nulls = 0;
    for (b1 = 0; b1 < nbands; b1++) {
	n_nulls[b1] = 0;
	mean[b1] = 0.0;
	for (i = 0; i < Sig->ClassData.npixels; i++) {
	    if (G_is_d_null_value(&Sig->ClassData.x[i][b1])) {
		n_nulls[b1]++;
		total_nulls++;
	    }
	    else
		mean[b1] += Sig->ClassData.x[i][b1];
	}
	mean[b1] /= (double)(Sig->ClassData.npixels - n_nulls[b1]);
    }

    for (b1 = 0; b1 < nbands; b1++)
	for (b2 = 0; b2 < nbands; b2++) {
	    R[b1][b2] = 0.0;
	    for (i = 0; i < Sig->ClassData.npixels; i++) {
		if (!G_is_d_null_value(&Sig->ClassData.x[i][b1]) &&
		    !G_is_d_null_value(&Sig->ClassData.x[i][b2]))
		    R[b1][b2] +=
			(Sig->ClassData.x[i][b1]) * (Sig->ClassData.x[i][b2]);
	    }
	    R[b1][b2] /= (double)(Sig->ClassData.npixels - n_nulls[b1] -
				  n_nulls[b2]);
	    R[b1][b2] -= mean[b1] * mean[b2];
	}

    /* Compute the sampling period for seeding */
    if (Sig->nsubclasses > 1) {
	period = (Sig->ClassData.npixels - 1) / (Sig->nsubclasses - 1.0);
    }
    else
	period = 0;


    /* Seed the means and set the diagonal covariance components */
    for (i = 0; i < Sig->nsubclasses; i++) {
	for (b1 = 0; b1 < nbands; b1++) {
	    if (G_is_d_null_value(&Sig->ClassData.x[(int)(i * period)][b1]))
		G_set_d_null_value(&Sig->SubSig[i].means[b1], 1);
	    else
		Sig->SubSig[i].means[b1] =
		    Sig->ClassData.x[(int)(i * period)][b1];
	}

	for (b1 = 0; b1 < nbands; b1++)
	    for (b2 = 0; b2 < nbands; b2++) {
		Sig->SubSig[i].R[b1][b2] = R[b1][b2];
	    }
	Sig->SubSig[i].pi = 1.0 / Sig->nsubclasses;
    }

    G_free_vector(mean);
    G_free_matrix(R);

    compute_constants(Sig, nbands);
}
Beispiel #16
0
static int reestimate(struct ClassSig *Sig, int nbands)
{
    int i;
    int s;
    int b1, b2;
    int singular;
    double pi_sum;
    double diff1, diff2;
    struct ClassData *Data;

    /* set data pointer */
    Data = &(Sig->ClassData);

    /* Compute N */
    for (i = 0; i < Sig->nsubclasses; i++) {
	Sig->SubSig[i].N = 0;
	for (s = 0; s < Data->npixels; s++)
	    Sig->SubSig[i].N += Data->p[s][i];
	Sig->SubSig[i].pi = Sig->SubSig[i].N;
    }




    /* Compute means and variances for each subcluster, */
    /* and remove small clusters.                       */
    for (i = 0; i < Sig->nsubclasses; i++) {
	/* For large subclusters */
	if (Sig->SubSig[i].N > SMALLEST_SUBCLUST) {
	    /* Compute mean */
	    for (b1 = 0; b1 < nbands; b1++) {
		Sig->SubSig[i].means[b1] = 0;
		for (s = 0; s < Data->npixels; s++)
		    if (!G_is_d_null_value(&Data->x[s][b1]))
			Sig->SubSig[i].means[b1] +=
			    Data->p[s][i] * Data->x[s][b1];
		Sig->SubSig[i].means[b1] /= (Sig->SubSig[i].N);
	    }

	    /* Compute R */
	    for (b1 = 0; b1 < nbands; b1++)
		for (b2 = b1; b2 < nbands; b2++) {
		    Sig->SubSig[i].R[b1][b2] = 0;
		    for (s = 0; s < Data->npixels; s++) {
			if (!G_is_d_null_value(&Data->x[s][b1])
			    && !G_is_d_null_value(&Data->x[s][b2])) {
			    diff1 = Data->x[s][b1] - Sig->SubSig[i].means[b1];
			    diff2 = Data->x[s][b2] - Sig->SubSig[i].means[b2];
			    Sig->SubSig[i].R[b1][b2] +=
				Data->p[s][i] * diff1 * diff2;
			}
		    }
		    Sig->SubSig[i].R[b1][b2] /= (Sig->SubSig[i].N);
		    Sig->SubSig[i].R[b2][b1] = Sig->SubSig[i].R[b1][b2];
		}
	}
	/* For small subclusters */
	else {
	    G_warning(_("Subsignature %d only contains %f pixels"),
		      i, Sig->SubSig[i].N);
	    
	    Sig->SubSig[i].pi = 0;

	    for (b1 = 0; b1 < nbands; b1++)
		Sig->SubSig[i].means[b1] = 0;

	    for (b1 = 0; b1 < nbands; b1++)
		for (b2 = 0; b2 < nbands; b2++)
		    Sig->SubSig[i].R[b1][b2] = 0;
	}
    }


    /* Normalize probabilities for subclusters */
    pi_sum = 0;
    for (i = 0; i < Sig->nsubclasses; i++)
	pi_sum += Sig->SubSig[i].pi;
    if (pi_sum > 0) {
	for (i = 0; i < Sig->nsubclasses; i++)
	    Sig->SubSig[i].pi /= pi_sum;
    }
    else {
	for (i = 0; i < Sig->nsubclasses; i++)
	    Sig->SubSig[i].pi = 0;
    }


    /* Compute constants and reestimate if any singular subclusters occur */
    singular = compute_constants(Sig, nbands);
    return (singular);
}
Beispiel #17
0
int main(int argc, char *argv[])
{
    struct GModule *module;
    struct Option *rastin, *rastout, *method;
    struct History history;
    char title[64];
    char buf_nsres[100], buf_ewres[100];
    struct Colors colors;
    char *inmap;
    int infile, outfile;
    DCELL *outbuf;
    int row, col;
    struct Cell_head dst_w, src_w;

    G_gisinit(argv[0]);

    module = G_define_module();
    module->keywords = _("raster, resample");
    module->description =
	_("Resamples raster map layers to a finer grid using interpolation.");

    rastin = G_define_standard_option(G_OPT_R_INPUT);
    rastout = G_define_standard_option(G_OPT_R_OUTPUT);

    method = G_define_option();
    method->key = "method";
    method->type = TYPE_STRING;
    method->required = NO;
    method->description = _("Interpolation method");
    method->options = "nearest,bilinear,bicubic";
    method->answer = "bilinear";

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

    if (G_strcasecmp(method->answer, "nearest") == 0)
	neighbors = 1;
    else if (G_strcasecmp(method->answer, "bilinear") == 0)
	neighbors = 2;
    else if (G_strcasecmp(method->answer, "bicubic") == 0)
	neighbors = 4;
    else
	G_fatal_error(_("Invalid method: %s"), method->answer);

    G_get_set_window(&dst_w);

    inmap = G_find_cell2(rastin->answer, "");
    if (!inmap)
	G_fatal_error(_("Raster map <%s> not found"), rastin->answer);

    /* set window to old map */
    G_get_cellhd(rastin->answer, inmap, &src_w);

    /* enlarge source window */
    {
	double north = G_row_to_northing(0.5, &dst_w);
	double south = G_row_to_northing(dst_w.rows - 0.5, &dst_w);
	int r0 = (int)floor(G_northing_to_row(north, &src_w) - 0.5) - 1;
	int r1 = (int)floor(G_northing_to_row(south, &src_w) - 0.5) + 3;
	double west = G_col_to_easting(0.5, &dst_w);
	double east = G_col_to_easting(dst_w.cols - 0.5, &dst_w);
	int c0 = (int)floor(G_easting_to_col(west, &src_w) - 0.5) - 1;
	int c1 = (int)floor(G_easting_to_col(east, &src_w) - 0.5) + 3;

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

    G_set_window(&src_w);

    /* allocate buffers for input rows */
    for (row = 0; row < neighbors; row++)
	bufs[row] = G_allocate_d_raster_buf();

    cur_row = -100;

    /* open old map */
    infile = G_open_cell_old(rastin->answer, inmap);
    if (infile < 0)
	G_fatal_error(_("Unable to open raster map <%s>"), rastin->answer);

    /* reset window to current region */
    G_set_window(&dst_w);

    outbuf = G_allocate_d_raster_buf();

    /* open new map */
    outfile = G_open_raster_new(rastout->answer, DCELL_TYPE);
    if (outfile < 0)
	G_fatal_error(_("Unable to create raster map <%s>"), rastout->answer);

    G_suppress_warnings(1);
    /* otherwise get complaints about window changes */

    switch (neighbors) {
    case 1:			/* nearest */
	for (row = 0; row < dst_w.rows; row++) {
	    double north = G_row_to_northing(row + 0.5, &dst_w);
	    double maprow_f = G_northing_to_row(north, &src_w) - 0.5;
	    int maprow0 = (int)floor(maprow_f + 0.5);

	    G_percent(row, dst_w.rows, 2);

	    G_set_window(&src_w);
	    read_rows(infile, maprow0);

	    for (col = 0; col < dst_w.cols; col++) {
		double east = G_col_to_easting(col + 0.5, &dst_w);
		double mapcol_f = G_easting_to_col(east, &src_w) - 0.5;
		int mapcol0 = (int)floor(mapcol_f + 0.5);

		double c = bufs[0][mapcol0];

		if (G_is_d_null_value(&c)) {
		    G_set_d_null_value(&outbuf[col], 1);
		}
		else {
		    outbuf[col] = c;
		}
	    }

	    G_set_window(&dst_w);
	    G_put_d_raster_row(outfile, outbuf);
	}
	break;

    case 2:			/* bilinear */
	for (row = 0; row < dst_w.rows; row++) {
	    double north = G_row_to_northing(row + 0.5, &dst_w);
	    double maprow_f = G_northing_to_row(north, &src_w) - 0.5;
	    int maprow0 = (int)floor(maprow_f);
	    double v = maprow_f - maprow0;

	    G_percent(row, dst_w.rows, 2);

	    G_set_window(&src_w);
	    read_rows(infile, maprow0);

	    for (col = 0; col < dst_w.cols; col++) {
		double east = G_col_to_easting(col + 0.5, &dst_w);
		double mapcol_f = G_easting_to_col(east, &src_w) - 0.5;
		int mapcol0 = (int)floor(mapcol_f);
		int mapcol1 = mapcol0 + 1;
		double u = mapcol_f - mapcol0;

		double c00 = bufs[0][mapcol0];
		double c01 = bufs[0][mapcol1];
		double c10 = bufs[1][mapcol0];
		double c11 = bufs[1][mapcol1];

		if (G_is_d_null_value(&c00) ||
		    G_is_d_null_value(&c01) ||
		    G_is_d_null_value(&c10) || G_is_d_null_value(&c11)) {
		    G_set_d_null_value(&outbuf[col], 1);
		}
		else {
		    outbuf[col] = G_interp_bilinear(u, v, c00, c01, c10, c11);
		}
	    }

	    G_set_window(&dst_w);
	    G_put_d_raster_row(outfile, outbuf);
	}
	break;

    case 4:			/* bicubic */
	for (row = 0; row < dst_w.rows; row++) {
	    double north = G_row_to_northing(row + 0.5, &dst_w);
	    double maprow_f = G_northing_to_row(north, &src_w) - 0.5;
	    int maprow1 = (int)floor(maprow_f);
	    int maprow0 = maprow1 - 1;
	    double v = maprow_f - maprow1;

	    G_percent(row, dst_w.rows, 2);

	    G_set_window(&src_w);
	    read_rows(infile, maprow0);

	    for (col = 0; col < dst_w.cols; col++) {
		double east = G_col_to_easting(col + 0.5, &dst_w);
		double mapcol_f = G_easting_to_col(east, &src_w) - 0.5;
		int mapcol1 = (int)floor(mapcol_f);
		int mapcol0 = mapcol1 - 1;
		int mapcol2 = mapcol1 + 1;
		int mapcol3 = mapcol1 + 2;
		double u = mapcol_f - mapcol1;

		double c00 = bufs[0][mapcol0];
		double c01 = bufs[0][mapcol1];
		double c02 = bufs[0][mapcol2];
		double c03 = bufs[0][mapcol3];

		double c10 = bufs[1][mapcol0];
		double c11 = bufs[1][mapcol1];
		double c12 = bufs[1][mapcol2];
		double c13 = bufs[1][mapcol3];

		double c20 = bufs[2][mapcol0];
		double c21 = bufs[2][mapcol1];
		double c22 = bufs[2][mapcol2];
		double c23 = bufs[2][mapcol3];

		double c30 = bufs[3][mapcol0];
		double c31 = bufs[3][mapcol1];
		double c32 = bufs[3][mapcol2];
		double c33 = bufs[3][mapcol3];

		if (G_is_d_null_value(&c00) ||
		    G_is_d_null_value(&c01) ||
		    G_is_d_null_value(&c02) ||
		    G_is_d_null_value(&c03) ||
		    G_is_d_null_value(&c10) ||
		    G_is_d_null_value(&c11) ||
		    G_is_d_null_value(&c12) ||
		    G_is_d_null_value(&c13) ||
		    G_is_d_null_value(&c20) ||
		    G_is_d_null_value(&c21) ||
		    G_is_d_null_value(&c22) ||
		    G_is_d_null_value(&c23) ||
		    G_is_d_null_value(&c30) ||
		    G_is_d_null_value(&c31) ||
		    G_is_d_null_value(&c32) || G_is_d_null_value(&c33)) {
		    G_set_d_null_value(&outbuf[col], 1);
		}
		else {
		    outbuf[col] = G_interp_bicubic(u, v,
						   c00, c01, c02, c03,
						   c10, c11, c12, c13,
						   c20, c21, c22, c23,
						   c30, c31, c32, c33);
		}
	    }

	    G_set_window(&dst_w);
	    G_put_d_raster_row(outfile, outbuf);
	}
	break;
    }

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

    G_close_cell(infile);
    G_close_cell(outfile);


    /* record map metadata/history info */
    sprintf(title, "Resample by %s interpolation", method->answer);
    G_put_cell_title(rastout->answer, title);

    G_short_history(rastout->answer, "raster", &history);
    strncpy(history.datsrc_1, rastin->answer, RECORD_LEN);
    history.datsrc_1[RECORD_LEN - 1] = '\0';	/* strncpy() doesn't null terminate if maxfill */
    G_format_resolution(src_w.ns_res, buf_nsres, src_w.proj);
    G_format_resolution(src_w.ew_res, buf_ewres, src_w.proj);
    sprintf(history.datsrc_2, "Source map NS res: %s   EW res: %s", buf_nsres,
	    buf_ewres);
    G_command_history(&history);
    G_write_history(rastout->answer, &history);

    /* copy color table from source map */
    if (G_read_colors(rastin->answer, inmap, &colors) < 0)
	G_fatal_error(_("Unable to read color table for %s"), rastin->answer);
    G_mark_colors_as_fp(&colors);
    if (G_write_colors(rastout->answer, G_mapset(), &colors) < 0)
	G_fatal_error(_("Unable to write color table for %s"),
		      rastout->answer);

    return (EXIT_SUCCESS);
}
Beispiel #18
0
/* useful to create randomised samples for statistical tests */
void do_split_sample ( char *input, char *output, int in_types, double percentage, char *map,  
						int all, int processing_mode, int quiet) {
        CELL *cellbuf;
	DCELL *dcellbuf;
	GT_Row_cache_t *cache;
	int fd;
	int i,j,k,l;
	int no_sites;
	int sites_tried = 0;
	struct Cell_head region;
	int error;
	char *mapset, errmsg [200];
	unsigned int *taken; /* this is an array of 0/1 which signals, if
	                       a certain site has already been 'drawn' */
	long row_idx, col_idx;
	struct Map_info in_vect_map;
	struct Map_info out_vect_map;
  	struct line_pnts *vect_points;
	struct line_cats *vect_cats;
	double x,y,z;
	int n_points = 1;
	int cur_type;
	
	
	cellbuf = NULL;
	dcellbuf = NULL;
	cache = NULL;
	
	/* get current region */
	G_get_window (&region);
	
	
	/* attempt to create new file for output */
	Vect_set_open_level (2);
	if (0 > Vect_open_new (&out_vect_map, output, 0) ) {
		G_fatal_error ("Could not open output vector map.\n");
	}

	/* open input vector map */  	
	if ((mapset = G_find_vector2 (input, "")) == NULL) {
	     sprintf (errmsg, "Could not find input %s\n", input);
	     G_fatal_error ("%s",errmsg);
	}

  	if (1 > Vect_open_old (&in_vect_map, input, "")) {
    		sprintf (errmsg, "Could not open input map %s.\n", input);
    		G_fatal_error ("%s",errmsg);
  	}

	vect_points = Vect_new_line_struct ();
	vect_cats = Vect_new_cats_struct ();

	/* set constraints specified */
	if (in_types != 0) {
		Vect_set_constraint_type (&in_vect_map, in_types);	
	}
	if (all != 1) {
		Vect_set_constraint_region (&in_vect_map, region.north, region.south, 
			region.east, region.west, 0.0, 0.0);
	}

	
	/* get total number of objects with constraints */
	i = 0;
	while ((cur_type = Vect_read_next_line (&in_vect_map, vect_points, vect_cats) > 0)) {
		i ++;
	}
	
	k = ( ((float) i/100)) * percentage; /* k now has the number of objects wanted */
	
	if ( quiet != 1 ) {
		fprintf (stderr,"Creating randomised sample of size n = %i.\n",k);
	}
	
	/* now, we need to acquire exactly 'k' random objects that fall in NON-NULL */
	/* coverage raster cells. */	
	taken = G_calloc (i, sizeof (unsigned int));
	for ( l = 0; l < k; l ++ ) {
		taken[l] = 0;
	}
	no_sites = i; /* store this for later use */
	
	/* does user want to filter objects through a raster map? */
	if ( map != NULL) {
		/* open raster map */
		fd = G_open_cell_old (map, G_find_cell (map, ""));
		if (fd < 0)
		{
			G_fatal_error ("Could not open raster map for reading!\n");
		}
		/* allocate cache and buffer, according to type of coverage */
		if ( processing_mode == CELL_TYPE) {
			/* INT coverage */
			cache = (GT_Row_cache_t *) G_malloc (sizeof (GT_Row_cache_t));
			/* TODO: check error value */
			error = GT_RC_open (cache, cachesize, fd, CELL_TYPE);
			cellbuf = G_allocate_raster_buf (CELL_TYPE);			
		}
		if ( (processing_mode == FCELL_TYPE) || (processing_mode == DCELL_TYPE) ) {
			/* FP coverage */
			cache = (GT_Row_cache_t *) G_malloc (sizeof (GT_Row_cache_t));
			/* TODO: check error value */
			error = GT_RC_open (cache, cachesize, fd, DCELL_TYPE);
			dcellbuf = G_allocate_raster_buf (DCELL_TYPE);	
		}
	}
	
	srand ( ((unsigned int) time (NULL)) + getpid()); /* set seed for random number generator from system time and process ID*/
	i = 0;
	
	/* MAIN LOOP */
	while ( i < k ) {
		/* get a random index, but one that was not taken already */
		l = 0;
		while ( l == 0 ) {
			j = rand () % ( no_sites - 1 + 1) + 1; /* j now has the random position to try */
			if ( taken[j-1] == 0 ) {
				l = 1; /* exit loop */
			}
		}
		taken [j-1] = 1; /* mark this index as 'taken' */
		sites_tried ++; /* keep track of this so we do not enter an infinite loop */
		if ( sites_tried > no_sites ) {
			/* could not create a large enough sample */
			G_fatal_error ("Could not find enough objects for split sampling.\nDecrease split sample size.\n");
		}
		/* get next vector object */
		cur_type = Vect_read_line (&in_vect_map, vect_points, vect_cats, j);
		if (cur_type < 0 ) {
			G_fatal_error ("Error reading vector map: premature EOF.\n");	
		}	
		/* now, check if coverage under site is NON-NULL and within region */
		/* convert site northing to row! */
		/* for this check, we use only the first pair of coordinates! */
		Vect_copy_pnts_to_xyz (vect_points, &x, &y, &z, &n_points);	
		row_idx =
			(long) G_northing_to_row (y,
				  &region);
				
		col_idx =
			(long) G_easting_to_col (x,
				 &region);
		/* do region check, first... OBSOLETE */
			/* read row from cache and check for NULL */
			/* if required */
			if ( map != NULL ) {
				if ( processing_mode == CELL_TYPE ) {
					cellbuf = GT_RC_get (cache, row_idx);			
					if (!G_is_c_null_value(&cellbuf[col_idx])) {
						i ++;
						Vect_write_line (&out_vect_map, cur_type, 
								vect_points, vect_cats );
						fflush (stdout);
					}
				}
				if ( (processing_mode == FCELL_TYPE) || (processing_mode == DCELL_TYPE) ) {
					dcellbuf = GT_RC_get (cache, row_idx);
					if (!G_is_d_null_value(&dcellbuf[col_idx])) {
						i ++;
						Vect_write_line (&out_vect_map, cur_type, 
								vect_points, vect_cats );
						fflush (stdout);
					}
				}
			} else {
				i ++;
				Vect_write_line (&out_vect_map, GV_POINT, 
								vect_points, vect_cats );
				fflush (stdout);
			}
		/* disregard region setting and map, if -a flag is given */
		if ( all == 1 ) {
			i ++;
			Vect_write_line (&out_vect_map, cur_type, 
					vect_points, vect_cats );
			fflush (stdout);
		}
		
		if ( quiet != 1 ) {
			G_percent(i,k,1);
		}
	}
	/* END OF MAIN LOOP */
	Vect_copy_head_data (&in_vect_map, &out_vect_map);
	fprintf (stdout, "Building topology information for output map.\n");
	Vect_build (&out_vect_map);
	Vect_close (&in_vect_map);
	Vect_close (&out_vect_map);
	
	if ( map != NULL ) {
		/* close cache, free buffers! */
		GT_RC_close (cache);
		if ( processing_mode == CELL_TYPE ) {
			G_free (cellbuf);
		}
		if ( (processing_mode == FCELL_TYPE) || (processing_mode == DCELL_TYPE) ) {
			G_free (dcellbuf);
		}
		G_free (cache);
		}
}
Beispiel #19
0
static int nabors(void)
{
    int tl_null = G_is_d_null_value(&tl);
    int tr_null = G_is_d_null_value(&tr);
    int bl_null = G_is_d_null_value(&bl);
    int br_null = G_is_d_null_value(&br);

    /* if both a and b are NULLs, thery are equal */
#define cmp(a, b) (a##_null+b##_null==1 || (a##_null+b##_null==0 && a != b))

    if (cmp(tl, tr) != 0) {	/* 0, 4, 5, 6, 8, 9, 10 */
	if (cmp(tl, bl) != 0) {	/* 4, 6, 8, 10 */
	    if (cmp(bl, br) != 0) {	/* 8, 10 */
		if (cmp(tr, br) != 0)
		    return (10);
		else
		    return (8);
	    }
	    else {		/* 4, 6 */

		if (cmp(tr, br) != 0)
		    return (6);
		else
		    return (4);
	    }
	}
	else {			/* 0, 5, 9 */

	    if (cmp(bl, br) != 0) {	/* 0, 9 */
		if (cmp(tr, br) != 0)
		    return (9);
		else
		    return (0);
	    }
	    else
		return (5);
	}
    }
    else {			/* 1, 2, 3, 7, 11 */

	if (cmp(tl, bl) != 0) {	/* 2, 3, 7 */
	    if (cmp(bl, br) != 0) {	/* 3, 7 */
		if (cmp(tr, br) != 0)
		    return (7);
		else
		    return (3);
	    }
	    else
		return (2);
	}
	else {			/* 1, 11 */

	    if (cmp(bl, br) != 0)
		return (1);
	    else
		return (11);
	}
    }

    return 0;
}
Beispiel #20
0
void extract(DCELL *** img,	/* multispectral image, img[band][i][j] */
	     struct Region *region,	/* region to extract */
	     LIKELIHOOD *** ll,	/* log likelihood, ll[i][j][class] */
	     struct SigSet *S	/* class signatures */
    )
{
    int i, j;			/* column and row indexes */
    int m;			/* class index */
    int k;			/* subclass index */
    int b1, b2;			/* spectral index */
    int no_data;		/* no data flag */
    int max_nsubclasses;	/* maximum number of subclasses */
    int nbands;			/* number of spectral bands */
    double *subll;		/* log likelihood of subclasses */
    double *diff;
    double maxlike = 0.0L;
    double subsum;
    struct ClassSig *C;
    struct SubSig *SubS;

    nbands = S->nbands;

    /* determine the maximum number of subclasses */
    max_nsubclasses = 0;
    for (m = 0; m < S->nclasses; m++)
	if (S->ClassSig[m].nsubclasses > max_nsubclasses)
	    max_nsubclasses = S->ClassSig[m].nsubclasses;

    /* allocate memory */
    diff = (double *)G_malloc(nbands * sizeof(double));
    subll = (double *)G_malloc(max_nsubclasses * sizeof(double));

    /* Compute log likelihood at each pixel and for every class. */

    /* for each pixel */
    for (i = region->ymin; i < region->ymax; i++)
	for (j = region->xmin; j < region->xmax; j++) {

	    /* Check for no data condition */
	    no_data = 1;
	    for (b1 = 0; (b1 < nbands) && no_data; b1++)
		no_data = no_data && (G_is_d_null_value(&img[b1][i][j]));

	    if (no_data) {
		for (m = 0; m < S->nclasses; m++)
		    ll[i][j][m] = 0.0;
	    }
	    else {
		/* for each class */
		for (m = 0; m < S->nclasses; m++) {
		    C = &(S->ClassSig[m]);

		    /* compute log likelihood for each subclass */
		    for (k = 0; k < C->nsubclasses; k++) {
			SubS = &(C->SubSig[k]);
			subll[k] = SubS->cnst;
			for (b1 = 0; b1 < nbands; b1++) {
			    diff[b1] = img[b1][i][j] - SubS->means[b1];
			    subll[k] -=
				0.5 * diff[b1] * diff[b1] *
				SubS->Rinv[b1][b1];
			}
			for (b1 = 0; b1 < nbands; b1++)
			    for (b2 = b1 + 1; b2 < nbands; b2++)
				subll[k] -=
				    diff[b1] * diff[b2] * SubS->Rinv[b1][b2];
		    }

		    /* shortcut for one subclass */
		    if (C->nsubclasses == 1) {
			ll[i][j][m] = subll[0];
		    }
		    /* compute mixture likelihood */
		    else {
			/* find the most likely subclass */
			for (k = 0; k < C->nsubclasses; k++) {
			    if (k == 0)
				maxlike = subll[k];
			    if (subll[k] > maxlike)
				maxlike = subll[k];
			}

			/* Sum weighted subclass likelihoods */
			subsum = 0;
			for (k = 0; k < C->nsubclasses; k++)
			    subsum +=
				exp(subll[k] - maxlike) * C->SubSig[k].pi;

			ll[i][j][m] = log(subsum) + maxlike;
		    }
		}
	    }
	}
    G_free((char *)diff);
    G_free((char *)subll);
}
Beispiel #21
0
int find_con(int r, int c, double *d1, double *d2, DCELL * con1, DCELL * con2)
{
    int ct, low_ct, node_ct;
    int rr, cc, dor, doc;
    double dd, shortest;
    DCELL value;

    G_set_d_null_value(con1, 1);
    G_set_d_null_value(con2, 1);
    *d1 = *d2 = 1.0;
    shortest = nrows * ncols;
    for (rr = minr; rr <= maxr; rr++) {
	for (cc = minc; cc <= maxc; cc++)
	    FLAG_UNSET(seen, rr, cc);
    }
    minr = nrows;
    minc = ncols;
    maxr = maxc = -1;
    FLAG_SET(seen, r, c);
    if (r < minr)
	minr = r;
    if (r > maxr)
	maxr = r;
    if (c < minc)
	minc = c;
    if (c > maxc)
	maxc = c;
    node_ct = 0;
    zero = addpts(zero, r, c, r, c, &node_ct);
    low_ct = 0;
    while (1) {
	ct = low_ct++;
	if (node_ct <= ct)
	    return 1;
	rr = zero[ct].r;
	cc = zero[ct].c;
	dor = ABS(rr - r);
	doc = ABS(cc - c);
	if (rr >= 0 && cc >= 0 && rr < nrows && cc < ncols
	    && zero[ct].d < shortest && !flag_get(mask, rr, cc)) {
	    dseg_get(&con, rr, cc, &value);
	    if (G_is_d_null_value(&value))
		zero = addpts(zero, r, c, rr, cc, &node_ct);
	    else if (G_is_d_null_value(con1)) {
		*con1 = value;
		*d1 = MIN(dor, doc) * 1.414 + ABS(dor - doc);
		shortest = *d1 * 2.0 * i_val_l_f;
	    }
	    else if (*con1 == value) {
		dd = MIN(dor, doc) * 1.414 + ABS(dor - doc);
		if (dd < *d1) {
		    *d1 = dd;
		    shortest = dd * 2.0 * i_val_l_f;
		}
	    }
	    else if (G_is_d_null_value(con2)) {
		*con2 = value;
		*d2 = MIN(dor, doc) * 1.414 + ABS(dor - doc);
		shortest = *d2;
	    }
	    else {
		dd = MIN(dor, doc) * 1.414 + ABS(dor - doc);
		shortest = MIN(shortest, dd);
	    }
	}
    }

    return 0;
}
Beispiel #22
0
/*!
   \brief Get categories/labels

   Formats label as in d.what.rast -> (catval) catlabel 

   \param filename raster map name
   \param drow
   \param dcol
   \param catstr category string

   \return 1 on success
   \return 0 on failure
 */
int Gs_get_cat_label(const char *filename, int drow, int dcol, char *catstr)
{
    struct Categories cats;
    const char *mapset;
    CELL *buf;
    DCELL *dbuf;
    RASTER_MAP_TYPE map_type;
    int fd;

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

    if (-1 != G_read_cats(filename, mapset, &cats)) {
	fd = G_open_cell_old(filename, mapset);
	map_type = G_get_raster_map_type(fd);

	if (map_type == CELL_TYPE) {
	    buf = G_allocate_c_raster_buf();

	    if (G_get_c_raster_row(fd, buf, drow) < 0) {
		sprintf(catstr, "error");
	    }
	    else if (G_is_c_null_value(&buf[dcol])) {
		sprintf(catstr, "(NULL) %s",
			G_get_c_raster_cat(&buf[dcol], &cats));
	    }
	    else {
		sprintf(catstr, "(%d) %s", buf[dcol],
			G_get_c_raster_cat(&buf[dcol], &cats));
	    }

	    G_free(buf);
	}

	else {
	    /* fp map */
	    dbuf = G_allocate_d_raster_buf();

	    if (G_get_d_raster_row(fd, dbuf, drow) < 0) {
		sprintf(catstr, "error");
	    }
	    else if (G_is_d_null_value(&dbuf[dcol])) {
		sprintf(catstr, "(NULL) %s",
			G_get_d_raster_cat(&dbuf[dcol], &cats));
	    }
	    else {
		sprintf(catstr, "(%g) %s", dbuf[dcol],
			G_get_d_raster_cat(&dbuf[dcol], &cats));
	    }

	    G_free(dbuf);
	}
    }
    else {
	strcpy(catstr, "no category label");
    }

    /* TODO: may want to keep these around for multiple queries */
    G_free_cats(&cats);

    G_close_cell(fd);

    return (1);
}
Beispiel #23
0
int G_ask_colors(const char *name, const char *mapset, struct Colors *pcolr)
{
    char buff[128];
    int answ;
    struct FPRange range;
    DCELL min, max;

    G_init_colors(pcolr);

    /* determine range cell values */
    if (G_read_fp_range(name, mapset, &range) < 0)
	return -1;
    G_get_fp_range_min_max(&range, &min, &max);
    if (G_is_d_null_value(&min) || G_is_d_null_value(&max)) {
	sprintf(buff, _(" The raster map %s@%s is empty"), name, mapset);
	G_warning(buff);
	return -1;
    }

    /* Prompting */
  ASK:
    G_clear_screen();
    fprintf(stderr,
	    _("\n\nColor table needed for file [%s] in mapset [%s].\n"), name,
	    mapset);

    fprintf(stderr, _("\nPlease identify the type desired:\n"));
    fprintf(stderr, _("    1:  Random colors\n"));
    fprintf(stderr, _("    2:  Red, green, and blue color ramps\n"));
    fprintf(stderr, _("    3:  Color wave\n"));
    fprintf(stderr, _("    4:  Gray scale\n"));
    fprintf(stderr, _("    5:  Aspect\n"));
    fprintf(stderr, _("    6:  Rainbow colors\n"));
    fprintf(stderr, _("    7:  Red through yellow to green\n"));
    fprintf(stderr, _("    8:  Green through yellow to red\n"));
    fprintf(stderr, _("RETURN  quit\n"));
    fprintf(stderr, "\n> ");

    for (;;) {
	if (!G_gets(buff))
	    goto ASK;
	G_strip(buff);
	if (*buff == 0)
	    return -1;
	if (sscanf(buff, "%d", &answ) != 1)
	    answ = -1;

	switch (answ) {
	case 1:
	    return G_make_random_colors(pcolr, (CELL) min, (CELL) max);
	case 2:
	    return G_make_ramp_fp_colors(pcolr, min, max);
	case 3:
	    return G_make_wave_fp_colors(pcolr, min, max);
	case 4:
	    return G_make_grey_scale_fp_colors(pcolr, min, max);
	case 5:
	    return G_make_aspect_fp_colors(pcolr, min, max);
	case 6:
	    return G_make_rainbow_fp_colors(pcolr, min, max);
	case 7:
	    return G_make_ryg_fp_colors(pcolr, min, max);
	case 8:
	    return G_make_gyr_fp_colors(pcolr, min, max);
	default:
	    fprintf(stderr, _("\n%s invalid; Try again > "), buff);
	    break;
	}
    }
}
Beispiel #24
0
/* NULL cell handling added by Benjamin Ducke, May 2004 */
void Close_segmented_outfile (char* map_name, int map_fd,
			             char* seg_name, int seg_fd, SEGMENT* seg, 
                         CELL* cell_buf, int terse,
                         SEGMENT* elevation_seg, RASTER_MAP_TYPE data_type, int make_nulls)
{
  unsigned long row, nrows, col, ncols;
  void *value = NULL;
  char *null_flags;
  /* the following are used to store different raster map types */
  CELL c_value;
  FCELL f_value;
  DCELL d_value;  	

	
  /* Find number of rows and columns in elevation map */
  nrows = G_window_rows();
  ncols = G_window_cols();
	
  /* allocate memory for a NULL data row */	
  null_flags = G_calloc ((unsigned) ncols, sizeof (char));
    
  /* Write pending updates by segment_put() to output map */
  segment_flush(seg);
  
  if (!terse) {	
    fprintf (stdout, "\nWriting raster map '%s': \n", map_name);	
  }
	
  /* Convert output submatrices to full cell overlay */
  for(row=0; row< nrows; row++) {
    segment_get_row(seg, cell_buf, (signed) row);
	/* check for NULL values in the corresponding row of the */
	/* elevation input file. If there are any, set the CELLs */
	/* in the output file to NULL, as well */
	
	/* initialize null data row */
	for (col=0; col<ncols; col++) {
		null_flags[col] = 0;
	}
	
	/* convert all -1 cells to NULL, if user wants it so */
    if ( make_nulls == 1 ) {
	    for (col=0; col<ncols; col++) {
		   if ( cell_buf[col] == -1 ) {
		     null_flags[col] = 1;
		   }
		}
	}
	
	/* update NULL flags in row */
    for (col=0; col<ncols; col++) {
		if ( data_type == CELL_TYPE ) {
		    value = (CELL*) &c_value;
		}		  
		if ( data_type == FCELL_TYPE ) {
		    value = (FCELL*) &f_value;
		}		  
		if ( data_type == DCELL_TYPE ) {
		    value = (DCELL*) &d_value;
		}
		
        segment_get (elevation_seg, value, (signed) row, (signed) col);
		
		/* check for NULL value and record in null_flags row */
		if ( data_type == CELL_TYPE ) {
		    if (G_is_c_null_value (&c_value) ) {
			  null_flags[col] = 1; /* signal NULL value in null_flags row */
			}			
		}		  
		if ( data_type == FCELL_TYPE ) {
		    if (G_is_f_null_value (&f_value) ) {
			  null_flags[col] = 1; /* signal NULL value in null_flags row */
			}
		}		  
		if ( data_type == DCELL_TYPE ) {
		    if (G_is_d_null_value (&d_value) ) {
			  null_flags[col] = 1; /* signal NULL value in null_flags row */
			}						
		}
	}
    /* set all NULL cells according to null_flags row */
	G_insert_c_null_values (cell_buf, null_flags, (signed) ncols);
	
	/* now, write this row to disk */  
    if(G_put_raster_row (map_fd, cell_buf, CELL_TYPE) < 0) {
	  G_fatal_error ("Failed to convert output submatrices ");	  
	}
	
	/* progress display */
	if (! terse) {
		G_percent ((signed) row, (signed) nrows-1,2);
	}	
  }
  
  G_free (null_flags);
  
/* Close files */
  segment_release (seg);
  close (seg_fd);
  unlink (seg_name);
  G_close_cell (map_fd);
}