Ejemplo n.º 1
0
/* ************************************************************************* */
void write_vtk_vector_data(void *map_x, void *map_y, void *map_z,
                           FILE * fp, const char *varname,
                           RASTER3D_Region region, int dp)
{
    double value = 0;
    int x, y, z, percentage, k;
    int rows, cols, depths;
    int typeIntern[3];
    void *mapvect = NULL;

    G_debug(3, "write_vtk_vector_data: Writing vector data");

    rows = region.rows;
    cols = region.cols;
    depths = region.depths;

    typeIntern[0] = Rast3d_tile_type_map(map_x);
    typeIntern[1] = Rast3d_tile_type_map(map_y);
    typeIntern[2] = Rast3d_tile_type_map(map_z);

    percentage = 0;

    /********************** WRITE VECTOR DATA; CELL OR POINT ****************/
    fprintf(fp, "VECTORS %s float\n", varname);

    for (z = 0; z < depths; z++) { /*From the bottom to the top */
        for (y = 0; y < rows; y++) {
            G_percent(percentage, (rows * depths - 1), 10);
            percentage++;

            for (x = 0; x < cols; x++) {
                for (k = 0; k < 3; k++) {

                    if (k == 0)
                        mapvect = map_x;
                    if (k == 1)
                        mapvect = map_y;
                    if (k == 2)
                        mapvect = map_z;

                    /* In case of structured grid data, the point/cell coordinates
                       are computed based on the default north->south raster3d coordinate system.
                       We need to compute south -> north ordering for image data.
                     */
                    if (!param.structgrid->answer)
                        value =
                        get_g3d_raster_value_as_double(mapvect, x, rows - y - 1, z,
                                                       typeIntern[k],
                                                       0.0);
                    else
                        value =
                        get_g3d_raster_value_as_double(mapvect, x, y, z,
                                                       typeIntern[k],
                                                       0.0);
                    fprintf(fp, "%.*f ", dp, value);
                }
                fprintf(fp, "\n");
            }
        }
    }
    return;
}
Ejemplo n.º 2
0
int do_cum(void)
{
    int r, c, dr, dc;
    char asp_val, asp_val_down;
    char is_swale, this_flag_value, flag_value;
    DCELL value, valued;
    POINT point;
    int killer, threshold;
    int asp_r[9] = { 0, -1, -1, -1, 0, 1, 1, 1, 0 };
    int asp_c[9] = { 0, 1, 0, -1, -1, -1, 0, 1, 1 };
    WAT_ALT wa, wadown;

    G_message(_("SECTION 3: Accumulating Surface Flow with SFD."));

    if (bas_thres <= 0)
	threshold = 60;
    else
	threshold = bas_thres;
    for (killer = 0; killer < do_points; killer++) {
	G_percent(killer, do_points, 1);
	seg_get(&astar_pts, (char *)&point, 0, killer);
	r = point.r;
	c = point.c;
	bseg_get(&asp, &asp_val, r, c);
	if (asp_val) {
	    dr = r + asp_r[ABS(asp_val)];
	    dc = c + asp_c[ABS(asp_val)];
	}
	/* skip user-defined depressions */
	else
	    dr = dc = -1;

	bseg_get(&bitflags, &this_flag_value, r, c);
	FLAG_UNSET(this_flag_value, WORKEDFLAG);

	if (dr >= 0 && dr < nrows && dc >= 0 && dc < ncols) {
	    /* TODO: do not distribute flow along edges, this causes artifacts */
	    seg_get(&watalt, (char *)&wa, r, c);
	    value = wa.wat;
	    is_swale = FLAG_GET(this_flag_value, SWALEFLAG);
	    if (fabs(value) >= threshold && !is_swale) {
		is_swale = 1;
		FLAG_SET(this_flag_value, SWALEFLAG);
	    }
	    seg_get(&watalt, (char *)&wadown, dr, dc);
	    valued = wadown.wat;
	    if (value > 0) {
		if (valued > 0)
		    valued += value;
		else
		    valued -= value;
	    }
	    else {
		if (valued < 0)
		    valued += value;
		else
		    valued = value - valued;
	    }
	    wadown.wat = valued;
	    seg_put(&watalt, (char *)&wadown, dr, dc);
	    /* update asp for depression */
	    if (is_swale || fabs(valued) >= threshold) {
		bseg_get(&bitflags, &flag_value, dr, dc);
		FLAG_SET(flag_value, SWALEFLAG);
		bseg_put(&bitflags, &flag_value, dr, dc);
		is_swale = 1;
	    }
	    else {
		if (er_flag && !is_swale && !FLAG_GET(this_flag_value, RUSLEBLOCKFLAG))
		    slope_length(r, c, dr, dc);
	    }
	}
	bseg_put(&bitflags, &this_flag_value, r, c);
    }
    G_percent(do_points, do_points, 1);	/* finish it */

    seg_close(&astar_pts);

    return 0;
}
Ejemplo n.º 3
0
/* write_area - make table of area equivalences and write attribute file */
int write_area(struct area_table *a_list,	/* list of areas */
	       struct equiv_table *e_list,	/* list of equivalences between areas */
	       int n_areas,	/* lengths of e_list, a_list */
	       int n_equiv)
{
    struct line_pnts *points = Vect_new_line_struct();
    int n, i;
    struct area_table *p;
    char *temp_buf;
    int *equivs;
    int cat;
    int catNum;
    double x, y;

    equivs = NULL;
    total_areas = 0;
    if (n_equiv < n_areas) {
	equivs = (int *)G_malloc(n_areas * sizeof(int));
	n = n_equiv;
    }
    else {
	equivs = (int *)G_malloc(n_equiv * sizeof(int));
	n = n_areas;
    }

    for (i = 0; i < n; i++) {
	if ((e_list + i)->mapped)
	    equivs[i] = (e_list + i)->where;
	else {
	    total_areas++;
	    equivs[i] = i;
	}
    }

    if (n < n_areas) {
	for (i = n; i < n_areas; i++) {
	    total_areas++;
	    equivs[i] = i;
	}
    }

    catNum = 1;

    G_important_message(_("Writing areas..."));
    for (i = 0, p = a_list; i < n_areas; i++, p++) {
	G_percent(i, n_areas, 3);

	if (equivs[i] == i && p->width > 0 && !Rast_is_d_null_value(&(p->cat))) {
	    char buf[1000];

	    if (value_flag) {	/* raster value */
		cat = (int)p->cat;
	    }
	    else {		/* sequence */
		cat = catNum;
		catNum++;
	    }

	    x = cell_head.west + (p->col +
				  (p->width / 2.0)) * cell_head.ew_res;
	    y = cell_head.north - (p->row + 0.5) * cell_head.ns_res;

	    switch (data_type) {
	    case CELL_TYPE:
		G_debug(3,
			"vector x = %.3f, y = %.3f, cat = %d; raster cat = %d",
			x, y, cat, (int)p->cat);
		break;
	    case FCELL_TYPE:
		G_debug(3,
			"vector x = %.3f, y = %.3f, cat = %d; raster cat = %f",
			x, y, cat, (float)p->cat);
		break;
	    case DCELL_TYPE:
		G_debug(3,
			"vector x = %.3f, y = %.3f, cat = %d; raster cat = %lf",
			x, y, cat, p->cat);
		break;
	    }

	    Vect_reset_line(points);
	    Vect_append_point(points, x, y, 0.0);

	    Vect_reset_cats(Cats);
	    Vect_cat_set(Cats, 1, cat);

	    Vect_write_line(&Map, GV_CENTROID, points, Cats);

	    if (driver != NULL && !value_flag) {
		sprintf(buf, "insert into %s values (%d, ", Fi->table, cat);
		db_set_string(&sql, buf);
		switch (data_type) {
		case CELL_TYPE:
		    sprintf(buf, "%d", (int)p->cat);
		    break;
		case FCELL_TYPE:
		case DCELL_TYPE:
		    sprintf(buf, "%f", p->cat);
		    break;
		}
		db_append_string(&sql, buf);

		if (has_cats) {
		    temp_buf = Rast_get_d_cat(&p->cat, &RastCats);

		    db_set_string(&label, temp_buf);
		    db_double_quote_string(&label);
		    sprintf(buf, ", '%s'", db_get_string(&label));
		    db_append_string(&sql, buf);
		}

		db_append_string(&sql, ")");
		G_debug(3, "%s", db_get_string(&sql));

		if (db_execute_immediate(driver, &sql) != DB_OK)
		    G_fatal_error(_("Cannot insert new row: %s"),
				  db_get_string(&sql));
	    }
	}
    }
    G_percent(1, 1, 1);

    if (equivs)
	G_free(equivs);
    
    return 0;
}
Ejemplo n.º 4
0
/*
 * check_stats() - Check and update statistics 
 *
 * RETURN: 0 on success / 1 on failure
 */
int check_stats(const char *name)
{
    RASTER_MAP_TYPE data_type;
    struct Histogram histogram;
    struct Categories cats;
    struct Range range;
    struct FPRange fprange;
    int i, histo_num;
    int cats_ok;
    int max;

    data_type = Rast_map_type(name, "");

    G_message(_("Updating statistics for [%s]..."), name);

    if (!do_histogram(name))
	return 1;
    if (Rast_read_histogram(name, "", &histogram) <= 0)
	return 1;

    /* Init histogram range */
    if (data_type == CELL_TYPE)
	Rast_init_range(&range);
    else
	Rast_init_fp_range(&fprange);

    G_message(_("Updating histogram range..."));
    i = histo_num = Rast_get_histogram_num(&histogram);
    while (i >= 0) {
	G_percent(i, histo_num, 2);

	if (data_type == CELL_TYPE)
	    Rast_update_range(Rast_get_histogram_cat(i--, &histogram), &range);
	else
	    Rast_update_fp_range((DCELL) Rast_get_histogram_cat(i--, &histogram),
			      &fprange);
    }

    /* Write histogram range */
    if (data_type == CELL_TYPE)
	Rast_write_range(name, &range);
    else
	Rast_write_fp_range(name, &fprange);

    /* Get category status and max */
    cats_ok = (Rast_read_cats(name, "", &cats) >= 0);
    max = (data_type == CELL_TYPE ? range.max : fprange.max);

    /* Further category checks */
    if (!cats_ok)
	Rast_init_cats("", &cats);
    else if (cats.num != max) {
	cats.num = max;
	cats_ok = 0;
    }

    /* Update categories if needed */
    if (!cats_ok) {
	G_message(_("Updating the number of categories for [%s]..."), name);
	Rast_write_cats(name, &cats);
    }

    Rast_free_histogram(&histogram);
    Rast_free_cats(&cats);

    return 0;
}
Ejemplo n.º 5
0
void do_calculations_rast (Shypothesis **samples, char **groups, int norm,
						  char* basename, char **outvals, char *hypspec, int quiet_flag,
						  char *logfile, xmlDocPtr doc, Sfp_struct* file_pointers) {
	
	long y,x;
	int i, j, k, l, m;
	long ymax,xmax;
	double woc;
	struct Categories cats, icats;
	DCELL cmin, cmax;
	Sresult_struct *result_row; /* one result_struct for each DST value */
	BOOL **garbage;
	int no_hyps;
	char* val_names[NUMVALS]={"bel","pl","doubt","common","bint","woc","maxbpa","minbpa",
				  "maxsrc","minsrc"};
	int error;
	char **outhyps;
	int no_sets;
	
	/* for keeping min and max statistics */
	Uint nsets;
	double *min_backup, *max_backup;
	int *minev_backup, *maxev_backup;
	
	woc = 0;

	/* check for output options */
	if ( G_legal_filename(basename) != 1 ) {
		G_fatal_error ("Please provide a legal filename as basename for output maps(s).\n");
	}
	
	if ( hypspec != NULL ) { 
		/* user specified hyps, let's see if they're valid */		
		/* create an outhyps array that has as each of its elements the name
			of one of the hypotheses specified on the command line */
		outhyps = parse_hyps (hypspec, &no_hyps);
		check_hyps ( outhyps, no_hyps, doc );				
	} else {
		/* just process all hypotheses */
		outhyps = get_hyp_names_XML ( &no_hyps, doc );
	}

	if ( logfile != NULL ) {	
		fprintf (lp,"Writing output RASTER maps for: \n");
	}
	
	/* create raster rows to store results */
	result_row = G_malloc ( NUMVALS * sizeof (Sresult_struct) );	
	for (i=0; i<NUMVALS; i++) {
		result_row[i].use = NO;
		strcpy (result_row[i].valname,val_names[i]);
		/* individual raster rows will be alloc'd later */
		result_row[i].row = (DCELL **) G_malloc ( no_hyps * sizeof (DCELL*) ); 
		result_row[i].crow = (CELL **) G_malloc ( no_hyps * sizeof (CELL*) );
		result_row[i].filename = NULL;
	}	
	
	j = 0;
	while ( outvals[j] != NULL ) {
	
		if ( !strcmp (outvals[j],"bel") ) {
			if ( logfile != NULL ) 
				fprintf (lp,"\t'bel' (Believe) values\n");
			make_result_row ( BEL, basename, outhyps, no_hyps, &result_row[BEL], doc );			
		}
		if ( !strcmp (outvals[j],"pl") ) {
			if ( logfile != NULL ) 
				fprintf (lp,"\t'pl' (Plausibility) values\n");
			make_result_row ( PL, basename, outhyps, no_hyps, &result_row[PL], doc );
		}
		if ( !strcmp (outvals[j],"doubt") ) {
			if ( logfile != NULL ) 
				fprintf (lp,"\t'doubt' (Doubt) values\n");
			make_result_row ( DOUBT, basename, outhyps, no_hyps, &result_row[DOUBT], doc );
		}
		if ( !strcmp (outvals[j],"common") ) {
			if ( logfile != NULL ) 
				fprintf (lp,"\t'common' (Commonality) values\n");
			make_result_row ( COMMON, basename, outhyps, no_hyps, &result_row[COMMON], doc );
		}
		if ( !strcmp (outvals[j],"bint") ) {
			if ( logfile != NULL ) 
				fprintf (lp,"\t'bint' (Believe interval) values\n");
			make_result_row ( BINT, basename, outhyps, no_hyps, &result_row[BINT], doc );
		}
		if ( !strcmp (outvals[j],"woc") ) {
			if ( logfile != NULL ) 
				fprintf (lp,"\t'woc' (Weight of conflict) values\n");
			make_result_row ( WOC, basename, outhyps, no_hyps,&result_row[WOC], doc );
		}
		if ( !strcmp (outvals[j],"maxbpa") ) {
			if ( logfile != NULL ) 
				fprintf (lp,"\t'maxbpa' (Maximum BPA) values\n");
			make_result_row ( MAXBPA, basename, outhyps, no_hyps,&result_row[MAXBPA], doc );
		}
		if ( !strcmp (outvals[j],"minbpa") ) {
			if ( logfile != NULL ) 
				fprintf (lp,"\t'minbpa' (Minimum BPA) values\n");
			make_result_row ( MINBPA, basename, outhyps, no_hyps,&result_row[MINBPA], doc );
		}
		if ( !strcmp (outvals[j],"maxsrc") ) {
			if ( logfile != NULL ) 
				fprintf (lp,"\t'maxsrc' (source of highest BPA) values\n");
			make_result_row ( MAXSRC, basename, outhyps, no_hyps,&result_row[MAXSRC], doc );
		}
		if ( !strcmp (outvals[j],"minsrc") ) {
			if ( logfile != NULL ) 
				fprintf (lp,"\t'minsrc' (source of lowest BPA) values\n");
			make_result_row ( MINSRC, basename, outhyps, no_hyps,&result_row[MINSRC], doc );
		}
		j ++;
	}
	
	/* open output maps to store results */
	if ( logfile != NULL ) 
		fprintf (lp,"Opening output maps:\n");
	for (i=0; i<NUMVALS;i++) {
		if (result_row[i].use == YES) {
			if ( i == WOC ) {
				if ( logfile != NULL ) 
					fprintf (lp,"\t%s\n",result_row[i].filename[0]);
				result_row[i].fd[0] = G_open_raster_new (result_row[i].filename[0],DCELL_TYPE);
			} else {
				for (j=0; j < no_hyps; j++) {
					if ( logfile != NULL ) 
						fprintf (lp,"\t%s\n",result_row[i].filename[j]);
					if ((i == MAXSRC) || (i == MINSRC)) {
						result_row[i].fd[j] = G_open_raster_new (result_row[i].filename[j],CELL_TYPE);
					} else {
						result_row[i].fd[j] = G_open_raster_new (result_row[i].filename[j],DCELL_TYPE);
					}
					/* check fd for errors */
					if ( result_row[i].fd[j] < 0 ) {
						G_fatal_error ("Could not create output map for %s\n",
										result_row[i].filename[j]);
					}
				}
			}
		}
	}		
	
	if ( logfile != NULL ) {
		fprintf (lp, "Evidence will be combined for these groups:\n");
		for ( i=0; i < N; i++) {
			fprintf (lp,"\t%s\n",groups[i]);
		}
		fprintf (lp, "Output will be stored in mapset '%s'.\n", G_mapset());
		fprintf (lp,"\nRead output below carefully to detect potential problems:\n");
	}			
			
	/* set start coordinates for reading from raster maps */
    	ReadX = 0;
	ReadY = 0;
	
	ymax = G_window_rows ();
	xmax = G_window_cols ();	
	
	if ( !quiet_flag ) {
		fprintf	(stdout,"Combining RAST evidence: \n");
		fflush (stdout);
	}
	
	/* allocate all file pointers */
	/* open raster maps for this group */
	/* 0 is the NULL hypothesis, so we start at 1 */
	no_sets = (Uint) pow((float) 2, (float) NO_SINGLETONS);
	for (l=0; l<N; l++) {
		for ( m = 1; m < no_sets; m ++ ) {
			file_pointers[l].fp[m] = G_open_cell_old ( file_pointers[l].filename[m], G_find_cell ( file_pointers[l].filename[m],"") );
			if ( file_pointers[l].fp[m] < 0 ) {
				G_fatal_error ("Could not open raster map '%s' for reading.\n", file_pointers[l].filename[m] );
			}
		}
	}	
	
	for (y=0; y<ymax; y++) {
		for (x=0; x<xmax; x++) {
			garbage = garbage_init ();
			NULL_SIGNAL = 0;
			
			for (i=0; i<N; i++) {
				samples[i] = get_rast_samples_XML (groups[i],i, norm, &nsets, garbage, doc, file_pointers );	
			}		

			/* get min and max values */
			for (i=0; i<N; i++) {
				if (NULL_SIGNAL == 0) {
					for (k=0; k < nsets; k++) {
						samples[i][k].minbpn = samples[i][k].bpa;
						samples[i][k].maxbpn = samples[i][k].bpa;
						samples[i][k].minbpnev = i + 1;
						samples[i][k].maxbpnev = i + 1;
					}
				}
								
			}
			
			for (i=0; i<N; i++) {
				if (NULL_SIGNAL == 0) {								
					for (j=0; j < N; j++) {
						for (k=0; k < nsets; k++) {
							if (samples[i][k].bpa < samples[j][k].minbpn) {
								samples[j][k].minbpn = samples[i][k].bpa;
								samples[j][k].minbpnev = i + 1;
							}
							if (samples[i][k].bpa > samples[j][k].maxbpn) {
								samples[j][k].maxbpn = samples[i][k].bpa;
								samples[j][k].maxbpnev = i + 1;
							}
						}
					}					
				}
			}
									
			/* initialise: */
			/* set belief and plausibility before first combination of evidence */
			for(i=0;i<N;i++)
			{
				if ( NULL_SIGNAL == 0 ) {
					set_beliefs(samples[i]);					
					set_plausibilities(samples[i]);
				}
			}
			
								
			/* combine evidence and set bel and pl again */
			/* AFTER COMBINE_BPN(), VALUES IN SAMPLES[0] WILL ALL BE ALTERED */
			/* so we must save min and max values for later use */
			min_backup = G_malloc ((unsigned)(nsets * sizeof(double)));			
			max_backup = G_malloc ((unsigned)(nsets * sizeof(double)));			
			minev_backup = G_malloc ((unsigned)(nsets * sizeof(int)));			
			maxev_backup = G_malloc ((unsigned)(nsets * sizeof(int)));
			for (k=0; k < nsets; k++) {
				min_backup[k] = samples[0][k].minbpn;
				max_backup[k] = samples[0][k].maxbpn;
				minev_backup[k] = samples[0][k].minbpnev;
				maxev_backup[k] = samples[0][k].maxbpnev;
			}

			/* now, do the combination! */
			for(i=0;i<N-1;i++)
			{
				if ( NULL_SIGNAL == 0 ) {
					woc = combine_bpn(samples[0], samples[i+1], garbage, RAST_MODE );					
					set_beliefs(samples[0]);					
					set_plausibilities(samples[0]);
				}
			}
			
			/* restore min and max values */
			for (k=0; k < nsets; k++) {
				samples[0][k].minbpn = min_backup[k];
				samples[0][k].maxbpn = max_backup[k];
				samples[0][k].minbpnev = minev_backup[k];
				samples[0][k].maxbpnev = maxev_backup[k];
			}			
			G_free (min_backup);
			G_free (max_backup);
			G_free (minev_backup);
			G_free (maxev_backup);
			
			/* all other metrics can be derived from bel and pl, no need */
			/* to combine evidence again! */
			if ( NULL_SIGNAL == 0 ) {
				set_commonalities(samples[0]);
				set_doubts(samples[0]);
				set_bint(samples[0]);
			}
			
									
			if ( NULL_SIGNAL == 1 ) {
				for (i=0; i<NUMVALS;i++) {
					if (result_row[i].use == YES) {
						if ( i == WOC) {
								write_row_null (result_row[i].row[0], ReadX);							
						} else {
							if ((i == MAXSRC)||(i == MINSRC)) {
								for (j=0; j < no_hyps; j++) {
									write_crow_null (result_row[i].crow[j], ReadX);
								}
					
							} else {							
								for (j=0; j < no_hyps; j++) {
									write_row_null (result_row[i].row[j], ReadX);							
								}
							}
						}
					}
				}				
			} else {
				for (i=0; i<NUMVALS;i++) {
					if (result_row[i].use == YES) {			
						if ( i == WOC ) {
							write_row_val (result_row[i].row[0], ReadX, samples[0], result_row[i].hyp_idx[0], i, woc);
						} else {
							if (( i == MAXSRC ) || ( i == MINSRC )) {
								for (j=0; j < no_hyps; j++) {
									write_crow_val (result_row[i].crow[j], ReadX, samples[0], result_row[i].hyp_idx[j], i);
								}
							} else {
								for (j=0; j < no_hyps; j++) {
									write_row_val (result_row[i].row[j], ReadX, samples[0], result_row[i].hyp_idx[j], i, woc);							
								}
							}
						}
					}
				}
			}
			ReadX ++;
			garbage_free ( garbage );									
			for (i=0; i<N; i++) {
				free_sample (samples[i]);				
			}					
		}
		ReadY ++; /* go to next row */
		ReadX = 0;				
		/* save this row to the result file */
		for (i=0; i<NUMVALS;i++) {
			if (result_row[i].use == YES) {			
				if ( i == WOC ) {
					write_row_file ( result_row[i].row[0],result_row[i].fd[0]);
				} else {
					if ( ( i == MAXSRC ) || ( i == MINSRC ) ) {
						for (j=0; j<no_hyps; j++) {
							write_crow_file ( result_row[i].crow[j],result_row[i].fd[j]);
						}
					} else {
						for (j=0; j<no_hyps; j++) {
							write_row_file ( result_row[i].row[j],result_row[i].fd[j]);
						}
					}
				}
			}
		}
		if ( !quiet_flag ) {
			G_percent (ReadY,ymax,1);
			fflush (stdout);		
		}
	}
	if ( !quiet_flag ) {
		fprintf (stdout,"\n");
		fflush (stdout);
	}
	for (i=0; i<NUMVALS;i++) {
		if (result_row[i].use == YES) {
			if ( i == WOC ) {
				G_close_cell (result_row[i].fd[0]);
			} else {				
				for (j=0; j<no_hyps; j++) {				
					G_close_cell (result_row[i].fd[j]);
				}
			}
		}
	}			
	
	
	/* close raster maps */
	/* 0 is the NULL hypothesis, so we start at 1 */
	for (l=0; l<N; l++) {
		for ( m = 1; m < no_sets; m ++ ) {
			G_close_cell (file_pointers[l].fp[m]);
		}
	}
	
	/* create a categories structure for output maps */
	/* DCELL maps */
	G_init_cats (3, "Value ranges", &cats);
	cmin = 0;
	cmax = 0.333333;
	G_set_d_raster_cat (&cmin, &cmax, "low", &cats);
	cmin = 0.333334;
	cmax = 0.666666;
	G_set_d_raster_cat (&cmin, &cmax, "medium", &cats);
	cmin = 0.666667;
	cmax = 1;
	G_set_d_raster_cat (&cmin, &cmax, "high", &cats);	

	/* CELL maps */
	G_init_cats (N+1, "Source of evidence", &icats);
	G_set_cat (0,"no data",&icats);
	for (i=1; i<=N; i++) {
		G_set_cat (i,groups[i-1],&icats);
	}

	/* write all color tables, categories information and history metadata */
	for (i=0; i<NUMVALS;i++) {
		if (result_row[i].use == YES) {
			if ( i == WOC ) {
				error = G_write_colors (result_row[i].filename[0], G_mapset(), result_row[i].colors[0]);
				if (error == -1) {
					G_warning ("Could not create color table for map '%s'.\n",result_row[i].filename[j]);
				}
			} else {
				if (( i == MAXSRC ) || ( i == MINSRC )) {					
					for (j=0; j<no_hyps; j++) {
						G_write_cats (result_row[i].filename[j], &icats);
					}
				} else {				
					for (j=0; j<no_hyps; j++) {
						error = G_write_colors (result_row[i].filename[j], G_mapset(), result_row[i].colors[j]);
						if (error == -1) {
							G_warning ("Could not create color table for map '%s'.\n",result_row[i].filename[j]);
						}
						G_write_raster_cats (result_row[i].filename[j], &cats);
					}
				}				
			}
		}
	}					
	G_free (samples);
	for ( i=0; i < no_hyps; i ++ ) {
		G_free ( outhyps[i]);
	}
	G_free (outhyps);
}
Ejemplo n.º 6
0
int main(int argc, char *argv[])
{
    struct GModule *module;
    struct
    {
	struct Option *input;
	struct Option *output;
	struct Option *null;
	struct Option *bytes;
	struct Option *order;
    } parm;
    struct
    {
	struct Flag *int_out;
	struct Flag *float_out;
	struct Flag *gmt_hd;
	struct Flag *bil_hd;
	struct Flag *swap;
    } flag;
    char *name;
    char *outfile;
    double null_val;
    int do_stdout;
    int is_fp;
    int bytes;
    int order;
    int swap_flag;
    struct Cell_head region;
    int nrows, ncols;
    DCELL *in_buf;
    unsigned char *out_buf;
    int fd;
    FILE *fp;
    struct GRD_HEADER header;
    int row;

    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("raster"));
    G_add_keyword(_("export"));
    module->description = _("Exports a GRASS raster to a binary array.");

    /* Define the different options */

    parm.input = G_define_option();
    parm.input->key = "input";
    parm.input->type = TYPE_STRING;
    parm.input->required = YES;
    parm.input->gisprompt = "old,cell,raster";
    parm.input->description = _("Name of input raster map");

    parm.output = G_define_option();
    parm.output->key = "output";
    parm.output->type = TYPE_STRING;
    parm.output->required = NO;
    parm.output->description =
	_("Name for output binary map (use output=- for stdout)");

    parm.null = G_define_option();
    parm.null->key = "null";
    parm.null->type = TYPE_DOUBLE;
    parm.null->required = NO;
    parm.null->answer = "0";
    parm.null->description = _("Value to write out for null");

    parm.bytes = G_define_option();
    parm.bytes->key = "bytes";
    parm.bytes->type = TYPE_INTEGER;
    parm.bytes->required = NO;
    parm.bytes->options = "1,2,4,8";
    parm.bytes->description = _("Number of bytes per cell");

    parm.order = G_define_option();
    parm.order->key = "order";
    parm.order->type = TYPE_STRING;
    parm.order->required = NO;
    parm.order->options = "big,little,native,swap";
    parm.order->description = _("Output byte order");
    parm.order->answer = "native";

    flag.int_out = G_define_flag();
    flag.int_out->key = 'i';
    flag.int_out->description = _("Generate integer output");

    flag.float_out = G_define_flag();
    flag.float_out->key = 'f';
    flag.float_out->description = _("Generate floating-point output");

    flag.gmt_hd = G_define_flag();
    flag.gmt_hd->key = 'h';
    flag.gmt_hd->description = _("Export array with GMT compatible header");

    flag.bil_hd = G_define_flag();
    flag.bil_hd->key = 'b';
    flag.bil_hd->description = _("Generate BIL world and header files");

    flag.swap = G_define_flag();
    flag.swap->key = 's';
    flag.swap->description = _("Byte swap output");

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

    if (sscanf(parm.null->answer, "%lf", &null_val) != 1)
	G_fatal_error(_("Invalid value for null (integers only)"));

    name = parm.input->answer;

    if (parm.output->answer)
	outfile = parm.output->answer;
    else {
	outfile = G_malloc(strlen(name) + 4 + 1);
	sprintf(outfile, "%s.bin", name);
    }

    if (G_strcasecmp(parm.order->answer, "big") == 0)
	order = 0;
    else if (G_strcasecmp(parm.order->answer, "little") == 0)
	order = 1;
    else if (G_strcasecmp(parm.order->answer, "native") == 0)
	order = G_is_little_endian() ? 1 : 0;
    else if (G_strcasecmp(parm.order->answer, "swap") == 0)
	order = G_is_little_endian() ? 0 : 1;

    if (flag.swap->answer) {
	if (strcmp(parm.order->answer, "native") != 0)
	    G_fatal_error(_("order= and -s are mutually exclusive"));
	order = G_is_little_endian() ? 0 : 1;
    }

    swap_flag = order == (G_is_little_endian() ? 0 : 1);

    do_stdout = strcmp("-", outfile) == 0;

    if (flag.int_out->answer && flag.float_out->answer)
	G_fatal_error(_("-i and -f are mutually exclusive"));

    fd = Rast_open_old(name, "");

    if (flag.int_out->answer)
	is_fp = 0;
    else if (flag.float_out->answer)
	is_fp = 1;
    else
	is_fp = Rast_get_map_type(fd) != CELL_TYPE;

    if (parm.bytes->answer)
	bytes = atoi(parm.bytes->answer);
    else if (is_fp)
	bytes = 4;
    else
	bytes = 2;

    if (is_fp && bytes < 4)
	G_fatal_error(_("Floating-point output requires bytes=4 or bytes=8"));

#ifndef HAVE_LONG_LONG_INT
    if (!is_fp && bytes > 4)
	G_fatal_error(_("Integer output doesn't support bytes=8 in this build"));
#endif

    G_get_window(&region);

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

    /* Set up Parameters for GMT header */
    if (flag.gmt_hd->answer) {
	if (!is_fp && bytes > 4)
	    G_fatal_error(_("GMT grid doesn't support 64-bit integers"));
	make_gmt_header(&header, name, outfile, &region, null_val);
    }

    /* Write out BIL support files compatible with Arc-View */
    if (flag.bil_hd->answer) {
	G_message(_("Creating BIL support files..."));
	write_bil_hdr(outfile, &region,
		      bytes, order, flag.gmt_hd->answer, null_val);
	write_bil_wld(outfile, &region);
    }

    /* Write out GMT Header if required */
    if (flag.gmt_hd->answer)
	write_gmt_header(&header, swap_flag, fp);

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

    in_buf = Rast_allocate_d_buf();
    out_buf = G_malloc(ncols * bytes);

    if (is_fp) {
	G_message(_("Exporting raster as floating values (bytes=%d)"), bytes);
	if (flag.gmt_hd->answer)
	    G_message(_("Writing GMT float format ID=1"));
    }
    else {
	G_message(_("Exporting raster as integer values (bytes=%d)"), bytes);
	if (flag.gmt_hd->answer)
	    G_message(_("Writing GMT integer format ID=2"));
    }

    G_verbose_message(_("Using the current region settings..."));
    G_verbose_message(_("north=%f"), region.north);
    G_verbose_message(_("south=%f"), region.south);
    G_verbose_message(_("east=%f"), region.east);
    G_verbose_message(_("west=%f"), region.west);
    G_verbose_message(_("r=%d"), region.rows);
    G_verbose_message(_("c=%d"), region.cols);

    for (row = 0; row < nrows; row++) {
	G_percent(row, nrows, 2);

	Rast_get_d_row(fd, in_buf, row);

	convert_row(out_buf, in_buf, ncols, is_fp, bytes, swap_flag, null_val);

	if (fwrite(out_buf, bytes, ncols, fp) != ncols)
	    G_fatal_error(_("Error writing data"));
    }

    G_percent(row, nrows, 2);	/* finish it off */

    Rast_close(fd);
    fclose(fp);

    return EXIT_SUCCESS;
}
Ejemplo n.º 7
0
int test_large_file_sparse_random(int depths, int rows, int cols, int tile_size)
{
    int sum = 0;
    int x, y, z, i;
    DCELL value, random_value;
    DCELL *random_value_vector = G_calloc(RAND_VALUE_VECTOR_SIZE, sizeof(DCELL));

    G_message("Testing DCELL put function for large files filled with sparse random values");

    RASTER3D_Region region;
    RASTER3D_Map *map = NULL;

    /* We need to set up a specific region for the new raster3d map.
     * First we safe the default region. */
    Rast3d_get_window(&region);

    region.bottom = -365.5;
    region.top = 365.5;
    region.south = -90;
    region.north = 90;
    region.west = -180;
    region.east = 180;
    region.rows = rows;
    region.cols = cols;
    region.depths = depths;

    Rast3d_adjust_region(&region);

    G_message("Creating 3D raster map filled with sparse random values");

    map = Rast3d_open_new_opt_tile_size("test_put_get_value_dcell_large_sparse_random",
                                        RASTER3D_USE_CACHE_XY, &region, DCELL_TYPE, tile_size);

    /* The window is the same as the map region ... of course */
    Rast3d_set_window_map(map, &region);

    srand(1);

    /* We fill the random value vector */
    for(i = 0; i < RAND_VALUE_VECTOR_SIZE; i++) {
        /* Put the counter as cell value */
        value = (DCELL)rand();
        value /= RAND_MAX;
        if(value <= 0.7)
            value = 0.0;
        else if(value <= 0.8)
            value = 1.0;
        else if(value <= 0.9)
            value = 2.0;
        else if(value <= 1.0)
            value = 3.0;
        else
            value = 4.0;
        random_value_vector[i] = value;
    }

    i = 0;

    for(z = 0; z < region.depths; z++) {
        G_percent(z, region.depths, 1);
        for(y = 0; y < region.rows; y++) {
            for(x = 0; x < region.cols; x++) {
                /* Put the counter as cell value */
                value = random_value_vector[i];
                Rast3d_put_value(map, x, y, z, &value, DCELL_TYPE);
                i++;
                if(i == RAND_VALUE_VECTOR_SIZE)
                    i = 0;
            }
        }
    }

    G_percent(1, 1, 1);
    /* Write everything to the disk */
    Rast3d_flush_all_tiles(map);
    Rast3d_close(map);

    G_message("Verifying 3D raster map filled with sparse random values");

    map = Rast3d_open_cell_old("test_put_get_value_dcell_large_sparse_random",
                               G_mapset(), &region, DCELL_TYPE, RASTER3D_USE_CACHE_XY);

    i = 0;

    for(z = 0; z < region.depths; z++) {
        G_percent(z, region.depths, 1);
        for(y = 0; y < region.rows; y++) {
            for(x = 0; x < region.cols; x++) {
                /* Check the counter as cell value */
                Rast3d_get_value(map, x, y, z, &value, DCELL_TYPE);
                if(fabs(value - random_value_vector[i]) > EPSILON) {
                    G_message("At: z %i y %i x %i -- value %.14lf != %.14lf\n",
                              z, y, x, value, random_value);
                    sum++;
                }
                i++;
                if(i == RAND_VALUE_VECTOR_SIZE)
                    i = 0;
            }
        }
    }
    G_percent(1, 1, 1);
    Rast3d_close(map);

    G_free(random_value_vector);

    G_remove("grid3", "test_put_get_value_dcell_large_sparse_random");

    return sum;
}
Ejemplo n.º 8
0
int main(int argc, char *argv[])
{
    struct Cell_head cellhd;	/*region+header info */
    char *mapset;		/*mapset name */
    int nrows, ncols;
    int row, col;
    struct GModule *module;
    struct Option *input, *output;
    struct Option *input1, *input2;
    struct Flag *flag0, *flag1, *flag2;
    struct Flag *flag3, *flag4, *flag5;
    struct History history;	/*metadata */

    /************************************/
    char *name;			/*input raster name */
    char *result;		/*output raster name */

    /*Prepare new names for output files */
    char result0[GNAME_MAX], result1[GNAME_MAX];
    char result2[GNAME_MAX], result3[GNAME_MAX];
    char result4[GNAME_MAX], result5[GNAME_MAX];
    char result6[GNAME_MAX], result7[GNAME_MAX];
    char result8[GNAME_MAX], result9[GNAME_MAX];
    char result10[GNAME_MAX], result11[GNAME_MAX];
    char result12[GNAME_MAX], result13[GNAME_MAX];
    char result14[GNAME_MAX];

    /*File Descriptors */
    int infd[MAXFILES];
    int outfd[MAXFILES];
    char **names, **ptr;
    /* For some strange reason infd[0] cannot be used later */
    /* So nfiles is initialized with nfiles = 1 */
    int nfiles = 1;
    int i = 0, j = 0;
    int radiance = 0;
    void *inrast[MAXFILES];
    DCELL *outrast[MAXFILES];
    RASTER_MAP_TYPE in_data_type[MAXFILES];
    RASTER_MAP_TYPE out_data_type = DCELL_TYPE;	/* 0=numbers  1=text */
    double gain[MAXFILES], offset[MAXFILES];
    double kexo[MAXFILES];
    double doy, sun_elevation;

    /************************************/
    G_gisinit(argv[0]);
    module = G_define_module();
    G_add_keyword(_("imagery"));
    G_add_keyword(_("radiometric conversion"));
    G_add_keyword(_("radiance"));
    G_add_keyword(_("reflectance"));
    G_add_keyword(_("brightness temperature"));
    G_add_keyword(_("satellite"));
    G_add_keyword(_("ASTER"));
    module->description =
	_("Calculates Top of Atmosphere Radiance/Reflectance/Brightness Temperature from ASTER DN.\n");

    /* Define the different options */
    input = G_define_standard_option(G_OPT_R_INPUTS);
    input->description = _("Names of ASTER DN layers (15 layers)");

    input1 = G_define_option();
    input1->key = "dayofyear";
    input1->type = TYPE_DOUBLE;
    input1->required = YES;
    input1->gisprompt = "value";
    input1->description = _("Day of Year of satellite overpass [0-366]");

    input2 = G_define_option();
    input2->key = "sun_elevation";
    input2->type = TYPE_DOUBLE;
    input2->required = YES;
    input2->gisprompt = "value";
    input2->description = _("Sun elevation angle (degrees, < 90.0)");

    output = G_define_standard_option(G_OPT_R_OUTPUT);
    output->description = _("Base name of the output layers (will add .x)");

    /* Define the different flags */
    flag0 = G_define_flag();
    flag0->key = 'r';
    flag0->description = _("Output is radiance (W/m2)");

    flag1 = G_define_flag();
    flag1->key = 'a';
    flag1->description = _("VNIR is High Gain");

    flag2 = G_define_flag();
    flag2->key = 'b';
    flag2->description = _("SWIR is High Gain");

    flag3 = G_define_flag();
    flag3->key = 'c';
    flag3->description = _("VNIR is Low Gain 1");

    flag4 = G_define_flag();
    flag4->key = 'd';
    flag4->description = _("SWIR is Low Gain 1");

    flag5 = G_define_flag();
    flag5->key = 'e';
    flag5->description = _("SWIR is Low Gain 2");

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

    names = input->answers;
    ptr = input->answers;
    doy = atof(input1->answer);
    sun_elevation = atof(input2->answer);
    result = output->answer;

    radiance = (flag0->answer);

    /********************/
    /*Prepare the output file names */

    /********************/
    sprintf(result0,"%s%s", result, ".1");
    sprintf(result1,"%s%s", result, ".2");
    sprintf(result2,"%s%s", result, ".3N");
    sprintf(result3,"%s%s", result, ".3B");
    sprintf(result4,"%s%s", result, ".4");
    sprintf(result5,"%s%s", result, ".5");
    sprintf(result6,"%s%s", result, ".6");
    sprintf(result7,"%s%s", result, ".7");
    sprintf(result8,"%s%s", result, ".8");
    sprintf(result9,"%s%s", result, ".9");
    sprintf(result10,"%s%s", result, ".10");
    sprintf(result11,"%s%s", result, ".11");
    sprintf(result12,"%s%s", result, ".12");
    sprintf(result13,"%s%s", result, ".13");
    sprintf(result14,"%s%s", result, ".14");
    /********************/
    /*Prepare radiance boundaries */

    /********************/
    int gain_code = 1;

    for (i = 0; i < MAXFILES; i++) {
	/*0 - High (Not Applicable for band 10-14: TIR) */
	/*1 - Normal */
	/*2 - Low 1(Not Applicable for band 10-14: TIR) */
	/*3 - Low 2(Not Applicable for Band 1-3N/B & 10-14) */
	if (flag1->answer && i <= 3)
	    gain_code = 0;
	if (flag2->answer && i >= 4 && i <= 9)
	    gain_code = 0;
	if (flag3->answer && i <= 3)
	    gain_code = 2;
	if (flag4->answer && i >= 4 && i <= 9)
	    gain_code = 2;
	if (flag5->answer && i >= 4 && i <= 9)
	    gain_code = 3;
	gain[i] = gain_aster(i, gain_code);
	/* Reset to NORMAL GAIN */
	gain_code = 1;
    }

    /********************/
    /*Prepare sun exo-atm irradiance */

    /********************/
    kexo[0] = KEXO1;
    kexo[1] = KEXO2;
    kexo[2] = KEXO3;
    kexo[3] = KEXO3;
    kexo[4] = KEXO4;
    kexo[5] = KEXO5;
    kexo[6] = KEXO6;
    kexo[7] = KEXO7;
    kexo[8] = KEXO8;
    kexo[9] = KEXO9;

    /********************/

    /********************/
    for (; *ptr != NULL; ptr++) {
	if (nfiles > MAXFILES)
	    G_fatal_error(_("Too many input maps. Only %d allowed."),
			  MAXFILES);
	name = *ptr;
	/* Allocate input buffer */
	in_data_type[nfiles-1] = Rast_map_type(name, "");
	/* For some strange reason infd[0] cannot be used later */
	/* So nfiles is initialized with nfiles = 1 */
	infd[nfiles] = Rast_open_old(name, "");

	Rast_get_cellhd(name, "", &cellhd);
	inrast[nfiles-1] = Rast_allocate_buf(in_data_type[nfiles-1]);
	nfiles++;
    }
    nfiles--;
    if (nfiles < MAXFILES) 
	G_fatal_error(_("The input band number should be 15"));

    /***************************************************/
    /* Allocate output buffer, use input map data_type */
    nrows = Rast_window_rows();
    ncols = Rast_window_cols();
    out_data_type = DCELL_TYPE;
    for (i = 0; i < MAXFILES; i++)
	outrast[i] = Rast_allocate_buf(out_data_type);

    outfd[1] = Rast_open_new(result0, 1);
    outfd[2] = Rast_open_new(result1, 1);
    outfd[3] = Rast_open_new(result2, 1);
    outfd[4] = Rast_open_new(result3, 1);
    outfd[5] = Rast_open_new(result4, 1);
    outfd[6] = Rast_open_new(result5, 1);
    outfd[7] = Rast_open_new(result6, 1);
    outfd[8] = Rast_open_new(result7, 1);
    outfd[9] = Rast_open_new(result8, 1);
    outfd[10] = Rast_open_new(result9, 1);
    outfd[11] = Rast_open_new(result10, 1);
    outfd[12] = Rast_open_new(result11, 1);
    outfd[13] = Rast_open_new(result12, 1);
    outfd[14] = Rast_open_new(result13, 1);
    outfd[15] = Rast_open_new(result14, 1);
    /* Process pixels */

    DCELL dout[MAXFILES];
    DCELL d[MAXFILES];

    for (row = 0; row < nrows; row++) {
	G_percent(row, nrows, 2);
	/* read input map */
	for (i = 1; i <= MAXFILES; i++)
	    Rast_get_row(infd[i], inrast[i-1], row, in_data_type[i-1]);

	/*process the data */
	for (col = 0; col < ncols; col++) {
	    for (i = 0; i < MAXFILES; i++) {
		switch (in_data_type[i]) {
		case CELL_TYPE:
		    d[i] = (double)((CELL *) inrast[i])[col];
		    break;
		case FCELL_TYPE:
		    d[i] = (double)((FCELL *) inrast[i])[col];
		    break;
		case DCELL_TYPE:
		    d[i] = (double)((DCELL *) inrast[i])[col];
		    break;
		}
		/* if radiance mode or Thermal band */
		if (radiance || i >= 10) {
		    dout[i] = gain[i] * (d[i] - 1.0);
		}
		/* if reflectance default mode and Not Thermal Band */
		else {
		    dout[i] = gain[i] * (d[i] - 1.0);
		    dout[i] =
			rad2ref_aster(dout[i], doy, sun_elevation, kexo[i]);
		}
		outrast[i][col] = dout[i];
	    }
	}
	for (i = 1; i <= MAXFILES; i++)
	    Rast_put_row(outfd[i], outrast[i-1], out_data_type);
    }
    for (i = 1; i <= MAXFILES; i++) {
	G_free(inrast[i-1]);
	Rast_close(infd[i]);
	G_free(outrast[i-1]);
	Rast_close(outfd[i]);
    }
    exit(EXIT_SUCCESS);
}
Ejemplo n.º 9
0
/* *************************************************************** */
int main(int argc, char *argv[])
{
    FCELL val_f;		/* for misc use */
    DCELL val_d;		/* for misc use */
    int map_type, zmap_type;
    univar_stat *stats;

    char *infile, *zonemap;
    void *map, *zmap = NULL;
    RASTER3D_Region region;
    unsigned int i;
    unsigned int rows, cols, depths;
    unsigned int x, y, z;
    double dmin, dmax;
    int zone, n_zones, use_zone = 0;
    char *mapset, *name;

    struct GModule *module;

    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("raster3d"));
    G_add_keyword(_("statistics"));
    module->description =
	_("Calculates univariate statistics from the non-null 3d cells of a raster3d map.");

    /* Define the different options */
    set_params();

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

    /* Set the defaults */
    Rast3d_init_defaults();

    /* get the current region */
    Rast3d_get_window(&region);

    cols = region.cols;
    rows = region.rows;
    depths = region.depths;

    name = param.output_file->answer;
    if (name != NULL && strcmp(name, "-") != 0) {
	if (NULL == freopen(name, "w", stdout)) {
	    G_fatal_error(_("Unable to open file <%s> for writing"), name);
	}
    }

    /* table field separator */
    zone_info.sep = param.separator->answer;
    if (strcmp(zone_info.sep, "\\t") == 0)
	zone_info.sep = "\t";
    if (strcmp(zone_info.sep, "tab") == 0)
	zone_info.sep = "\t";
    if (strcmp(zone_info.sep, "space") == 0)
	zone_info.sep = " ";
    if (strcmp(zone_info.sep, "comma") == 0)
	zone_info.sep = ",";

    dmin = 0.0 / 0.0;	/* set to nan as default */
    dmax = 0.0 / 0.0;	/* set to nan as default */
    zone_info.min = 0.0 / 0.0;	/* set to nan as default */
    zone_info.max = 0.0 / 0.0;	/* set to nan as default */
    zone_info.n_zones = 0;

    /* open 3D zoning raster with default region */
    if ((zonemap = param.zonefile->answer) != NULL) {
	if (NULL == (mapset = G_find_raster3d(zonemap, "")))
	    Rast3d_fatal_error(_("3D raster map <%s> not found"), zonemap);

	zmap =
	    Rast3d_open_cell_old(zonemap, G_find_raster3d(zonemap, ""), &region,
			    RASTER3D_TILE_SAME_AS_FILE, RASTER3D_USE_CACHE_DEFAULT);

	if (zmap == NULL)
	    Rast3d_fatal_error(_("Unable to open 3D raster map <%s>"), zonemap);

	zmap_type = Rast3d_tile_type_map(zmap);
	
	if (Rast3d_read_cats(zonemap, mapset, &(zone_info.cats)))
	    G_warning("No category support for zoning raster");
	    
	Rast3d_range_init(zmap);
	Rast3d_range_load(zmap);
	Rast3d_range_min_max(zmap, &dmin, &dmax);

	/* properly round dmin and dmax */
	if (dmin < 0)
	    zone_info.min = dmin - 0.5;
	else
	    zone_info.min = dmin + 0.5;
	if (dmax < 0)
	    zone_info.max = dmax - 0.5;
	else
	    zone_info.max = dmax + 0.5;

	G_debug(1, "min: %d, max: %d", zone_info.min, zone_info.max);
	zone_info.n_zones = zone_info.max - zone_info.min + 1;

	use_zone = 1;
    }

    /* Open 3D input raster with default region */
    infile = param.inputfile->answer;

    if (NULL == G_find_raster3d(infile, ""))
	Rast3d_fatal_error(_("3D raster map <%s> not found"), infile);

    map =
	Rast3d_open_cell_old(infile, G_find_raster3d(infile, ""), &region,
			RASTER3D_TILE_SAME_AS_FILE, RASTER3D_USE_CACHE_DEFAULT);

    if (map == NULL)
	Rast3d_fatal_error(_("Unable to open 3D raster map <%s>"), infile);

    map_type = Rast3d_tile_type_map(map);

    i = 0;
    while (param.percentile->answers[i])
	i++;
 
    n_zones = zone_info.n_zones;

    if (n_zones == 0)
        n_zones = 1;

    stats = create_univar_stat_struct(map_type, i);
    for (i = 0; i < n_zones; i++) {
	unsigned int j;
	for (j = 0; j < stats[i].n_perc; j++) {
	    sscanf(param.percentile->answers[j], "%lf", &(stats[i].perc[j]));
	}
    }

    for (z = 0; z < depths; z++) {	/* From the bottom to the top */
	if (!(param.shell_style->answer))
	    G_percent(z, depths - 1, 10);
	for (y = 0; y < rows; y++) {
	    for (x = 0; x < cols; x++) {
		zone = 0;
		if (zone_info.n_zones) {
		    if (zmap_type == FCELL_TYPE) {
			Rast3d_get_value(zmap, x, y, z, &val_f, FCELL_TYPE);
			if (Rast3d_is_null_value_num(&val_f, FCELL_TYPE))
			    continue;
			if (val_f < 0)
			    zone = val_f - 0.5;
			else
			    zone = val_f + 0.5;
		    }
		    else if (zmap_type == DCELL_TYPE) {
			Rast3d_get_value(zmap, x, y, z, &val_d, DCELL_TYPE);
			if (Rast3d_is_null_value_num(&val_d, DCELL_TYPE))
			    continue;
			if (val_d < 0)
			    zone = val_d - 0.5;
			else
			    zone = val_d + 0.5;
		    }
                    zone -= zone_info.min;
                }
		if (map_type == FCELL_TYPE) {
		    Rast3d_get_value(map, x, y, z, &val_f, map_type);
		    if (!Rast3d_is_null_value_num(&val_f, map_type)) {
			if (param.extended->answer) {
			    if (stats[zone].n >= stats[zone].n_alloc) {
				size_t msize;
				stats[zone].n_alloc += 1000;
				msize = stats[zone].n_alloc * sizeof(FCELL);
				stats[zone].fcell_array =
				    (FCELL *)G_realloc((void *)stats[zone].fcell_array, msize);
			    }

			    stats[zone].fcell_array[stats[zone].n] = val_f;
			}

			stats[zone].sum += val_f;
			stats[zone].sumsq += (val_f * val_f);
			stats[zone].sum_abs += fabs(val_f);

			if (stats[zone].first) {
			    stats[zone].max = val_f;
			    stats[zone].min = val_f;
			    stats[zone].first = FALSE;
			}
			else {
			    if (val_f > stats[zone].max)
				stats[zone].max = val_f;
			    if (val_f < stats[zone].min)
				stats[zone].min = val_f;
			}
			stats[zone].n++;
		    }
		    stats[zone].size++;
		}
		else if (map_type == DCELL_TYPE) {
		    Rast3d_get_value(map, x, y, z, &val_d, map_type);
		    if (!Rast3d_is_null_value_num(&val_d, map_type)) {
			if (param.extended->answer) {
			    if (stats[zone].n >= stats[zone].n_alloc) {
				size_t msize;
				stats[zone].n_alloc += 1000;
				msize = stats[zone].n_alloc * sizeof(DCELL);
				stats[zone].dcell_array =
				    (DCELL *)G_realloc((void *)stats[zone].dcell_array, msize);
				}

			    stats[zone].dcell_array[stats[zone].n] = val_d;
			}

			stats[zone].sum += val_d;
			stats[zone].sumsq += val_d * val_d;
			stats[zone].sum_abs += fabs(val_d);

			if (stats[zone].first) {
			    stats[zone].max = val_d;
			    stats[zone].min = val_d;
			    stats[zone].first = FALSE;
			}
			else {
			    if (val_d > stats[zone].max)
				stats[zone].max = val_d;
			    if (val_d < stats[zone].min)
				stats[zone].min = val_d;
			}
			stats[zone].n++;
		    }
		    stats[zone].size++;
		}
	    }
	}
    }

    /* close maps */
    Rast3d_close(map);
    if (zone_info.n_zones)
	Rast3d_close(zmap);

    /* create the output */
    if (param.table->answer)
	print_stats_table(stats);
    else
	print_stats(stats);

    /* release memory */
    free_univar_stat_struct(stats);

    exit(EXIT_SUCCESS);
}
Ejemplo n.º 10
0
int null_distance(const char *name1, const char *name2, int *zerro_row, int *zerro_col)
{
    RASTER_MAP_TYPE maptype1, maptype2;
    const char *mapset;
    int mapd1, mapd2;
    void *inrast1, *inrast2;
    int nrows, ncols, row, col;
    void *cell1, *cell2;

    /* NOTE: no need to controll, if the map exists. it should be checked in edge.c */
    mapset = G_find_raster2(name1, "");
    maptype1 = Rast_map_type(name1, mapset);
    mapd1 = Rast_open_old(name1, mapset);
    inrast1 = Rast_allocate_buf(maptype1);

    mapset = G_find_raster2(name2, "");
    maptype2 = Rast_map_type(name2, mapset);
    mapd2 = Rast_open_old(name2, mapset);
    inrast2 = Rast_allocate_buf(maptype2);

    G_message(_("Reading maps  <%s,%s> while finding 0 distance ..."), name1,
              name2);

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

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

        G_percent(row, nrows, 2);

        Rast_get_row(mapd1, inrast1, row, maptype1);
        Rast_get_row(mapd2, inrast2, row, maptype2);

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

            /* first raster */
            switch (maptype1) {
            case CELL_TYPE:
                cell1 = ((CELL **) inrast1)[col];
                break;
            case FCELL_TYPE:
                cell1 = ((FCELL **) inrast1)[col];
                break;
            case DCELL_TYPE:
                cell1 = ((DCELL **) inrast1)[col];
                break;
            }
            /* second raster */
            switch (maptype2) {
            case CELL_TYPE:
                cell2 = ((CELL **) inrast2)[col];
                break;
            case FCELL_TYPE:
                cell2 = ((FCELL **) inrast2)[col];
                break;
            case DCELL_TYPE:
                cell2 = ((DCELL **) inrast2)[col];
                break;
            }

            if (!Rast_is_null_value(&cell1, maptype1) &&
                    !Rast_is_null_value(&cell2, maptype2)) {

                *zerro_row = row;
                *zerro_col = col;

                /* memory cleanup */
                G_free(inrast1);
                G_free(inrast2);

                /* closing raster maps */
                Rast_close(mapd1);
                Rast_close(mapd2);
                return 1;
            }
        }
    }
    /* memory cleanup */
    G_free(inrast1);
    G_free(inrast2);

    /* closing raster maps */
    Rast_close(mapd1);
    Rast_close(mapd2);

    return 0;
}
Ejemplo n.º 11
0
Archivo: main.c Proyecto: caomw/grass
int main(int argc, char *argv[])
{
    struct Cell_head cellhd;
    /* buffer for in, tmp and out raster */
    void *inrast_Rn, *inrast_g0;
    void *inrast_z0m, *inrast_t0dem;
    DCELL *outrast;
    int nrows, ncols;
    int row, col;
    int row_wet, col_wet;
    int row_dry, col_dry;
    double m_row_wet, m_col_wet;
    double m_row_dry, m_col_dry;
    int infd_Rn, infd_g0;
    int infd_z0m, infd_t0dem;
    int outfd;
    char *Rn, *g0;
    char *z0m, *t0dem;
    char *h0;

    double ustar, ea;
    struct History history;
    struct GModule *module;
    struct Option *input_Rn, *input_g0;
    struct Option *input_z0m, *input_t0dem, *input_ustar;
    struct Option *input_ea, *output;
    struct Option *input_row_wet, *input_col_wet;
    struct Option *input_row_dry, *input_col_dry;
    struct Flag *flag2, *flag3;
    /********************************/
    double xp, yp;
    double xmin, ymin;
    double xmax, ymax;
    double stepx, stepy;
    double latitude, longitude;
    int rowDry, colDry, rowWet, colWet;
    /********************************/
    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("imagery"));
    G_add_keyword(_("energy balance"));
    G_add_keyword(_("soil moisture"));
    G_add_keyword(_("evaporative fraction"));
    G_add_keyword(_("SEBAL"));
    module->description = _("Computes sensible heat flux iteration SEBAL 01.");

    /* Define different options */
    input_Rn = G_define_standard_option(G_OPT_R_INPUT);
    input_Rn->key = "netradiation";
    input_Rn->description =
	_("Name of instantaneous net radiation raster map [W/m2]");

    input_g0 = G_define_standard_option(G_OPT_R_INPUT);
    input_g0->key = "soilheatflux";
    input_g0->description =
	_("Name of instantaneous soil heat flux raster map [W/m2]");

    input_z0m = G_define_standard_option(G_OPT_R_INPUT);
    input_z0m->key = "aerodynresistance";
    input_z0m->description =
	_("Name of aerodynamic resistance to heat momentum raster map [s/m]");

    input_t0dem = G_define_standard_option(G_OPT_R_INPUT);
    input_t0dem->key = "temperaturemeansealevel";
    input_t0dem->description =
	_("Name of altitude corrected surface temperature raster map [K]");

    input_ustar = G_define_option();
    input_ustar->key = "frictionvelocitystar";
    input_ustar->type = TYPE_DOUBLE;
    input_ustar->required = YES;
    input_ustar->gisprompt = "old,value";
    input_ustar->answer = "0.32407";
    input_ustar->description = _("Value of the height independent friction velocity (u*) [m/s]");
    input_ustar->guisection = _("Parameters");

    input_ea = G_define_option();
    input_ea->key = "vapourpressureactual";
    input_ea->type = TYPE_DOUBLE;
    input_ea->required = YES;
    input_ea->answer = "1.511";
    input_ea->description = _("Value of the actual vapour pressure (e_act) [KPa]");
    input_ea->guisection = _("Parameters");

    input_row_wet = G_define_option();
    input_row_wet->key = "row_wet_pixel";
    input_row_wet->type = TYPE_DOUBLE;
    input_row_wet->required = NO;
    input_row_wet->description = _("Row value of the wet pixel");
    input_row_wet->guisection = _("Parameters");

    input_col_wet = G_define_option();
    input_col_wet->key = "column_wet_pixel";
    input_col_wet->type = TYPE_DOUBLE;
    input_col_wet->required = NO;
    input_col_wet->description = _("Column value of the wet pixel");
    input_col_wet->guisection = _("Parameters");

    input_row_dry = G_define_option();
    input_row_dry->key = "row_dry_pixel";
    input_row_dry->type = TYPE_DOUBLE;
    input_row_dry->required = NO;
    input_row_dry->description = _("Row value of the dry pixel");
    input_row_dry->guisection = _("Parameters");

    input_col_dry = G_define_option();
    input_col_dry->key = "column_dry_pixel";
    input_col_dry->type = TYPE_DOUBLE;
    input_col_dry->required = NO;
    input_col_dry->description = _("Column value of the dry pixel");
    input_col_dry->guisection = _("Parameters");

    output = G_define_standard_option(G_OPT_R_OUTPUT);
    output->description = _("Name for output sensible heat flux raster map [W/m2]");
    
    /* Define the different flags */
    flag2 = G_define_flag();
    flag2->key = 'a';
    flag2->description = _("Automatic wet/dry pixel (careful!)");

    flag3 = G_define_flag();
    flag3->key = 'c';
    flag3->description =
	_("Dry/Wet pixels coordinates are in image projection, not row/col");

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

    /* get entered parameters */
    Rn = input_Rn->answer;
    g0 = input_g0->answer;
    z0m = input_z0m->answer;
    t0dem = input_t0dem->answer;

    h0 = output->answer;

    ustar = atof(input_ustar->answer);
    ea = atof(input_ea->answer);

    if(input_row_wet->answer&&
    input_col_wet->answer&&
    input_row_dry->answer&&
    input_col_dry->answer){
        m_row_wet = atof(input_row_wet->answer);
        m_col_wet = atof(input_col_wet->answer);
        m_row_dry = atof(input_row_dry->answer);
        m_col_dry = atof(input_col_dry->answer);
    }
    if ((!input_row_wet->answer || !input_col_wet->answer ||
	 !input_row_dry->answer || !input_col_dry->answer) &&
	!flag2->answer) {
	G_fatal_error(_("Either auto-mode either wet/dry pixels coordinates should be provided!"));
    }
    if (flag3->answer) {
	G_message(_("Manual wet/dry pixels in image coordinates"));
	G_message(_("Wet Pixel=> x:%f y:%f"), m_col_wet, m_row_wet);
	G_message(_("Dry Pixel=> x:%f y:%f"), m_col_dry, m_row_dry);
    }
    else {
        if(flag2->answer)
	    G_message(_("Automatic mode selected"));
	else {
	    G_message(_("Wet Pixel=> row:%.0f col:%.0f"), m_row_wet, m_col_wet);
	    G_message(_("Dry Pixel=> row:%.0f col:%.0f"), m_row_dry, m_col_dry);
	}
    }
    /* check legal output name */
    if (G_legal_filename(h0) < 0)
	G_fatal_error(_("<%s> is an illegal name"), h0);

    infd_Rn = Rast_open_old(Rn, "");
    infd_g0 = Rast_open_old(g0, "");
    infd_z0m = Rast_open_old(z0m, "");
    infd_t0dem = Rast_open_old(t0dem, "");

    Rast_get_cellhd(Rn, "", &cellhd);
    Rast_get_cellhd(g0, "", &cellhd);
    Rast_get_cellhd(z0m, "", &cellhd);
    Rast_get_cellhd(t0dem, "", &cellhd);

    /* Allocate input buffer */
    inrast_Rn = Rast_allocate_d_buf();
    inrast_g0 = Rast_allocate_d_buf();
    inrast_z0m = Rast_allocate_d_buf();
    inrast_t0dem = Rast_allocate_d_buf();

    /***************************************************/
    /* Setup pixel location variables */
    /***************************************************/
    stepx = cellhd.ew_res;
    stepy = cellhd.ns_res;

    xmin = cellhd.west;
    xmax = cellhd.east;
    ymin = cellhd.south;
    ymax = cellhd.north;

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

    /***************************************************/
    /* Allocate output buffer */
    /***************************************************/
    outrast = Rast_allocate_d_buf();
    outfd = Rast_open_new(h0, DCELL_TYPE);
    /***************************************************/
    /* Allocate memory for temporary images            */
    double **d_Roh, **d_Rah;

    if ((d_Roh = G_alloc_matrix(nrows, ncols)) == NULL)
	G_message("Unable to allocate memory for temporary d_Roh image");
    if ((d_Rah = G_alloc_matrix(nrows, ncols)) == NULL)
	G_message("Unable to allocate memory for temporary d_Rah image");
    /***************************************************/

    /* MANUAL T0DEM WET/DRY PIXELS */
    DCELL d_Rn_dry,d_g0_dry;
    DCELL d_t0dem_dry,d_t0dem_wet;

    if (flag2->answer) {
	/* Process tempk min / max pixels */
	/* Internal use only */
	DCELL d_Rn_wet,d_g0_wet;
	DCELL d_Rn,d_g0,d_h0;
	DCELL t0dem_min,t0dem_max;
        /*********************/
	for (row = 0; row < nrows; row++) {
	    DCELL d_t0dem;
	    G_percent(row, nrows, 2);
	    Rast_get_d_row(infd_t0dem,inrast_t0dem,row);
	    Rast_get_d_row(infd_Rn,inrast_Rn,row);
	    Rast_get_d_row(infd_g0,inrast_g0,row);
	    /*process the data */
	    for (col = 0; col < ncols; col++) {
		d_t0dem = ((DCELL *) inrast_t0dem)[col];
		d_Rn = ((DCELL *) inrast_Rn)[col];
		d_g0 = ((DCELL *) inrast_g0)[col];
		if (Rast_is_d_null_value(&d_t0dem) ||
		    Rast_is_d_null_value(&d_Rn) || 
                    Rast_is_d_null_value(&d_g0)) {
		    /* do nothing */
		}
		else {
		    if (d_t0dem <= 250.0) {
			/* do nothing */
		    }
		    else {
			d_h0 = d_Rn - d_g0;
			if (d_t0dem < t0dem_min &&
			    d_Rn > 0.0 && d_g0 > 0.0 && d_h0 > 0.0 &&
			    d_h0 < 100.0) {
			    t0dem_min = d_t0dem;
			    d_t0dem_wet = d_t0dem;
			    d_Rn_wet = d_Rn;
			    d_g0_wet = d_g0;
			    m_col_wet = col;
			    m_row_wet = row;
			}
			if (d_t0dem > t0dem_max &&
			    d_Rn > 0.0 && d_g0 > 0.0 && d_h0 > 100.0 &&
			    d_h0 < 500.0) {
			    t0dem_max = d_t0dem;
			    d_t0dem_dry = d_t0dem;
			    d_Rn_dry = d_Rn;
			    d_g0_dry = d_g0;
			    m_col_dry = col;
			    m_row_dry = row;
			}
		    }
		}
	    }
	}
	G_message("row_wet=%d\tcol_wet=%d", row_wet, col_wet);
	G_message("row_dry=%d\tcol_dry=%d", row_dry, col_dry);
	G_message("g0_wet=%f", d_g0_wet);
	G_message("Rn_wet=%f", d_Rn_wet);
	G_message("LE_wet=%f", d_Rn_wet - d_g0_wet);
	G_message("t0dem_dry=%f", d_t0dem_dry);
	G_message("rnet_dry=%f", d_Rn_dry);
	G_message("g0_dry=%f", d_g0_dry);
	G_message("h0_dry=%f", d_Rn_dry - d_g0_dry);
    }/* END OF FLAG2 */

    G_message("Passed here");

    /* MANUAL T0DEM WET/DRY PIXELS */
    /*DRY PIXEL */
    if (flag3->answer) {
	/*Calculate coordinates of row/col from projected ones */
	row = (int)((ymax - m_row_dry) / (double)stepy);
	col = (int)((m_col_dry - xmin) / (double)stepx);
	G_message("Dry Pixel | row:%i col:%i", row, col);
    }
    else {
	row = (int)m_row_dry;
	col = (int)m_col_dry;
	G_message("Dry Pixel | row:%i col:%i", row, col);
    }
    rowDry = row;
    colDry = col;
    Rast_get_d_row(infd_Rn, inrast_Rn, row);
    Rast_get_d_row(infd_g0, inrast_g0, row);
    Rast_get_d_row(infd_t0dem, inrast_t0dem, row);
    d_Rn_dry = ((DCELL *) inrast_Rn)[col];
    d_g0_dry = ((DCELL *) inrast_g0)[col];
    d_t0dem_dry = ((DCELL *) inrast_t0dem)[col];
    /*WET PIXEL */
    if (flag3->answer) {
	/*Calculate coordinates of row/col from projected ones */
	row = (int)((ymax - m_row_wet) / (double)stepy);
	col = (int)((m_col_wet - xmin) / (double)stepx);
	G_message("Wet Pixel | row:%i col:%i", row, col);
    }
    else {
	row = m_row_wet;
	col = m_col_wet;
	G_message("Wet Pixel | row:%i col:%i", row, col);
    }
    rowWet = row;
    colWet = col;
    Rast_get_d_row(infd_t0dem, inrast_t0dem, row);
    d_t0dem_wet = ((DCELL *) inrast_t0dem)[col];
    /* END OF MANUAL WET/DRY PIXELS */
    double h_dry;

    h_dry = d_Rn_dry - d_g0_dry;
    G_message("h_dry = %f", h_dry);
    G_message("t0dem_dry = %f", d_t0dem_dry);
    G_message("t0dem_wet = %f", d_t0dem_wet);
    DCELL d_rah_dry;
    DCELL d_roh_dry;

    /* INITIALIZATION */
    for (row = 0; row < nrows; row++) {
	DCELL d_t0dem,d_z0m;
	DCELL d_rah1,d_roh1;
	DCELL d_u5;
	G_percent(row, nrows, 2);
	/* read a line input maps into buffers */
	Rast_get_d_row(infd_z0m, inrast_z0m, row);
	Rast_get_d_row(infd_t0dem, inrast_t0dem,row);
	/* read every cell in the line buffers */
	for (col = 0; col < ncols; col++) {
            d_z0m = ((DCELL *) inrast_z0m)[col];
            d_t0dem = ((DCELL *) inrast_t0dem)[col];
	    if (Rast_is_d_null_value(&d_t0dem) || Rast_is_d_null_value(&d_z0m)) {
		/* do nothing */
		d_Roh[row][col] = -999.9;
		d_Rah[row][col] = -999.9;
	    }
	    else {
		d_u5 = (ustar / 0.41) * log(5 / d_z0m);
		d_rah1=(1/(d_u5*pow(0.41,2)))*log(5/d_z0m)*log(5/(d_z0m*0.1));
		d_roh1=((998-ea)/(d_t0dem*2.87))+(ea/(d_t0dem*4.61));
		if (d_roh1 > 5)  d_roh1 = 1.0;
		else d_roh1=((1000-4.65)/(d_t0dem*2.87))+(4.65/(d_t0dem*4.61));
		if (row == rowDry && col == colDry) {	/*collect dry pix info */
		    d_rah_dry = d_rah1;
		    d_roh_dry = d_roh1;
		    G_message("d_rah_dry=%f d_roh_dry=%f",d_rah_dry,d_roh_dry);
		}
		d_Roh[row][col] = d_roh1;
		d_Rah[row][col] = d_rah1;
	    }
	}
    }
    DCELL d_dT_dry;

    /*Calculate dT_dry */
    d_dT_dry = (h_dry * d_rah_dry) / (1004 * d_roh_dry);
    double a, b;

    /*Calculate coefficients for next dT equation */
    /*a = 1.0/ ((d_dT_dry-0.0) / (d_t0dem_dry-d_t0dem_wet)); */
    /*b = ( a * d_t0dem_wet ) * (-1.0); */
    double sumx = d_t0dem_wet + d_t0dem_dry;
    double sumy = d_dT_dry + 0.0;
    double sumx2 = pow(d_t0dem_wet, 2) + pow(d_t0dem_dry, 2);
    double sumxy = (d_t0dem_wet * 0.0) + (d_t0dem_dry * d_dT_dry);
    a = (sumxy - ((sumx * sumy) / 2.0)) / (sumx2 - (pow(sumx, 2) / 2.0));
    b = (sumy - (a * sumx)) / 2.0;
    G_message("d_dT_dry=%f", d_dT_dry);
    G_message("dT1=%f * t0dem + (%f)", a, b);
    DCELL d_h_dry;

    /* ITERATION 1 */
    for (row = 0; row < nrows; row++) {
	DCELL d_t0dem,d_z0m;
	DCELL d_h1,d_rah1,d_rah2,d_roh1;
	DCELL d_L,d_x,d_psih,d_psim;
	DCELL d_u5;
	G_percent(row, nrows, 2);
	/* read a line input maps into buffers */
	Rast_get_d_row(infd_z0m, inrast_z0m, row);
	Rast_get_d_row(infd_t0dem, inrast_t0dem,row);
	/* read every cell in the line buffers */
	for (col = 0; col < ncols; col++) {
            d_z0m = ((DCELL *) inrast_z0m)[col];
            d_t0dem = ((DCELL *) inrast_t0dem)[col];
	    d_rah1 = d_Rah[row][col];
	    d_roh1 = d_Roh[row][col];
	    if (Rast_is_d_null_value(&d_t0dem) || Rast_is_d_null_value(&d_z0m)) {
		/* do nothing */
	    }
	    else {
		if (d_rah1 < 1.0) 
		    d_h1 = 0.0;
		else 
		    d_h1 = (1004 * d_roh1) * (a * d_t0dem + b) / d_rah1;
		d_L =-1004*d_roh1*pow(ustar,3)*d_t0dem/(d_h1*9.81*0.41);
		d_x = pow((1-16*(5/d_L)),0.25);
		d_psim =2*log((1+d_x)/2)+log((1+pow(d_x,2))/2)-2*atan(d_x)+0.5*M_PI;
		d_psih =2*log((1+pow(d_x,2))/2);
		d_u5 =(ustar/0.41)*log(5/d_z0m);
		d_rah2 = (1/(d_u5*pow(0.41,2)))*log((5/d_z0m)-d_psim)
                        *log((5/(d_z0m*0.1))-d_psih);
		if (row == rowDry && col == colDry) {/*collect dry pix info */
		    d_rah_dry = d_rah2;
		    d_h_dry = d_h1;
		}
		d_Rah[row][col] = d_rah1;
	    }
	}
    }

    /*Calculate dT_dry */
    d_dT_dry = (d_h_dry * d_rah_dry) / (1004 * d_roh_dry);
    /*Calculate coefficients for next dT equation */
    /*      a = (d_dT_dry-0)/(d_t0dem_dry-d_t0dem_wet); */
    /*      b = (-1.0) * ( a * d_t0dem_wet ); */
    /*      G_message("d_dT_dry=%f",d_dT_dry); */
    /*      G_message("dT2=%f * t0dem + (%f)", a, b); */
    sumx = d_t0dem_wet + d_t0dem_dry;
    sumy = d_dT_dry + 0.0;
    sumx2 = pow(d_t0dem_wet, 2) + pow(d_t0dem_dry, 2);
    sumxy = (d_t0dem_wet * 0.0) + (d_t0dem_dry * d_dT_dry);
    a = (sumxy - ((sumx * sumy) / 2.0)) / (sumx2 - (pow(sumx, 2) / 2.0));
    b = (sumy - (a * sumx)) / 2.0;
    G_message("d_dT_dry=%f", d_dT_dry);
    G_message("dT1=%f * t0dem + (%f)", a, b);

    /* ITERATION 2 */
    /***************************************************/
    /***************************************************/
    for (row = 0; row < nrows; row++) {
	DCELL d_t0dem;
	DCELL d_z0m;
	DCELL d_rah2;
	DCELL d_rah3;
	DCELL d_roh1;
	DCELL d_h2;
	DCELL d_L;
	DCELL d_x;
	DCELL d_psih;
	DCELL d_psim;
	DCELL d_u5;
	G_percent(row, nrows, 2);
	/* read a line input maps into buffers */
	Rast_get_d_row(infd_z0m,inrast_z0m,row);
	Rast_get_d_row(infd_t0dem,inrast_t0dem,row);
	/* read every cell in the line buffers */
	for (col = 0; col < ncols; col++) {
            d_z0m = ((DCELL *) inrast_z0m)[col];
            d_t0dem = ((DCELL *) inrast_t0dem)[col];
	    d_rah2 = d_Rah[row][col];
	    d_roh1 = d_Roh[row][col];
	    if (Rast_is_d_null_value(&d_t0dem) || Rast_is_d_null_value(&d_z0m)) {
		/* do nothing */
	    }
	    else {
		if (d_rah2 < 1.0) {
		    d_h2 = 0.0;
		}
		else {
		    d_h2 =(1004*d_roh1)*(a*d_t0dem+b)/d_rah2;
		}
		d_L =-1004*d_roh1*pow(ustar,3)*d_t0dem/(d_h2*9.81*0.41);
		d_x = pow((1 - 16 * (5 / d_L)), 0.25);
		d_psim =2*log((1+d_x)/2)+log((1+pow(d_x,2))/2)-
		    2*atan(d_x)+0.5*M_PI;
		d_psih =2*log((1+pow(d_x,2))/2);
		d_u5 =(ustar/0.41)*log(5/d_z0m);
		d_rah3=(1/(d_u5*pow(0.41,2)))*log((5/d_z0m)-d_psim)*
                       log((5/(d_z0m*0.1))-d_psih);
		if (row == rowDry && col == colDry) {/*collect dry pix info */
		    d_rah_dry = d_rah2;
		    d_h_dry = d_h2;
		}
		d_Rah[row][col] = d_rah2;
	    }
	}
    }

    /*Calculate dT_dry */
    d_dT_dry = (d_h_dry * d_rah_dry) / (1004 * d_roh_dry);
    /*Calculate coefficients for next dT equation */
    /*      a = (d_dT_dry-0)/(d_t0dem_dry-d_t0dem_wet); */
    /*      b = (-1.0) * ( a * d_t0dem_wet ); */
    /*      G_message("d_dT_dry=%f",d_dT_dry); */
    /*      G_message("dT3=%f * t0dem + (%f)", a, b); */
    sumx = d_t0dem_wet + d_t0dem_dry;
    sumy = d_dT_dry + 0.0;
    sumx2 = pow(d_t0dem_wet, 2) + pow(d_t0dem_dry, 2);
    sumxy = (d_t0dem_wet * 0.0) + (d_t0dem_dry * d_dT_dry);
    a = (sumxy - ((sumx * sumy) / 2.0)) / (sumx2 - (pow(sumx, 2) / 2.0));
    b = (sumy - (a * sumx)) / 2.0;
    G_message("d_dT_dry=%f", d_dT_dry);
    G_message("dT1=%f * t0dem + (%f)", a, b);

    /* ITERATION 3 */
    /***************************************************/
    /***************************************************/

    for (row = 0; row < nrows; row++) {
	DCELL d_t0dem;
	DCELL d_z0m;
	DCELL d_rah3;
	DCELL d_roh1;
	DCELL d_h3;
	DCELL d_L;
	DCELL d_x;
	DCELL d_psih;
	DCELL d_psim;
	DCELL d;		/* Output pixel */
	G_percent(row, nrows, 2);
	/* read a line input maps into buffers */
	Rast_get_d_row(infd_z0m, inrast_z0m, row);
	Rast_get_d_row(infd_t0dem,inrast_t0dem,row);
	/* read every cell in the line buffers */
	for (col = 0; col < ncols; col++) {
            d_z0m = ((DCELL *) inrast_z0m)[col];
            d_t0dem = ((DCELL *) inrast_t0dem)[col];
	    d_rah3 = d_Rah[row][col];
	    d_roh1 = d_Roh[row][col];
	    if (Rast_is_d_null_value(&d_t0dem) || Rast_is_d_null_value(&d_z0m)) {
		Rast_set_d_null_value(&outrast[col], 1);
	    }
	    else {
		if (d_rah3 < 1.0) {
		    d_h3 = 0.0;
		}
		else {
		    d_h3 = (1004 * d_roh1) * (a * d_t0dem + b) / d_rah3;
		}
		if (d_h3 < 0 && d_h3 > -50) {
		    d_h3 = 0.0;
		}
		if (d_h3 < -50 || d_h3 > 1000) {
		    Rast_set_d_null_value(&outrast[col], 1);
		}
		outrast[col] = d_h3;
	    }
	}
	Rast_put_d_row(outfd, outrast);
    }


    G_free(inrast_z0m);
    Rast_close(infd_z0m);
    G_free(inrast_t0dem);
    Rast_close(infd_t0dem);

    G_free(outrast);
    Rast_close(outfd);

    /* add command line incantation to history file */
    Rast_short_history(h0, "raster", &history);
    Rast_command_history(&history);
    Rast_write_history(h0, &history);

    exit(EXIT_SUCCESS);
}
Ejemplo n.º 12
0
int main(int argc, char **argv)
{
    int i, j, k, ret;
    int nlines, type, ltype, afield, tfield, geo, cat;
    int sp, nsp, nspused, node, line;
    struct Option *map, *output, *afield_opt, *tfield_opt, *afcol, *type_opt,
	*term_opt, *nsp_opt;
    struct Flag *geo_f;
    struct GModule *module;
    struct Map_info Map, Out;
    int *testnode;		/* array all nodes: 1 - should be tested as Steiner, 
				 * 0 - no need to test (unreachable or terminal) */
    struct ilist *TList;	/* list of terminal nodes */
    struct ilist *StArcs;	/* list of arcs on Steiner tree */
    struct ilist *StNodes;	/* list of nodes on Steiner tree */
    struct boxlist *pointlist;
    double cost, tmpcost;
    struct cat_list *Clist;
    struct line_cats *Cats;
    struct line_pnts *Points;
    
    /* Initialize the GIS calls */
    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("vector"));
    G_add_keyword(_("network"));
    G_add_keyword(_("steiner tree"));
    module->label =
	_("Creates Steiner tree for the network and given terminals.");
    module->description =
	_("Note that 'Minimum Steiner Tree' problem is NP-hard "
	  "and heuristic algorithm is used in this module so "
	  "the result may be sub optimal.");

    map = G_define_standard_option(G_OPT_V_INPUT);
    output = G_define_standard_option(G_OPT_V_OUTPUT);

    type_opt = G_define_standard_option(G_OPT_V_TYPE);
    type_opt->key = "arc_type";
    type_opt->options = "line,boundary";
    type_opt->answer = "line,boundary";
    type_opt->label = _("Arc type");

    afield_opt = G_define_standard_option(G_OPT_V_FIELD);
    afield_opt->key = "arc_layer";
    afield_opt->answer = "1";
    afield_opt->label = _("Arc layer");

    tfield_opt = G_define_standard_option(G_OPT_V_FIELD);
    tfield_opt->key = "node_layer";
    tfield_opt->answer = "2";
    tfield_opt->label = _("Node layer (used for terminals)");

    afcol = G_define_option();
    afcol->key = "acolumn";
    afcol->type = TYPE_STRING;
    afcol->required = NO;
    afcol->description = _("Arcs' cost column (for both directions)");

    term_opt = G_define_standard_option(G_OPT_V_CATS);
    term_opt->key = "terminal_cats";
    term_opt->required = YES;
    term_opt->description =
	_("Categories of points on terminals (layer is specified by nlayer)");

    nsp_opt = G_define_option();
    nsp_opt->key = "npoints";
    nsp_opt->type = TYPE_INTEGER;
    nsp_opt->required = NO;
    nsp_opt->multiple = NO;
    nsp_opt->answer = "-1";
    nsp_opt->description = _("Number of Steiner points (-1 for all possible)");

    geo_f = G_define_flag();
    geo_f->key = 'g';
    geo_f->description =
	_("Use geodesic calculation for longitude-latitude locations");

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

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

    type = Vect_option_to_types(type_opt);
    afield = atoi(afield_opt->answer);

    TList = Vect_new_list();
    StArcs = Vect_new_list();
    StNodes = Vect_new_list();

    Clist = Vect_new_cat_list();
    tfield = atoi(tfield_opt->answer);
    Vect_str_to_cat_list(term_opt->answer, Clist);

    G_debug(1, "Imput categories:\n");
    for (i = 0; i < Clist->n_ranges; i++) {
	G_debug(1, "%d - %d\n", Clist->min[i], Clist->max[i]);
    }

    if (geo_f->answer)
	geo = 1;
    else
	geo = 0;

    Vect_check_input_output_name(map->answer, output->answer, G_FATAL_EXIT);

    Vect_set_open_level(2);

    if (Vect_open_old(&Map, map->answer, "") < 0)
	G_fatal_error(_("Unable to open vector map <%s>"), map->answer);

    nnodes = Vect_get_num_nodes(&Map);
    nlines = Vect_get_num_lines(&Map);

    /* Create list of terminals based on list of categories */
    for (i = 1; i <= nlines; i++) {
	ltype = Vect_get_line_type(&Map, i);
	if (!(ltype & GV_POINT))
	    continue;

	Vect_read_line(&Map, Points, Cats, i);
	if (!(Vect_cat_get(Cats, tfield, &cat)))
	    continue;
	node = Vect_find_node(&Map, Points->x[0], Points->y[0], Points->z[0], 0, 0);
	if (!node) {
	    G_warning(_("Point is not connected to the network (cat=%d)"), cat);
	    continue;
	}
	if (Vect_cat_in_cat_list(cat, Clist)) {
	    Vect_list_append(TList, node);
	}
    }

    nterms = TList->n_values;
    /* GTC Terminal refers to an Steiner tree endpoint */
    G_message(_("Number of terminals: %d\n"), nterms);

    if (nterms < 2) {
        /* GTC Terminal refers to an Steiner tree endpoint */
        G_fatal_error(_("Not enough terminals (< 2)"));
    }

    /* Number of steiner points */
    nsp = atoi(nsp_opt->answer);
    if (nsp > nterms - 2) {
	nsp = nterms - 2;
	G_warning(_("Requested number of Steiner points > than possible"));
    }
    else if (nsp == -1) {
	nsp = nterms - 2;
    }

    G_message(_("Number of Steiner points set to %d\n"), nsp);

    testnode = (int *)G_malloc((nnodes + 1) * sizeof(int));
    for (i = 1; i <= nnodes; i++)
	testnode[i] = 1;

    /* Alloc arrays of costs for nodes, first node at 1 (0 not used) */
    nodes_costs = (double **)G_malloc((nnodes) * sizeof(double *));
    for (i = 0; i < nnodes; i++) {
	nodes_costs[i] =
	    (double *)G_malloc((nnodes - i) * sizeof(double));
	for (j = 0; j < nnodes - i; j++)
	    nodes_costs[i][j] = -1;	/* init, i.e. cost was not calculated yet */
    }

    /* alloc memory from each to each other (not directed) terminal */
    i = nterms + nterms - 2;	/*  max number of terms + Steiner points */
    comps = (int *)G_malloc(i * sizeof(int));
    i = i * (i - 1) / 2;	/* number of combinations */
    term_costs = (COST *) G_malloc(i * sizeof(COST));

    /* alloc memory for costs from Stp to each other terminal */
    i = nterms + nterms - 2 - 1;	/*  max number of terms + Steiner points - 1 */
    sp_costs = (COST *) G_malloc(i * sizeof(COST));

    terms = (int *)G_malloc((nterms + nterms - 2) * sizeof(int));	/* i.e. +(nterms - 2)  St Points */
    /* Create initial parts from list of terminals */
    G_debug(1, "List of terminal nodes (%d):\n", nterms);
    for (i = 0; i < nterms; i++) {
	G_debug(1, "%d\n", TList->value[i]);
	terms[i] = TList->value[i];
	testnode[terms[i]] = 0;	/* do not test as Steiner */
    }

    /* Build graph */
    Vect_net_build_graph(&Map, type, afield, 0, afcol->answer, NULL, NULL,
			 geo, 0);

    /* Init costs for all terminals */
    for (i = 0; i < nterms; i++)
	init_node_costs(&Map, terms[i]);

    /* Test if all terminal may be connected */
    for (i = 1; i < nterms; i++) {
	ret = get_node_costs(terms[0], terms[i], &cost);
	if (ret == 0) {
            /* GTC Terminal refers to an Steiner tree endpoint */
	    G_fatal_error(_("Terminal at node [%d] cannot be connected "
			    "to terminal at node [%d]"), terms[0], terms[i]);
	}
    }

    /* Remove not reachable from list of SP candidates */
    j = 0;
    for (i = 1; i <= nnodes; i++) {
	ret = get_node_costs(terms[0], i, &cost);
	if (ret == 0) {
	    testnode[i] = 0;
	    G_debug(2, "node %d removed from list of Steiner point candidates\n", i );
	    j++;
	}
    }

    G_message(_("[%d] (not reachable) nodes removed from list "
		"of Steiner point candidates"), j);

    /* calc costs for terminals MST */
    ret = mst(&Map, terms, nterms, &cost, PORT_DOUBLE_MAX, NULL, NULL, 0, 1);	/* no StP, rebuild */
    G_message(_("MST costs = %f"), cost);

    /* Go through all nodes and try to use as steiner points -> find that which saves most costs */
    nspused = 0;
    for (j = 0; j < nsp; j++) {
	sp = 0;
	G_verbose_message(_("Search for [%d]. Steiner point"), j + 1);

	for (i = 1; i <= nnodes; i++) {
	    G_percent(i, nnodes, 1);
	    if (testnode[i] == 0) {
		G_debug(3, "skip test for %d\n", i);
		continue;
	    }
	    ret =
		mst(&Map, terms, nterms + j, &tmpcost, cost, NULL, NULL, i,
		    0);
	    G_debug(2, "cost = %f x %f\n", tmpcost, cost);
	    if (tmpcost < cost) {	/* sp candidate */
		G_debug(3,
			"  steiner candidate node = %d mst = %f (x last = %f)\n",
			i, tmpcost, cost);
		sp = i;
		cost = tmpcost;
	    }
	}
	if (sp > 0) {
	    G_message(_("Steiner point at node [%d] was added "
			"to terminals (MST costs = %f)"), sp, cost);
	    terms[nterms + j] = sp;
	    init_node_costs(&Map, sp);
	    testnode[sp] = 0;
	    nspused++;
	    /* rebuild for nex cycle */
	    ret =
		mst(&Map, terms, nterms + nspused, &tmpcost, PORT_DOUBLE_MAX,
		    NULL, NULL, 0, 1);
	}
	else {			/* no steiner found */
	    G_message(_("No Steiner point found -> leaving cycle"));
	    break;
	}
    }

    G_message(_("Number of added Steiner points: %d "
	    "(theoretic max is %d).\n"), nspused, nterms - 2);

    /* Build lists of arcs and nodes for final version */
    ret =
	mst(&Map, terms, nterms + nspused, &cost, PORT_DOUBLE_MAX, StArcs,
	    StNodes, 0, 0);

    /* Calculate true costs, which may be lower than MST if steiner points were not used */

    if (nsp < nterms - 2) {
        G_message(_("Spanning tree costs on complet graph = %f\n"
            "(may be higher than resulting Steiner tree costs!!!)"),
		cost);
    }
    else
        G_message(_("Steiner tree costs = %f"), cost);

    /* Write arcs to new map */
    if (Vect_open_new(&Out, output->answer, Vect_is_3d(&Map)) < 0)
	G_fatal_error(_("Unable to create vector map <%s>"), output->answer);

    Vect_hist_command(&Out);

    G_debug(1, "Steiner tree:");
    G_debug(1, "Arcs' categories (layer %d, %d arcs):", afield,
	    StArcs->n_values);
    
    for (i = 0; i < StArcs->n_values; i++) {
	line = StArcs->value[i];
	ltype = Vect_read_line(&Map, Points, Cats, line);
	Vect_write_line(&Out, ltype, Points, Cats);
	Vect_cat_get(Cats, afield, &cat);
        G_debug(1, "arc cat = %d", cat);
    }
    
    G_debug(1, "Nodes' categories (layer %d, %d nodes):", tfield,
	    StNodes->n_values);

    k = 0;
    pointlist = Vect_new_boxlist(0);
    for (i = 0; i < StNodes->n_values; i++) {
	double x, y, z;
	struct bound_box box;
	
	node = StNodes->value[i];
	
	Vect_get_node_coor(&Map, node, &x, &y, &z);
	box.E = box.W = x;
	box.N = box.S = y;
	box.T = box.B = z;
	Vect_select_lines_by_box(&Map, &box, GV_POINT, pointlist);
	
	nlines = Vect_get_node_n_lines(&Map, node);
	for (j = 0; j < pointlist->n_values; j++) {
	    line = pointlist->id[j];
	    ltype = Vect_read_line(&Map, Points, Cats, line);
	    if (!(ltype & GV_POINT))
		continue;
	    if (!(Vect_cat_get(Cats, tfield, &cat)))
		continue;
	    Vect_write_line(&Out, ltype, Points, Cats);
	    G_debug(1, "node cat = %d", cat);
	    k++;
	}
    }

    Vect_build(&Out);

    G_message(n_("A Steiner tree with %d arc has been built",
            "A Steiner tree with %d arcs has been built", StArcs->n_values),
        StArcs->n_values);
    
    /* Free, ... */
    Vect_destroy_list(StArcs);
    Vect_destroy_list(StNodes);
    Vect_close(&Map);
    Vect_close(&Out);

    exit(EXIT_SUCCESS);
}
Ejemplo n.º 13
0
void CalcSurface(void)
{
    int Count, OutRows, OutCols;
    int Row, Row2, Col, Col2, RanRows, RanCols;
    int owC, oeC, onR, osR, wC, eC, nR, sR;
    double **Randoms;

    G_debug(2, "CalcSurface()");

    OutRows = BigF.RowPlus;
    OutCols = BigF.ColPlus;
    RanRows = (2 * OutRows + Rs);
    RanCols = (2 * OutCols + Cs);
    owC = osR = 0;
    wC = OutCols;
    sR = OutRows;
    oeC = RanCols - 1;
    onR = RanRows - 1;

    if (OutCols > 0)
	eC = RanCols - (OutCols + 1);
    else
	eC = oeC;

    if (OutRows > 0)
	nR = RanRows - (OutRows + 1);
    else
	nR = onR;

    Randoms = (double **)G_malloc(sizeof(double *) * RanRows);
    for (Row = 0; Row < RanRows; Row++)
	Randoms[Row] = (double *)G_malloc(RanCols * sizeof(double));

    /* OLD
       for( Row = OutRows; Row < RanRows; Row++) {
       for( Col = OutCols; Col < OutCols + Cs; Col++) {
       Randoms[ Row][ Col] = GasDev();
       }
       }

       for( Row = OutRows - 1; Row >= 0; Row--) {
       for( Col = OutCols; Col < OutCols + Cs; Col++) {
       Randoms[ Row][ Col] = GasDev();
       }
       }

       for( Row = 0; Row < RanRows; Row++) {
       for( Col = 0; Col < OutCols; Col++)
       Randoms[ Row][ Col] = GasDev();
       for( Col = OutCols + Cs; Col < RanCols; Col++)
       Randoms[ Row][ Col] = GasDev();
       }
       end OLD */

    for (Row = sR; Row <= nR; Row++) {
	for (Col = wC; Col <= eC; Col++) {
	    Randoms[Row][Col] = GasDev();
	}
    }

    Col = wC - 1;
    Col2 = eC + 1;
    while (Col >= 0) {
	for (Row = sR; Row <= nR; Row++) {
	    Randoms[Row][Col] = GasDev();
	    Randoms[Row][Col2] = GasDev();
	}
	Col--;
	Col2++;
    }

    Row = sR - 1;
    Row2 = nR + 1;
    while (Row >= 0) {
	for (Col = 0; Col < RanCols; Col++) {
	    Randoms[Row][Col] = GasDev();
	    Randoms[Row2][Col] = GasDev();
	}
	Row--;
	Row2++;
    }

    Count = 0;
    if (FDM == -1) {
	for (Row = 0; Row < Rs; Row++) {
	    if (ODD(Row)) {
		for (Col = Cs - 1; Col >= 0; Col--) {
		    G_percent(Count++, MapCount, 1);
		    Surface[Row][Col] =
			MakePP(Row, Col, OutRows, OutCols, Randoms, BigF);
		}
	    }
	    else {
		for (Col = 0; Col < Cs; Col++) {
		    G_percent(Count++, MapCount, 1);
		    Surface[Row][Col] =
			MakePP(Row, Col, OutRows, OutCols, Randoms, BigF);
		}
	    }
	}
	G_percent(1, 1, 1);
    }
    else {
	for (Row = 0; Row < Rs; Row++) {
	    G_get_map_row_nomask(FDM, CellBuffer, Row);
	    if (ODD(Row)) {
		for (Col = Cs - 1; Col >= 0; Col--) {
		    if (CellBuffer[Col] == 0)
			Surface[Row][Col] = 0.0;
		    else {
			G_percent(Count++, MapCount, 1);
			Surface[Row][Col] =
			    MakePP(Row, Col, OutRows, OutCols, Randoms, BigF);
		    }
		}
	    }
	    else {
		for (Col = 0; Col < Cs; Col++) {
		    if (CellBuffer[Col] == 0)
			Surface[Row][Col] = 0.0;
		    else {
			G_percent(Count++, MapCount, 1);
			Surface[Row][Col] =
			    MakePP(Row, Col, OutRows, OutCols, Randoms, BigF);
		    }
		}
	    }
	}
	G_percent(1, 1, 1);
    }

    G_free(Randoms);
}
Ejemplo n.º 14
0
int main(int argc, char *argv[])
{
    /* Global variable & function declarations */
    char Cellmap_orig[50];
    FILE *realfp, *imagfp;	/* the input and output file descriptors */
    int outputfd, maskfd;	/* the input and output file descriptors */
    char *realmapset, *imagmapset;	/* the input mapset names */
    struct Cell_head orig_wind, realhead;
    CELL *cell_row, *maskbuf = NULL;

    int i, j;			/* Loop control variables */
    int or, oc;			/* Original dimensions of image */
    int rows, cols;		/* Smallest powers of 2 >= number of rows & columns */
    long totsize;		/* Total number of data points */
    int halfrows, halfcols;
    double *data[2];		/* Data structure containing real & complex values of FFT */
    struct Option *op1, *op2, *op3;
    struct GModule *module;

    G_gisinit(argv[0]);

    /* Set description */
    module = G_define_module();
    module->keywords = _("imagery, FFT");
    module->description =
	_("Inverse Fast Fourier Transform (IFFT) for image processing.");

    /* define options */
    op1 = G_define_standard_option(G_OPT_R_INPUT);
    op1->key = "real_image";
    op1->description = _("Name of input raster map (image fft, real part)");

    op2 = G_define_standard_option(G_OPT_R_INPUT);
    op2->key = "imaginary_image";
    op2->description = _("Name of input raster map (image fft, imaginary part");

    op3 = G_define_standard_option(G_OPT_R_OUTPUT);
    op3->key = "output_image";
    op3->description = _("Name for output raster map");

    /*call parser */
    if (G_parser(argc, argv))
	exit(EXIT_FAILURE);

    strcpy(Cellmap_real, op1->answer);
    strcpy(Cellmap_imag, op2->answer);
    strcpy(Cellmap_orig, op3->answer);

    /* open input raster map */
    if ((realmapset = G_find_cell(Cellmap_real, "")) == NULL)
	G_fatal_error(_("Raster map <%s> not found"),
		      Cellmap_real);

    if ((realfp =
	 G_fopen_old_misc("cell_misc", "fftreal", Cellmap_real,
			  realmapset)) == NULL)
	G_fatal_error(_("Unable to open real-image in the 'cell_misc' directory. "
			"Raster map probably wasn't created by i.fft"));

    if ((imagmapset = G_find_cell(Cellmap_imag, "")) == NULL)
	G_fatal_error(_("Raster map <%s> not found"),
		      Cellmap_imag);

    if ((imagfp =
	 G_fopen_old_misc("cell_misc", "fftimag", Cellmap_imag,
			  imagmapset)) == NULL)
	G_fatal_error(_("Unable to open imaginary-image in the 'cell_misc' directory. "
			"Raster map probably wasn't created by i.fft"));

    /* check command line args for validity */
    if (G_legal_filename(Cellmap_orig) < 0)
	G_fatal_error(_("<%s> is an illegal file name"),
		      Cellmap_orig);

    /* get and compare the original window data */
    get_orig_window(&orig_wind, realmapset, imagmapset);

    or = orig_wind.rows;
    oc = orig_wind.cols;
    G_get_cellhd(Cellmap_real, realmapset, &realhead);
    G_set_window(&realhead);	/* set the window to the whole cell map */

    /* get the rows and columns in the current window */
    rows = G_window_rows();
    cols = G_window_cols();
    totsize = rows * cols;
    halfrows = rows / 2;
    halfcols = cols / 2;

    G_verbose_message(_("Power 2 values: %d rows %d columns"), rows, cols);

    /* Allocate appropriate memory for the structure containing
       the real and complex components of the FFT.  DATA[0] will
       contain the real, and DATA[1] the complex component.
     */
    data[0] = (double *)G_malloc((rows * cols) * sizeof(double));
    data[1] = (double *)G_malloc((rows * cols) * sizeof(double));

    /* Initialize real & complex components to zero */
    G_message(_("Reading raster maps..."));
    {
	fread((char *)data[0], sizeof(double), totsize, realfp);
	fread((char *)data[1], sizeof(double), totsize, imagfp);
    }

    /* Read in cell map values */
    G_message(_("Masking raster maps..."));
    maskfd = G_maskfd();
    if (maskfd >= 0)
	maskbuf = G_allocate_cell_buf();

    if (maskfd >= 0) {
	for (i = 0; i < rows; i++) {
	    double *data0, *data1;

	    data0 = data[0] + i * cols;
	    data1 = data[1] + i * cols;
	    G_get_map_row(maskfd, maskbuf, i);
	    for (j = 0; j < cols; j++, data0++, data1++) {
		if (maskbuf[j] == (CELL) 0) {
		    *(data0) = 0.0;
		    *(data1) = 0.0;
		}
	    }
	}
    }

    G_message(_("Rotating data..."));
    /* rotate the data array for standard display */
    for (i = 0; i < rows; i++) {
	double temp;

	for (j = 0; j < halfcols; j++) {
	    temp = *(data[0] + i * cols + j);
	    *(data[0] + i * cols + j) = *(data[0] + i * cols + j + halfcols);
	    *(data[0] + i * cols + j + halfcols) = temp;
	    temp = *(data[1] + i * cols + j);
	    *(data[1] + i * cols + j) = *(data[1] + i * cols + j + halfcols);
	    *(data[1] + i * cols + j + halfcols) = temp;
	}
    }
    for (i = 0; i < halfrows; i++) {
	double temp;

	for (j = 0; j < cols; j++) {
	    temp = *(data[0] + i * cols + j);
	    *(data[0] + i * cols + j) =
		*(data[0] + (i + halfrows) * cols + j);
	    *(data[0] + (i + halfrows) * cols + j) = temp;
	    temp = *(data[1] + i * cols + j);
	    *(data[1] + i * cols + j) =
		*(data[1] + (i + halfrows) * cols + j);
	    *(data[1] + (i + halfrows) * cols + j) = temp;
	}
    }


    /* close input cell maps and release the row buffers */
    fclose(realfp);
    fclose(imagfp);
    if (maskfd >= 0) {
	G_close_cell(maskfd);
	G_free(maskbuf);
    }

    /* perform inverse FFT */
    G_message(_("Starting Inverse FFT..."));
    fft(1, data, totsize, cols, rows);

    /* set up a window for the transform cell map */
    G_set_window(&orig_wind);

    /* open the output cell map and allocate a cell row buffer */
    if ((outputfd = G_open_cell_new(Cellmap_orig)) < 0)
	G_fatal_error(_("Unable to create raster map <%s>"),
		      Cellmap_orig);

    cell_row = G_allocate_cell_buf();

    /* Write out result to a new cell map */
    G_message(_("Writing data..."));
    for (i = 0; i < or; i++) {
	for (j = 0; j < oc; j++) {
	    *(cell_row + j) = (CELL) (*(data[0] + i * cols + j) + 0.5);
	}
	G_put_raster_row(outputfd, cell_row, CELL_TYPE);

	G_percent(i+1, or, 2);
    }
    G_close_cell(outputfd);

    G_free(cell_row);
    {
	struct Colors colors;
	struct Range range;
	CELL min, max;

	/* make a real component color table */
	G_read_range(Cellmap_orig, G_mapset(), &range);
	G_get_range_min_max(&range, &min, &max);
	G_make_grey_scale_colors(&colors, min, max);
	G_write_colors(Cellmap_orig, G_mapset(), &colors);
    }

    /* Release memory resources */
    G_free(data[0]);
    G_free(data[1]);

    G_done_msg(" ");

    exit(EXIT_SUCCESS);
}
Ejemplo n.º 15
0
Archivo: main.c Proyecto: caomw/grass
int main(int argc, char *argv[]) 
{
    int nrows, ncols;
    int row, col;
    int makin = 0;		/*Makin Flag for root zone soil moisture output */
    struct GModule *module;
    struct Option *input1, *input2, *input3, *output1, *output2;
    struct Flag *flag1;
    struct History history;	/*metadata */
    char *result1, *result2;	/*output raster name */
    
    int infd_rnet, infd_g0, infd_h0;
    int outfd1, outfd2;
    char *rnet, *g0, *h0;
    void *inrast_rnet, *inrast_g0, *inrast_h0;

    DCELL * outrast1, *outrast2;

    /************************************/ 
    G_gisinit(argv[0]);
    module = G_define_module();
    G_add_keyword(_("imagery"));
    G_add_keyword(_("energy balance"));
    G_add_keyword(_("soil moisture"));
    G_add_keyword(_("evaporative fraction"));
    G_add_keyword(_("SEBAL"));
    module->description =
	_("Computes evaporative fraction (Bastiaanssen, 1995) and "
	  "root zone soil moisture (Makin, Molden and Bastiaanssen, 2001).");
    
    /* Define the different options */ 
    input1 = G_define_standard_option(G_OPT_R_INPUT);
    input1->key = "netradiation";
    input1->description = _("Name of Net Radiation raster map [W/m2]");

    input2 = G_define_standard_option(G_OPT_R_INPUT);
    input2->key = "soilheatflux";
    input2->description = _("Name of soil heat flux raster map [W/m2]");

    input3 = G_define_standard_option(G_OPT_R_INPUT);
    input3->key = "sensibleheatflux";
    input3->description = _("Name of sensible heat flux raster map [W/m2]");

    output1 = G_define_standard_option(G_OPT_R_OUTPUT);
    output1->key = "evaporativefraction";
    output1->description =
	_("Name for output evaporative fraction raster map");

    output2 = G_define_standard_option(G_OPT_R_OUTPUT);
    output2->key = "soilmoisture";
    output2->required = NO;
    output2->description =
	_("Name for output root zone soil moisture raster map");

    flag1 = G_define_flag();
    flag1->key = 'm';
    flag1->description =
	_("Root zone soil moisture output (Makin, Molden and Bastiaanssen, 2001)");
    
    /********************/
    if (G_parser(argc, argv))
	exit(EXIT_FAILURE);
    
    rnet = input1->answer;
    g0 = input2->answer;
    h0 = input3->answer;
    result1 = output1->answer;
    result2 = output2->answer;
    makin = flag1->answer;
    
    /***************************************************/ 
    infd_rnet = Rast_open_old(rnet, "");
    inrast_rnet = Rast_allocate_d_buf();
    
    /***************************************************/ 
    infd_g0 = Rast_open_old(g0, "");
    inrast_g0 = Rast_allocate_d_buf();
    
    /***************************************************/ 
    infd_h0 = Rast_open_old(h0, "");
    inrast_h0 = Rast_allocate_d_buf();
    
    /***************************************************/ 
    nrows = Rast_window_rows();
    ncols = Rast_window_cols();
    outrast1 = Rast_allocate_d_buf();

    if (makin) 
	outrast2 = Rast_allocate_d_buf();
    
    /* Create New raster files */ 
    outfd1 = Rast_open_new(result1, DCELL_TYPE);
    if (makin) 
	outfd2 = Rast_open_new(result2, DCELL_TYPE);
        
    /* Process pixels */ 
    for (row = 0; row < nrows; row++)
    {
	DCELL d;
	DCELL d_rnet;
	DCELL d_g0;
	DCELL d_h0;
	G_percent(row, nrows, 2);
	
        /* read input maps */ 
        Rast_get_d_row(infd_rnet, inrast_rnet, row);
	Rast_get_d_row(infd_g0, inrast_g0, row);
	Rast_get_d_row(infd_h0, inrast_h0, row);
	
        /*process the data */ 
        for (col = 0; col < ncols; col++)
        {
            d_rnet = ((DCELL *) inrast_rnet)[col];
            d_g0 = ((DCELL *) inrast_g0)[col];
            d_h0 = ((DCELL *) inrast_h0)[col];
	    if (Rast_is_d_null_value(&d_rnet) || 
                Rast_is_d_null_value(&d_g0) ||
		Rast_is_d_null_value(&d_h0)) {
		Rast_set_d_null_value(&outrast1[col], 1);
		if (makin) 
		    Rast_set_d_null_value(&outrast2[col], 1);
	    }
	    else {
                /* calculate evaporative fraction       */ 
                d = evap_fr(d_rnet, d_g0, d_h0);
		outrast1[col] = d;
                /* calculate soil moisture              */ 
                if (makin) 
                {
                    d = soilmoisture(d);
                    outrast2[col] = d;
		}
	    }
        }
	Rast_put_d_row(outfd1, outrast1);
	if (makin) 
            Rast_put_d_row(outfd2, outrast2);
    }
    G_free(inrast_rnet);
    G_free(inrast_g0);
    G_free(inrast_h0);
    Rast_close(infd_rnet);
    Rast_close(infd_g0);
    Rast_close(infd_h0);
    G_free(outrast1);
    Rast_close(outfd1);
    if (makin) {
        G_free(outrast2);
	Rast_close(outfd2);
    }
    Rast_short_history(result1, "raster", &history);
    Rast_command_history(&history);
    Rast_write_history(result1, &history);
    if (makin) {
	Rast_short_history(result2, "raster", &history);
	Rast_command_history(&history);
	Rast_write_history(result2, &history);
    }

    exit(EXIT_SUCCESS);
}
Ejemplo n.º 16
0
int main(int argc, char *argv[])
{
    int i, j, centroid, otype, count;
    int nlines, nareas;
    int field;
    struct GModule *module;
    struct Option *in_opt, *field_opt, *out_opt, *type_opt;
    struct Option *size_opt, *zmod_opt, *objmod_opt;
    FILE *fd;

    /* Vector */
    struct Map_info In;
    struct line_pnts *Points;
    struct line_cats *Cats;
    int type;

    G_gisinit(argv[0]);

    /* Module options */
    module = G_define_module();
    G_add_keyword(_("vector"));
    G_add_keyword(_("export"));
    module->description =
	_("Converts GRASS x,y,z points to POV-Ray x,z,y format.");

    in_opt = G_define_standard_option(G_OPT_V_INPUT);

    field_opt = G_define_standard_option(G_OPT_V_FIELD_ALL);
    
    type_opt = G_define_standard_option(G_OPT_V3_TYPE);
    type_opt->answer = "point,line,area,face";

    out_opt = G_define_standard_option(G_OPT_F_OUTPUT);
    out_opt->required = YES;
    out_opt->description = _("Name for output POV file");

    size_opt = G_define_option();
    size_opt->key = "size";
    size_opt->type = TYPE_STRING;
    size_opt->required = NO;
    size_opt->answer = "10";
    size_opt->label = _("Radius of sphere for points and tube for lines");
    size_opt->description = _("May be also variable, e.g. grass_r.");

    zmod_opt = G_define_option();
    zmod_opt->key = "zmod";
    zmod_opt->type = TYPE_STRING;
    zmod_opt->required = NO;
    zmod_opt->description = _("Modifier for z coordinates");
    zmod_opt->description = _("This string is appended to each z coordinate. "
			      "Examples: '*10', '+1000', '*10+100', '*exaggeration'");

    objmod_opt = G_define_option();
    objmod_opt->key = "objmod";
    objmod_opt->type = TYPE_STRING;
    objmod_opt->required = NO;
    objmod_opt->label = _("Object modifier (OBJECT_MODIFIER in POV-Ray documentation)");
    objmod_opt->description = _("Example: \"pigment { color red 0 green 1 blue 0 }\"");
    
    if (G_parser(argc, argv))
	exit(EXIT_FAILURE);

    /* Check output type */
    otype = Vect_option_to_types(type_opt);

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

    /* open input vector */
    Vect_set_open_level(2);
    if (Vect_open_old2(&In, in_opt->answer, "", field_opt->answer) < 0)
	G_fatal_error(_("Unable to open vector map <%s>"), in_opt->answer);
    
    field = Vect_get_field_number(&In, field_opt->answer);
    
    /* Open output file */
    if ((fd = fopen(out_opt->answer, "w")) == NULL) {
	Vect_close(&In);
	G_fatal_error(_("Unable to create output file <%s>"), out_opt->answer);
    }

    if (zmod_opt->answer == NULL)
	    zmod_opt->answer = G_store("");
    if (objmod_opt->answer == NULL)
	    objmod_opt->answer = G_store("");

    nlines = Vect_get_num_lines(&In);
    nareas = Vect_get_num_areas(&In);
    count = 0;
    /* Lines */
    if ((otype &
	 (GV_POINTS | GV_LINES | GV_BOUNDARY | GV_CENTROID | GV_FACE |
	  GV_KERNEL))) {
	for (i = 1; i <= nlines; i++) {
	    G_percent(i, nlines, 2);
	    type = Vect_read_line(&In, Points, Cats, i);
	    G_debug(2, "line = %d type = %d", i, type);
	    
	    if (field != -1 && Vect_cat_get(Cats, field, NULL) == 0)
		continue;
	    
	    if (!(otype & type)) {
		continue;
	    }
	    
	    switch (type) {
	    case GV_POINT:
	    case GV_CENTROID:
	    case GV_KERNEL:
		fprintf(fd, "sphere { <%f, %f %s, %f>, %s\n%s\n}\n",
			Points->x[0], Points->z[0], zmod_opt->answer,
			Points->y[0], size_opt->answer, objmod_opt->answer);
		count++;
		break;
	    case GV_LINE:
	    case GV_BOUNDARY:
		if (Points->n_points < 2)
		    break;	/* At least 2 points */

		fprintf(fd, "sphere_sweep { linear_spline %d,\n",
			Points->n_points);
		for (j = 0; j < Points->n_points; j++) {
		    fprintf(fd, " <%f, %f %s, %f>, %s\n",
			    Points->x[j], Points->z[j], zmod_opt->answer,
			    Points->y[j], size_opt->answer);
		}
		fprintf(fd, " %s\n}\n", objmod_opt->answer);
		count++;
		break;
	    case GV_FACE:
		if (Points->n_points < 3)
		    break;	/* At least 3 points */

		Vect_append_point(Points, Points->x[0], Points->y[0], Points->z[0]);	/* close */
		fprintf(fd, "polygon { %d, \n", Points->n_points);
		for (j = 0; j < Points->n_points; j++) {
		    fprintf(fd, " <%f, %f %s, %f>\n",
			    Points->x[j], Points->z[j], zmod_opt->answer,
			    Points->y[j]);
		}
		fprintf(fd, " %s\n}\n", objmod_opt->answer);
		count++;
		break;
	    }
	}
    }

    /* Areas (run always to count features of different type) */
    if (otype & GV_AREA && nareas > 0) {
	G_message(_("Processing areas..."));
	for (i = 1; i <= nareas; i++) {
	    G_percent(i, nareas, 2);
	    /* TODO : Use this later for attributes from database: */
	    centroid = Vect_get_area_centroid(&In, i);
	    if (centroid > 0) {
		Vect_read_line(&In, NULL, Cats, centroid);
		if (field != -1 && Vect_cat_get(Cats, field, NULL) < 0)
		    continue;
	    }
	    G_debug(2, "area = %d centroid = %d", i, centroid);

	    /* Geometry */
	    /* Area */
	    Vect_get_area_points(&In, i, Points);
	    if (Points->n_points > 2) {
		for (j = 0; j < Points->n_points; j++) {
		    fprintf(fd, "polygon { %d, \n", Points->n_points);
		    for (j = 0; j < Points->n_points; j++) {
			fprintf(fd, " <%f, %f %s, %f>\n",
				Points->x[j], Points->z[j], zmod_opt->answer,
				Points->y[j]);
		    }
		    fprintf(fd, " %s\n}\n", objmod_opt->answer);
		}

		/* TODO: Isles */
		/*
		   for ( k = 0; k < Vect_get_area_num_isles (&In, i); k++ ) {
		   Vect_get_isle_points ( &In, Vect_get_area_isle (&In, i, k), Points );
		   for ( j = 0; j < Points->n_points; j++ ) {
		   }
		   }
		 */
		count++;
	    }
	}
    }

    fclose(fd);
    Vect_close(&In);

    /* Summary */
    G_done_msg(n_("%d feature written.",
                  "%d features written.",
                  count), count);

    exit(EXIT_SUCCESS);
}
Ejemplo n.º 17
0
/* 
   Called by Vect_remove_bridges() and Vect_chtype_bridges():
   chtype = 0 -> works like Vect_remove_bridges()
   chtype = 1 -> works like Vect_chtype_bridges()

   Algorithm: Go thorough all lines, 
   if both sides of the line have left and side 0 (candidate) do this check:
   follow adjacent lines in one direction (nearest to the right at the end node),
   if we reach this line again without dangle in the way, but with this line 
   traversed from other side it is a bridge.

   List of all lines in chain is created during the cycle.
 */
void
remove_bridges(struct Map_info *Map, int chtype, struct Map_info *Err)
{
    int i, type, nlines, line;
    int left, right, node1, node2, current_line, next_line;
    int bridges_removed = 0;	/* number of removed bridges */
    int lines_removed = 0;	/* number of lines removed */
    char *lmsg;
    struct Plus_head *Plus;
    struct line_pnts *Points;
    struct line_cats *Cats;
    struct ilist *CycleList;
    struct ilist *BridgeList;

    int dangle, other_side;

    if (chtype)
	lmsg = "changed lines";
    else
	lmsg = "removed lines";

    Plus = &(Map->plus);

    Points = Vect_new_line_struct();
    Cats = Vect_new_cats_struct();
    CycleList = Vect_new_list();
    BridgeList = Vect_new_list();

    nlines = Vect_get_num_lines(Map);

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

    for (line = 1; line <= nlines; line++) {
	G_percent(line, nlines, 1);
	if (!Vect_line_alive(Map, line))
	    continue;

	type = Vect_read_line(Map, NULL, NULL, line);
	if (!(type & GV_BOUNDARY))
	    continue;

	Vect_get_line_areas(Map, line, &left, &right);

	if (left != 0 || right != 0)
	    continue;		/* Cannot be bridge */

	G_debug(2, "line %d - bridge candidate", line);

	Vect_get_line_nodes(Map, line, &node1, &node2);

	if (abs(node1) == abs(node2))
	    continue;		/* either zero length or loop -> cannot be a bridge */

	current_line = -line;	/* we start with negative (go forward, node2 ) */

	dangle = 0;
	other_side = 0;
	Vect_reset_list(CycleList);
	Vect_reset_list(BridgeList);
	while (1) {
	    next_line =
		dig_angle_next_line(Plus, current_line, GV_RIGHT,
				    GV_BOUNDARY);

	    /* Add this line to the list */
	    /* TODO: Vect_val_in_list() and Vect_list_append() behave O(n)
	     * change to O(log n) */
	    if (Vect_val_in_list(CycleList, abs(next_line)))	/* other side -> bridge chain */
		Vect_list_append(BridgeList, abs(next_line));
	    else
		dig_list_add(CycleList, abs(next_line)); /* not in list, can add new line fast */

	    if (abs(next_line) == abs(current_line)) {
		G_debug(4, "  dangle -> no bridge");
		dangle = 1;
		break;
	    }
	    if (abs(next_line) == line) {	/* start line reached */
		/* which side */
		if (next_line < 0) {	/* other side (connected by node 2) */
		    G_debug(5, "  other side reached");
		    other_side = 1;
		}
		else {		/* start side */
		    break;
		}
	    }

	    current_line = -next_line;	/* change the sign to look at the next node in following cycle */
	}

	if (!dangle && other_side) {
	    G_debug(3, " line %d is part of bridge chain", line);

	    for (i = 0; i < BridgeList->n_values; i++) {
		Vect_read_line(Map, Points, Cats, BridgeList->value[i]);

		if (Err) {
		    Vect_write_line(Err, GV_BOUNDARY, Points, Cats);
		}

		if (!chtype)
		    Vect_delete_line(Map, BridgeList->value[i]);
		else
		    Vect_rewrite_line(Map, BridgeList->value[i], GV_LINE,
				      Points, Cats);

		lines_removed++;
	    }
	    bridges_removed++;
	}
    }
    G_verbose_message("Removed lines: %d", lines_removed);
    G_verbose_message("Removed bridges: %d", bridges_removed);
}
Ejemplo n.º 18
0
int main(int argc, char **argv)
{
    long i;
    int band, rows, cols;
    CELL *rowbuffer[3];
    struct Option *opt_hue, *opt_red;
    struct Option *opt_inten, *opt_green;
    struct Option *opt_sat, *opt_blue;
    struct GModule *module;
    int fd_input[3];
    int fd_output[3];

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

    /* Set description */
    module = G_define_module();
    G_add_keyword(_("imagery"));
    G_add_keyword(_("color transformation"));
    G_add_keyword(_("RGB"));
    G_add_keyword(_("HIS"));
    module->description =
        _("Transforms raster maps from RGB (Red-Green-Blue) color space to "
          "HIS (Hue-Intensity-Saturation) color space.");

    /* Define the different options */
    opt_red = G_define_standard_option(G_OPT_R_INPUT);
    opt_red->key = "red_input";
    opt_red->description = _("Name of input raster map (red)");

    opt_green = G_define_standard_option(G_OPT_R_INPUT);
    opt_green->key = "green_input";
    opt_green->description = _("Name of input raster map (green)");

    opt_blue = G_define_standard_option(G_OPT_R_INPUT);
    opt_blue->key = "blue_input";
    opt_blue->description = _("Name of input raster map (blue)");

    opt_hue = G_define_standard_option(G_OPT_R_OUTPUT);
    opt_hue->key = "hue_output";
    opt_hue->description = _("Name for output raster map (hue)");

    opt_inten = G_define_standard_option(G_OPT_R_OUTPUT);
    opt_inten->key = "intensity_output";
    opt_inten->description = _("Name for output raster map (intensity)");

    opt_sat = G_define_standard_option(G_OPT_R_OUTPUT);
    opt_sat->key = "saturation_output";
    opt_sat->description = _("Name for output raster map (saturation)");

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


    /* get dimension of the image */
    rows = Rast_window_rows();
    cols = Rast_window_cols();

    openfiles(opt_red->answer, opt_green->answer, opt_blue->answer,
              opt_hue->answer, opt_inten->answer, opt_sat->answer,
              fd_input, fd_output, rowbuffer);

    for (i = 0; i < rows; i++) {
        /* read in a row from each cell map */
        G_percent(i, rows, 2);

        for (band = 0; band < 3; band++)
            Rast_get_c_row(fd_input[band], rowbuffer[band], i);

        /* process this row of the map */
        rgb2his(rowbuffer, cols);

        /* write out the new row for each cell map */
        for (band = 0; band < 3; band++)
            Rast_put_row(fd_output[band], rowbuffer[band], CELL_TYPE);
    }
    G_percent(i, rows, 2);

    closefiles(opt_hue->answer, opt_inten->answer, opt_sat->answer,
               fd_output, rowbuffer);


    exit(EXIT_SUCCESS);
}
Ejemplo n.º 19
0
int test_large_file_zeros(int depths, int rows, int cols, int tile_size)
{
    int sum = 0;
    int x, y, z;
    DCELL value;

    G_message("Testing DCELL put function for large files filled with zeros");

    RASTER3D_Region region;
    RASTER3D_Map *map = NULL;

    /* We need to set up a specific region for the new raster3d map.
     * First we safe the default region. */
    Rast3d_get_window(&region);

    region.bottom = -365.5;
    region.top = 365.5;
    region.south = -90;
    region.north = 90;
    region.west = -180;
    region.east = 180;
    region.rows = rows;
    region.cols = cols;
    region.depths = depths;

    Rast3d_adjust_region(&region);

    G_message("Creating 3D raster map filled with zeros");

    map = Rast3d_open_new_opt_tile_size("test_put_get_value_dcell_large_zeros",
                                        RASTER3D_USE_CACHE_XY, &region, DCELL_TYPE, tile_size);

    /* The window is the same as the map region ... of course */
    Rast3d_set_window_map(map, &region);

    for(z = 0; z < region.depths; z++) {
        G_percent(z, region.depths, 1);
        for(y = 0; y < region.rows; y++) {
            for(x = 0; x < region.cols; x++) {
                /* Put the counter as cell value */
                value = 0.0;
                Rast3d_put_value(map, x, y, z, &value, DCELL_TYPE);
            }
        }
    }

    G_percent(1, 1, 1);
    /* Write everything to the disk */
    Rast3d_flush_all_tiles(map);
    Rast3d_close(map);

    G_message("Verifying 3D raster map filled with zeros");

    map = Rast3d_open_cell_old("test_put_get_value_dcell_large_zeros",
                               G_mapset(), &region, DCELL_TYPE, RASTER3D_USE_CACHE_XY);

    for(z = 0; z < region.depths; z++) {
        G_percent(z, region.depths, 1);
        for(y = 0; y < region.rows; y++) {
            for(x = 0; x < region.cols; x++) {
                /* Check the counter as cell value */
                Rast3d_get_value(map, x, y, z, &value, DCELL_TYPE);
                if(value > EPSILON) {
                    G_message("At: z %i y %i x %i -- value %.14lf != 0.0\n",
                              z, y, x, value);
                    sum++;
                }
            }
        }
    }
    G_percent(1, 1, 1);
    Rast3d_close(map);

    G_remove("grid3", "test_put_get_value_dcell_large_zeros");

    return sum;
}
Ejemplo n.º 20
0
int main(int argc, char *argv[])
{
    char *input;
    char *output;
    char *title;
    char *temp;
    FILE *fd, *ft;
    int cf, direction, sz;
    struct Cell_head cellhd;
    struct History history;
    void *rast, *rast_ptr;
    int row, col;
    int nrows, ncols;
    double x;
    char y[128];
    struct GModule *module;
    struct
    {
	struct Option *input, *output, *title, *mult, *nv, *type;
    } parm;
    struct
    {
	struct Flag *s;
    } flag;
    char *null_val_str;
    DCELL mult;
    RASTER_MAP_TYPE data_type;
    double atof();

    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("raster"));
    G_add_keyword(_("import"));
    G_add_keyword(_("conversion"));
    G_add_keyword("ASCII");
    module->description =
	_("Converts a GRASS ASCII raster file to binary raster map.");

    parm.input = G_define_standard_option(G_OPT_F_INPUT);
    parm.input->label =
	_("Name of input file to be imported");
    parm.input->description = _("'-' for standard input");

    parm.output = G_define_standard_option(G_OPT_R_OUTPUT);

    parm.type = G_define_option();
    parm.type->key = "type";
    parm.type->type = TYPE_STRING;
    parm.type->required = NO;
    parm.type->options = "CELL,FCELL,DCELL";
    parm.type->label = _("Storage type for resultant raster map");
    parm.type->description = _("Default: CELL for integer values, DCELL for floating-point values");
    
    parm.title = G_define_option();
    parm.title->key = "title";
    parm.title->key_desc = "phrase";
    parm.title->type = TYPE_STRING;
    parm.title->required = NO;
    parm.title->description = _("Title for resultant raster map");

    parm.mult = G_define_option();
    parm.mult->key = "multiplier";
    parm.mult->type = TYPE_DOUBLE;
    parm.mult->description = _("Default: read from header");
    parm.mult->required = NO;
    parm.mult->label = _("Multiplier for ASCII data");

    parm.nv = G_define_standard_option(G_OPT_M_NULL_VALUE);
    parm.nv->description = _("Default: read from header");
    parm.nv->label = _("String representing NULL value data cell");
    parm.nv->guisection = _("NULL data");
    
    flag.s = G_define_flag();
    flag.s->key = 's';
    flag.s->description =
	_("SURFER (Golden Software) ASCII file will be imported");

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

    input = parm.input->answer;
    output = parm.output->answer;

    temp = G_tempfile();
    ft = fopen(temp, "w+");
    if (ft == NULL)
	G_fatal_error(_("Unable to open temporary file <%s>"), temp);

    if ((title = parm.title->answer))
	G_strip(title);
    
    if (!parm.mult->answer)
	Rast_set_d_null_value(&mult, 1);
    else if ((sscanf(parm.mult->answer, "%lf", &mult)) != 1)
	G_fatal_error(_("Wrong entry for multiplier: %s"), parm.mult->answer);
    
    null_val_str = parm.nv->answer;

    data_type = -1;
    if (parm.type->answer) {
	switch(parm.type->answer[0]) {
	case 'C':
	    data_type = CELL_TYPE;
	    break;
	case 'F':
	    data_type = FCELL_TYPE;
	    break;
	case 'D':
	    data_type = DCELL_TYPE;
	    break;
	}
    }
    
    if (strcmp(input, "-") == 0) {
	Tmp_file = G_tempfile();
	if (NULL == (Tmp_fd = fopen(Tmp_file, "w+")))
	    G_fatal_error(_("Unable to open temporary file <%s>"), Tmp_file);
	unlink(Tmp_file);
	if (0 > file_cpy(stdin, Tmp_fd))
	    G_fatal_error(_("Unable to read input from stdin"));
	fd = Tmp_fd;
    }
    else
	fd = fopen(input, "r");

    if (fd == NULL) {
	G_fatal_error(_("Unable to read input from <%s>"), input);
    }

    direction = 1;
    sz = 0;
    if (flag.s->answer) {
	sz = getgrdhead(fd, &cellhd);
	/* for Surfer files, the data type is always FCELL_TYPE,
	   the multiplier and the null_val_str are never used */
	data_type = FCELL_TYPE;
	mult = 1.;
	null_val_str = "";
	/* rows in surfer files are ordered from bottom to top,
	   opposite of normal GRASS ordering */
	direction = -1;
    }
    else
	sz = gethead(fd, &cellhd, &data_type, &mult, &null_val_str);

    if (!sz)
	G_fatal_error(_("Can't get cell header"));

    nrows = cellhd.rows;
    ncols = cellhd.cols;
    Rast_set_window(&cellhd);

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


    rast_ptr = Rast_allocate_buf(data_type);
    rast = rast_ptr;
    cf = Rast_open_new(output, data_type);
    for (row = 0; row < nrows; row++) {
	G_percent(row, nrows, 2);
	for (col = 0; col < ncols; col++) {
	    if (fscanf(fd, "%s", y) != 1) {
		Rast_unopen(cf);
		G_fatal_error(_("Data conversion failed at row %d, col %d"),
			      row + 1, col + 1);
	    }
	    if (strcmp(y, null_val_str)) {
		x = atof(y);
		if ((float)x == GS_BLANK) {
		    Rast_set_null_value(rast_ptr, 1, data_type);
		}
		else {
		    Rast_set_d_value(rast_ptr,
					 (DCELL) (x * mult), data_type);
		}
	    }
	    else {
		Rast_set_null_value(rast_ptr, 1, data_type);
	    }
	    rast_ptr = G_incr_void_ptr(rast_ptr, Rast_cell_size(data_type));
	}
	fwrite(rast, Rast_cell_size(data_type), ncols, ft);
	rast_ptr = rast;
    }
    G_percent(nrows, nrows, 2);
    G_debug(1, "Creating support files for %s", output);

    sz = 0;
    if (direction < 0) {
	sz = -ncols * Rast_cell_size(data_type);
	G_fseek(ft, sz, SEEK_END);
	sz *= 2;
    }
    else {
	G_fseek(ft, 0L, SEEK_SET);
    }

    for (row = 0; row < nrows; row += 1) {
	fread(rast, Rast_cell_size(data_type), ncols, ft);
	Rast_put_row(cf, rast, data_type);
	G_fseek(ft, sz, SEEK_CUR);
    }
    fclose(ft);
    unlink(temp);

    Rast_close(cf);

    if (title)
	Rast_put_cell_title(output, title);

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

    G_done_msg(" ");

    exit(EXIT_SUCCESS);
}
Ejemplo n.º 21
0
int test_large_file(int depths, int rows, int cols, int tile_size)
{
    int sum = 0;
    int x, y, z, count;
    DCELL value;

    G_message("Testing DCELL put function for large files");

    RASTER3D_Region region;
    RASTER3D_Map *map = NULL;

    /* We need to set up a specific region for the new raster3d map.
     * First we safe the default region. */
    Rast3d_get_window(&region);

    region.bottom = -365.5;
    region.top = 365.5;
    region.south = -90;
    region.north = 90;
    region.west = -180;
    region.east = 180;
    region.rows = rows;
    region.cols = cols;
    region.depths = depths;

    Rast3d_adjust_region(&region);

    G_message("Creating 3D raster map");

    map = Rast3d_open_new_opt_tile_size("test_put_get_value_dcell_large",
                                        RASTER3D_USE_CACHE_XY, &region, DCELL_TYPE, tile_size);

    /* The window is the same as the map region ... of course */
    Rast3d_set_window_map(map, &region);

    /*Write -1 first to see if the tile handling works correctly */
    for(z = 0; z < region.depths; z++) {
        G_percent(z, region.depths, 1);
        for(y = 0; y < region.rows; y++) {
            for(x = 0; x < region.cols; x++) {
                /* Put the counter as cell value */
                value = -1;
                Rast3d_put_value(map, x, y, z, &value, DCELL_TYPE);
            }
        }
    }

    G_percent(1, 1, 1);
    G_message("Rewriting the values");

    /* Now write the values to be evaluated */
    count = 1;
    for(z = 0; z < region.depths; z++) {
        G_percent(z, region.depths, 1);
        for(y = 0; y < region.rows; y++) {
            for(x = 0; x < region.cols; x++) {
                /* Put the counter as cell value */
                value = count;
                Rast3d_put_value(map, x, y, z, &value, DCELL_TYPE);
                count++;
            }
        }
    }

    G_percent(1, 1, 1);

    G_message("Verifying 3D raster map");

    count = 1;
    for(z = 0; z < region.depths; z++) {
        G_percent(z, region.depths, 1);
        for(y = 0; y < region.rows; y++) {
            for(x = 0; x < region.cols; x++) {
                /* Check the counter as cell value */
                Rast3d_get_value(map, x, y, z, &value, DCELL_TYPE);
                if(fabs(value - (double)(count) > EPSILON)) {
                    G_message("At: z %i y %i x %i -- value %.14lf != %.14lf\n",
                              z, y, x, value, (double)(count));
                    sum++;
                }
                count++;
            }
        }
    }
    G_percent(1, 1, 1);
    Rast3d_close(map);

    G_remove("grid3", "test_put_get_value_dcell_large");

    return sum;
}
Ejemplo n.º 22
0
int open_files(struct globals *globals)
{
    struct Ref Ref;		/* group reference list */
    int *in_fd, bounds_fd, is_null;
    int n, row, col, srows, scols, inlen, outlen, nseg;
    DCELL **inbuf;		/* buffers to store lines from each of the imagery group rasters */
    CELL *boundsbuf, bounds_val;
    int have_bounds = 0;
    CELL s, id;
    struct Range range;	/* min/max values of bounds map */
    struct FPRange *fp_range;	/* min/max values of each input raster */
    DCELL *min, *max;
    struct ngbr_stats Ri, Rk;

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

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

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

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

    if (!I_get_group_ref(globals->image_group, &Ref))
	G_fatal_error(_("Unable to read REF file for group <%s>"),
		      globals->image_group);

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

    /* Read Imagery Group */

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

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

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

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

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

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

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

    /* size of each element to be stored */

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

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

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

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

    nseg = manage_memory(srows, scols, globals);

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

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

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

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

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

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

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

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

    /* bounds/constraints */

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

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

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

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

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

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

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

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

    /* Free memory */

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

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

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

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

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

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

    return TRUE;
}
Ejemplo n.º 23
0
int main(int argc, char *argv[])
{
    int nrows, ncols;
    int row, col;
    char *viflag;		/*Switch for particular index */
    char *desc;
    struct GModule *module;
    struct {
        struct Option *viname, *red, *nir, *green, *blue, *chan5,
            *chan7, *sl_slope, *sl_int, *sl_red, *bits, *output;
    } opt;
    struct History history;	/*metadata */
    struct Colors colors;	/*Color rules */

    char *result;		/*output raster name */
    int infd_redchan, infd_nirchan, infd_greenchan;
    int infd_bluechan, infd_chan5chan, infd_chan7chan;
    int outfd;
    char *bluechan, *greenchan, *redchan, *nirchan, *chan5chan, *chan7chan;
    DCELL *inrast_redchan, *inrast_nirchan, *inrast_greenchan;
    DCELL *inrast_bluechan, *inrast_chan5chan, *inrast_chan7chan;
    DCELL *outrast;
    RASTER_MAP_TYPE data_type_redchan;
    RASTER_MAP_TYPE data_type_nirchan, data_type_greenchan;
    RASTER_MAP_TYPE data_type_bluechan;
    RASTER_MAP_TYPE data_type_chan5chan, data_type_chan7chan;
    DCELL msavip1, msavip2, msavip3, dnbits;
    CELL val1, val2;

    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("imagery"));
    G_add_keyword(_("vegetation index"));
    G_add_keyword(_("biophysical parameters"));
    module->label =
	_("Calculates different types of vegetation indices.");
    module->description = _("Uses red and nir bands mostly, "
			    "and some indices require additional bands.");

    /* Define the different options */
    opt.red = G_define_standard_option(G_OPT_R_INPUT);
    opt.red->key = "red";
    opt.red->label =
	_("Name of input red channel surface reflectance map");
    opt.red->description = _("Range: [0.0;1.0]");

    opt.output = G_define_standard_option(G_OPT_R_OUTPUT);

    opt.viname = G_define_option();
    opt.viname->key = "viname";
    opt.viname->type = TYPE_STRING;
    opt.viname->required = YES;
    opt.viname->description = _("Type of vegetation index");
    desc = NULL;
    G_asprintf(&desc,
	       "arvi;%s;dvi;%s;evi;%s;evi2;%s;gvi;%s;gari;%s;gemi;%s;ipvi;%s;msavi;%s;"
	       "msavi2;%s;ndvi;%s;pvi;%s;savi;%s;sr;%s;vari;%s;wdvi;%s",
	       _("Atmospherically Resistant Vegetation Index"),
	       _("Difference Vegetation Index"),
	       _("Enhanced Vegetation Index"),
	       _("Enhanced Vegetation Index 2"),
	       _("Green Vegetation Index"),
	       _("Green Atmospherically Resistant Vegetation Index"),
	       _("Global Environmental Monitoring Index"),
	       _("Infrared Percentage Vegetation Index"),
	       _("Modified Soil Adjusted Vegetation Index"),
	       _("second Modified Soil Adjusted Vegetation Index"),
	       _("Normalized Difference Vegetation Index"),
	       _("Perpendicular Vegetation Index"),
	       _("Soil Adjusted Vegetation Index"),
	       _("Simple Ratio"),
	       _("Visible Atmospherically Resistant Index"),
	       _("Weighted Difference Vegetation Index"));
    opt.viname->descriptions = desc;
    opt.viname->options = "arvi,dvi,evi,evi2,gvi,gari,gemi,ipvi,msavi,msavi2,ndvi,pvi,savi,sr,vari,wdvi";
    opt.viname->answer = "ndvi";
    opt.viname->key_desc = _("type");

    opt.nir = G_define_standard_option(G_OPT_R_INPUT);
    opt.nir->key = "nir";
    opt.nir->required = NO;
    opt.nir->label =
	_("Name of input nir channel surface reflectance map");
    opt.nir->description = _("Range: [0.0;1.0]");
    opt.nir->guisection = _("Optional inputs");

    opt.green = G_define_standard_option(G_OPT_R_INPUT);
    opt.green->key = "green";
    opt.green->required = NO;
    opt.green->label =
	_("Name of input green channel surface reflectance map");
    opt.green->description = _("Range: [0.0;1.0]");
    opt.green->guisection = _("Optional inputs");

    opt.blue = G_define_standard_option(G_OPT_R_INPUT);
    opt.blue->key = "blue";
    opt.blue->required = NO;
    opt.blue->label =
	_("Name of input blue channel surface reflectance map");
    opt.blue->description = _("Range: [0.0;1.0]");
    opt.blue->guisection = _("Optional inputs");

    opt.chan5 = G_define_standard_option(G_OPT_R_INPUT);
    opt.chan5->key = "band5";
    opt.chan5->required = NO;
    opt.chan5->label =
	_("Name of input 5th channel surface reflectance map");
    opt.chan5->description = _("Range: [0.0;1.0]");
    opt.chan5->guisection = _("Optional inputs");

    opt.chan7 = G_define_standard_option(G_OPT_R_INPUT);
    opt.chan7->key = "band7";
    opt.chan7->required = NO;
    opt.chan7->label =
	_("Name of input 7th channel surface reflectance map");
    opt.chan7->description = _("Range: [0.0;1.0]");
    opt.chan7->guisection = _("Optional inputs");

    opt.sl_slope = G_define_option();
    opt.sl_slope->key = "soil_line_slope";
    opt.sl_slope->type = TYPE_DOUBLE;
    opt.sl_slope->required = NO;
    opt.sl_slope->description = _("Value of the slope of the soil line (MSAVI only)");
    opt.sl_slope->guisection = _("MSAVI settings");

    opt.sl_int = G_define_option();
    opt.sl_int->key = "soil_line_intercept";
    opt.sl_int->type = TYPE_DOUBLE;
    opt.sl_int->required = NO;
    opt.sl_int->description = _("Value of the intercept of the soil line (MSAVI only)");
    opt.sl_int->guisection = _("MSAVI settings");

    opt.sl_red = G_define_option();
    opt.sl_red->key = "soil_noise_reduction";
    opt.sl_red->type = TYPE_DOUBLE;
    opt.sl_red->required = NO;
    opt.sl_red->description = _("Value of the factor of reduction of soil noise (MSAVI only)");
    opt.sl_red->guisection = _("MSAVI settings");

    opt.bits = G_define_option();
    opt.bits->key = "storage_bit";
    opt.bits->type = TYPE_INTEGER;
    opt.bits->required = NO;
    opt.bits->label = _("Maximum bits for digital numbers");
    opt.bits->description = _("If data is in Digital Numbers (i.e. integer type), give the max bits (i.e. 8 for Landsat -> [0-255])");
    opt.bits->options = "7,8,10,16";
    opt.bits->answer = "8";

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

    viflag = opt.viname->answer;
    redchan = opt.red->answer;
    nirchan = opt.nir->answer;
    greenchan = opt.green->answer;
    bluechan = opt.blue->answer;
    chan5chan = opt.chan5->answer;
    chan7chan = opt.chan7->answer;
    if(opt.sl_slope->answer)
        msavip1 = atof(opt.sl_slope->answer);
    if(opt.sl_int->answer)
        msavip2 = atof(opt.sl_int->answer);
    if(opt.sl_red->answer)
        msavip3 = atof(opt.sl_red->answer);
    if(opt.bits->answer)
        dnbits = atof(opt.bits->answer);
    result = opt.output->answer;
    G_verbose_message(_("Calculating %s..."), viflag);

    if (!strcasecmp(viflag, "sr") && (!(opt.red->answer) || !(opt.nir->answer)) )
	G_fatal_error(_("sr index requires red and nir maps"));

    if (!strcasecmp(viflag, "ndvi") && (!(opt.red->answer) || !(opt.nir->answer)) )
	G_fatal_error(_("ndvi index requires red and nir maps"));

    if (!strcasecmp(viflag, "ipvi") && (!(opt.red->answer) || !(opt.nir->answer)) )
	G_fatal_error(_("ipvi index requires red and nir maps"));

    if (!strcasecmp(viflag, "dvi") && (!(opt.red->answer) || !(opt.nir->answer)) )
	G_fatal_error(_("dvi index requires red and nir maps"));

    if (!strcasecmp(viflag, "pvi") && (!(opt.red->answer) || !(opt.nir->answer)) )
	G_fatal_error(_("pvi index requires red and nir maps"));

    if (!strcasecmp(viflag, "wdvi") && (!(opt.red->answer) || !(opt.nir->answer)) )
	G_fatal_error(_("wdvi index requires red and nir maps"));

    if (!strcasecmp(viflag, "savi") && (!(opt.red->answer) || !(opt.nir->answer)) )
	G_fatal_error(_("savi index requires red and nir maps"));

    if (!strcasecmp(viflag, "msavi") && (!(opt.red->answer) || !(opt.nir->answer) || 
                                          !(opt.sl_slope->answer) || !(opt.sl_int->answer) || 
                                          !(opt.sl_red->answer)) )
	G_fatal_error(_("msavi index requires red and nir maps, and 3 parameters related to soil line"));

    if (!strcasecmp(viflag, "msavi2") && (!(opt.red->answer) || !(opt.nir->answer)) )
	G_fatal_error(_("msavi2 index requires red and nir maps"));

    if (!strcasecmp(viflag, "gemi") && (!(opt.red->answer) || !(opt.nir->answer)) )
	G_fatal_error(_("gemi index requires red and nir maps"));

    if (!strcasecmp(viflag, "arvi") && (!(opt.red->answer) || !(opt.nir->answer)
                || !(opt.blue->answer)) )
	G_fatal_error(_("arvi index requires blue, red and nir maps"));

    if (!strcasecmp(viflag, "evi") && (!(opt.red->answer) || !(opt.nir->answer)
                || !(opt.blue->answer)) )
	G_fatal_error(_("evi index requires blue, red and nir maps"));

	if (!strcasecmp(viflag, "evi2") && (!(opt.red->answer) || !(opt.nir->answer) ) )
	G_fatal_error(_("evi2 index requires red and nir maps"));
	
    if (!strcasecmp(viflag, "vari") && (!(opt.red->answer) || !(opt.green->answer)
                || !(opt.blue->answer)) )
	G_fatal_error(_("vari index requires blue, green and red maps"));

    if (!strcasecmp(viflag, "gari") && (!(opt.red->answer) || !(opt.nir->answer)
                || !(opt.green->answer) || !(opt.blue->answer)) )
	G_fatal_error(_("gari index requires blue, green, red and nir maps"));

    if (!strcasecmp(viflag, "gvi") && (!(opt.red->answer) || !(opt.nir->answer)
                || !(opt.green->answer) || !(opt.blue->answer)
                || !(opt.chan5->answer) || !(opt.chan7->answer)) )
	G_fatal_error(_("gvi index requires blue, green, red, nir, chan5 and chan7 maps"));

    infd_redchan = Rast_open_old(redchan, "");
    data_type_redchan = Rast_map_type(redchan, "");
    inrast_redchan = Rast_allocate_buf(data_type_redchan);

    if (nirchan) {
        infd_nirchan = Rast_open_old(nirchan, "");
        data_type_nirchan = Rast_map_type(nirchan, "");
        inrast_nirchan = Rast_allocate_buf(data_type_nirchan);
    }

    if (greenchan) {
        infd_greenchan = Rast_open_old(greenchan, "");
        data_type_greenchan = Rast_map_type(greenchan, "");
        inrast_greenchan = Rast_allocate_buf(data_type_greenchan);
    }

    if (bluechan) {
        infd_bluechan = Rast_open_old(bluechan, "");
        data_type_bluechan = Rast_map_type(bluechan, "");
        inrast_bluechan = Rast_allocate_buf(data_type_bluechan);
    }

    if (chan5chan) {
        infd_chan5chan = Rast_open_old(chan5chan, "");
        data_type_chan5chan = Rast_map_type(chan5chan, "");
        inrast_chan5chan = Rast_allocate_buf(data_type_chan5chan);
    }

    if (chan7chan) {
        infd_chan7chan = Rast_open_old(chan7chan, "");
        data_type_chan7chan = Rast_map_type(chan7chan, "");
        inrast_chan7chan = Rast_allocate_buf(data_type_chan7chan);
    }

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

    /* Create New raster files */
    outfd = Rast_open_new(result, DCELL_TYPE);
    outrast = Rast_allocate_d_buf();

    /* Process pixels */
    for (row = 0; row < nrows; row++)
    {
	DCELL d_bluechan;
	DCELL d_greenchan;
	DCELL d_redchan;
	DCELL d_nirchan;
	DCELL d_chan5chan;
	DCELL d_chan7chan;

	G_percent(row, nrows, 2);

	/* read input maps */
	Rast_get_row(infd_redchan,inrast_redchan,row,data_type_redchan);
	if (nirchan) {
	    Rast_get_row(infd_nirchan,inrast_nirchan,row,data_type_nirchan);
	}
	if (bluechan) {
	    Rast_get_row(infd_bluechan,inrast_bluechan,row,data_type_bluechan);
	}
	if (greenchan) {
	    Rast_get_row(infd_greenchan,inrast_greenchan,row,data_type_greenchan);
	}
	if (chan5chan) {
	    Rast_get_row(infd_chan5chan,inrast_chan5chan,row,data_type_chan5chan);
	}
	if (chan7chan) {
	    Rast_get_row(infd_chan7chan,inrast_chan7chan,row,data_type_chan7chan);
	}
	/* process the data */
	for (col = 0; col < ncols; col++)
	{
	    switch(data_type_redchan){
		    case CELL_TYPE:
			d_redchan   = (double) ((CELL *) inrast_redchan)[col];
			if(opt.bits->answer)
				d_redchan *= 1.0/(pow(2,dnbits)-1);	
			break;
		    case FCELL_TYPE:
			d_redchan   = (double) ((FCELL *) inrast_redchan)[col];
			break;
		    case DCELL_TYPE:
			d_redchan   = ((DCELL *) inrast_redchan)[col];
			break;
	    }
	    if (nirchan) {
		switch(data_type_nirchan){
		    case CELL_TYPE:
			d_nirchan   = (double) ((CELL *) inrast_nirchan)[col];
			if(opt.bits->answer)
				d_nirchan *= 1.0/(pow(2,dnbits)-1);	
			break;
		    case FCELL_TYPE:
			d_nirchan   = (double) ((FCELL *) inrast_nirchan)[col];
			break;
		    case DCELL_TYPE:
			d_nirchan   = ((DCELL *) inrast_nirchan)[col];
			break;
		}
	    }
	    if (greenchan) {
		switch(data_type_greenchan){
		    case CELL_TYPE:
			d_greenchan   = (double) ((CELL *) inrast_greenchan)[col];
			if(opt.bits->answer)
				d_greenchan *= 1.0/(pow(2,dnbits)-1);	
			break;
		    case FCELL_TYPE:
			d_greenchan   = (double) ((FCELL *) inrast_greenchan)[col];
			break;
		    case DCELL_TYPE:
			d_greenchan   = ((DCELL *) inrast_greenchan)[col];
			break;
		}
	    }
	    if (bluechan) {
		switch(data_type_bluechan){
		    case CELL_TYPE:
			d_bluechan   = (double) ((CELL *) inrast_bluechan)[col];
			if(opt.bits->answer)
				d_bluechan *= 1.0/(pow(2,dnbits)-1);	
			break;
		    case FCELL_TYPE:
			d_bluechan   = (double) ((FCELL *) inrast_bluechan)[col];
			break;
		    case DCELL_TYPE:
			d_bluechan   = ((DCELL *) inrast_bluechan)[col];
			break;
		}
	    }
	    if (chan5chan) {
		switch(data_type_chan5chan){
		    case CELL_TYPE:
			d_chan5chan   = (double) ((CELL *) inrast_chan5chan)[col];
			if(opt.bits->answer)
				d_chan5chan *= 1.0/(pow(2,dnbits)-1);	
			break;
		    case FCELL_TYPE:
			d_chan5chan   = (double) ((FCELL *) inrast_chan5chan)[col];
			break;
		    case DCELL_TYPE:
			d_chan5chan   = ((DCELL *) inrast_chan5chan)[col];
			break;
		}
	    }
	    if (chan7chan) {
		switch(data_type_chan7chan){
		    case CELL_TYPE:
			d_chan7chan   = (double) ((CELL *) inrast_chan7chan)[col];
			if(opt.bits->answer)
				d_chan7chan *= 1.0/(pow(2,dnbits)-1);	
			break;
		    case FCELL_TYPE:
			d_chan7chan   = (double) ((FCELL *) inrast_chan7chan)[col];
			break;
		    case DCELL_TYPE:
			d_chan7chan   = ((DCELL *) inrast_chan7chan)[col];
			break;
		}
	    }

	    if (Rast_is_d_null_value(&d_redchan) ||
		((nirchan) && Rast_is_d_null_value(&d_nirchan)) ||
		((greenchan) && Rast_is_d_null_value(&d_greenchan)) ||
		((bluechan) && Rast_is_d_null_value(&d_bluechan)) ||
		((chan5chan) && Rast_is_d_null_value(&d_chan5chan)) ||
		((chan7chan) && Rast_is_d_null_value(&d_chan7chan))) {
		Rast_set_d_null_value(&outrast[col], 1);
	    }
	    else {
		/* calculate simple_ratio        */
		if (!strcasecmp(viflag, "sr"))
		    outrast[col] = s_r(d_redchan, d_nirchan);

		/* calculate ndvi                    */
		if (!strcasecmp(viflag, "ndvi")) {
		    if (d_redchan + d_nirchan < 0.001)
			Rast_set_d_null_value(&outrast[col], 1);
		    else
			outrast[col] = nd_vi(d_redchan, d_nirchan);
		}

		if (!strcasecmp(viflag, "ipvi"))
		    outrast[col] = ip_vi(d_redchan, d_nirchan);

		if (!strcasecmp(viflag, "dvi"))
		    outrast[col] = d_vi(d_redchan, d_nirchan);

		if (!strcasecmp(viflag, "evi"))
		    outrast[col] = e_vi(d_bluechan, d_redchan, d_nirchan);

		if (!strcasecmp(viflag, "evi2"))
		    outrast[col] = e_vi2(d_redchan, d_nirchan);

		if (!strcasecmp(viflag, "pvi"))
		    outrast[col] = p_vi(d_redchan, d_nirchan);

		if (!strcasecmp(viflag, "wdvi"))
		    outrast[col] = wd_vi(d_redchan, d_nirchan);

		if (!strcasecmp(viflag, "savi"))
		    outrast[col] = sa_vi(d_redchan, d_nirchan);

		if (!strcasecmp(viflag, "msavi"))
		    outrast[col] = msa_vi(d_redchan, d_nirchan, msavip1, msavip2, msavip3);

		if (!strcasecmp(viflag, "msavi2"))
		    outrast[col] = msa_vi2(d_redchan, d_nirchan);

		if (!strcasecmp(viflag, "gemi"))
		    outrast[col] = ge_mi(d_redchan, d_nirchan);

		if (!strcasecmp(viflag, "arvi"))
		    outrast[col] = ar_vi(d_redchan, d_nirchan, d_bluechan);

		if (!strcasecmp(viflag, "gvi"))
		    outrast[col] = g_vi(d_bluechan, d_greenchan, d_redchan, d_nirchan, d_chan5chan, d_chan7chan);

		if (!strcasecmp(viflag, "gari"))
		    outrast[col] = ga_ri(d_redchan, d_nirchan, d_bluechan, d_greenchan);

		if (!strcasecmp(viflag, "vari"))
		    outrast[col] = va_ri(d_redchan, d_greenchan, d_bluechan);
	    }
	}
	Rast_put_d_row(outfd, outrast);
    }
    G_percent(1, 1, 1);
      
    G_free(inrast_redchan);
    Rast_close(infd_redchan);
    if (nirchan) {
    	G_free(inrast_nirchan);
    	Rast_close(infd_nirchan);
    }
    if (greenchan) {
	G_free(inrast_greenchan);
	Rast_close(infd_greenchan);
    }
    if (bluechan) {
	G_free(inrast_bluechan);
	Rast_close(infd_bluechan);
    }
    if (chan5chan) {
	G_free(inrast_chan5chan);
	Rast_close(infd_chan5chan);
    }
    if (chan7chan) {
	G_free(inrast_chan7chan);
	Rast_close(infd_chan7chan);
    }

    G_free(outrast);
    Rast_close(outfd);

    if (!strcasecmp(viflag, "ndvi")) {
 	/* apply predefined NDVI color table */
	const char *style = "ndvi";
	if (G_find_color_rule("ndvi")) {
	   Rast_make_fp_colors(&colors, style, -1.0, 1.0);
	} else
	   G_fatal_error(_("Unknown color request '%s'"), style);
    } else {
	/* Color from -1.0 to +1.0 in grey */
	Rast_init_colors(&colors);
	val1 = -1;
	val2 = 1;
	Rast_add_c_color_rule(&val1, 0, 0, 0, &val2, 255, 255, 255, &colors);
    }
    Rast_write_colors(result, G_mapset(), &colors);

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

    exit(EXIT_SUCCESS);
}
Ejemplo n.º 24
0
int main(int argc, char **argv)
{
    int i;
    int **cats, *ncats, nfields, *fields;
    struct Flag *line_flag;

    /* struct Flag *all_flag; */
    struct Option *in_opt, *out_opt;
    struct Flag *table_flag;
    struct GModule *module;
    struct line_pnts *Points;
    struct line_cats *Cats;
    int node, nnodes;
    COOR *coor;
    int ncoor, acoor;
    int line, nlines, type, ctype, area, nareas;
    int err_boundaries, err_centr_out, err_centr_dupl, err_nocentr;

    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("vector"));
    G_add_keyword(_("geometry"));
    G_add_keyword(_("triangulation"));
    module->description = _("Creates a Voronoi diagram from an input vector "
			    "map containing points or centroids.");

    in_opt = G_define_standard_option(G_OPT_V_INPUT);
    out_opt = G_define_standard_option(G_OPT_V_OUTPUT);

    /*
       all_flag = G_define_flag ();
       all_flag->key = 'a';
       all_flag->description = _("Use all points (do not limit to current region)");
     */

    line_flag = G_define_flag();
    line_flag->key = 'l';
    line_flag->description =
	_("Output tessellation as a graph (lines), not areas");

    table_flag = G_define_flag();
    table_flag->key = 't';
    table_flag->description = _("Do not create attribute table");

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


    if (line_flag->answer)
	Type = GV_LINE;
    else
	Type = GV_BOUNDARY;

    All = 0;

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

    /* open files */
    Vect_set_open_level(2);
    Vect_open_old(&In, in_opt->answer, "");

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

    Vect_hist_copy(&In, &Out);
    Vect_hist_command(&Out);

    /* initialize working region */
    G_get_window(&Window);
    Vect_region_box(&Window, &Box);
    Box.T = 0.5;
    Box.B = -0.5;

    freeinit(&sfl, sizeof(struct Site));

    G_message(_("Reading sites..."));
    readsites();

    siteidx = 0;
    geominit();

    triangulate = 0;
    plot = 0;
    debug = 0;

    G_message(_("Voronoi triangulation..."));
    voronoi(triangulate, nextone);

    /* Close free ends by current region */
    Vect_build_partial(&Out, GV_BUILD_BASE);

    ncoor = 0;
    acoor = 100;
    coor = (COOR *) G_malloc(sizeof(COOR) * acoor);

    nnodes = Vect_get_num_nodes(&Out);
    for (node = 1; node <= nnodes; node++) {
	double x, y;

	if (Vect_get_node_n_lines(&Out, node) < 2) {	/* add coordinates */
	    Vect_get_node_coor(&Out, node, &x, &y, NULL);

	    if (ncoor == acoor - 5) {	/* always space for 5 region corners */
		acoor += 100;
		coor = (COOR *) G_realloc(coor, sizeof(COOR) * acoor);
	    }

	    coor[ncoor].x = x;
	    coor[ncoor].y = y;
	    ncoor++;
	}
    }

    /* Add region corners */
    coor[ncoor].x = Box.W;
    coor[ncoor].y = Box.S;
    ncoor++;
    coor[ncoor].x = Box.E;
    coor[ncoor].y = Box.S;
    ncoor++;
    coor[ncoor].x = Box.E;
    coor[ncoor].y = Box.N;
    ncoor++;
    coor[ncoor].x = Box.W;
    coor[ncoor].y = Box.N;
    ncoor++;

    /* Sort */
    qsort(coor, ncoor, sizeof(COOR), (void *)cmp);

    /* add last (first corner) */
    coor[ncoor].x = Box.W;
    coor[ncoor].y = Box.S;
    ncoor++;

    for (i = 1; i < ncoor; i++) {
	if (coor[i].x == coor[i - 1].x && coor[i].y == coor[i - 1].y)
	    continue;		/* duplicate */

	Vect_reset_line(Points);
	Vect_append_point(Points, coor[i].x, coor[i].y, 0.0);
	Vect_append_point(Points, coor[i - 1].x, coor[i - 1].y, 0.0);
	Vect_write_line(&Out, Type, Points, Cats);
    }

    G_free(coor);

    /* Copy input points as centroids */
    nfields = Vect_cidx_get_num_fields(&In);
    cats = (int **)G_malloc(nfields * sizeof(int *));
    ncats = (int *)G_malloc(nfields * sizeof(int));
    fields = (int *)G_malloc(nfields * sizeof(int));
    for (i = 0; i < nfields; i++) {
	ncats[i] = 0;
	cats[i] =
	    (int *)G_malloc(Vect_cidx_get_num_cats_by_index(&In, i) *
			    sizeof(int));
	fields[i] = Vect_cidx_get_field_number(&In, i);
    }

    if (line_flag->answer)
	ctype = GV_POINT;
    else
	ctype = GV_CENTROID;

    nlines = Vect_get_num_lines(&In);

    G_message(_("Writing sites to output..."));

    for (line = 1; line <= nlines; line++) {

	G_percent(line, nlines, 2);

	type = Vect_read_line(&In, Points, Cats, line);
	if (!(type & GV_POINTS))
	    continue;

	if (!Vect_point_in_box(Points->x[0], Points->y[0], 0.0, &Box))
	    continue;

	Vect_write_line(&Out, ctype, Points, Cats);


	for (i = 0; i < Cats->n_cats; i++) {
	    int f, j;

	    f = -1;
	    for (j = 0; j < nfields; j++) {	/* find field */
		if (fields[j] == Cats->field[i]) {
		    f = j;
		    break;
		}
	    }
	    if (f > -1) {
		cats[f][ncats[f]] = Cats->cat[i];
		ncats[f]++;
	    }
	}
    }

    /* Copy tables */
    if (!(table_flag->answer)) {
	int ttype, ntabs = 0;
	struct field_info *IFi, *OFi;

	/* Number of output tabs */
	for (i = 0; i < Vect_get_num_dblinks(&In); i++) {
	    int f, j;

	    IFi = Vect_get_dblink(&In, i);

	    f = -1;
	    for (j = 0; j < nfields; j++) {	/* find field */
		if (fields[j] == IFi->number) {
		    f = j;
		    break;
		}
	    }
	    if (f > -1) {
		if (ncats[f] > 0)
		    ntabs++;
	    }
	}

	if (ntabs > 1)
	    ttype = GV_MTABLE;
	else
	    ttype = GV_1TABLE;

	for (i = 0; i < nfields; i++) {
	    int ret;

	    if (fields[i] == 0)
		continue;

	    G_message(_("Layer %d"), fields[i]);

	    /* Make a list of categories */
	    IFi = Vect_get_field(&In, fields[i]);
	    if (!IFi) {		/* no table */
		G_message(_("No table"));
		continue;
	    }

	    OFi =
		Vect_default_field_info(&Out, IFi->number, IFi->name, ttype);

	    ret =
		db_copy_table_by_ints(IFi->driver, IFi->database, IFi->table,
				      OFi->driver,
				      Vect_subst_var(OFi->database, &Out),
				      OFi->table, IFi->key, cats[i],
				      ncats[i]);

	    if (ret == DB_FAILED) {
		G_warning(_("Cannot copy table"));
	    }
	    else {
		Vect_map_add_dblink(&Out, OFi->number, OFi->name, OFi->table,
				    IFi->key, OFi->database, OFi->driver);
	    }
	}
    }


    Vect_close(&In);

    /* cleaning part 1: count errors */
    Vect_build_partial(&Out, GV_BUILD_CENTROIDS);
    err_boundaries = err_centr_out = err_centr_dupl = err_nocentr = 0;
    nlines = Vect_get_num_lines(&Out);
    for (line = 1; line <= nlines; line++) {

	if (!Vect_line_alive(&Out, line))
	    continue;

	type = Vect_get_line_type(&Out, line);
	if (type == GV_BOUNDARY) {
	    int left, right;

	    Vect_get_line_areas(&Out, line, &left, &right);

	    if (left == 0 || right == 0) {
		G_debug(3, "line = %d left = %d right = %d", line, 
			left, right);
		err_boundaries++;
	    }
	}
	if (type == GV_CENTROID) {
	    area = Vect_get_centroid_area(&Out, line);
	    if (area == 0)
		err_centr_out++;
	    else if (area < 0)
		err_centr_dupl++;
	}
    }

    err_nocentr = 0;
    nareas = Vect_get_num_areas(&Out);
    for (area = 1; area <= nareas; area++) {
	if (!Vect_area_alive(&Out, area))
	    continue;
	line = Vect_get_area_centroid(&Out, area);
	if (line == 0)
	    err_nocentr++;
    }

    /* cleaning part 2: snap */
    if (err_nocentr || err_centr_dupl || err_centr_out) {
	int nmod;

	G_important_message(_("Output needs topological cleaning"));
	Vect_snap_lines(&Out, GV_BOUNDARY, 1e-7, NULL);
	do {
	    Vect_break_lines(&Out, GV_BOUNDARY, NULL);
	    Vect_remove_duplicates(&Out, GV_BOUNDARY, NULL);
	    nmod =
		Vect_clean_small_angles_at_nodes(&Out, GV_BOUNDARY, NULL);
	} while (nmod > 0);

	err_boundaries = 0;
	nlines = Vect_get_num_lines(&Out);
	for (line = 1; line <= nlines; line++) {

	    if (!Vect_line_alive(&Out, line))
		continue;

	    type = Vect_get_line_type(&Out, line);
	    if (type == GV_BOUNDARY) {
		int left, right;

		Vect_get_line_areas(&Out, line, &left, &right);

		if (left == 0 || right == 0) {
		    G_debug(3, "line = %d left = %d right = %d", line, 
			    left, right);
		    err_boundaries++;
		}
	    }
	}
    }
    /* cleaning part 3: remove remaining incorrect boundaries */
    if (err_boundaries) {
	G_important_message(_("Removing incorrect boundaries from output"));
	nlines = Vect_get_num_lines(&Out);
	for (line = 1; line <= nlines; line++) {

	    if (!Vect_line_alive(&Out, line))
		continue;

	    type = Vect_get_line_type(&Out, line);
	    if (type == GV_BOUNDARY) {
		int left, right;

		Vect_get_line_areas(&Out, line, &left, &right);

		/* &&, not ||, no typo */
		if (left == 0 && right == 0) {
		    G_debug(3, "line = %d left = %d right = %d", line, 
			    left, right);
		    Vect_delete_line(&Out, line);
		}
	    }
	}
    }

    /* build clean topology */
    Vect_build_partial(&Out, GV_BUILD_NONE);
    Vect_build(&Out);
    Vect_close(&Out);

    G_done_msg(" ");
    exit(EXIT_SUCCESS);
}
Ejemplo n.º 25
0
int do_cum_mfd(void)
{
    int r, c, dr, dc;
    DCELL value, valued, *wat_nbr;
    POINT point;
    WAT_ALT wa;
    int killer, threshold;

    /* MFD */
    int mfd_cells, stream_cells, swale_cells, astar_not_set, is_null;
    double *dist_to_nbr, *weight, sum_weight, max_weight;
    int r_nbr, c_nbr, r_max, c_max, ct_dir, np_side, max_side;
    double dx, dy;
    CELL ele, *ele_nbr;
    char asp_val, asp_val_down;
    double prop, max_acc;
    int workedon, edge, is_swale, flat;
    char *flag_nbr, this_flag_value, flag_value;
    int asp_r[9] = { 0, -1, -1, -1, 0, 1, 1, 1, 0 };
    int asp_c[9] = { 0, 1, 0, -1, -1, -1, 0, 1, 1 };

    G_message(_("SECTION 3: Accumulating Surface Flow with MFD."));
    G_debug(1, "MFD convergence factor set to %d.", c_fac);

    /* distances to neighbours */
    dist_to_nbr = (double *)G_malloc(sides * sizeof(double));
    weight = (double *)G_malloc(sides * sizeof(double));

    for (ct_dir = 0; ct_dir < sides; ct_dir++) {
	/* get r, c (r_nbr, c_nbr) for neighbours */
	r_nbr = nextdr[ct_dir];
	c_nbr = nextdc[ct_dir];
	/* account for rare cases when ns_res != ew_res */
	dy = ABS(r_nbr) * window.ns_res;
	dx = ABS(c_nbr) * window.ew_res;
	if (ct_dir < 4)
	    dist_to_nbr[ct_dir] = dx + dy;
	else
	    dist_to_nbr[ct_dir] = sqrt(dx * dx + dy * dy);
    }

    flag_nbr = (char *)G_malloc(sides * sizeof(char));
    wat_nbr = (DCELL *)G_malloc(sides * sizeof(DCELL));
    ele_nbr = (CELL *)G_malloc(sides * sizeof(CELL));

    workedon = 0;

    if (bas_thres <= 0)
	threshold = 60;
    else
	threshold = bas_thres;

    for (killer = 0; killer < do_points; killer++) {
	G_percent(killer, do_points, 1);
	seg_get(&astar_pts, (char *)&point, 0, killer);
	r = point.r;
	c = point.c;
	bseg_get(&asp, &asp_val, r, c);
	if (asp_val) {
	    dr = r + asp_r[ABS(asp_val)];
	    dc = c + asp_c[ABS(asp_val)];
	}
	/* skip user-defined depressions */
	else
	    dr = dc = -1;

	/* WORKEDFLAG has been set during A* Search
	 * reversed meaning here: 0 = done, 1 = not yet done */
	bseg_get(&bitflags, &this_flag_value, r, c);
	FLAG_UNSET(this_flag_value, WORKEDFLAG);
	
	if (dr >= 0 && dr < nrows && dc >= 0 && dc < ncols) {
	    r_max = dr;
	    c_max = dc;

	    seg_get(&watalt, (char *)&wa, r, c);
	    value = wa.wat;

	    /* get weights */
	    max_weight = 0;
	    sum_weight = 0;
	    np_side = -1;
	    mfd_cells = 0;
	    stream_cells = 0;
	    swale_cells = 0;
	    astar_not_set = 1;
	    ele = wa.ele;
	    is_null = 0;
	    edge = 0;
	    flat = 1;
	    /* this loop is needed to get the sum of weights */
	    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];
		weight[ct_dir] = -1;

		wat_nbr[ct_dir] = 0;
		ele_nbr[ct_dir] = 0;

		/* check if neighbour is within region */
		if (r_nbr >= 0 && r_nbr < nrows && c_nbr >= 0 &&
		    c_nbr < ncols) {

		    if (dr == r_nbr && dc == c_nbr)
			np_side = ct_dir;

		    bseg_get(&bitflags, &flag_nbr[ct_dir], r_nbr, c_nbr);
		    seg_get(&watalt, (char *)&wa, r_nbr, c_nbr);
		    wat_nbr[ct_dir] = wa.wat;
		    ele_nbr[ct_dir] = wa.ele;

		    /* check for swale or stream cells */
		    is_swale = FLAG_GET(flag_nbr[ct_dir], SWALEFLAG);
		    if (is_swale)
			swale_cells++;
		    if ((ABS(wat_nbr[ct_dir]) + 0.5) >= threshold &&
		        ct_dir != np_side && ele_nbr[ct_dir] > ele)
			stream_cells++;

		    if (FLAG_GET(flag_nbr[ct_dir], WORKEDFLAG)) {

			if (ele_nbr[ct_dir] != ele)
			    flat = 0;

			edge = is_null = FLAG_GET(flag_nbr[ct_dir], NULLFLAG);
			if (!is_null && ele_nbr[ct_dir] <= ele) {
			    if (ele_nbr[ct_dir] < ele) {
				weight[ct_dir] =
				    mfd_pow(((ele -
					      ele_nbr[ct_dir]) / dist_to_nbr[ct_dir]),
					    c_fac);
			    }
			    if (ele_nbr[ct_dir] == ele) {
				weight[ct_dir] =
				    mfd_pow((0.5 / dist_to_nbr[ct_dir]),
					    c_fac);
			    }
			    sum_weight += weight[ct_dir];
			    mfd_cells++;

			    if (weight[ct_dir] > max_weight) {
				max_weight = weight[ct_dir];
			    }

			    if (dr == r_nbr && dc == c_nbr) {
				astar_not_set = 0;
			    }
			}
		    }
		}
		else
		    edge = 1;
		if (edge)
		    break;
	    }
	    /* do not continue streams along edges, this causes artifacts */
	    if (edge) {
		is_swale = FLAG_GET(this_flag_value, SWALEFLAG);
		if (is_swale && asp_val > 0) {
		    asp_val = -1 * drain[r - r_nbr + 1][c - c_nbr + 1];
		    bseg_put(&asp, &asp_val, r, c);
		}
		bseg_put(&bitflags, &this_flag_value, r, c);
		continue;
	    }

	    /* honour A * path 
	     * mfd_cells == 0: fine, SFD along A * path
	     * mfd_cells == 1 && astar_not_set == 0: fine, SFD along A * path
	     * mfd_cells > 0 && astar_not_set == 1: A * path not included, add to mfd_cells
	     */

	    /* MFD, A * path not included, add to mfd_cells */
	    if (mfd_cells > 0 && astar_not_set == 1) {
		mfd_cells++;
		sum_weight += max_weight;
		weight[np_side] = max_weight;
		max_side = np_side;
	    }

	    /* set flow accumulation for neighbours */
	    max_acc = -1;
	    max_side = np_side;

	    if (mfd_cells > 1) {
		prop = 0.0;
		for (ct_dir = 0; ct_dir < sides; ct_dir++) {
		    r_nbr = r + nextdr[ct_dir];
		    c_nbr = c + nextdc[ct_dir];

		    /* check if neighbour is within region */
		    if (r_nbr >= 0 && r_nbr < nrows && c_nbr >= 0 &&
			c_nbr < ncols && weight[ct_dir] > -0.5) {

			if (FLAG_GET(flag_nbr[ct_dir], WORKEDFLAG)) {

			    weight[ct_dir] = weight[ct_dir] / sum_weight;
			    /* check everything adds up to 1.0 */
			    prop += weight[ct_dir];

			    if (value > 0) {
				if (wat_nbr[ct_dir] > 0)
				    wat_nbr[ct_dir] += value * weight[ct_dir];
				else
				    wat_nbr[ct_dir] -= value * weight[ct_dir];
			    }
			    else {
				if (wat_nbr[ct_dir] < 0)
				    wat_nbr[ct_dir] += value * weight[ct_dir];
				else
				    wat_nbr[ct_dir] = value * weight[ct_dir] - wat_nbr[ct_dir];
			    }
			    valued = wat_nbr[ct_dir];
			    wa.wat = valued;
			    wa.ele = ele_nbr[ct_dir];
			    seg_put(&watalt, (char *)&wa, r_nbr, c_nbr);

			    /* get main drainage direction */
			    if (ABS(wat_nbr[ct_dir]) >= max_acc) {
				max_acc = ABS(wat_nbr[ct_dir]);
				r_max = r_nbr;
				c_max = c_nbr;
				max_side = ct_dir;
			    }
			}
			else if (ct_dir == np_side) {
			    /* check for consistency with A * path */
			    workedon++;
			}
		    }
		}

		/* adjust main drainage direction to A* path if possible */
		/*if (fabs(wat_nbr[np_side]) >= max_acc) {
		    max_acc = fabs(wat_nbr[np_side]);
		    r_max = dr;
		    c_max = dc;
		} */

		if (ABS(prop - 1.0) > 5E-6f) {
		    G_warning(_("MFD: cumulative proportion of flow distribution not 1.0 but %f"),
			      prop);
		}
	    }
	    /* SFD-like accumulation */
	    else {
		valued = wat_nbr[np_side];
		if (value > 0) {
		    if (valued > 0)
			valued += value;
		    else
			valued -= value;
		}
		else {
		    if (valued < 0)
			valued += value;
		    else
			valued = value - valued;
		}
		wa.wat = valued;
		wa.ele = ele_nbr[np_side];
		seg_put(&watalt, (char *)&wa, dr, dc);
	    }

	    /* update asp */
	    if (dr != r_max || dc != c_max) {
		if (asp_val < 0) {
		    asp_val = -1 * drain[r - r_max + 1][c - c_max + 1];
		}
		else
		    asp_val = drain[r - r_max + 1][c - c_max + 1];
		    
		bseg_put(&asp, &asp_val, r, c);
	    }
	    is_swale = FLAG_GET(this_flag_value, SWALEFLAG);
	    /* start new stream */
	    value = ABS(value) + 0.5;
	    if (!is_swale && (int)value >= threshold && stream_cells < 1 &&
		swale_cells < 1 && !flat) {
		FLAG_SET(this_flag_value, SWALEFLAG);
		is_swale = 1;
	    }
	    /* continue stream */
	    if (is_swale) {
		flag_value = flag_nbr[max_side];
		FLAG_SET(flag_value, SWALEFLAG);
		bseg_put(&bitflags, &flag_value, r_max, c_max);
	    }
	    else {
		if (er_flag && !is_swale && !FLAG_GET(this_flag_value, RUSLEBLOCKFLAG))
		    slope_length(r, c, r_max, c_max);
	    }
	}
	bseg_put(&bitflags, &this_flag_value, r, c);
    }
    G_percent(do_points, do_points, 1);	/* finish it */
    
    if (workedon)
	G_warning(_("MFD: A * path already processed when distributing flow: %d of %d cells"),
		  workedon, do_points);

    seg_close(&astar_pts);
    
    G_free(dist_to_nbr);
    G_free(weight);
    G_free(wat_nbr);
    G_free(ele_nbr);
    G_free(flag_nbr);

    return 0;
}
Ejemplo n.º 26
0
int write_grid(struct grid_description *grid_info, struct Map_info *Map, int nbreaks, int out_type)
{

    int i, k, j;
    int rows, cols;
    int num_v_rows, num_v_cols;
    double x, y, x_len, y_len;
    double sx, sy;
    double width, length;
    double next_x, next_y;
    double snext_x, snext_y;
    double angle, dum;

    struct line_pnts *Points;

    Points = Vect_new_line_struct();

    num_v_rows = grid_info->num_vect_rows;
    num_v_cols = grid_info->num_vect_cols;
    rows = grid_info->num_rows;
    cols = grid_info->num_cols;
    width = grid_info->width;
    length = grid_info->length;
    angle = grid_info->angle;

    /*
     * For latlon, must draw in shorter sections
     * to make sure that each section of the grid
     * line is less than half way around the globe
     */
     x_len = length / (1. * nbreaks + 1);
     y_len = width / (1. * nbreaks + 1);

    /* write out all the vector lengths (x vectors) of the entire grid  */
    G_verbose_message(_("Writing out vector rows..."));
    y = grid_info->origin_y;
    for (i = 0; i < num_v_rows; ++i) {
	double startx;

	startx = grid_info->origin_x;
	G_percent(i, num_v_rows, 2);

	for (k = 0; k < cols; k++) {
	    x = startx;
            j = 0;
	    do {
		if (j < nbreaks)
		    next_x = x + x_len;
		else
		    next_x = startx + length;

		sx = x;
		sy = y;
		snext_x = next_x;
		dum = y;

		rotate(&x, &y, grid_info->origin_x, grid_info->origin_y,
		       angle);
		rotate(&next_x, &dum, grid_info->origin_x,
		       grid_info->origin_y, angle);
		write_vect(x, y, next_x, dum, Map, Points, out_type);

		y = sy;
		x = next_x = snext_x;
                j++;
	    } while (j <= nbreaks);
	    startx += length;
	}
	y += width;
    }

    /* write out all the vector widths (y vectors) of the entire grid  */
    G_verbose_message(_("Writing out vector columns..."));
    x = grid_info->origin_x;
    for (i = 0; i < num_v_cols; ++i) {
        double starty;
	starty = grid_info->origin_y;
	G_percent(i, num_v_cols, 2);

	for (k = 0; k < rows; k++) {
	  y = starty;
	  j = 0;
	  do {
	      if (j < nbreaks)
		  next_y = y + y_len;
	      else
		  next_y = starty + width;

	      sx = x;
	      sy = y;
	      snext_y = next_y;
	      dum = x;
	      rotate(&x, &y, grid_info->origin_x, grid_info->origin_y, angle);
	      rotate(&dum, &next_y, grid_info->origin_x, grid_info->origin_y,
		    angle);

	      write_vect(x, y, dum, next_y, Map, Points, out_type);

	      x = sx;
	      y = next_y = snext_y;
	      j++;
	  } while (j <= nbreaks);
	  /* To get exactly the same coordinates as above, y+=width is wrong */
	  starty += width;
	}
	x += length;
    }

    /* new with Vlib */
    Vect_destroy_line_struct(Points);

    return (0);
}
Ejemplo n.º 27
0
int main(int argc, char *argv[])
{
    struct Cell_head cellhd;	/*region+header info */
    char *mapset;		/*mapset name */
    int nrows, ncols;
    int row, col;
    struct GModule *module;
    struct Option *input, *input1, *input2, *input3, *input4, *input5, *output;
    struct History history;	/*metadata */
    struct Colors colors;	/*Color rules */

    /************************************/
    char *name, *name1, *name2;	/*input raster name */
    char *result;		/*output raster name */

    /*File Descriptors */
    int nfiles, nfiles1, nfiles2;
    int infd[MAXFILES], infd1[MAXFILES], infd2[MAXFILES];
    int outfd;

    /****************************************/
    /* Pointers for file names              */
    char **names;
    char **ptr;
    char **names1;
    char **ptr1;
    char **names2;
    char **ptr2;

    /****************************************/
    int DOYbeforeETa[MAXFILES], DOYafterETa[MAXFILES];
    int bfr, aft;

    /****************************************/
    int ok;
    int i = 0, j = 0;
    double etodoy;		/*minimum ETo DOY */
    double startperiod, endperiod;  /*first and last days (DOYs) of the period studied */
    void *inrast[MAXFILES], *inrast1[MAXFILES], *inrast2[MAXFILES];
    DCELL *outrast;
    CELL val1, val2;
    
    RASTER_MAP_TYPE in_data_type[MAXFILES];	/* ETa */
    RASTER_MAP_TYPE in_data_type1[MAXFILES];	/* DOY of ETa */
    RASTER_MAP_TYPE in_data_type2[MAXFILES];	/* ETo */
    RASTER_MAP_TYPE out_data_type = DCELL_TYPE;

    /************************************/
    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("imagery"));
    G_add_keyword(_("evapotranspiration"));
    module->description =_("Computes temporal integration of satellite "
			   "ET actual (ETa) following the daily ET reference "
			   "(ETo) from meteorological station(s).");
    
    /* Define the different options */
    input = G_define_standard_option(G_OPT_R_INPUTS);
    input->key = "eta";
    input->description = _("Names of satellite ETa raster maps [mm/d or cm/d]");

    input1 = G_define_standard_option(G_OPT_R_INPUTS);
    input1->key = "eta_doy";
    input1->description =
	_("Names of satellite ETa Day of Year (DOY) raster maps [0-400] [-]");

    input2 = G_define_standard_option(G_OPT_R_INPUTS);
    input2->key = "eto";
    input2->description =
	_("Names of meteorological station ETo raster maps [0-400] [mm/d or cm/d]");

    input3 = G_define_option();
    input3->key = "eto_doy_min";
    input3->type = TYPE_DOUBLE;
    input3->required = YES;
    input3->description = _("Value of DOY for ETo first day");
    
    input4 = G_define_option();
    input4->key = "start_period";
    input4->type = TYPE_DOUBLE;
    input4->required = YES;
    input4->description = _("Value of DOY for the first day of the period studied");

    input5 = G_define_option();
    input5->key = "end_period";
    input5->type = TYPE_DOUBLE;
    input5->required = YES;
    input5->description = _("Value of DOY for the last day of the period studied");

    output = G_define_standard_option(G_OPT_R_OUTPUT);
    
    /* init nfiles */
    nfiles = 1;
    nfiles1 = 1;
    nfiles2 = 1;

    /********************/

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

    ok = 1;
    names = input->answers;
    ptr = input->answers;
    names1 = input1->answers;
    ptr1 = input1->answers;
    names2 = input2->answers;
    ptr2 = input2->answers;
    etodoy = atof(input3->answer);
    startperiod = atof(input4->answer);
    endperiod = atof(input5->answer);
    result = output->answer;

    /****************************************/
    if (endperiod<startperiod) {
	G_fatal_error(_("The DOY for end_period can not be smaller than start_period"));
	ok = 0;
    }
    if (etodoy>startperiod) {
	G_fatal_error(_("The DOY for start_period can not be smaller than eto_doy_min"));
	ok = 0;
    }
    for (; *ptr != NULL; ptr++) {
	if (nfiles > MAXFILES)
	    G_fatal_error(_("Too many ETa files. Only %d allowed."),
			  MAXFILES);
	name = *ptr;
	/* Allocate input buffer */
	infd[nfiles] = Rast_open_old(name, "");
	Rast_get_cellhd(name, "", &cellhd);
	inrast[nfiles] = Rast_allocate_d_buf();
	nfiles++;
    }
    nfiles--;
    if (nfiles <= 1)
	G_fatal_error(_("The min specified input map is two"));
	
	/****************************************/
    for (; *ptr1 != NULL; ptr1++) {
	if (nfiles1 > MAXFILES)
	    G_fatal_error(_("Too many ETa_doy files. Only %d allowed."),
			  MAXFILES);
	name1 = *ptr1;
	/* Allocate input buffer */
	infd1[nfiles1] = Rast_open_old(name1, "");
	Rast_get_cellhd(name1, "", &cellhd);
	inrast1[nfiles1] = Rast_allocate_d_buf();
	nfiles1++;
    }
    nfiles1--;
    if (nfiles1 <= 1)
	G_fatal_error(_("The min specified input map is two"));


	/****************************************/
    if (nfiles != nfiles1)
	G_fatal_error(_("ETa and ETa_DOY file numbers are not equal!"));

	/****************************************/

    for (; *ptr2 != NULL; ptr2++) {
	if (nfiles > MAXFILES)
	    G_fatal_error(_("Too many ETo files. Only %d allowed."),
			  MAXFILES);
	name2 = *ptr2;
	/* Allocate input buffer */
	infd2[nfiles2] = Rast_open_old(name2, "");
	Rast_get_cellhd(name2, "", &cellhd);
	inrast2[nfiles2] = Rast_allocate_d_buf();
	nfiles2++;
    }
    nfiles2--;
    if (nfiles2 <= 1)
	G_fatal_error(_("The min specified input map is two"));

    /* Allocate output buffer, use input map data_type */
    nrows = Rast_window_rows();
    ncols = Rast_window_cols();
    outrast = Rast_allocate_d_buf();

    /* Create New raster files */
    outfd = Rast_open_new(result, 1);

    /*******************/
    /* Process pixels */
    double doy[MAXFILES];
    double sum[MAXFILES];

    for (row = 0; row < nrows; row++) 
    {
	DCELL d_out;
	DCELL d_ETrF[MAXFILES];
	DCELL d[MAXFILES];
	DCELL d1[MAXFILES];
	DCELL d2[MAXFILES];
	G_percent(row, nrows, 2);

	/* read input map */
	for (i = 1; i <= nfiles; i++) 
	    Rast_get_d_row(infd[i], inrast[i], row);
	
	for (i = 1; i <= nfiles1; i++) 
	    Rast_get_d_row(infd1[i], inrast1[i], row);

	for (i = 1; i <= nfiles2; i++) 
	    Rast_get_d_row (infd2[i], inrast2[i], row);

	/*process the data */
	for (col = 0; col < ncols; col++) 
        {
            int	d1_null=0;
            int	d_null=0;
	    for (i = 1; i <= nfiles; i++) 
            {
		    if (Rast_is_d_null_value(&((DCELL *) inrast[i])[col]))
		    	d_null=1;
		    else
	                d[i] = ((DCELL *) inrast[i])[col];
	    }
	    for (i = 1; i <= nfiles1; i++) 
            {
		    if (Rast_is_d_null_value(&((DCELL *) inrast1[i])[col]))
			d1_null=1;
		    else
	                d1[i] = ((DCELL *) inrast1[i])[col];
	    }

	    for (i = 1; i <= nfiles2; i++) 
		    d2[i] = ((DCELL *) inrast2[i])[col];

	    /* Find out the DOY of the eto image    */
	    for (i = 1; i <= nfiles1; i++) 
            {
		if ( d_null==1 || d1_null==1 )
			Rast_set_d_null_value(&outrast[col],1);	
		else
		{
			doy[i] = d1[i] - etodoy+1;
			if (Rast_is_d_null_value(&d2[(int)doy[i]]) || d2[(int)doy[i]]==0 )
				Rast_set_d_null_value(&outrast[col],1);
			else
				d_ETrF[i] = d[i] / d2[(int)doy[i]];
		} 
	    }

	    for (i = 1; i <= nfiles1; i++) 
            {
		/* do nothing	*/
		if ( d_null==1 || d1_null==1)
                {
			/*G_message("  null value ");*/
                }
		else
		{
			DOYbeforeETa[i]=0; DOYafterETa[i]=0;
			if (i == 1)   
				DOYbeforeETa[i] = startperiod;
			else
			{
 				int k=i-1;
				while (d1[k]>=startperiod )
				{
					if (d1[k]<0)	 // case were d1[k] is null
						k=k-1;					
					else
					{
						DOYbeforeETa[i] = 1+((d1[i] + d1[k])/2.0);
						break;
					}			
				}

			}
	
			if (i == nfiles1)  
				DOYafterETa[i] = endperiod;
			else
			{
				int k=i+1;
				while (d1[k]<=endperiod)
				{
					if (d1[k]<0)   // case were d1[k] is null
						k=k+1;
					else
					{
						DOYafterETa[i] = (d1[i] + d1[k]) / 2.0;
						break;
	   				}					
				}
			}
		}	
	    }

	    sum[MAXFILES] = 0.0;
	    for (i = 1; i <= nfiles1; i++) 
            {
		if(d_null==1 || d1_null==1)
                {
		    /* do nothing	 */
		} 
                else
                {
			if (DOYbeforeETa[i]==0 || DOYbeforeETa[i]==0 ) 	
                            Rast_set_d_null_value(&outrast[col],1);
			else 
                        {
				bfr = (int)DOYbeforeETa[i];
				aft = (int)DOYafterETa[i];
				sum[i]=0.0;
				for (j = bfr; j < aft; j++) 
					sum[i] += d2[(int)(j-etodoy+1)];
			}
		}
	    }
	
	    d_out = 0.0;
	    for (i = 1; i <= nfiles1; i++)
            {
		if(d_null==1 || d_null==1)
			Rast_set_d_null_value(&outrast[col],1);
		else
                {	
			d_out += d_ETrF[i] * sum[i];
		     	outrast[col] = d_out;
		}	
	    }
	}
	Rast_put_row(outfd, outrast, out_data_type);
    }

    for (i = 1; i <= nfiles; i++) {
	G_free(inrast[i]);
	Rast_close(infd[i]);
    }
    for (i = 1; i <= nfiles1; i++) {
	G_free(inrast1[i]);
	Rast_close(infd1[i]);
    }
    for (i = 1; i <= nfiles2; i++) {
	G_free(inrast2[i]);
	Rast_close(infd2[i]);
    }
    G_free(outrast);
    Rast_close(outfd);

    /* Color table from 0.0 to 10.0 */
    Rast_init_colors(&colors);
    val1 = 0;
    val2 = 10;
    Rast_add_c_color_rule(&val1, 0, 0, 0, &val2, 255, 255, 255, &colors);
    /* Metadata */
    Rast_short_history(result, "raster", &history);
    Rast_command_history(&history);
    Rast_write_history(result, &history);

    exit(EXIT_SUCCESS);
}
Ejemplo n.º 28
0
/*!
   \brief Remove duplicate features from vector map.

   Remove duplicate lines of given types from vector map. Duplicate
   lines may be optionally written to error map. Input map must be
   opened on level 2 for update. Categories are merged.
   GV_BUILD_BASE is sufficient.

   \param[in,out] Map vector map where duplicate lines will be deleted
   \param type type of line to be delete
   \param[out] Err vector map where duplicate lines will be written or NULL

   \return void
 */
void
Vect_remove_duplicates(struct Map_info *Map, int type, struct Map_info *Err)
{
    struct line_pnts *APoints, *BPoints;
    struct line_cats *ACats, *BCats, *Cats;
    int i, j, c, atype, btype, bline;
    int nlines, nbcats_orig;
    struct bound_box ABox;
    struct boxlist *List;
    int ndupl;


    APoints = Vect_new_line_struct();
    BPoints = Vect_new_line_struct();
    ACats = Vect_new_cats_struct();
    BCats = Vect_new_cats_struct();
    Cats = Vect_new_cats_struct();
    List = Vect_new_boxlist(0);

    nlines = Vect_get_num_lines(Map);

    G_debug(1, "nlines =  %d", nlines);
    /* Go through all lines in vector, for each select lines which overlap MBR of
     *  this line and check if some of them is identical. If someone is identical
     *  remove current line. (In each step just one line is deleted)
     */

    ndupl = 0;

    for (i = 1; i <= nlines; i++) {
	G_percent(i, nlines, 1);
	if (!Vect_line_alive(Map, i))
	    continue;

	atype = Vect_read_line(Map, APoints, ACats, i);
	if (!(atype & type))
	    continue;

	Vect_line_box(APoints, &ABox);
	Vect_select_lines_by_box(Map, &ABox, type, List);
	G_debug(3, "  %d lines selected by box", List->n_values);

	for (j = 0; j < List->n_values; j++) {
	    bline = List->id[j];
	    G_debug(3, "  j = %d bline = %d", j, bline);
	    if (i == bline)
		continue;

	    btype = Vect_read_line(Map, BPoints, BCats, bline);

	    /* check for duplicates */
	    if (!Vect_line_check_duplicate(APoints, BPoints, Vect_is_3d(Map)))
		continue;

	    /* Lines area identical -> remove current */
	    if (Err) {
		Vect_write_line(Err, atype, APoints, ACats);
	    }

	    Vect_delete_line(Map, i);

	    /* Merge categories */
	    nbcats_orig = BCats->n_cats;

	    for (c = 0; c < ACats->n_cats; c++)
		Vect_cat_set(BCats, ACats->field[c], ACats->cat[c]);

	    if (BCats->n_cats > nbcats_orig) {
		G_debug(4, "cats merged: n_cats %d -> %d", nbcats_orig,
			BCats->n_cats);
		Vect_rewrite_line(Map, bline, btype, BPoints, BCats);
	    }

	    ndupl++;

	    break;		/* line was deleted -> take the next one */
	}
	nlines = Vect_get_num_lines(Map);	/* For future when lines with cats will be rewritten */
	G_debug(3, "nlines =  %d\n", nlines);
    }
    G_verbose_message("Removed duplicates: %d", ndupl);
}
Ejemplo n.º 29
0
int main(int argc, char *argv[])
{
    struct GModule *module;
    struct {
        struct Option *input, *output, *zshift, *height, *elevation, *hcolumn,
            *type, *field, *cats, *where, *interp, *scale, *null;
    } opt;
    struct {
        struct Flag *trace;
    } flag;
    
    struct Map_info In, Out;
    struct line_pnts *Points;
    struct line_cats *Cats;
    struct bound_box map_box;

    struct cat_list *cat_list;
    
    struct Cell_head window;
    
    int field;
    int only_type, cat;
    int fdrast, interp_method, trace;
    double objheight, objheight_default, voffset;
    double scale, null_val;
    
    struct field_info *Fi;
    dbDriver *driver = NULL;
    
    char *comment;
    
    module = G_define_module();
    G_add_keyword(_("vector"));
    G_add_keyword(_("geometry"));
    G_add_keyword(_("sampling"));
    G_add_keyword(_("3D"));
    module->label =
	_("Extrudes flat vector features to 3D vector features with defined height.");
    module->description = 
        _("Optionally the height can be derived from sampling of elevation raster map.");
    
    flag.trace = G_define_flag();
    flag.trace->key = 't';
    flag.trace->description = _("Trace elevation");
    flag.trace->guisection = _("Elevation");

    opt.input = G_define_standard_option(G_OPT_V_INPUT);

    opt.field = G_define_standard_option(G_OPT_V_FIELD_ALL);
    opt.field->guisection = _("Selection");

    opt.cats = G_define_standard_option(G_OPT_V_CATS);
    opt.cats->guisection = _("Selection");
    
    opt.where = G_define_standard_option(G_OPT_DB_WHERE);
    opt.where->guisection = _("Selection");

    opt.type = G_define_standard_option(G_OPT_V_TYPE);
    opt.type->answer = "point,line,area";
    opt.type->options = "point,line,area";
    opt.type->guisection = _("Selection");

    opt.output = G_define_standard_option(G_OPT_V_OUTPUT);

    opt.zshift = G_define_option();
    opt.zshift->key = "zshift";
    opt.zshift->description = _("Shifting value for z coordinates");
    opt.zshift->type = TYPE_DOUBLE;
    opt.zshift->required = NO;
    opt.zshift->answer = "0";
    opt.zshift->guisection = _("Height");

    opt.height = G_define_option();
    opt.height->key = "height";
    opt.height->type = TYPE_DOUBLE;
    opt.height->required = NO;
    opt.height->multiple = NO;
    opt.height->description = _("Fixed height for 3D vector features");
    opt.height->guisection = _("Height");

    opt.hcolumn = G_define_standard_option(G_OPT_DB_COLUMN);
    opt.hcolumn->key = "height_column";
    opt.hcolumn->multiple = NO;
    opt.hcolumn->description = _("Name of attribute column with feature height");
    opt.hcolumn->guisection = _("Height");
 
    /* raster sampling */
    opt.elevation = G_define_standard_option(G_OPT_R_ELEV);
    opt.elevation->required = NO;
    opt.elevation->description = _("Elevation raster map for height extraction");
    opt.elevation->guisection = _("Elevation");

    opt.interp = G_define_standard_option(G_OPT_R_INTERP_TYPE);
    opt.interp->answer = "nearest";
    opt.interp->guisection = _("Elevation");

    opt.scale = G_define_option();
    opt.scale->key = "scale";
    opt.scale->type = TYPE_DOUBLE;
    opt.scale->description = _("Scale factor sampled raster values");
    opt.scale->answer = "1.0";
    opt.scale->guisection = _("Elevation");

    opt.null = G_define_option();
    opt.null->key = "null_value";
    opt.null->type = TYPE_DOUBLE;
    opt.null->description =
	_("Height for sampled raster NULL values");
    opt.null->guisection = _("Elevation");

    G_gisinit(argv[0]);

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

    if (!opt.height->answer && !opt.hcolumn->answer) {
	G_fatal_error(_("One of '%s' or '%s' parameters must be set"),
		      opt.height->key, opt.hcolumn->key);
    }

    sscanf(opt.zshift->answer, "%lf", &voffset);
    G_debug(1, "voffset = %f", voffset);
    
    if (opt.height->answer)
	sscanf(opt.height->answer, "%lf", &objheight);
    else
	objheight = 0.;
    G_debug(1, "objheight = %f", objheight);
    objheight_default = objheight;

    only_type = Vect_option_to_types(opt.type);

    /* sampling method */
    interp_method = Rast_option_to_interp_type(opt.interp);

    /* used to scale sampled raster values */
    scale = atof(opt.scale->answer);

    /* is null value defined */
    if (opt.null->answer)
	null_val = atof(opt.null->answer);

    /* trace elevation */
    trace = flag.trace->answer ? TRUE : FALSE;
    
    /* set input vector map name and mapset */
    Vect_check_input_output_name(opt.input->answer, opt.output->answer, G_FATAL_EXIT);

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

    Vect_set_open_level(2); /* topology required for input */

    /* opening input vector map */
    if (Vect_open_old2(&In, opt.input->answer, "", opt.field->answer) < 0)
	G_fatal_error(_("Unable to open vector map <%s>"), opt.input->answer);

    Vect_set_error_handler_io(&In, &Out);

    /* creating output vector map */
    if (Vect_open_new(&Out, opt.output->answer, WITH_Z) < 0)
	G_fatal_error(_("Unable to create vector map <%s>"),
			opt.output->answer);

    field = Vect_get_field_number(&In, opt.field->answer);

    if ((opt.hcolumn->answer || opt.cats->answer || opt.where->answer) && field == -1) {
        G_warning(_("Invalid layer number (%d). "
                    "Parameter '%s', '%s' or '%s' specified, assuming layer '1'."),
                  field, opt.hcolumn->key, opt.cats->key, opt.where->key);
        field = 1;
    }

    /* set constraint for cats or where */
    cat_list = NULL;
    if (field > 0)
	cat_list = Vect_cats_set_constraint(&In, field, opt.where->answer,
                                            opt.cats->answer);
    
    
    Vect_hist_copy(&In, &Out);
    Vect_hist_command(&Out);

    /* opening database connection, if required */
    if (opt.hcolumn->answer) {
        int ctype;
        dbColumn *column;
        
	if ((Fi = Vect_get_field(&In, field)) == NULL)
	    G_fatal_error(_("Database connection not defined for layer %d"),
			  field);

	if ((driver =
	     db_start_driver_open_database(Fi->driver, Fi->database)) == NULL)
	    G_fatal_error(_("Unable to open database <%s> by driver <%s>"),
			  Fi->database, Fi->driver);
        db_set_error_handler_driver(driver);
        
	if (db_get_column(driver, Fi->table, opt.hcolumn->answer, &column) != DB_OK)
	    G_fatal_error(_("Column <%s> does not exist"),
			  opt.hcolumn->answer);
	else
	    db_free_column(column);

	ctype = db_column_Ctype(driver, Fi->table, opt.hcolumn->answer);

	if (ctype != DB_C_TYPE_INT && ctype != DB_C_TYPE_STRING &&
	    ctype != DB_C_TYPE_DOUBLE) {
	    G_fatal_error(_("Column <%s>: invalid data type"),
			  opt.hcolumn->answer);
	}
    }

    /* do we work with elevation raster? */
    fdrast = -1;
    if (opt.elevation->answer) {
	/* raster setup */
	G_get_window(&window);

	/* open the elev raster, and check for error condition */
	fdrast = Rast_open_old(opt.elevation->answer, "");
    }

    /* if area */
    if (only_type & GV_AREA) {
        int area, nareas, centroid;
        
        nareas = Vect_get_num_areas(&In);
	G_debug(2, "n_areas = %d", nareas);
	if (nareas > 0)
	    G_message(_("Extruding areas..."));
	for (area = 1; area <= nareas; area++) {
	    G_debug(3, "area = %d", area);
	    G_percent(area, nareas, 2);
            
	    if (!Vect_area_alive(&In, area))
		continue;
            
	    centroid = Vect_get_area_centroid(&In, area);
	    if (!centroid) {
		G_warning(_("Skipping area %d without centroid"), area);
		continue;
	    }

	    Vect_read_line(&In, NULL, Cats, centroid);
	    if (field > 0 && !Vect_cats_in_constraint(Cats, field, cat_list))
		continue;
            
	    /* height attribute */
	    if (opt.hcolumn->answer) {
		cat = Vect_get_area_cat(&In, area, field);
                if (cat == -1) {
                    G_warning(_("No category defined for area %d. Using default fixed height %f."),
                              area, objheight_default);
                    objheight = objheight_default;
                }
                if (get_height(Fi, opt.hcolumn->answer,
                               driver, cat, &objheight) != 0) {
                    G_warning(_("Unable to fetch height from DB for area %d. Using default fixed height %f."),
                              area, objheight_default);
                    objheight = objheight_default;
                }
	    } /* if opt.hcolumn->answer */

	    Vect_get_area_points(&In, area, Points);

	    G_debug(3, "area: %d height: %f", area, objheight);

	    extrude(&In, &Out, Cats, Points,
		    fdrast, trace, interp_method, scale,
                    opt.null->answer ? TRUE : FALSE, null_val,
                    objheight, voffset, &window, GV_AREA,
		    centroid);
	} /* foreach area */

    }

    if (only_type > 0) {
        int line, nlines;
        int type;
        
	G_debug(1, "other than areas");
	/* loop through each line in the dataset */
        nlines = Vect_get_num_lines(&In);
	G_message(_("Extruding features..."));
	for (line = 1; line <= nlines; line++) {
	    /* progress feedback */
	    G_percent(line, nlines, 2);

	    if (!Vect_line_alive(&In, line))
		continue;

	    /* read line */
	    type = Vect_read_line(&In, Points, Cats, line);

	    if (!(type & only_type))
		continue;

	    if (field > 0 && !Vect_cats_in_constraint(Cats, field, cat_list))
		continue;

	    /* height attribute */
	    if (opt.hcolumn->answer) {
		cat = Vect_get_line_cat(&In, line, field);
                if (cat == -1) {
                    G_warning(_("No category defined for feature %d. Using default fixed height %f."),
                              line, objheight_default);
                    objheight = objheight_default;
                }
                if (get_height(Fi, opt.hcolumn->answer,
                               driver, cat, &objheight) != 0) {
                    G_warning(_("Unable to fetch height from DB for line %d. Using default fixed height %f."),
                              line, objheight_default);
                    objheight = objheight_default;
                }
	    } /* if opt.hcolumn->answer */
            
	    extrude(&In, &Out, Cats, Points,
		    fdrast, trace, interp_method, scale,
                    opt.null->answer ? TRUE : FALSE, null_val,
                    objheight, voffset, &window, type, -1);
	} /* for each line */
    }	  /* else if area */

    if (driver) {
	db_close_database(driver);
	db_shutdown_driver(driver);
    }

    G_important_message(_("Copying attribute table..."));
    if (field < 0)
        Vect_copy_tables(&In, &Out, 0);
    else 
        Vect_copy_table_by_cat_list(&In, &Out, field, field, NULL,
                                    GV_1TABLE, cat_list);
    
    Vect_build(&Out);

    /* header */
    G_asprintf(&comment, "Generated by %s from vector map <%s>",
	       G_program_name(), Vect_get_full_name(&In));
    Vect_set_comment(&Out, comment);
    G_free(comment);

    Vect_get_map_box(&Out, &map_box);

    Vect_close(&In);
    Vect_close(&Out);

    Vect_destroy_line_struct(Points);
    Vect_destroy_cats_struct(Cats);

    G_done_msg("T: %f B: %f.", map_box.T, map_box.B);
    
    exit(EXIT_SUCCESS);
}
Ejemplo n.º 30
0
/* ************************************************************************* */
void write_vtk_rgb_data(void *map_r, void *map_g, void *map_b,
                        FILE * fp, const char *varname,
                        RASTER3D_Region region, int dp)
{
    double value = 0;
    int x, y, z, percentage, k;
    int rows, cols, depths;
    int typeIntern[3];
    void *maprgb = NULL;

    G_debug(3, "write_vtk_rgb_data: Writing RGB data");

    rows = region.rows;
    cols = region.cols;
    depths = region.depths;

    typeIntern[0] = Rast3d_tile_type_map(map_r);
    typeIntern[1] = Rast3d_tile_type_map(map_g);
    typeIntern[2] = Rast3d_tile_type_map(map_b);

    percentage = 0;

    /********************** WRITE RGB VOXEL DATA; CELL OR POINT ****************/
    fprintf(fp, "COLOR_SCALARS %s 3\n", varname);

    for (z = 0; z < depths; z++) {
        for (y = 0; y < rows; y++) {
            G_percent(percentage, (rows * depths - 1), 10);
            percentage++;

            for (x = 0; x < cols; x++) {
                for (k = 0; k < 3; k++) {

                    if (k == 0)
                        maprgb = map_r;
                    if (k == 1)
                        maprgb = map_g;
                    if (k == 2)
                        maprgb = map_b;

                    /* In case of structured grid data, the point/cell coordinates
                       are computed based on the default north->south raster3d coordinate system.
                       We need to compute south -> north ordering for image data.
                     */
                    if (!param.structgrid->answer)
                        value =
                        get_g3d_raster_value_as_double(maprgb, x, rows - y - 1, z,
                                                       typeIntern[k],
                                                       0.0);
                    else
                        value =
                        get_g3d_raster_value_as_double(maprgb, x, y, z,
                                                       typeIntern[k],
                                                       0.0);
                    /*Test of value range, the data should be 1 byte gray values */
                    if (value > 255 || value < 0) {
                        G_warning(_("Wrong 3d raster map values! Values should in between 0 and 255!\n"));
                        fprintf(fp, "0 ");
                    } else {

                        fprintf(fp, "%.*f ", dp, (value / 255));
                    }
                }
                fprintf(fp, "\n");
            }
        }
    }
    return;
}