Esempio n. 1
0
static int ask_camera(char *prompt, char *camera)
{
    char buf[1024];

    while (1) {
	fprintf(stderr, "\n%s\n", prompt);
	fprintf(stderr, "Enter 'list' for a list of existing camera files\n");
	fprintf(stderr, "Enter 'list -f' for a verbose listing\n");
	fprintf(stderr, "Hit RETURN %s\n", G_get_ask_return_msg());
	fprintf(stderr, "> ");
	if (!G_gets(buf))
	    continue;

	G_squeeze(buf);
	fprintf(stderr, "<%s>\n", buf);
	if (*buf == 0)
	    return 0;

	if (strcmp(buf, "list") == 0)
	    I_list_cameras(0);
	else if (strcmp(buf, "list -f") == 0)
	    I_list_cameras(1);
	else if (G_legal_filename(buf) < 0)
	    fprintf(stderr, "\n** <%s> - illegal name **\n\n", buf);
	else
	    break;
    }
    strcpy(camera, buf);
    return 1;
}
Esempio n. 2
0
/* return NULL on error: otherwise returns dspout */
char *check_get_any_dspname(char *dspf, char *g3f, char *mset)
{
    char element[200], question[200];
    static char dspout[200];

    if (!G_legal_filename(dspf))
	return (NULL);

    if (!G_find_grid3(g3f, ""))
	G_fatal_error("[%s] 3D raster map not found", g3f);

    if (mset) {			/* otherwise must be reading only  */
	if (g3_find_dsp_file(g3f, dspf, mset)) {	/* already exists */
	    sprintf(question, "\n** %s exists. ok to overwrite? ", dspf);
	    if (!G_yes(question, 0)) {
		if (NULL == G_ask_any("", dspout, element, "display", 1))
		    return (NULL);

		return (dspout);
	    }
	    /* or else just print a warning & use it as is */
	}
    }

    strcpy(dspout, dspf);

    return (dspout);
}
Esempio n. 3
0
/*!
  \brief Lowest level open routine.

  Opens the file <i>name</i> in <i>element</i> ("cell", etc.) in mapset <i>mapset</i>
  according to the i/o <i>mode</i>.

   - mode = 0 (read) will look for <i>name</i> in <i>mapset</i> and
               open the file for read only the file must exist
 
   - mode = 1 (write) will create an empty file <i>name</i> in the
               current mapset and open the file for write only
               <i>mapset</i> ignored

   - mode = 2 (read and write) will open a file in the current mapset
               for reading and writing creating a new file if
               necessary <i>mapset</i> ignored

  \param element database element name
  \param name map file name
  \param mapset mapset containing map <i>name</i>
  \param mode r/w mode 0=read, 1=write, 2=read/write
 
  \return open file descriptor (int)
  \return -1 could not open
*/
static int G__open(const char *element,
		   const char *name, const char *mapset, int mode)
{
    char path[GPATH_MAX];
    char xname[GNAME_MAX], xmapset[GMAPSET_MAX];


    G__check_gisinit();

    /* READ */
    if (mode == 0) {
	if (G_name_is_fully_qualified(name, xname, xmapset)) {
	    if (*mapset && strcmp(xmapset, mapset) != 0) {
		G_warning(_("G__open(read): mapset <%s> doesn't match xmapset <%s>"),
			  mapset, xmapset);
		return -1;
	    }
	    name = xname;
	    mapset = xmapset;
	}
	else if (!mapset || !*mapset)
	    mapset = G_find_file2(element, name, mapset);

	if (!mapset)
	    return -1;

	G_file_name(path, element, name, mapset);

	return open(path, 0);
    }
    /* WRITE */
    if (mode == 1 || mode == 2) {
	mapset = G_mapset();
	if (G_name_is_fully_qualified(name, xname, xmapset)) {
	    if (strcmp(xmapset, mapset) != 0) {
		G_warning(_("G__open(write): xmapset <%s> != G_mapset() <%s>"),
			  xmapset, mapset);
		return -1;
	    }
	    name = xname;
	}

	if (*name && G_legal_filename(name) == -1)
	    return -1;

	G_file_name(path, element, name, mapset);

	if (mode == 1 || access(path, 0) != 0) {
	    G__make_mapset_element(element);
	    close(open(path, O_WRONLY | O_CREAT | O_TRUNC, 0666));
	}

	return open(path, mode);
    }
    return -1;
}
Esempio n. 4
0
/* ---------------------------------------------------------------------- */
void check_args() {

  /* check if filled elevation grid name is  valid */
  if (G_legal_filename (opt->filled_grid) < 0) {
    G_fatal_error(_("<%s> is an illegal file name"), opt->filled_grid);
  }
  /* check if output grid names are valid */
  if (G_legal_filename (opt->dir_grid) < 0) {
    G_fatal_error(_("<%s> is an illegal file name"), opt->dir_grid);
  }
  if (G_legal_filename (opt->filled_grid) < 0) {
    G_fatal_error(_("<%s> is an illegal file name"), opt->filled_grid);
  }
  if (G_legal_filename (opt->flowaccu_grid) < 0) {
    G_fatal_error(_("<%s> is an illegal file name"), opt->flowaccu_grid);
  }
  if (G_legal_filename (opt->watershed_grid) < 0) {
    G_fatal_error(_("<%s> is an illegal file name"), opt->watershed_grid);
  }
#ifdef OUTPU_TCI
  if (G_legal_filename (opt->tci_grid) < 0) {
  G_fatal_error(_("<%s> is an illegal file name"), opt->tci_grid);
  }
#endif
  
  /* check compatibility with region */
  check_header(opt->elev_grid);

  /* what else ? */  


}
Esempio n. 5
0
char *construct_pattern(char **names)
{
    char *pattern, *p;
    int i, len, found_illegal_names;
    const char *mapset;
    char xname[GNAME_MAX], xmapset[GMAPSET_MAX];

    len = 0;
    for (i = 0; names[i]; i++) {
	if ((p = strchr(names[i], '@')))
	    len += p - names[i];
	else
	    len += strlen(names[i]);
    }
    len += i; /* # names - 1 commas + \0 */

    pattern = p = (char *)G_malloc(len);

    mapset = G_mapset();
    found_illegal_names = 0;

    for (i = 0; names[i]; i++) {
	char *name;

	name = names[i];
	if (G_name_is_fully_qualified(name, xname, xmapset)) {
	    if (strcmp(xmapset, mapset) != 0)
		G_fatal_error(_("%s: Cannot remove or exclude files not in "
				"the current mapset."), name);
	    name = xname;
	}

	if (G_legal_filename(name) == -1)
	    found_illegal_names = 1;

	if (i)
	    *p++ = ',';
	strcpy(p, name);
	p += strlen(name);
    }

    if (found_illegal_names)
	G_fatal_error(_("Illegal filenames not allowed in the names or ignore "
			"option."));

    return pattern;
}
Esempio n. 6
0
/* checks if user-supplied parameters are valid */
int
check_parms (char *map_answer, char *input_answer, char *output_answer, int all )
{

	if ( map_answer != NULL ) {
		if ((G_find_file ("fcell", map_answer, "") == NULL)
	    	&& (G_find_file ("dcell", map_answer, "") == NULL)
	    	&& (G_find_file ("cell", map_answer, "") == NULL))	
		{
			/* no coverage map found */
			G_fatal_error
				("No raster map exists with the given name.");
		}
		
		/* specifying all means to disregard the map! */
		if ( all == 1 ) {
			G_warning ("Map was specified, but the -a flag disregards map values!\n Your results might not be what you expect.");
		}
	}

	/* check if sample sites exist */
	if (G_find_file ("vector", input_answer, "") == NULL)
	{
		G_fatal_error
			("No sample/sites list exists with the given name!");
	}	

	/* check if a legal file name was given for output map
	   this just overwrites existing sites */ 
	if (G_legal_filename (output_answer) == -1)
	{
		G_fatal_error
			("Name chosen for result map is not a valid file name!");
	}
		
	/* return raster mode to caller */
	if ( map_answer != NULL ) {
		return (G_raster_map_type (map_answer,""));
	}
	else return (-1);
}
Esempio n. 7
0
File: main.c Progetto: lichinka/cai
/*
 * main function
 */
int main(int argc, char *argv[])
{

/*    struct Cell_head window;	     database window         */
    struct Cell_head cellhd;	/* it stores region information,
				   and header information of rasters */
    char *name, *name2;			/* input raster name */
    char *result;		/* output raster name */
    char *mapset;		/* mapset name */
    void *inrast;		/* input buffer */
    unsigned char *outrast;	/* output buffer */
    int nrows, ncols;
    int row, col;
    int infd, outfd;		/* file descriptor */
    int verbose;
    struct History history;	/* holds meta-data (title, comments,..) */

    struct GModule *module;	/* GRASS module for parsing arguments */

    struct Option *input, *output, *input2;	/* options */
    FILE *in;			/*file for Path loss factors*/
	
    struct Flag *flag1;		/* flags */
   	
   char buffer_out[1000];
        
        
	strcpy(buffer_out,getenv("GISBASE"));
	strcat(buffer_out,"/etc/radio_coverage/lossfactors_new.txt");
	/*G_message(_("1!! Pot1: %s, Pot2: %s"), buffer_path, buffer_path1);     
	buffer_out=strcat(buffer_path,buffer_path1);
	G_message(_("Pot1: %s, Pot2: %s"), buffer_path, buffer_path1);*/

    /* initialize GIS environment */
    G_gisinit(argv[0]);		/* reads grass env, stores program name to G_program_name() */

    /* initialize module */
    module = G_define_module();
    module->keywords = _("raster, clutter");
    module->description = _("Clutter convert module");

    /* Define the different options as defined in gis.h */
    input = G_define_standard_option(G_OPT_R_INPUT);

    input2 = G_define_standard_option(G_OPT_F_INPUT);
    input2->key = "Path_loss_values";
    input2->type = TYPE_STRING;
    input2->required = YES;
    input2->answer = buffer_out;//getenv("GISBASE"); //strcat(buffer_path1,(char *)getenv("GISBASE"));//,"/etc/radio_coverage");
    input2->gisprompt = "old_file,file,input";
    input2->description = _("Path loss factors for land usage");
  
    /* Define the different flags */
     flag1 = G_define_flag();
     flag1->key = 'o';
     flag1->description = _("Old_Cipher");     

    output = G_define_standard_option(G_OPT_R_OUTPUT);
	
    /* options and flags parser */
    if (G_parser(argc, argv))
	{
	exit(EXIT_FAILURE);
	}
      

        /*G_message(_("1!! Pot1: %s, Pot2: %s"), buffer_path, buffer_path1);     
	strcat(buffer_path,buffer_path1);
	G_message(_("Pot1: %s, Pot2: %s"), buffer_path, buffer_path1);
        input2->answer = buffer_path;//getenv("GISBASE"); //strcat(buffer_path1,(char *)getenv("GISBASE"));//,"/etc/radio_coverage");*/

/* stores options and flags to variables */
    name = input->answer;
    name2 = input2->answer;
    result = output->answer;
    verbose = (flag1->answer);
	
G_message(_("Verbose: %d"),verbose);  

    /* returns NULL if the map was not found in any mapset, 
     * mapset name otherwise */
//G_message(_("3_START"));

    mapset = G_find_cell2(name, "");
    if (mapset == NULL)
	G_fatal_error(_("Raster map <%s> not found"), name);
       
    if (G_legal_filename(result) < 0)
	G_fatal_error(_("<%s> is an illegal file name"), result);

    /* G_open_cell_old - returns file destriptor (>0) */
    if ((infd = G_open_cell_old(name, mapset)) < 0)
	G_fatal_error(_("Unable to open raster map <%s>"), name);

       /* controlling, if we can open input raster */   
    if (G_get_cellhd(name, mapset, &cellhd) < 0)
	G_fatal_error(_("Unable to read file header of <%s>"), name);

    G_debug(3, "number of rows %d", cellhd.rows);

	G_set_window(&cellhd);
	G_get_set_window(&cellhd);

    /* Allocate input buffer */
    inrast = G_allocate_raster_buf(FCELL_TYPE);

    /* Allocate output buffer, use input map data_type */
    nrows = G_window_rows();
    ncols = G_window_cols();
    outrast = G_allocate_raster_buf(FCELL_TYPE);

G_message(_("nrows %d and ncols %d"),nrows,ncols);

    /* controlling, if we can write the raster */
    if ((outfd = G_open_raster_new(result, FCELL_TYPE)) < 0)
	G_fatal_error(_("Unable to create raster map <%s>"), result);
 
/* do Clutter Convert */

    /* open file for model tuning parameters*/
    char fileName[150];
    strcpy (fileName, name2);

//G_message(_("Path: %s"),name2); 

    if( (in = fopen(fileName,"r")) == NULL )
		G_fatal_error(_("Unable to open file <%s>"), fileName);  
    
    char buffer[256];
    double terr_path_loss[100];
    int counter=0;  
    fgets (buffer, 250, in);	

    while(fgets(buffer,250,in)!=NULL){
   	sscanf(buffer,"%lf %lf", &terr_path_loss[counter]);	
	counter++;
    }
    
    int cipher_cont=0;	
   /* old or new clutter */
    if (verbose == 1)
    {
	cipher_cont=1;  
	G_message(_("Parameter UR: %f, GP: %f, RP: %f, GI: %f, GL: %f, GM: %f, GR: %f, VO: %f, KM: %f, OD: %f"), terr_path_loss[0], terr_path_loss[1], terr_path_loss[2], terr_path_loss[3], terr_path_loss[4], terr_path_loss[5], terr_path_loss[6], terr_path_loss[7], terr_path_loss[8], terr_path_loss[9]);
    }
   else if (verbose == 0)
   {
	cipher_cont=11;
	G_message(_("Parameter UR1: %f, UR2: %f, UR3: %f, UR4: %f, UR5: %f, GI: %f, GL: %f, GM: %f, GR: %f, VO: %f, KM: %f, OD: %f"), terr_path_loss[0], terr_path_loss[1], terr_path_loss[2], terr_path_loss[3], terr_path_loss[4], terr_path_loss[5], terr_path_loss[6], terr_path_loss[7], terr_path_loss[8], terr_path_loss[9], terr_path_loss[10], terr_path_loss[11]);
   }


    G_message(_("Counter: %d"),counter); 
    G_message(_("cipher_cont: %d"),cipher_cont);      
    G_message(_("START"));

    /* for each row */
    for (row = 0; row < nrows; row++) 
      {	  

	  FCELL f_in, f_out;	  
	 
	/* read input map */
	if (G_get_raster_row(infd, inrast, row, FCELL_TYPE) < 0)
	  G_fatal_error(_("Unable to read raster map <%s> row %d"), name, row);
	 
	/* process the data */
	for (col = 0; col < ncols; col++) 
	  { 
	    f_in = ((FCELL *) inrast)[col];

	    //G_message(_("Input data: %d"),(int)f_in);
	        	      	     
	    f_out = terr_path_loss[(int)f_in-cipher_cont];
            	    
           //G_message(_("Output data: %f"),(double)f_out);

	    ((FCELL *) outrast)[col] = f_out;

	  }
      
	/* write raster row to output raster map */
	if (G_put_raster_row(outfd, outrast, FCELL_TYPE) < 0)
	  G_fatal_error(_("Failed writing raster map <%s>"), result);
      }
         
//G_message(_("END_clutconvert_test"));
G_message(_("END"));

    /* memory cleanup */
    G_free(inrast);
    G_free(outrast);

    /* closing raster maps */
    G_close_cell(infd);
    G_close_cell(outfd);

    /* add command line incantation to history file */
    G_short_history(result, "raster", &history);
    G_command_history(&history);
    G_write_history(result, &history);

    exit(EXIT_SUCCESS);
}
Esempio n. 8
0
int main(int argc, char *argv[])
{
	struct Cell_head cellhd; 
        struct Range range;
        char *name;                     /* input raster name */
	char *result;                   /* output raster name */
        char *mapset;                   /* mapset name */
	DCELL *inrast;                  /* input buffer */
	DCELL *outrast;                 /* output buffer */
	int row,col;
	int infd, outfd;                /* file descriptor */
	int verbose;
        double *weights;                /* array of weights */
        DCELL **D_rows;
        DCELL *tmp;
        int nrows;                      
        int ncols;
        double min, max;                /* raster map range */
        
	RASTER_MAP_TYPE data_type;      /* type of the map */
        void *values;                   /* neighborhood values */
        int n,i;                        /* number of neighborhood cells */
        int size;                       /* matrix size */
        double ssigma;                  /* sigma of the spatial part */
        double csigma;                  /* sigma of the color part */
        char title[1024];               /* map title */


	struct GModule *module;         /* GRASS module for parsing arguments */
	struct
	    {
		struct Option *input, *output;
		struct Option *sigma_s, *sigma_c, *size;
		struct Option *title;
	} parm;
	struct
	    {
		struct Flag *quiet;
		struct Flag *print_sigmas;
	} flag;

        /* initialize GIS environment */
	G_gisinit(argv[0]);     /* reads grass env, 
                                   stores program name to 
                                   G_program_name
                                   */

        /* initialize module */
	module = G_define_module();
	module->description = ("Gaussian filter for raster maps.");
					        
	/* Define the different options */
	parm.input = G_define_option() ;
	parm.input->key        = "input";
	parm.input->type       = TYPE_STRING;
	parm.input->required   = YES;
	parm.input->description= ("Name of an input layer" );

	parm.output = G_define_option() ;
	parm.output->key        = "output";
	parm.output->type       = TYPE_STRING;
	parm.output->required   = YES;
	parm.output->description= ("Name of an output layer");

	parm.sigma_s = G_define_option() ;
	parm.sigma_s->key        = "ssigma";
	parm.sigma_s->type       = TYPE_DOUBLE;
	parm.sigma_s->required   = NO;
	parm.sigma_s->description= ("Sigma for space part of the filter\n\t(default: 0.465*((size-1)/2)");

	parm.sigma_c = G_define_option() ;
	parm.sigma_c->key        = "csigma";
	parm.sigma_c->type       = TYPE_DOUBLE;
	parm.sigma_c->required   = NO;
	parm.sigma_c->description= ("Sigma for color part of the filter\n(default: 0.465*((color_range)/2)");

        parm.size = G_define_option() ;
	parm.size->key        = "size";
	parm.size->type       = TYPE_INTEGER;
	parm.size->required   = YES;
	parm.size->description= ("Size of the matrix (odd number)");

        flag.print_sigmas = G_define_flag() ;
	flag.print_sigmas->key         = 's' ;
	flag.print_sigmas->description = "Print calculated values for sigmas" ;
        
        flag.quiet = G_define_flag() ;
	flag.quiet->key         = 'q' ;
	flag.quiet->description = "Quiet" ;
        
        /* options and flags pareser */
	if (G_parser(argc, argv))
		exit (-1);
		
        /* stores options and flags to variables */
	name    = parm.input->answer;
	result  = parm.output->answer;
	verbose = (! flag.quiet->answer);
        sscanf(parm.size->answer, "%d", &size);
        if (!parm.sigma_s->answer)
            ssigma = 0.465*((size-1)/2);
        else 
            sscanf(parm.sigma_s->answer, "%lf", &ssigma);
      
        

        /* controlling the input values */
        if (size%2 == 0) 
            G_fatal_error("Size <%d> is not odd number", size);

	/* returs NULL if the map was not found in any mapset, 
         * mapset name otherwise*/
	mapset = G_find_cell2 (name, ""); 
        if (mapset == NULL)
                G_fatal_error ("cell file [%s] not found", name);

       /* color sigma next */
        if (!parm.sigma_c->answer) {
            if (G_read_range(name, mapset, &range) < 0) 
                G_fatal_error("Could not read the raster map range");
                
            /* for raster maps with range from 0-255 the result
             * should be around 60 
             */
            min = (double)range.min;
            max = (double)range.max;
            csigma = 0.456*(max - min)/2;
        }
        else
            sscanf(parm.sigma_c->answer, "%lf", &csigma);
        
        /* print if appropriate */
        if (flag.print_sigmas->answer)
            printf("Space sigma: %f\nColor sigma: %f\n", ssigma, csigma);

 
        if (G_legal_filename (result) < 0)
                G_fatal_error ("[%s] is an illegal name", result);

        /* count weights */
        weights = (double *)malloc(size * size * sizeof(double));
        /* stores values of gauss. bell into 'weigts'*/
        count_weights(weights, size, ssigma);
        
	/* determine the inputmap type (CELL/FCELL/DCELL) */
	data_type = G_raster_map_type(name, mapset);

        /* G_open_cell_old - returns file destriptor (>0) */
	if ( (infd = G_open_cell_old (name, mapset)) < 0)
		G_fatal_error ("Cannot open cell file [%s]", name);

        /* controlling, if we can open input raster */
	if (G_get_cellhd (name, mapset, &cellhd) < 0)
		G_fatal_error ("Cannot read file header of [%s]", name);

	/* Allocate input buffer */
	inrast = G_allocate_raster_buf(data_type);
	
	/* Allocate output buffer, use input map data_type */
	nrows = G_window_rows();
	ncols = G_window_cols();
	outrast = G_allocate_d_raster_buf();


        /* Allocate values buffers */
        values = (DCELL *) malloc(size * size * sizeof(DCELL));
        
        /* allocating memory for rows */
        D_rows = (DCELL **)malloc(size * sizeof(DCELL));
        for (i = 0; i < size; i++) {
            D_rows[i] = G_allocate_raster_buf(DCELL_TYPE);
        }
        
        if (values == NULL) 
            G_fatal_error("Cannot allocate memory");

        /* controlling, if we can write the raster */
	if ( (outfd = G_open_raster_new (result, data_type)) < 0)
		G_fatal_error ("Could not open <%s>",result);

        /* write first rows as NULL values */
        for (row = 0; row < size/2; row++) {
            G_set_d_null_value(outrast, ncols);
            if (G_put_d_raster_row (outfd, outrast) < 0)
                G_fatal_error ("Cannot write to <%s>",result);
        }

        /* allocate first size/2 rows */
        for (row = 0; row < size; row++) 
            if (G_get_d_raster_row(infd, D_rows[row], row) < 0)
		G_fatal_error ("Could not open <%s>",result);
            
        /****************************************************************/
        /* for each row inside the region */
	for ( row = size/2; row < nrows - size/2; row++) {
            

		if (verbose)
		    G_percent (row, nrows, 2);
                
                /* allocate new last row */
               G_get_d_raster_row(infd, D_rows[size-1], row+(size/2));

                /*process the data */
		for (col=0; col < ncols; col++){

                    /* skip the outside columns */
                    if ( (col - size/2) < 0 || ncols <= (col + size/2)) {
                        G_set_d_null_value(outrast, 1);
                    }
                    /* work only with columns, which are inside */
                    else {

                        /* store values of the matrix into arry 'values', 'n' is
                         * number of elements of the matrix */
                        n = D_gather(infd, values, D_rows, col, row,size);
                        ((DCELL *)outrast)[col] = D_bilateral(values, ssigma, csigma, size, weights);
		    }
                } /* for each column */

                /* write raster row to output raster file */
		G_put_d_raster_row (outfd, outrast);

                /* switch rows */
		tmp = D_rows[0];
                for (i = 0; i < size; i++){
                   D_rows[i] = D_rows[i + 1];
                }
		D_rows[size-1] = tmp;

	} /* for each row */
        
        /* write last rows as NULL values */
        for (i = 0; i < size/2; i++) {
            G_set_d_null_value(outrast, ncols);
            G_put_d_raster_row (outfd, outrast);
        }
 
        /* memory cleaning */
	G_free(outrast);
	G_free(inrast);
        G_free(values);

        for (i = 0; i < size; i++) {
            G_free(D_rows[i]);
        }
        free((void *) D_rows);


        /* closing rastr files */
	G_close_cell (infd);
	G_close_cell (outfd);

        /* set the map title */
        sprintf(title, "Bilateral filter of %s with %dx%d matrix: ssigma %.3f, csigma %.3f", name, size, size, ssigma, csigma ); 
        G_put_cell_title (result, title ); 

	return 0;
}
Esempio n. 9
0
/* in addition there seem to be some useful user options here which are not currently available from the main parser */
int com_line_Gwater(INPUT * input, OUTPUT * output)
{
    struct Cell_head *window;
    char map_layer[48], buf[100], *prog_name, *mapset;
    double d;
    int i;

    window = &(output->window);
    if (0 == G_yes("Continue?", 1))
	exit(EXIT_SUCCESS);

    input->haf_name = (char *)G_calloc(40, sizeof(char));
    input->accum_name = (char *)G_calloc(40, sizeof(char));

    G_message(_("\nThis set of questions will organize the command line for the"));
    G_message(_("%s program to run properly for your application."),
	      NON_NAME);
    G_message(_("The first question is whether you want %s to run"),
	      NON_NAME);
    G_message(_("in its fast mode or its slow mode.  If you run %s"),
	      NON_NAME);
    G_message(_("in the fast mode, the computer will finish about 10 times faster"));
    G_message(_("than in the slow mode, but will not allow other programs to run"));
    G_message(_("at the same time.  The fast mode also places all of the data into"));
    G_message(_("RAM, which limits the size of window that can be run.  The slow"));
    G_message(_("mode uses disk space in the same hard disk partition as where GRASS is"));
    G_message(_("stored.  Thus, if the program does not work in the slow mode, you will"));
    G_message(_("need to remove unnecessary files from that partition.  The slow mode"));
    G_message(_("will allow other processes to run concurrently with %s.\n"),
	      NON_NAME);

    sprintf(buf, "Do you want to use the fast mode of %s?", NON_NAME);
    input->com_line_ram = input->com_line_seg = NULL;
    input->fast = 0;
    input->slow = 0;
    if (G_yes(buf, 1)) {
	input->fast = 1;
	input->com_line_ram = (char *)G_calloc(400, sizeof(char));
	prog_name = G_store(RAM_NAME);
	sprintf(input->com_line_ram,
		"\"%s/etc/water/%s\"", G_gisbase(), RAM_NAME);
	fprintf(stderr,
		"\nIf there is not enough ram for the fast mode (%s) to run,\n",
		RAM_NAME);
	sprintf(buf, "should the slow mode (%s) be run instead?", SEG_NAME);
	if (G_yes(buf, 1)) {
	    input->slow = 1;
	    input->com_line_seg = (char *)G_calloc(400, sizeof(char));
	    sprintf(input->com_line_seg,
		    "\"%s/etc/water/%s\"", G_gisbase(), SEG_NAME);
	}
    }
    else {
	input->slow = 1;
	prog_name = G_store(SEG_NAME);
	input->com_line_seg = (char *)G_calloc(400, sizeof(char));
	sprintf(input->com_line_seg,
		"\"%s/etc/water/%s\"", G_gisbase(), SEG_NAME);
    }

    G_message(_("\nIf you hit <return> by itself for the next question, this"));
    G_message(_("program will terminate."));

    mapset = G_ask_old("What is the name of the elevation map layer?",
		       map_layer, "cell", "cell");
    if (!mapset)
	exit(EXIT_FAILURE);
    if (input->fast)
	com_line_add(&(input->com_line_ram), " el=", map_layer, mapset);
    if (input->slow)
	com_line_add(&(input->com_line_seg), " el=", map_layer, mapset);

    G_message(_("\nOne of the options for %s is a `depression map'.  A"),
	      prog_name);
    G_message(_("depression map indicates all the locations in the current map window where"));
    G_message(_("water accumulates and does not leave by the edge of the map. Lakes without"));
    G_message(_("outlet streams and sinkholes are examples of `depressions'.  If you wish to"));
    G_message(_("have a depression map, prepare a map where non-zero values indicate the"));
    G_message(_("locations where depressions occur.\n"));
    G_message(_("Hit <return> by itself for the next question if there is no depression map."));

    mapset = G_ask_old("What is the name of the depression map layer?",
		       map_layer, "cell", "cell");
    if (mapset) {
	if (input->fast)
	    com_line_add(&(input->com_line_ram), " de=", map_layer, mapset);
	if (input->slow)
	    com_line_add(&(input->com_line_seg), " de=", map_layer, mapset);
    }

    G_message(_("\nThe %s program will divide the elevation map into a number of"),
	      prog_name);
    G_message(_("watershed basins.  The number of watershed basins is indirectly determined"));
    G_message(_("by the `basin threshold' value.  The basin threshold is the area necessary for"));
    G_message(_("%s to define a unique watershed basin.  This area only applies to"),
	      prog_name);
    G_message(_("`exterior drainage basins'.  An exterior drainage basin does not have any"));
    G_message(_("drainage basins flowing into it.  Interior drainage basin size is determined"));
    G_message(_("by the surface flow going into stream segments between stream interceptions."));
    G_message(_("Thus interior drainage basins can be of any size.  The %s program"),
	      prog_name);
    G_message(_("also allows the user to relate basin size to potential overland flow"));
    G_message(_("(i.e., areas with low infiltration capacities will need smaller areas to"));
    G_message(_("develop stream channels than neighboring areas with high infiltration rates)."));
    G_message(_("The user can create a map layer with potential overland flow values, and"));
    G_message(_("%s will accumulate those values instead of area.\n"),
	      prog_name);
    G_message(_("What unit of measure will you use for the basin threshold:"));

    do {
	G_message(_(" 1) acres,          2) meters sq., 3) miles sq., 4) hectares,"));
	G_message(_(" 5) kilometers sq., 6) map cells,  7) overland flow units"));
	fprintf(stderr, _("Choose 1-7 or 0 to exit this program: "));
	G_gets(map_layer);
	sscanf(map_layer, "%d", &i);
    } while (i > 7 || i < 0);

    if (!i)
	exit(EXIT_SUCCESS);

    output->type_area = (char)i;

    G_message(_("\nHow large an area (or how many overland flow units) must a drainage basin"));
    fprintf(stderr, _("be for it to be an exterior drainage basin: "));
    G_gets(map_layer);
    sscanf(map_layer, "%lf", &d);

    switch (i) {
    case 1:
	if (input->fast)
	    basin_com_add(&(input->com_line_ram), d, ACRE_TO_METERSQ, window);
	if (input->slow)
	    basin_com_add(&(input->com_line_seg), d, ACRE_TO_METERSQ, window);
	break;
    case 2:
	if (input->fast)
	    basin_com_add(&(input->com_line_ram), d, 1.0, window);
	if (input->slow)
	    basin_com_add(&(input->com_line_seg), d, 1.0, window);
	break;
    case 3:
	if (input->fast)
	    basin_com_add(&(input->com_line_ram), d, MILESQ_TO_METERSQ,
			  window);
	if (input->slow)
	    basin_com_add(&(input->com_line_seg), d, MILESQ_TO_METERSQ,
			  window);
	break;
    case 4:
	if (input->fast)
	    basin_com_add(&(input->com_line_ram), d, HECTACRE_TO_METERSQ,
			  window);
	if (input->slow)
	    basin_com_add(&(input->com_line_seg), d, HECTACRE_TO_METERSQ,
			  window);
	break;
    case 5:
	if (input->fast)
	    basin_com_add(&(input->com_line_ram), d, KILOSQ_TO_METERSQ,
			  window);
	if (input->slow)
	    basin_com_add(&(input->com_line_seg), d, KILOSQ_TO_METERSQ,
			  window);
	break;
    case 6:
	if (input->fast)
	    basin_com_add(&(input->com_line_ram), d,
			  (window->ns_res * window->ew_res), window);
	if (input->slow)
	    basin_com_add(&(input->com_line_seg), d,
			  (window->ns_res * window->ew_res), window);
	break;
    case 7:			/* needs an overland flow map */
	G_message(_("\nIf you hit <return> by itself for the next question, this"));
	G_message(_("program will terminate."));
	mapset = G_ask_old("What is the name of the overland flow map layer?",
			   map_layer, "cell", "cell");
	if (!mapset)
	    exit(EXIT_FAILURE);
	if (input->fast) {
	    com_line_add(&(input->com_line_ram), " ov=", map_layer, mapset);
	    basin_com_add(&(input->com_line_ram), d,
			  (window->ns_res * window->ew_res), window);
	}
	if (input->slow) {
	    com_line_add(&(input->com_line_seg), " ov=", map_layer, mapset);
	    basin_com_add(&(input->com_line_seg), d,
			  (window->ns_res * window->ew_res), window);
	}
	break;
    }

    G_message(_("\n%s must create a map layer of watershed basins"),
	      prog_name);
    G_message(_("before %s can run properly."), G_program_name());

    strcpy(buf, "Please name the output watershed basin map:");
    do {
	mapset = G_ask_new(buf, input->haf_name, "cell", "");
    } while (NULL == mapset);

    if (input->fast)
	com_line_add(&(input->com_line_ram), " ba=", input->haf_name, NULL);
    if (input->slow)
	com_line_add(&(input->com_line_seg), " ba=", input->haf_name, NULL);

    /* 
       This section queries the user about the armsed file input. If
       you want to make this an option,  the code below "COMMENT2" needs to be
       modified. 
     */

#ifdef ARMSED
    G_message(_("\n%s must create a file of watershed basin relationships"),
	      prog_name);
    G_message(_("before %s can run properly."), G_program_name());

    input->ar_file_name = NULL;
    while (input->ar_file_name == NULL) {
	fprintf(stderr, _("\nPlease name this file:"));
	G_gets(char_input);
	if (1 != G_legal_filename(char_input)) {
	    G_message(_("<%s> is an illegal file name"), char_input);
	}
	else
	    input->ar_file_name = G_store(char_input);
    }

    if (input->fast)
	com_line_add(&(input->com_line_ram), " ar=", input->ar_file_name,
		     NULL);
    if (input->slow)
	com_line_add(&(input->com_line_seg), " ar=", input->ar_file_name,
		     NULL);

    /*
       end of ARMSED comment code
     */

    /*
       COMMENT2 This section of code tells the program where to place the statistics
       about the watershed basin. GRASS users don't need this (w/ r.stats), but the
       format is suppossed to be "user-friendly" to hydrologists. For the stats to be
       created, the armsed file output needs to exist. For the stats to be an option
       in this program: 1) it should be querried before the armsed file query, and 2)
       make the armsed file query manditory if this option is invoked.
     */

    G_message(_("\n%s will generate a lot of output.  Indicate a file"),
	      G_program_name());
    G_message(_("name for %s to send the output to."), G_program_name());

    output->file_name = NULL;
    while (output->file_name == NULL) {
	fprintf(stderr, _("\nPlease name this file:"));
	G_gets(char_input);
	if (1 != G_legal_filename(char_input)) {
	    G_message(_("<%s> is an illegal file name"), char_input);
	}
	else
	    output->file_name = G_store(char_input);
    }

    /* 
       end of COMMENT2
     */
#endif

    G_message(_("\nThe accumulation map from %s must be present for"),
	      prog_name);
    G_message(_("%s to work properly."), G_program_name());
    strcpy(buf, "Please name the accumulation map:");
    do {
	mapset = G_ask_new(buf, input->accum_name, "cell", "");
    } while (NULL == mapset);

    if (input->fast)
	com_line_add(&(input->com_line_ram), " ac=", input->accum_name, NULL);
    if (input->slow)
	com_line_add(&(input->com_line_seg), " ac=", input->accum_name, NULL);

    G_message(_("\n%s can produce several maps not necessary for"),
	      prog_name);
    G_message(_("%s to function (stream channels, overland flow aspect, and"),
	      G_program_name());
    G_message(_("a display version of the accumulation map).  %s also has the"),
	      prog_name);
    G_message(_("ability to generate several variables in the Revised Universal Soil Loss"));
    G_message(_("Equation (Rusle): Slope Length (LS), and Slope Steepness (S).\n"));

    sprintf(buf, "Would you like any of these maps to be created?");
    if (G_yes(buf, 1)) {
	mapset = G_ask_new("", map_layer, "cell", "stream channel");
	if (mapset != NULL) {
	    if (input->fast)
		com_line_add(&(input->com_line_ram), " se=", map_layer, NULL);
	    if (input->slow)
		com_line_add(&(input->com_line_seg), " se=", map_layer, NULL);
	}
	mapset = G_ask_new("", map_layer, "cell", "half basin");
	if (mapset != NULL) {
	    if (input->fast)
		com_line_add(&(input->com_line_ram), " ha=", map_layer, NULL);
	    if (input->slow)
		com_line_add(&(input->com_line_seg), " ha=", map_layer, NULL);
	}
	mapset = G_ask_new("", map_layer, "cell", "overland aspect");
	if (mapset != NULL) {
	    if (input->fast)
		com_line_add(&(input->com_line_ram), " dr=", map_layer, NULL);
	    if (input->slow)
		com_line_add(&(input->com_line_seg), " dr=", map_layer, NULL);
	}
	mapset = G_ask_new("", map_layer, "cell", "display");
	if (mapset != NULL) {
	    if (input->fast)
		com_line_add(&(input->com_line_ram), " di=", map_layer, NULL);
	    if (input->slow)
		com_line_add(&(input->com_line_seg), " di=", map_layer, NULL);
	}
	i = 0;
	mapset = G_ask_new("", map_layer, "cell", "Slope Length");
	if (mapset != NULL) {
	    i = 1;
	    if (input->fast)
		com_line_add(&(input->com_line_ram), " LS=", map_layer, NULL);
	    if (input->slow)
		com_line_add(&(input->com_line_seg), " LS=", map_layer, NULL);
	}
	mapset = G_ask_new("", map_layer, "cell", "Slope Steepness");
	if (mapset != NULL) {
	    i = 1;
	    if (input->fast)
		com_line_add(&(input->com_line_ram), " S=", map_layer, NULL);
	    if (input->slow)
		com_line_add(&(input->com_line_seg), " S=", map_layer, NULL);
	}

	if (i) {
	    G_message(_("\nThe Slope Length factor (LS) and Slope Steepness (S) are influenced by"));
	    G_message(_("disturbed land.  %s reflects this with an optional map layer or value"),
		      prog_name);
	    G_message(_("where the value indicates the percent of disturbed (barren) land in that cell."));
	    G_message(_("Type <return> if you do not have a disturbed land map layer."));

	    mapset = G_ask_old("", map_layer, "cell", "disturbed land");
	    if (mapset != NULL) {
		if (input->fast)
		    com_line_add(&(input->com_line_ram), " r=", map_layer,
				 NULL);
		if (input->slow)
		    com_line_add(&(input->com_line_seg), " r=", map_layer,
				 NULL);
	    }
	    else {
		G_message(_("\nType the value indicating the percent of disturbed land.  This value will"));
		G_message(_("be used for every cell in the current region."));
		i = -6;
		while (i < 0 || i > 100) {
		    fprintf(stderr, _("\nInput value here [0-100]: "));
		    fgets(buf, 80, stdin);
		    sscanf(buf, "%d", &i);
		}
		if (input->fast)
		    com_add(&(input->com_line_ram), " r=", i);
		if (input->slow)
		    com_add(&(input->com_line_seg), " r=", i);
	    }

	    /*       12345678901234567890123456789012345678901234567890123456789012345678901234567890 */
	    G_message(_("\nOverland surface flow only occurs for a set distance before swales form."));
	    G_message(_("Because of digital terrain model limitations, %s cannot pick up"),
		      prog_name);
	    G_message(_("these swales.  %s allows for an input (warning: kludge factor)"),
		      prog_name);
	    G_message(_("that prevents the surface flow distance from getting too long.  Normally,"));
	    G_message(_("maximum slope length is around 600 feet (about 183 meters)."));

	    i = -1;
	    while (i < 0) {
		fprintf(stdout,
			"\nInput maximum slope length here (in meters): ");
		fgets(buf, 80, stdin);
		sscanf(buf, "%d", &i);
	    }
	    if (input->fast)
		com_add(&(input->com_line_ram), " ms=", i);
	    if (input->slow)
		com_add(&(input->com_line_seg), " ms=", i);

	    /*       12345678901234567890123456789012345678901234567890123456789012345678901234567890 */
	    G_message(_("\nRoads, ditches, changes in ground cover, and other factors will stop"));
	    G_message(_("slope length.  You may input a raster map indicating the locations of these"));
	    G_message(_("blocking factors.\n"));
	    G_message(_("Hit <return> by itself for the next question if there is no blocking map."));

	    mapset = G_ask_old("What is the name of the blocking map layer?",
			       map_layer, "cell", "cell");
	    if (mapset) {
		if (input->fast)
		    com_line_add(&(input->com_line_ram), " ob=", map_layer,
				 mapset);
		if (input->slow)
		    com_line_add(&(input->com_line_seg), " ob=", map_layer,
				 mapset);
	    }
	}
    }

    return 0;
}
Esempio n. 10
0
/* create the actual report */
void do_report_CELL ( char *map, char *mapset, char *sites,
					int precision, int null_flag, int uncat_flag,
					int all_flag, int quiet_flag, int skip_flag,
				  	char *logfile, int background, int gain, int show_progress) {
    	CELL *cellbuf;
	struct Cell_head region;
	GT_Row_cache_t *cache;
	unsigned long row_idx, col_idx;	
	int fd;
	unsigned long i,j,k;
	unsigned long no_sites;
	FILE *lp;	
	unsigned long nrows, ncols;
	unsigned long *share_smp = NULL; /* array that keeps percentage of sites */
	double total = 0;
	double map_total = 0;
	double kvamme_gain;
	long null_count = 0; /* keeps count of sites on NULL cells */
	long nocat_count = 0;
	/* category counts and descriptions */
	int cats;
	char **cats_description; /* category labels */
	long *cat_count; /* category counts */
	long null_count_map; /* number of NULL cells in input map */
	long nocat_count_map; /* number of cells that do not fall into the category range [0 .. n] */		
	int debug_mode = 0;		/* 1 to enable writing additional output to logfile */
	time_t systime;

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

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

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

	vect_points = Vect_new_line_struct ();

	if (all_flag != 1) {
		Vect_set_constraint_region (&in_vect_map, region.north, region.south, 
			region.east, region.west, 0.0, 0.0);
	}
		
	/* get total number of sampling points */
	i = 0;	
	while ((cur_type = Vect_read_next_line (&in_vect_map, vect_points, NULL) > 0)) {
		i ++;
	}

	no_sites = i; /* store this for later use */
			
	/* open raster map */
	fd = G_open_cell_old (map, G_find_cell (map, ""));
	if (fd < 0)
	{
		delete_tmpfile (map);
		G_fatal_error ("Could not open raster map for reading!\n");
	}
	/* allocate a cache and a raster buffer */
	cache = (GT_Row_cache_t *) G_malloc (sizeof (GT_Row_cache_t));
	GT_RC_open (cache, CACHESIZE, fd, CELL_TYPE);
	cellbuf = G_allocate_raster_buf (CELL_TYPE);			
	
	cats = GT_get_stats (map,mapset,&null_count_map, &nocat_count_map, show_progress);
	if ( cats < 2 ) {
		delete_tmpfile (map);
		G_fatal_error ("Input map must have at least two categories.");
	}
	
	/* get category labels and counts */
	cats_description = GT_get_labels (map,mapset);
	if (cats_description == NULL) {
		delete_tmpfile (map);
		G_fatal_error ("Could not read category labels from input map.");
	}
	cat_count = GT_get_c_counts (map,mapset, show_progress);
	if (cat_count == NULL) {
		delete_tmpfile (map);
		G_fatal_error ("Could not count categories in input map.");
	}		
	
	/* allocate a double array to hold statistics */
	share_smp = (unsigned long *) G_malloc ((signed)(cats * sizeof (unsigned long)));
	for (i = 0; i < cats; i++)
	{
		share_smp[i] = 0;
		
	}	
	
	/* count raster values under sampling points */
	i = 0;
	k = 0; /* progress counter for status display */
	
	Vect_rewind (&in_vect_map);	
	
	if ( !quiet_flag ) {
		fprintf (stdout, "Counting sample: \n");
		fflush (stdout);	
	}
	
	/* we MUST not set constraints so that no raster values outside the current region are
	   accessed, which would give an "illegal cache request" error */
	Vect_set_constraint_region (&in_vect_map, region.north, region.south, 
				     region.east, region.west, 0.0, 0.0);
	
	while ((cur_type = Vect_read_next_line (&in_vect_map, vect_points, NULL) > 0)) {	
		Vect_copy_pnts_to_xyz (vect_points, &x, &y, &z, &n_points);		
		k ++;
		if ( !quiet_flag ) {
			G_percent ((signed) k, (signed) no_sites, 1);
		}
		/* get raster row with same northing as sample and perform
		   quantification */
		row_idx = (long) G_northing_to_row (y, &region);
		col_idx = (long) G_easting_to_col (x, &region);				
				
		cellbuf = GT_RC_get (cache, (signed) row_idx);
		/* now read the raster value under the current site */
		if (G_is_c_null_value (&cellbuf[col_idx]) == 0) {
			/* site on cell within category range [0..cats] ? */
			if ( (cellbuf[col_idx] > -1) && (cellbuf[col_idx] <= cats) ) {
				share_smp [cellbuf[col_idx] ] ++;
				/* i keeps track of samples on non-null coverage only */
				/* inside the current region */
				i ++;
			} else {
				if ( uncat_flag ) {
					/* also keep count of sites on uncategorised cells? */
					i ++;
					nocat_count++;
				}
			}				
		}
		if (G_is_c_null_value (&cellbuf[col_idx]) == 1) { 
			/* got a NULL value under this site */
			if (null_flag) { /* only count this, if null flag is set */
				null_count ++;
				i ++;
			}
		}
	}
	
	Vect_close (&in_vect_map);		
	
	fprintf (lp,"\n");
	if ( background ) {
		fprintf (lp,"Distribution of categories under %lu points (%lu in region) and in input map:\n",i,no_sites);	
	} else {
		fprintf (lp,"Distribution of categories under %lu points (%lu in region):\n",i,no_sites);	
	}
	/* determine starting value for total of sites analysed */
	total = 0;
	for ( j=0; j < cats; j ++) {
		total = total + share_smp[j];
		map_total = map_total + cat_count[j];
	}
	if (null_flag) { /* add NULL values to total */	
		total = total + null_count;
		map_total = map_total + null_count_map;
	}
	if (uncat_flag) { /* add uncategorised cells to total */
		total = total + nocat_count;
		map_total = map_total + nocat_count_map;
		
	}
	
	/* Now display those values which the user has chosen */
	if ( (background) && (gain) ) {	
		fprintf (lp,"Cat.\tPts.\t(%%)\tMap\t(%%)\tGain\tDescription\n");				
	}
	if ( (background) && (!gain) ) {	
		fprintf (lp,"Cat.\tPts.\t(%%)\tMap\t(%%)\tDescription\n");		
	}
	if ( (!background) && (gain) ) {	
		fprintf (lp,"Cat.\tPts.\t(%%)\tGain\tDescription\n");
	}
	if ( (!background) && (!gain) ) {	
		fprintf (lp,"Cat.\tPts.\t(%%)\tDescription\n");
	}	
	for ( j = 0; j < cats; j ++) {
		/* if skip_flag is not set: only show categories that have count > 0 */
		if ((skip_flag == 1) || ((skip_flag == 0) && (share_smp[j] > 0))) {
			if ( (background) && (gain) ) {
				/* Kvamme's Gain = 1 - (%area/%sites) */
				kvamme_gain = gstats_gain_K(((double) share_smp[j]*(100/total)),
							    ((double) cat_count[j]*(100/map_total)));							    				
				fprintf (lp, "%lu\t%6lu\t%6.2f\t%8lu %6.2f\t%6.2f\t%s\n", j, share_smp[j], (float) share_smp[j]*(100/total),
						cat_count[j], (float) cat_count[j]*(100/map_total),
						kvamme_gain, cats_description[j]);
			} 
			if ( (background) && (!gain) ) {
				fprintf (lp, "%lu\t%6lu\t%6.2f\t%8lu %6.2f\t%s\n", j, share_smp[j], (float) share_smp[j]*(100/total),
						cat_count[j], (float) cat_count[j]*(100/map_total),
						cats_description[j]);
				
			} 			
			if ( (!background) && (gain) ) {
				kvamme_gain = 1-( (float) cat_count[j]*(100/map_total) / (float) share_smp[j]*(100/total) );
				fprintf (lp, "%lu\t%6lu\t%6.2f\t%6.2f\t%s\n", j, share_smp[j], (float) share_smp[j]*(100/total),						
						kvamme_gain, cats_description[j]);				
			} 			
			if ( (!background) && (!gain) ) {
				fprintf (lp, "%lu\t%6lu\t%6.2f\t%s\n", j, share_smp[j], (float) share_smp[j]*(100/total),
						cats_description[j]);
			} 									
		}
	}
	if (null_flag) {		
		if ( background ) {
			fprintf (lp,"NULL\t%6lu\t%6.2f\t%8lu %6.2f\n",null_count, (float) null_count * 100 / total
						,null_count_map, (float) null_count_map * 100 / map_total);
		} else {
			fprintf (lp,"NULL\t%6lu\t%6.2f\n",null_count, (float) null_count * 100 / total);
		}
	}
	if (uncat_flag) {
		if ( background ) {
			fprintf (lp,"NOCAT\t%6lu\t%6.2f\t%8lu %6.2f\n",nocat_count, (float) nocat_count * 100 / total
						,nocat_count_map, (float) nocat_count_map * 100 / map_total);
		} else {
			fprintf (lp,"NOCAT\t%6lu\t%6.2f\n",nocat_count, (float) nocat_count * 100 / total);
		}		
	}	
	if ( background) {
		fprintf (lp,"TOTAL\t%6lu\t%6.2f\t%8lu %6.2f\n",(long) total, (float) 100, (long) map_total, (float) 100);
	} else {
		fprintf (lp,"TOTAL\t%6lu\t%6.2f\n",(long) total, (float) 100);
	}
	
	/* close cache and sites file; free buffers. */
	GT_RC_close (cache);
	G_free (cellbuf);
	G_free (cache);	
}
Esempio n. 11
0
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);
}
Esempio n. 12
0
int main(int argc, char *argv[])
{
    char group[INAME_LEN], extension[INAME_LEN];
    int order;			/* ADDED WITH CRS MODIFICATIONS */
    char *ipolname;		/* name of interpolation method */
    int method;
    int n, i, m, k = 0;
    int got_file = 0, target_overwrite = 0;
    char *overstr;
    struct Cell_head cellhd;

    struct Option *grp,         /* imagery group */
     *val,                      /* transformation order */
     *ifile,			/* input files */
     *ext,			/* extension */
     *tres,			/* target resolution */
     *mem,			/* amount of memory for cache */
     *interpol;			/* interpolation method:
				   nearest neighbor, bilinear, cubic */
    struct Flag *c, *a;
    struct GModule *module;

    G_gisinit(argv[0]);

    module = G_define_module();
    module->keywords = _("imagery, rectify");
    module->description =
	_("Rectifies an image by computing a coordinate "
	  "transformation for each pixel in the image based on the "
	  "control points.");

    grp = G_define_standard_option(G_OPT_I_GROUP);

    ifile = G_define_standard_option(G_OPT_R_INPUTS);
    ifile->required = NO;

    ext = G_define_option();
    ext->key = "extension";
    ext->type = TYPE_STRING;
    ext->required = YES;
    ext->multiple = NO;
    ext->description = _("Output raster map(s) suffix");

    val = G_define_option();
    val->key = "order";
    val->type = TYPE_INTEGER;
    val->required = YES;
    val->description = _("Rectification polynom order (1-3)");

    tres = G_define_option();
    tres->key = "res";
    tres->type = TYPE_DOUBLE;
    tres->required = NO;
    tres->description = _("Target resolution (ignored if -c flag used)");

    mem = G_define_option();
    mem->key = "memory";
    mem->type = TYPE_DOUBLE;
    mem->key_desc = "memory in MB";
    mem->required = NO;
    mem->answer = "300";
    mem->description = _("Amount of memory to use in MB");

    ipolname = make_ipol_list();

    interpol = G_define_option();
    interpol->key = "method";
    interpol->type = TYPE_STRING;
    interpol->required = NO;
    interpol->answer = "nearest";
    interpol->options = ipolname;
    interpol->description = _("Interpolation method to use");

    c = G_define_flag();
    c->key = 'c';
    c->description =
	_("Use current region settings in target location (def.=calculate smallest area)");

    a = G_define_flag();
    a->key = 'a';
    a->description = _("Rectify all raster maps in group");

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

    /* get the method */
    for (method = 0; (ipolname = menu[method].name); method++)
	if (strcmp(ipolname, interpol->answer) == 0)
	    break;

    if (!ipolname)
	G_fatal_error(_("<%s=%s> unknown %s"),
		      interpol->key, interpol->answer, interpol->key);
    interpolate = menu[method].method;

    G_strip(grp->answer);
    strcpy(group, grp->answer);
    strcpy(extension, ext->answer);
    order = atoi(val->answer);

    seg_mb = NULL;
    if (mem->answer) {
	if (atoi(mem->answer) > 0)
	    seg_mb = mem->answer;
    }

    if (!ifile->answers)
	a->answer = 1;		/* force all */

    /* Find out how many files on command line */
    if (!a->answer) {
	for (m = 0; ifile->answers[m]; m++) {
	    k = m;
	}
	k++;
    }

    if (order < 1 || order > MAXORDER)
	G_fatal_error(_("Invalid order (%d); please enter 1 to %d"), order,
		      MAXORDER);

    /* determine the number of files in this group */
    if (I_get_group_ref(group, &ref) <= 0)
	G_fatal_error(_("Group <%s> does not exist"), grp->answer);

    if (ref.nfiles <= 0) {
	G_important_message(_("Group <%s> contains no raster maps; run i.group"),
			    grp->answer);
	exit(EXIT_SUCCESS);
    }

    ref_list = (int *)G_malloc(ref.nfiles * sizeof(int));

    if (a->answer) {
	for (n = 0; n < ref.nfiles; n++) {
	    ref_list[n] = 1;
	}
    }
    else {
	char xname[GNAME_MAX], xmapset[GMAPSET_MAX], *name, *mapset;

	for (n = 0; n < ref.nfiles; n++)
		ref_list[n] = 0;

	for (m = 0; m < k; m++) {
	    got_file = 0;
	    if (G__name_is_fully_qualified(ifile->answers[m], xname, xmapset)) {
		name = xname;
		mapset = xmapset;
	    }
	    else {
		name = ifile->answers[m];
		mapset = NULL;
	    }

	    got_file = 0;
	    for (n = 0; n < ref.nfiles; n++) {
		if (mapset) {
		    if (strcmp(name, ref.file[n].name) == 0 &&
		        strcmp(mapset, ref.file[n].mapset) == 0) {
			got_file = 1;
			ref_list[n] = 1;
			break;
		    }
		}
		else {
		    if (strcmp(name, ref.file[n].name) == 0) {
			got_file = 1;
			ref_list[n] = 1;
			break;
		    }
		}
	    }
	    if (got_file == 0)
		err_exit(ifile->answers[m], group);
	}
    }

    /* read the control points for the group */
    get_control_points(group, order);

    /* get the target */
    get_target(group);

    /* Check the GRASS_OVERWRITE environment variable */
    if ((overstr = getenv("GRASS_OVERWRITE")))  /* OK ? */
	target_overwrite = atoi(overstr);

    if (!target_overwrite) {
	/* check if output exists in target location/mapset */
	char result[GNAME_MAX];
	
	select_target_env();
	for (i = 0; i < ref.nfiles; i++) {
	    if (!ref_list[i])
		continue;

	    strcpy(result, ref.file[i].name);
	    strcat(result, extension);
	    
	    if (G_legal_filename(result) < 0)
		G_fatal_error(_("Extension <%s> is illegal"), extension);
		
	    if (G_find_cell(result, G_mapset())) {
		G_warning(_("The following raster map already exists in"));
		G_warning(_("target LOCATION %s, MAPSET %s:"),
			  G_location(), G_mapset());
		G_warning("<%s>", result);
		G_fatal_error(_("Orthorectification cancelled."));
	    }
	}
	
	select_current_env();
    }
    else
	G_debug(1, "Overwriting OK");

    /* do not use current region in target location */
    if (!c->answer) {
	double res = -1;
	
	if (tres->answer) {
	    if (!((res = atof(tres->answer)) > 0))
		G_warning(_("Target resolution must be > 0, ignored"));
	}
	/* Calculate smallest region */
	if (a->answer) {
	    if (G_get_cellhd(ref.file[0].name, ref.file[0].mapset, &cellhd) <
		0)
		G_fatal_error(_("Unable to read header of raster map <%s>"),
			      ref.file[0].name);
	}
	else {
	    if (G_get_cellhd(ifile->answers[0], ref.file[0].mapset, &cellhd) <
		0)
		G_fatal_error(_("Unable to read header of raster map <%s>"),
			      ifile->answers[0]);
	}
	georef_window(&cellhd, &target_window, order, res);
    }

    G_verbose_message(_("Using region: N=%f S=%f, E=%f W=%f"), target_window.north,
	      target_window.south, target_window.east, target_window.west);

    exec_rectify(order, extension, interpol->answer);

    G_done_msg(" ");

    exit(EXIT_SUCCESS);
}
Esempio n. 13
0
static const char *find_file(
    int misc,
    const char *dir,
    const char *element, const char *name, const char *mapset)
{
    char path[GPATH_MAX];
    char xname[GNAME_MAX], xmapset[GMAPSET_MAX];
    const char *pname, *pmapset;
    int n;

    if (*name == 0)
	return NULL;
    *path = 0;

    /*
     * if name is in the fully qualified format, split it into
     * name, mapset (overrides what was in mapset)
     */
    if (G_name_is_fully_qualified(name, xname, xmapset)) {
	pname = xname;
	pmapset = xmapset;
    }
    else {
	pname = name;
	pmapset = mapset;
    }

    if (strcmp(element, "vector") == 0 &&
	strcasecmp(pmapset, "ogr") == 0) {
	/* don't check for virtual OGR mapset */
	return G_store(pmapset);
    }
    
    /*
     * reject illegal names and mapsets
     */
    if (G_legal_filename(pname) == -1)
	return NULL;
    
    if (pmapset && *pmapset && G_legal_filename(pmapset) == -1)
	return NULL;

    /*
     * if no specific mapset is to be searched
     * then search all mapsets in the mapset search list
     */
    if (pmapset == NULL || *pmapset == 0) {
	int cnt = 0;
	const char *pselmapset = NULL;

	for (n = 0; (pmapset = G__mapset_name(n)); n++) {
	    if (misc)
		G_file_name_misc(path, dir, element, pname, pmapset);
	    else
		G_file_name(path, element, pname, pmapset);
	    if (access(path, 0) == 0) {
		if (!pselmapset)
		    pselmapset = pmapset;
		else
		    G_warning(_("'%s/%s' was found in more mapsets (also found in <%s>)"),
			      element, pname, pmapset);
		cnt++;
	    }
	}
	if (cnt > 0) {
	    /* If the same name exists in more mapsets and print a warning */
	    if (cnt > 1)
		G_warning(_("Using <%s@%s>"),
			  pname, pselmapset);
	    
	    return G_store(pselmapset);
	}
    }
    /*
     * otherwise just look for the file in the specified mapset.
     * since the name may have been qualified, mapset may point
     * to the xmapset, so we must should it to
     * permanent storage via G_store().
     */
    else {
	if (misc)
	    G_file_name_misc(path, dir, element, pname, pmapset);
	else
	    G_file_name(path, element, pname, pmapset);
	    
	if (access(path, 0) == 0)
	    return G_store(pmapset);
    }
    
    return NULL;
}
Esempio n. 14
0
int main( int argc, char *argv[] )
{
	Shypothesis **samples; /* Data to be combined */
	unsigned int i;
	FILE *kb;
	char **groups;
	int norm = 1; /* turn on normalisation of evidence by default */
	/* these are for time keeping in the logfile */	
	time_t systime;
	clock_t proctime;
	unsigned long timeused;
	unsigned int days, hours, mins, secs;
	
	xmlDocPtr dstXMLFile;
	Sfp_struct* file_pointers;	
	
	G_gisinit ( argv[0] );		
	
	module = G_define_module ();
	module->description = "Combines evidences from a DST knowledge base";
		
	parm.file = G_define_option ();
	parm.file->key = "file";
	parm.file->type = TYPE_STRING;
	parm.file->required = YES;
	parm.file->description = "Name of the knowledge base that contains the evidence";
	
	parm.groups = G_define_option ();
	parm.groups->key = "sources";
	parm.groups->type = TYPE_STRING;
	parm.groups->required = NO;
	parm.groups->multiple = YES;
	parm.groups->description = "Evidences to be combined (default: all)";
			
	parm.type = G_define_option ();
	parm.type->key = "type";
	parm.type->type = TYPE_STRING;
	parm.type->required = NO;
	parm.type->options = "const,rast,vect";
	parm.type->answer = "rast";
	parm.type->description = "Type(s) of evidences to combine";	
	
	parm.output = G_define_option ();
	parm.output->key = "output";
	parm.output->type = TYPE_STRING;
	parm.output->required = NO;
	parm.output->answer = G_location ();
	parm.output->description = "Prefix for result maps (dflt: location name)";

	parm.vals = G_define_option ();
	parm.vals->key = "values";
	parm.vals->type = TYPE_STRING;
	parm.vals->required = NO;
	parm.vals->multiple = YES;
	parm.vals->options = "bel,pl,doubt,common,bint,woc,maxbpa,minbpa,maxsrc,minsrc";
	parm.vals->answer = "bel";
	parm.vals->description = "Dempster-Shafer values to map";

	parm.hyps = G_define_option ();
	parm.hyps->key = "hypotheses";
	parm.hyps->type = TYPE_STRING;
	parm.hyps->required = NO;
	parm.hyps->multiple = NO;
	parm.hyps->description = "Hypotheses to map (default: all)";

	parm.logfile = G_define_option ();
	parm.logfile->key = "logfile";
	parm.logfile->type = TYPE_STRING;
	parm.logfile->required = NO;
	parm.logfile->description = "Name of logfile";

	/* TODO: not implemented yet
	parm.warnings = G_define_option ();
	parm.warnings->key = "warnings";
	parm.warnings->type = TYPE_STRING;
	parm.warnings->required = NO;
	parm.warnings->description = "Name of site list to store locations of warnings." ;
	*/

	flag.norm = G_define_flag ();
	flag.norm->key = 'n';
	flag.norm->description = "Turn off normalisation";

	flag.quiet = G_define_flag ();
	flag.quiet->key = 'q';
	flag.quiet->description = "Quiet operation: no progress diplay";

	/* append output to existing logfile ? */
	flag.append = G_define_flag ();
	flag.append->key = 'a';
	flag.append->description = "Append log output to existing file";
	
	no_assigns = 0;
	
	/* INIT GLOBAL VARS */
	WOC_MIN = 0;
	WOC_MAX = 0;
	
	/* do not pause after a warning message was displayed */
	G_sleep_on_error (0);
	
	/* parse command line */
	if (G_parser (argc, argv))
	{
		exit (-1);
	}			
	
	/* check if given parameters are valid */
	if (G_legal_filename (parm.file->answer) == -1) {
		G_fatal_error ("Please provide the name of an existing DST knowledge base.\n");
	}
	
	if (G_find_file ("DST",parm.file->answer,G_mapset()) == NULL) {
		G_fatal_error ("Knowledge base does not exist in user's MAPSET!\n");
	}
	
	/* check logfile */
	if (parm.logfile->answer != NULL) {		
		if ( !G_legal_filename (parm.logfile->answer) ) {
			G_fatal_error ("Please specify a legal filename for the logfile.\n");
		}
		/* attempt to write to logfile */
		if (flag.append->answer) {
			if (fopen (parm.logfile->answer, "r") == NULL) {
				lp = fopen (parm.logfile->answer, "w+");
				if (lp == NULL) {
					G_fatal_error ("Logfile error: %s\n", strerror (errno));
				}				
			} else {
				lp = fopen (parm.logfile->answer, "a");
				if (lp == NULL) {
					G_fatal_error ("Logfile error: %s\n", strerror (errno));
				}
				fprintf (lp,"\n\n * * * * * \n\n");
			}
		} else {
			if ( (lp = fopen ( parm.logfile->answer, "w+" ) ) == NULL ) {
				G_fatal_error ("Logfile error: %s\n", strerror (errno));
			}
		}
		/* we want unbuffered output for the logfile */
		setvbuf (lp,NULL,_IONBF,0);
	} else {		
		/* log output to stderr by default */
		lp = stderr;
	}
		
	/* setup coordinate file storage, if desired */
	/* try to create a sites file to store coordinates */
	/* set 'warn' to point to the user-defined sites file */	
	/*
	warn = NULL;
	if ( parm.warnings != NULL ) {
	}
	*/
			
	/* check if we have read/write access to knowledge base */
	kb = G_fopen_old ("DST",parm.file->answer,G_mapset());
	if ( kb == NULL ) {
		G_fatal_error ("Cannot open knowledge base file for reading and writing!\n");
	}
	fclose(kb);
	
	/* start logfile */
	if ( parm.logfile->answer != NULL) {
		fprintf (lp,"This is %s, version %.2f\n",argv[0],PROGVERSION);
		systime = time (NULL);
		fprintf (lp,"Calculation started on %s\n",ctime(&systime));
	}		
		
	/* open DST file and get basic evidence group information */
	dstXMLFile = stat_XML ( parm.file->answer, &NO_SINGLETONS, &N );
	groups = get_groups_XML ( N, dstXMLFile );
	
	if ( NO_SINGLETONS == 1 ) {
		G_fatal_error ("Knowledge base does not contain any user-supplied hypotheses.\n");
	}

	if ( parm.groups->answer != NULL ) {
		/* user specified a subset of groups */
		N = check_groups ( groups );
	}
		
	if ( N < 2 ) {
		G_fatal_error ("At least two groups of evidences must be present in the knowledge base.\n");
	}				

	/* allocate memory for all samples 
	 a sample holds one double for bel, pl and bpn for each
	 piece of evidence. The number of pieces of evidence is
	 the number of possible subsets in Theta 
	 = 2^NO_SINGLETONS ! 
	
	 The number of samples is = number of groups in the XML
	 knowledge base file (N) !
	*/
	samples = (Shypothesis**) G_malloc ((N * sizeof(Shypothesis*)));
	for ( i=0; i < N; i ++ ) {
		samples[i] = (Shypothesis*) G_malloc (sizeof(Shypothesis));
	}
	
	
	/* turn off normalisation if user wants it so */
	if ( flag.norm->answer == 1 ) {
		norm = 0;
	}	
			
	/* do some type-dependant checking */
	/* and open file pointers for all the maps to read! */
	file_pointers = NULL;
	if ( !strcmp (parm.type->answer,"rast") ) {
		if ( parm.groups->answer != NULL ) {
			/* check only user-specified groups */
			file_pointers = test_rast_XML ( parm.groups->answers, dstXMLFile );			
		} else {
			/* check all groups */
			file_pointers = test_rast_XML ( groups, dstXMLFile );
		}
	}	
	
	/* read in all samples in a type-dependant manner */
	if ( parm.groups->answer != NULL ) {
		/* read only user-specified groups */
		if ( !strcmp (parm.type->answer,"const") ) {
			if ( strcmp (parm.output->answer,G_location ()) != 0) {
				G_warning ("Ignoring parameter 'output='.\n");
			}
			if ( strcmp (parm.vals->answer,"bel") !=0 ) {
				G_warning ("Ignoring parameter 'values='.\n");
			}
			if ( parm.hyps->answer != NULL ) {
				G_warning ("Ignoring parameter 'hypotheses='.\n");
			}
			do_calculations_const (samples,parm.groups->answers, norm, dstXMLFile);
		}
		if ( !strcmp (parm.type->answer,"rast") ) {
			do_calculations_rast (samples,parm.groups->answers, norm,
								  parm.output->answer, parm.vals->answers, 
								  parm.hyps->answer, flag.quiet->answer,
							      parm.logfile->answer, dstXMLFile, file_pointers );
		}			
	} else {
		/* read all groups */
		if ( !strcmp (parm.type->answer,"const") ) {
			if ( strcmp (parm.output->answer,G_location ()) != 0) {
				G_warning ("Ignoring parameter 'output='.\n");
			}
			if ( strcmp (parm.vals->answer,"bel") !=0 ) {
				G_warning ("Ignoring parameter 'values='.\n");
			}
			if ( parm.hyps->answer != NULL ) {
				G_warning ("Ignoring parameter 'hypotheses='.\n");
			}
			do_calculations_const (samples,groups, norm, dstXMLFile);
		}
		if ( !strcmp (parm.type->answer,"rast") ) {
			do_calculations_rast (samples,groups, norm,
								  parm.output->answer, parm.vals->answers, 
							      parm.hyps->answer, flag.quiet->answer,
								  parm.logfile->answer, dstXMLFile, file_pointers );
		}			
	}	
		
	/* close logfile */
	/* write processing time to logfile */
	proctime = clock ();
	timeused = (unsigned long) proctime / CLOCKS_PER_SEC;
	days = timeused / 86400;
	hours = (timeused - (days * 86400)) / 3600;
	mins = (timeused - (days * 86400) - (hours * 3600)) / 60;		
	secs = (timeused - (days * 86400) - (hours * 3600) - (mins * 60));
	systime = time (NULL);
	
	if ( parm.logfile->answer != NULL ) {
		fprintf (lp,"\nCalculation finished on %s",ctime(&systime));		
		fprintf (lp,"Processing time: %id, %ih, %im, %is\n",
				days, hours, mins, secs );
		fflush (lp);
	}
	
	for (i=0; i<N; i++) {
		G_free (groups[i]);		
	}
	G_free (groups);
	
	return (EXIT_SUCCESS);
}
Esempio n. 15
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);
}
Esempio n. 16
0
int main(int argc, char *argv[])
{
    struct GModule *module;
    struct
    {
	struct Option *base, *cover, *output;
    } parm;
    char *basemap, *base_mapset;
    char *covermap, *cover_mapset;
    char *outmap;
    char command[1024];
    struct Categories cover_cats;
    FILE *stats, *reclass;
    int first;
    long basecat, covercat, catb, catc;
    double value, max;

    G_gisinit(argv[0]);

    module = G_define_module();
    module->keywords = _("raster, statistics");
    module->description =
	_("Finds the mode of values in a cover map within "
	  "areas assigned the same category value in a "
	  "user-specified base map.");

    parm.base = G_define_option();
    parm.base->key = "base";
    parm.base->description = _("Base map to be reclassified");
    parm.base->required = YES;
    parm.base->type = TYPE_STRING;
    parm.base->gisprompt = "old,cell,raster";

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

    parm.output = G_define_option();
    parm.output->key = "output";
    parm.output->description = _("Output map");
    parm.output->required = YES;
    parm.output->type = TYPE_STRING;
    parm.output->gisprompt = "new,cell,raster";

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

    basemap = parm.base->answer;
    covermap = parm.cover->answer;
    outmap = parm.output->answer;

    base_mapset = G_find_cell2(basemap, "");
    if (base_mapset == NULL) {
	G_fatal_error(_("%s: base raster map not found"), basemap);
    }

    cover_mapset = G_find_cell2(covermap, "");
    if (cover_mapset == NULL) {
	G_fatal_error(_("%s: cover raster map not found"), covermap);
    }
    if (G_legal_filename(outmap) < 0) {
	G_fatal_error(_("<%s> is an illegal file name"), outmap);
    }
    if (strcmp(G_mapset(), base_mapset) == 0 && strcmp(basemap, outmap) == 0) {
	G_fatal_error(_("%s: base map and output map must be different"),
		      outmap);
    }
    if (G_read_cats(covermap, cover_mapset, &cover_cats) < 0) {
	G_fatal_error(_("%s: Unable to read category labels"), covermap);
    }

    strcpy(command, "r.stats -an \"");
    strcat(command, G_fully_qualified_name(basemap, base_mapset));
    strcat(command, ",");
    strcat(command, G_fully_qualified_name(covermap, cover_mapset));
    strcat(command, "\"");

    /* printf(command); */
    stats = popen(command, "r");

    sprintf(command, "r.reclass i=\"%s\" o=\"%s\"",
	    G_fully_qualified_name(basemap, base_mapset), outmap);

    /* printf(command); */
    reclass = popen(command, "w");

    first = 1;
    while (read_stats(stats, &basecat, &covercat, &value)) {
	if (first) {
	    first = 0;
	    catb = basecat;
	    catc = covercat;
	    max = value;
	}
	if (basecat != catb) {
	    write_reclass(reclass, catb, catc, G_get_cat(catc, &cover_cats));
	    catb = basecat;
	    catc = covercat;
	    max = value;
	}
	if (value > max) {
	    catc = covercat;
	    max = value;
	}
    }
    if (first) {
	catb = catc = 0;
    }
    write_reclass(reclass, catb, catc, G_get_cat(catc, &cover_cats));

    pclose(stats);
    pclose(reclass);

    exit(0);
}
Esempio n. 17
0
File: open.c Progetto: cran/GRASS
int G__open (
    char *element,
    char *name,
    char *mapset,
    int mode)
{
    char path[1024];
    char xname[512], xmapset[512], *dummy;
    int G_fd;


    G__check_gisinit();

/* READ */
    if (mode == 0)
    {
	if (G__name_is_fully_qualified (name, xname, xmapset))
	{
	    if (strcmp (xmapset, mapset) != 0) {
		fprintf(stderr, "G__open(r): mapset (%s) doesn't match xmapset (%s)\n",
			mapset,xmapset);
		    return -1;
	    }
	    name = xname;
	}
	if ((dummy = G_find_file (element, name, mapset)) == NULL)
	    return -1;
	G_free (dummy);
	G__file_name (path, element, name, mapset);

        G_fd = open (path, 0);
#if defined R_GRASS_INTERFACE && defined __MINGW32_VERSION
        setmode(G_fd, O_BINARY);
#endif /* __MINGW32_VERSION && R_GRASS_INTERFACE */
        return G_fd;
    }
/* WRITE */
    if (mode == 1 || mode == 2)
    {
	if (G__name_is_fully_qualified (name, xname, xmapset))
	{
	    if (strcmp (xmapset, G_mapset()) != 0) {
		fprintf(stderr, "G__open(w): xmapset (%s) != G_mapset() (%s)\n",
			xmapset,G_mapset());
		return -1;
	    }
	    name = xname;
	}

	if (G_legal_filename(name) == -1)
	    return -1;

	G__file_name (path, element, name, G_mapset());
	if(mode == 1 || access(path,0) != 0)
	{
	    G__make_mapset_element (element);
	    close (creat (path, 0666));
	}

      G_fd = open (path, mode);
#if defined R_GRASS_INTERFACE && defined __MINGW32_VERSION
      setmode(G_fd, O_BINARY);
#endif /* __MINGW32_VERSION && R_GRASS_INTERFACE */
      return G_fd;
   }
    return -1;
}
Esempio n. 18
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);
}
Esempio n. 19
0
int main(int argc, char *argv[])
{
    char buf[512];
    FILE *fd;
    long old_min, old_max;
    long new_min, new_max;
    long new_delta, old_delta;
    long value, first, prev;
    long cat;
    float divisor;
    char *old_name;
    char *new_name;
    char *mapset;
    struct GModule *module;
    struct
    {
	struct Option *input, *from, *output, *to, *title;
    } parm;

    /* please, remove before GRASS 7 released */
    struct
    {
	struct Flag *quiet;
    } flag;

    G_gisinit(argv[0]);

    module = G_define_module();
    module->keywords = _("raster, rescale");
    module->description =
	_("Rescales the range of category values " "in a raster map layer.");

    /* 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 = _("The name of the raster map to be rescaled");

    parm.from = G_define_option();
    parm.from->key = "from";
    parm.from->key_desc = "min,max";
    parm.from->type = TYPE_INTEGER;
    parm.from->required = NO;
    parm.from->description =
	_("The input data range to be rescaled (default: full range of input map)");

    parm.output = G_define_option();
    parm.output->key = "output";
    parm.output->type = TYPE_STRING;
    parm.output->required = YES;
    parm.output->gisprompt = "new,cell,raster";
    parm.output->description = _("The resulting raster map name");

    parm.to = G_define_option();
    parm.to->key = "to";
    parm.to->key_desc = "min,max";
    parm.to->type = TYPE_INTEGER;
    parm.to->required = YES;
    parm.to->description = _("The output data range");

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

    /* please, remove before GRASS 7 released */
    flag.quiet = G_define_flag();
    flag.quiet->key = 'q';
    flag.quiet->description = _("Quietly");

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

    /* please, remove before GRASS 7 released */
    if (flag.quiet->answer) {
	putenv("GRASS_VERBOSE=0");
	G_warning(_("The '-q' flag is superseded and will be removed "
		    "in future. Please use '--quiet' instead."));
    }

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

    mapset = G_find_cell(old_name, "");
    if (mapset == NULL) {
	sprintf(buf, "%s - not found\n", old_name);
	G_fatal_error(buf);
    }
    if (G_legal_filename(new_name) < 0) {
	sprintf(buf, "%s - illegal map name\n", new_name);
	G_fatal_error(buf);
    }

    if (parm.from->answer) {
	sscanf(parm.from->answers[0], "%ld", &old_min);
	sscanf(parm.from->answers[1], "%ld", &old_max);

    }
    else
	get_range(old_name, mapset, &old_min, &old_max);
    if (old_min > old_max) {
	value = old_min;	/* swap */
	old_min = old_max;
	old_max = value;
    }

    sscanf(parm.to->answers[0], "%ld", &new_min);
    sscanf(parm.to->answers[1], "%ld", &new_max);
    if (new_min > new_max) {
	value = new_min;	/* swap */
	new_min = new_max;
	new_max = value;
    }

    G_message(_("Rescale %s[%ld,%ld] to %s[%ld,%ld]"),
	      old_name, old_min, old_max, new_name, new_min, new_max);

    sprintf(buf, "r.reclass input=\"%s\" output=\"%s\" title=\"", old_name,
	    new_name);
    if (parm.title->answer)
	strcat(buf, parm.title->answer);
    else {
	strcat(buf, "rescale of ");
	strcat(buf, old_name);
    }
    strcat(buf, "\"");

    fd = popen(buf, "w");
    old_delta = old_max - old_min;
    new_delta = new_max - new_min;
    divisor = (float)new_delta / (float)old_delta;

    prev = new_min;
    first = old_min;
    for (cat = old_min; cat <= old_max; cat++) {
	value = (int)(divisor * (cat - old_min) + new_min + .5);
	if (value != prev) {
	    fprintf(fd, "%ld thru %ld = %ld %ld", first, cat - 1, prev,
		    first);
	    if (cat - 1 != first)
		fprintf(fd, " thru %ld", cat - 1);
	    fprintf(fd, "\n");
	    prev = value;
	    first = cat;
	}
    }
    fprintf(fd, "%ld thru %ld = %ld %ld", first, cat - 1, prev, first);
    if (cat - 1 != first)
	fprintf(fd, " thru %ld", cat - 1);
    fprintf(fd, "\n");

    pclose(fd);
    exit(EXIT_SUCCESS);
}
Esempio n. 20
0
/*!
 * \brief Check input and output file names.
 *
 * Check: 
 *  1) output is legal map name,
 *  2) if can find input map, and
 *  3) if input was found in current mapset, check if input != output.
 *
 * \param input input map name
 * \param output output map name
 * \param error error type: G_FATAL_EXIT, G_FATAL_PRINT, G_FATAL_RETURN
 *
 * \return 0 OK
 * \return 1 error
 */
int G_check_input_output_name(const char *input, const char *output,
			      int error)
{
    const char *mapset;

    if (output == NULL)
	return 0;		/* don't die on undefined parameters */
    if (G_legal_filename(output) == -1) {
	if (error == G_FATAL_EXIT) {
	    G_fatal_error(_("Output raster map name <%s> is not valid map name"),
			  output);
	}
	else if (error == G_FATAL_PRINT) {
	    G_warning(_("Output raster map name <%s> is not valid map name"),
		      output);
	    return 1;
	}
	else {			/* G_FATAL_RETURN */
	    return 1;
	}
    }

    mapset = G_find_raster2(input, "");

    if (mapset == NULL) {
	if (error == G_FATAL_EXIT) {
	    G_fatal_error(_("Raster map <%s> not found"), input);
	}
	else if (error == G_FATAL_PRINT) {
	    G_warning(_("Raster map <%s> not found"), input);
	    return 1;
	}
	else {			/* G_FATAL_RETURN */
	    return 1;
	}
    }

    if (strcmp(mapset, G_mapset()) == 0) {
	char nm[1000], ms[1000];
	const char *in;

	if (G_name_is_fully_qualified(input, nm, ms)) {
	    in = nm;
	}
	else {
	    in = input;
	}

	if (strcmp(in, output) == 0) {
	    if (error == G_FATAL_EXIT) {
		G_fatal_error(_("Output raster map <%s> is used as input"),
			      output);
	    }
	    else if (error == G_FATAL_PRINT) {
		G_warning(_("Output raster map <%s> is used as input"),
			  output);
		return 1;
	    }
	    else {		/* G_FATAL_RETURN */
		return 1;
	    }
	}
    }

    return 0;
}
Esempio n. 21
0
int main(int argc, char *argv[])
{
    int i, n, nlist;
    const char *mapset;
    struct GModule *module;
    struct Option **parm;
    char *from, *to;
    int result = EXIT_SUCCESS;

    G_gisinit(argv[0]);

    M_read_list(FALSE, &nlist);

    module = G_define_module();
    G_add_keyword(_("general"));
    G_add_keyword(_("map management"));
    module->description =
	_("Copies available data files in the current mapset "
	  "search path to the user's current mapset.");
    module->overwrite = 1;

    parm = (struct Option **) G_calloc(nlist, sizeof(struct Option *));

    for (n = 0; n < nlist; n++) {
      parm[n] = M_define_option(n, _("copied"), NO);
    }

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

    for (n = 0; n < nlist; n++) {
	if (parm[n]->answers == NULL)
	    continue;
	i = 0;
	while (parm[n]->answers[i]) {
	    from = parm[n]->answers[i++];
	    to = parm[n]->answers[i++];
	    mapset = M_find(n, from, "");
	    if (!mapset) {
		G_warning(_("<%s> not found"), from);
		continue;
	    }
	    if (G_strcasecmp(mapset, G_mapset()) == 0 &&
		G_strcasecmp(from, to) == 0) {
		G_warning(_("%s=%s,%s: files are the same, no copy required"),
			  parm[n]->key, from, to);
		continue;
	    }
	    if (M_find(n, to, G_mapset()) && !(module->overwrite)) {
		G_warning(_("<%s> already exists. File not copied."), to);
		continue;
	    }
	    if (G_legal_filename(to) < 0) {
		G_warning(_("<%s> is an illegal file name"), to);
		continue;
	    }
	    if (M_do_copy(n, from, mapset, to) == 1) {
		result = EXIT_FAILURE;
	    }
	    G_remove_misc("cell_misc", "reclassed_to", to);
	}
    }

    exit(result);
}
Esempio n. 22
0
int parse_args(int argc, char *argv[], struct globals *globals)
{
    struct Option *group, *seeds, *bounds, *output,
                  *method, *similarity, *threshold, *min_segment_size,
#ifdef _OR_SHAPE_
		  *shape_weight, *smooth_weight,
#endif
		   *mem;
    struct Flag *diagonal, *weighted;
    struct Option *outband, *endt;

    /* required parameters */
    group = G_define_standard_option(G_OPT_I_GROUP);

    output = G_define_standard_option(G_OPT_R_OUTPUT);

    threshold = G_define_option();
    threshold->key = "threshold";
    threshold->type = TYPE_DOUBLE;
    threshold->required = YES;
    threshold->label = _("Difference threshold between 0 and 1");
    threshold->description = _("Threshold = 0 merges only identical segments; threshold = 1 merges all");

    /* optional parameters */

    method = G_define_option();
    method->key = "method";
    method->type = TYPE_STRING;
    method->required = NO;
    method->answer = "region_growing";
    method->options = "region_growing,mean_shift,watershed";
    method->description = _("Segmentation method");
    method->guisection = _("Settings");

    similarity = G_define_option();
    similarity->key = "similarity";
    similarity->type = TYPE_STRING;
    similarity->required = NO;
    similarity->answer = "euclidean";
    similarity->options = "euclidean,manhattan";
    similarity->description = _("Similarity calculation method");
    similarity->guisection = _("Settings");

    min_segment_size = G_define_option();
    min_segment_size->key = "minsize";
    min_segment_size->type = TYPE_INTEGER;
    min_segment_size->required = NO;
    min_segment_size->answer = "1";
    min_segment_size->options = "1-100000";
    min_segment_size->label = _("Minimum number of cells in a segment");
    min_segment_size->description =
	_("The final step will merge small segments with their best neighbor");
    min_segment_size->guisection = _("Settings");

#ifdef _OR_SHAPE_
    radio_weight = G_define_option();
    radio_weight->key = "radio_weight";
    radio_weight->type = TYPE_DOUBLE;
    radio_weight->required = NO;
    radio_weight->answer = "1";
    radio_weight->options = "0-1";
    radio_weight->label =
	_("Importance of radiometric (input raster) values relative to shape");
    radio_weight->guisection = _("Settings");

    smooth_weight = G_define_option();
    smooth_weight->key = "smooth_weight";
    smooth_weight->type = TYPE_DOUBLE;
    smooth_weight->required = NO;
    smooth_weight->answer = "0.5";
    smooth_weight->options = "0-1";
    smooth_weight->label =
	_("Importance of smoothness relative to compactness");
    smooth_weight->guisection = _("Settings");
#endif

    mem = G_define_option();
    mem->key = "memory";
    mem->type = TYPE_INTEGER;
    mem->required = NO;
    mem->answer = "300";
    mem->description = _("Memory in MB");

    /* TODO input for distance function */

    /* debug parameters */
    endt = G_define_option();
    endt->key = "iterations";
    endt->type = TYPE_INTEGER;
    endt->required = NO;
    endt->answer = "20";
    endt->description = _("Maximum number of iterations");
    endt->guisection = _("Settings");

    /* Using raster for seeds
     * Low priority TODO: allow vector points/centroids seed input. */
    seeds = G_define_standard_option(G_OPT_R_INPUT);
    seeds->key = "seeds";
    seeds->required = NO;
    seeds->description = _("Name for input raster map with starting seeds");

    /* Polygon constraints. */
    bounds = G_define_standard_option(G_OPT_R_INPUT);
    bounds->key = "bounds";
    bounds->required = NO;
    bounds->label = _("Name of input bounding/constraining raster map");
    bounds->description =
	_("Must be integer values, each area will be segmented independent of the others");

    outband = G_define_standard_option(G_OPT_R_OUTPUT);
    outband->key = "goodness";
    outband->required = NO;
    outband->description =
	_("Name for output goodness of fit estimate map");

    diagonal = G_define_flag();
    diagonal->key = 'd';
    diagonal->description =
	_("Use 8 neighbors (3x3 neighborhood) instead of the default 4 neighbors for each pixel");
    diagonal->guisection = _("Settings");

    weighted = G_define_flag();
    weighted->key = 'w';
    weighted->description =
	_("Weighted input, do not perform the default scaling of input raster maps");
    weighted->guisection = _("Settings");

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

    /* Check and save parameters */

    globals->image_group = group->answer;

    if (G_legal_filename(output->answer) == TRUE)
	globals->out_name = output->answer;
    else
	G_fatal_error("Invalid output raster name");

    /* Note: this threshold is scaled after we know more at the beginning of create_isegs() */
    globals->alpha = atof(threshold->answer);

    if (globals->alpha <= 0 || globals->alpha >= 1)
	G_fatal_error(_("Threshold should be > 0 and < 1"));

    /* segmentation methods */
    if (strcmp(method->answer, "region_growing") == 0) {
	globals->method = ORM_RG;
	globals->method_fn = region_growing;
    }
    else if (strcmp(method->answer, "mean_shift") == 0) {
	globals->method = ORM_MS;
	globals->method_fn = mean_shift;
    }
    else if (strcmp(method->answer, "watershed") == 0) {
	globals->method = ORM_WS;
	globals->method_fn = watershed;
    }
    else
	G_fatal_error(_("Unable to assign segmentation method"));

    G_debug(1, "segmentation method: %s", method->answer);

    /* distance methods for similarity measurement */
    if (strcmp(similarity->answer, "euclidean") == 0)
	globals->calculate_similarity = calculate_euclidean_similarity;
    else if (strcmp(similarity->answer, "manhattan") == 0)
	globals->calculate_similarity = calculate_manhattan_similarity;
    else
	G_fatal_error(_("Invalid similarity method"));

#ifdef _OR_SHAPE_
    /* consider shape */
    globals->radio_weight = atof(radio_weight->answer);
    if (globals->radio_weight <= 0)
	G_fatal_error(_("Option '%s' must be > 0"), radio_weight->key);
    if (globals->radio_weight > 1)
	G_fatal_error(_("Option '%s' must be <= 1"), radio_weight->key);
    globals->smooth_weight = atof(smooth_weight->answer);
    if (globals->smooth_weight < 0)
	G_fatal_error(_("Option '%s' must be >= 0"), smooth_weight->key);
    if (globals->smooth_weight > 1)
	G_fatal_error(_("Option '%s' must be <= 1"), smooth_weight->key);
#else
    globals->radio_weight = 1;
    globals->smooth_weight = 0.5;
#endif

    globals->min_segment_size = atoi(min_segment_size->answer);

    if (diagonal->answer == FALSE) {
	globals->find_neighbors = find_four_neighbors;
	globals->nn = 4;
	G_debug(1, "four pixel neighborhood");
    }
    else if (diagonal->answer == TRUE) {
	globals->find_neighbors = find_eight_neighbors;
	globals->nn = 8;
	G_debug(1, "eight (3x3) pixel neighborhood");
    }

    /* default/0 for performing the scaling
     * selected/1 if scaling should be skipped. */
    globals->weighted = weighted->answer;

    globals->seeds = seeds->answer;
    if (globals->seeds) {
	if (G_find_raster(globals->seeds, "") == NULL) {
	    G_fatal_error(_("Seeds raster map not found"));
	}
	if (Rast_map_type(globals->seeds, "") !=
	    CELL_TYPE) {
	    G_fatal_error(_("Seeeds raster map must be CELL type (integers)"));
	}
    }

    if (bounds->answer == NULL) {
	globals->bounds_map = NULL;
    }
    else {
	globals->bounds_map = bounds->answer;
	if ((globals->bounds_mapset = G_find_raster(globals->bounds_map, "")) == NULL) {
	    G_fatal_error(_("Segmentation constraint/boundary raster map not found"));
	}
	if (Rast_map_type(globals->bounds_map, globals->bounds_mapset) !=
	    CELL_TYPE) {
	    G_fatal_error(_("Segmentation constraint raster map must be CELL type (integers)"));
	}
    }

    /* other data */
    globals->nrows = Rast_window_rows();
    globals->ncols = Rast_window_cols();

    /* debug help */
    if (outband->answer == NULL)
	globals->out_band = NULL;
    else {
	if (G_legal_filename(outband->answer) == TRUE)
	    globals->out_band = outband->answer;
	else
	    G_fatal_error(_("Invalid output raster name for goodness of fit"));
    }

    if (endt->answer) {
	if (atoi(endt->answer) > 0)
	    globals->end_t = atoi(endt->answer);
	else {
	    globals->end_t = 100;
	    G_warning(_("Invalid number of iterations, 100 will be used"));
	}
    }
    else
	globals->end_t = 1000;

    if (mem->answer && atoi(mem->answer) > 10)
	globals->mb = atoi(mem->answer);
    else {
	globals->mb = 300;
	G_warning(_("Invalid number of MB, 300 will be used"));
    }

    return TRUE;
}
Esempio n. 23
0
int main(int argc, char **argv)
{
	IO rasters[] = { /* rasters stores output buffers */
		{"dem",YES,"Input dem","input",UNKNOWN,-1,NULL}, /* WARNING: this one map is input */
		{"forms",NO,"Most common geomorphic forms","patterns",CELL_TYPE,-1,NULL},
		{"ternary",NO,"code of ternary patterns","patterns",CELL_TYPE,-1,NULL},
		{"positive",NO,"code of binary positive patterns","patterns",CELL_TYPE,-1,NULL},
		{"negative",NO,"code of binary negative patterns","patterns",CELL_TYPE,-1,NULL},
		{"intensity",NO,"rasters containing mean relative elevation of the form","geometry",FCELL_TYPE,-1,NULL},
		{"exposition",NO,"rasters containing maximum difference between extend and central cell","geometry",FCELL_TYPE,-1,NULL},
		{"range",NO,"rasters containing difference between max and min elevation of the form extend","geometry",FCELL_TYPE,-1,NULL},
		{"variance",NO,"rasters containing variance of form boundary","geometry",FCELL_TYPE,-1,NULL},
		{"elongation",NO,"rasters containing local elongation","geometry",FCELL_TYPE,-1,NULL},
		{"azimuth",NO,"rasters containing local azimuth of the elongation","geometry",FCELL_TYPE,-1,NULL},
		{"extend",NO,"rasters containing local extend (area) of the form","geometry",FCELL_TYPE,-1,NULL},
		{"width",NO,"rasters containing local width of the form","geometry",FCELL_TYPE,-1,NULL}
	}; /* adding more maps change IOSIZE macro */
	
	CATCOLORS ccolors[CNT]={ /* colors and cats for forms */
		{ZERO, 0, 0, 0, "forms"},
		{FL, 220, 220, 220, "flat"},
		{PK, 56, 0, 0, "summit"},
		{RI, 200, 0, 0, "ridge"},
		{SH, 255, 80, 20, "shoulder"},
		{CV, 250, 210, 60, "spur"},
		{SL, 255, 255, 60, "slope"},
		{CN, 180, 230, 20, "hollow"},
		{FS, 60, 250, 150, "footslope"},
		{VL, 0, 0, 255, "valley"},
		{PT, 0, 0, 56, "depression"},
		{__, 255, 0, 255, "ERROR"}};

struct GModule *module;
	struct Option
					*opt_input,
					*opt_output[io_size],
					*par_search_radius,
					*par_skip_radius,
					*par_flat_treshold,
					*par_flat_distance;
	struct Flag *flag_units,
							*flag_extended;

	struct History history;

	int i,j, n;
	int meters=0, multires=0, extended=0; /* flags */
	int row,cur_row,col,radius;
	int pattern_size;
	double max_resolution;
	char prefix[20];

	G_gisinit(argv[0]);

{  /* interface  parameters */
	module = G_define_module();
	module->description =
	_("Calculate geomorphons (terrain forms)and associated geometry using machine vision approach");
	G_add_keyword("Geomorphons");
	G_add_keyword("Terrain patterns");
	G_add_keyword("Machine vision geomorphometry");

	opt_input = G_define_standard_option(G_OPT_R_INPUT);
	opt_input->key = rasters[0].name;
	opt_input->required = rasters[0].required;
	opt_input->description = _(rasters[0].description);

		for (i=1;i<io_size;++i) { /* WARNING: loop starts from one, zero is for input */
	opt_output[i] = G_define_standard_option(G_OPT_R_OUTPUT);
	opt_output[i]->key = rasters[i].name;
	opt_output[i]->required = NO;
	opt_output[i]->description = _(rasters[i].description);
	opt_output[i]->guisection = _(rasters[i].gui);
		}

	par_search_radius = G_define_option();
	par_search_radius->key = "search";
	par_search_radius->type = TYPE_INTEGER;
	par_search_radius->answer = "3";
	par_search_radius->required = YES;
	par_search_radius->description = _("Outer search radius");

	par_skip_radius = G_define_option();
	par_skip_radius->key = "skip";
	par_skip_radius->type = TYPE_INTEGER;
	par_skip_radius->answer = "0";
	par_skip_radius->required = YES;
	par_skip_radius->description = _("Inner search radius");

	par_flat_treshold = G_define_option();
	par_flat_treshold->key = "flat";
	par_flat_treshold->type = TYPE_DOUBLE;
	par_flat_treshold->answer = "1";
	par_flat_treshold->required = YES;
	par_flat_treshold->description = _("Flatenss treshold (degrees)");

	par_flat_distance = G_define_option();
	par_flat_distance->key = "dist";
	par_flat_distance->type = TYPE_DOUBLE;
	par_flat_distance->answer = "0";
	par_flat_distance->required = YES;
	par_flat_distance->description = _("Flatenss distance, zero for none");

	flag_units = G_define_flag();
	flag_units->key = 'm';
	flag_units->description = _("Use meters to define search units (default is cells)");

	flag_extended = G_define_flag();
	flag_extended->key = 'e';
	flag_extended->description = _("Use extended form correction");

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

{	/* calculate parameters */
	int num_outputs=0;
	double search_radius, skip_radius, start_radius, step_radius;
	double ns_resolution;

			for (i=1;i<io_size;++i) /* check for outputs */
	if(opt_output[i]->answer) {
			if (G_legal_filename(opt_output[i]->answer) < 0)
		G_fatal_error(_("<%s> is an illegal file name"), opt_output[i]->answer);
		num_outputs++;
	}
		if(!num_outputs && !multires)
	G_fatal_error(_("At least one output is required"));

	meters=(flag_units->answer != 0);
	extended=(flag_extended->answer != 0);
	nrows = Rast_window_rows();
	ncols = Rast_window_cols();
	Rast_get_window(&window);
	G_begin_distance_calculations();

	if(G_projection()==PROJECTION_LL)	{ /* for LL max_res should be NS */
		ns_resolution=G_distance(0,Rast_row_to_northing(0, &window),0,Rast_row_to_northing(1, &window));
		max_resolution=ns_resolution;
	} else {
		max_resolution=MAX(window.ns_res,window.ew_res); /* max_resolution MORE meters per cell */
	}
	G_message("NSRES, %f", ns_resolution);
	cell_res=max_resolution; /* this parameter is global */
	/* search distance */
	search_radius=atof(par_search_radius->answer);
	search_cells=meters?(int)(search_radius/max_resolution):search_radius;
		if(search_cells<1)
	G_fatal_error(_("Search radius size must cover at least 1 cell"));
	row_radius_size=meters?ceil(search_radius/max_resolution):search_radius;
	row_buffer_size=row_radius_size*2+1;
	search_distance=(meters)?search_radius:max_resolution*search_cells;
	/* skip distance */
	skip_radius=atof(par_skip_radius->answer);
	skip_cells=meters?(int)(skip_radius/max_resolution):skip_radius;
		if(skip_cells>=search_cells)
	G_fatal_error(_("Skip radius size must be at least 1 cell lower than radius"));
	skip_distance=(meters)?skip_radius:ns_resolution*skip_cells;

	/* flatness parameters */
	flat_threshold=atof(par_flat_treshold->answer);
		if(flat_threshold<=0.)
	G_fatal_error(_("Flatenss treshold must be grater than 0"));
	flat_threshold=DEGREE2RAD(flat_threshold);
	
	flat_distance=atof(par_flat_distance->answer);
	flat_distance=(meters)?flat_distance:ns_resolution*flat_distance;
	flat_threshold_height=tan(flat_threshold)*flat_distance;
	if((flat_distance>0&&flat_distance<=skip_distance)||flat_distance>=search_distance) {
		G_warning(_("Flatenss distance should be between skip and search radius. Otherwise ignored"));
		flat_distance=0;
	}
		if (search_distance<10*cell_res)
	extended=0;
	
	/* print information about distances */
	G_message("Search distance m: %f, cells: %d", search_distance, search_cells);
	G_message("Skip distance m: %f, cells: %d", skip_distance, skip_cells);
	G_message("Flat threshold distance m: %f, height: %f",flat_distance, flat_threshold_height);
	G_message("%s version",(extended)?"extended":"basic");
}

	/* generate global ternary codes */
		for(i=0;i<6561;++i)
	global_ternary_codes[i]=ternary_rotate(i);

	/* open DEM */
	strcpy(elevation.elevname,opt_input->answer);
	open_map(&elevation);

	PATTERN* pattern;
	PATTERN patterns[4];
	void* pointer_buf;
	int formA, formB, formC;
	double search_dist=search_distance;
	double skip_dist=skip_distance;
	double flat_dist=flat_distance;
	double area_of_octagon=4*(search_distance*search_distance)*sin(DEGREE2RAD(45.));

	cell_step=1;
	/* prepare outputs */
		for (i=1;i<io_size;++i) 
	if(opt_output[i]->answer) {
		rasters[i].fd=Rast_open_new(opt_output[i]->answer,rasters[i].out_data_type);
		rasters[i].buffer=Rast_allocate_buf(rasters[i].out_data_type);
	}
	
	/* main loop */
	for(row=0;row<nrows;++row) {
		G_percent(row, nrows, 2);
		cur_row = (row < row_radius_size)?row:
			((row >= nrows-row_radius_size-1) ? row_buffer_size - (nrows-row-1) : row_radius_size);
			
			if(row>(row_radius_size) && row<nrows-(row_radius_size+1))
		shift_buffers(row);
		for (col=0;col<ncols;++col) {
		/* on borders forms ussualy are innatural. */
			if(row<(skip_cells+1) || row>nrows-(skip_cells+2) ||
				col<(skip_cells+1) || col>ncols-(skip_cells+2) ||
				Rast_is_f_null_value(&elevation.elev[cur_row][col])) {
/* set outputs to NULL and do nothing if source value is null	or border*/
				for (i=1;i<io_size;++i)
					if(opt_output[i]->answer) {
						pointer_buf=rasters[i].buffer;
						switch (rasters[i].out_data_type) {
						case CELL_TYPE:
							Rast_set_c_null_value(&((CELL*)pointer_buf)[col],1);
							break;
						case FCELL_TYPE:
							Rast_set_f_null_value(&((FCELL*)pointer_buf)[col],1);
							break;
						case DCELL_TYPE:
							Rast_set_d_null_value(&((DCELL*)pointer_buf)[col],1);
							break;
						default:
							G_fatal_error(_("Unknown output data type"));
						}
					}
					continue; 
			} /* end null value */
{
	int cur_form, small_form;
	search_distance=search_dist;
	skip_distance=skip_dist;
	flat_distance=flat_dist;

	pattern_size=calc_pattern(&patterns[0],row,cur_row,col);
	pattern=&patterns[0];
	cur_form=determine_form(pattern->num_negatives,pattern->num_positives);

	/* correction of forms */
	if(extended) {
		/* 1) remove extensive innatural forms: ridges, peaks, shoulders and footslopes */
		if((cur_form==4||cur_form==8||cur_form==2||cur_form==3)) {
			search_distance=(search_dist/4.<4*max_resolution)? 4*max_resolution : search_dist/4.;
			skip_distance=0;
			flat_distance=0;
			pattern_size=calc_pattern(&patterns[1],row,cur_row,col);
			pattern=&patterns[1];
			small_form=determine_form(pattern->num_negatives,pattern->num_positives);
				if(cur_form==4||cur_form==8)
			cur_form=(small_form==1)? 1 : cur_form;
				if(cur_form==2||cur_form==3)
			cur_form=small_form;
		}
		
 } /* end of correction */
	pattern=&patterns[0];
		if(opt_output[o_forms]->answer) 
	((CELL*)rasters[o_forms].buffer)[col]=cur_form;
}

				if(opt_output[o_ternary]->answer)
			((CELL*)rasters[o_ternary].buffer)[col]=determine_ternary(pattern->pattern);
				if(opt_output[o_positive]->answer)
			((CELL*)rasters[o_positive].buffer)[col]=pattern->num_positives;//rotate(pattern->positives);
				if(opt_output[o_negative]->answer)
			((CELL*)rasters[o_negative].buffer)[col]=pattern->num_negatives;//rotate(pattern->negatives);
				if(opt_output[o_intensity]->answer)
			((FCELL*)rasters[o_intensity].buffer)[col]=intensity(pattern->elevation,pattern_size);
				if(opt_output[o_exposition]->answer)
			((FCELL*)rasters[o_exposition].buffer)[col]=exposition(pattern->elevation);
				if(opt_output[o_range]->answer)
			((FCELL*)rasters[o_range].buffer)[col]=range(pattern->elevation);
				if(opt_output[o_variance]->answer)
			((FCELL*)rasters[o_variance].buffer)[col]=variance(pattern->elevation, pattern_size);

//			 used only for next four shape functions 
			if(opt_output[o_elongation]->answer ||opt_output[o_azimuth]->answer||
				opt_output[o_extend]->answer || opt_output[o_width]->answer) {
				float azimuth,elongation,width;
				radial2cartesian(pattern);
				shape(pattern, pattern_size,&azimuth,&elongation,&width);
					if(opt_output[o_azimuth]->answer)
				((FCELL*)rasters[o_azimuth].buffer)[col]=azimuth;
					if(opt_output[o_elongation]->answer)
				((FCELL*)rasters[o_elongation].buffer)[col]=elongation;
					if(opt_output[o_width]->answer)
				((FCELL*)rasters[o_width].buffer)[col]=width;
			}
				if(opt_output[o_extend]->answer)
			((FCELL*)rasters[o_extend].buffer)[col]=extends(pattern, pattern_size)/area_of_octagon;

		} /* end for col */

		/* write existing outputs */
				for (i=1;i<io_size;++i)
			if(opt_output[i]->answer)
		Rast_put_row(rasters[i].fd, rasters[i].buffer, rasters[i].out_data_type);
	}
	G_percent(row, nrows, 2); /* end main loop */

	/* finish and close */
	free_map(elevation.elev, row_buffer_size+1);
		for (i=1;i<io_size;++i)
	if(opt_output[i]->answer) {
		G_free(rasters[i].buffer);
		Rast_close(rasters[i].fd);
		Rast_short_history(opt_output[i]->answer, "raster", &history);
		Rast_command_history(&history);
		Rast_write_history(opt_output[i]->answer, &history);
	}

		if(opt_output[o_forms]->answer)
	write_form_cat_colors(opt_output[o_forms]->answer,ccolors);
		if(opt_output[o_intensity]->answer)
	write_contrast_colors(opt_output[o_intensity]->answer);
		if(opt_output[o_exposition]->answer)
	write_contrast_colors(opt_output[o_exposition]->answer);
		if(opt_output[o_range]->answer)
	write_contrast_colors(opt_output[o_range]->answer);

G_message("Done!");
exit(EXIT_SUCCESS);
}
Esempio n. 24
0
int main(int argc, char *argv[])
{
    struct GModule *module;
    struct
    {
	struct Option *base, *cover, *output;
    } parm;
    char *basemap, *base_mapset;
    char *covermap, *cover_mapset;
    char *outmap;
    char command[1024];
    struct Categories cover_cats;
    FILE *stats_fd, *reclass_fd;
    int first;
    long basecat, covercat, catb, catc;
    double area;
    struct stats stats;

    G_gisinit(argv[0]);

    module = G_define_module();
    module->keywords = _("raster, statistics");
    module->description =
	_("Finds the median of values in a cover map within "
	  "areas assigned the same category value in a "
	  "user-specified base map.");

    parm.base = G_define_standard_option(G_OPT_R_INPUT);
    parm.base->key = "base";
    parm.base->description = _("Name of base raster map");

    parm.cover = G_define_standard_option(G_OPT_R_INPUT);
    parm.cover->key = "cover";
    parm.cover->description = _("Name of cover raster map");

    parm.output = G_define_standard_option(G_OPT_R_OUTPUT);

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

    basemap = parm.base->answer;
    covermap = parm.cover->answer;
    outmap = parm.output->answer;

    base_mapset = G_find_cell2(basemap, "");
    if (base_mapset == NULL)
	G_fatal_error(_("Base raster map <%s> not found"), basemap);

    cover_mapset = G_find_cell2(covermap, "");
    if (cover_mapset == NULL)
	G_fatal_error(_("Raster map <%s> not found"), covermap);
    if (G_legal_filename(outmap) < 0)
	G_fatal_error(_("<%s> is an illegal file name"), outmap);
    if (strcmp(G_mapset(), base_mapset) == 0 && strcmp(basemap, outmap) == 0)
	G_fatal_error(_("Base map and output map <%s> must be different"),
		      outmap);
    if (G_read_cats(covermap, cover_mapset, &cover_cats) < 0)
	G_fatal_error(_("Unable to read category labels of raster map <%s>"),
		      covermap);

    strcpy(command, "r.stats -an \"");
    strcat(command, G_fully_qualified_name(basemap, base_mapset));
    strcat(command, ",");
    strcat(command, G_fully_qualified_name(covermap, cover_mapset));
    strcat(command, "\"");

    /* strcpy (command,"cat /tmp/t"); */
    G_debug(3, "command: %s", command);
    stats_fd = popen(command, "r");

    G_debug(3, "r.reclass i=\"%s\" o=\"%s\"",
	    G_fully_qualified_name(basemap, base_mapset), outmap);
    sprintf(command, "r.reclass i=\"%s\" o=\"%s\"",
	    G_fully_qualified_name(basemap, base_mapset), outmap);

    reclass_fd = popen(command, "w");

    first = 1;
    while (read_stats(stats_fd, &basecat, &covercat, &area)) {
	if (first) {
	    stats.n = 0;
	    stats.nalloc = 16;
	    stats.cat = (long *)
		G_calloc(stats.nalloc, sizeof(long));
	    stats.area = (double *)
		G_calloc(stats.nalloc, sizeof(double));
	    first = 0;
	    catb = basecat;
	}
	if (basecat != catb) {
	    catc = median(&stats);
	    write_reclass(reclass_fd, catb, catc,
			  G_get_cat(catc, &cover_cats));
	    catb = basecat;
	    stats.n = 0;
	}
	stats.n++;
	if (stats.n > stats.nalloc) {
	    stats.nalloc *= 2;
	    stats.cat = (long *)
		G_realloc(stats.cat, stats.nalloc * sizeof(long));
	    stats.area = (double *)
		G_realloc(stats.area, stats.nalloc * sizeof(double));
	}
	stats.cat[stats.n - 1] = covercat;
	stats.area[stats.n - 1] = area;
    }
    if (!first) {
	catc = median(&stats);
	write_reclass(reclass_fd, catb, catc, G_get_cat(catc, &cover_cats));
    }

    pclose(stats_fd);
    pclose(reclass_fd);

    exit(EXIT_SUCCESS);
}
Esempio n. 25
0
int main(int argc, char *argv[])
{
    struct History history;
    struct GModule *module;
    char *desc;

    struct Cell_head cellhd, orig_cellhd;

    void *inrast, *outrast;
    int infd, outfd;
    void *ptr;
    int nrows, ncols, row, col;

    RASTER_MAP_TYPE in_data_type;

    struct Option *input_prefix, *output_prefix, *metfn, *sensor, *adate,
	*pdate, *elev, *bgain, *metho, *perc, *dark, *atmo, *lsatmet, *oscale;
    char *inputname, *met, *outputname, *sensorname;
    struct Flag *frad, *print_meta, *named;

    lsat_data lsat;
    char band_in[GNAME_MAX], band_out[GNAME_MAX];
    int i, j, q, method, pixel, dn_dark[MAX_BANDS], dn_mode[MAX_BANDS], dn_sat;
    int overwrite;
    double qcal, rad, ref, percent, ref_mode, rayleigh, scale;
    unsigned long hist[QCALMAX], h_max;

    struct Colors colors;
    struct FPRange range;
    double min, max;

    /* initialize GIS environment */
    G_gisinit(argv[0]);

    /* initialize module */
    module = G_define_module();
    module->description =
	_("Calculates top-of-atmosphere radiance or reflectance and temperature for Landsat MSS/TM/ETM+/OLI");
    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(_("Landsat"));
    G_add_keyword(_("atmospheric correction"));
    module->overwrite = TRUE;

    /* It defines the different parameters */
    input_prefix = G_define_standard_option(G_OPT_R_BASENAME_INPUT);
    input_prefix->label = _("Base name of input raster bands");
    input_prefix->description = _("Example: 'B.' for B.1, B.2, ...");

    output_prefix = G_define_standard_option(G_OPT_R_BASENAME_OUTPUT);
    output_prefix->label = _("Prefix for output raster maps");
    output_prefix->description =
	_("Example: 'B.toar.' generates B.toar.1, B.toar.2, ...");

    metfn = G_define_standard_option(G_OPT_F_INPUT);
    metfn->key = "metfile";
    metfn->required = NO;
    metfn->description = _("Name of Landsat metadata file (.met or MTL.txt)");
    metfn->guisection = _("Metadata");

    sensor = G_define_option();
    sensor->key = "sensor";
    sensor->type = TYPE_STRING;
    sensor->label = _("Spacecraft sensor");
    sensor->description = _("Required only if 'metfile' not given (recommended for sanity)");
    sensor->options = "mss1,mss2,mss3,mss4,mss5,tm4,tm5,tm7,oli8";
    desc = NULL;
    G_asprintf(&desc,
	        "mss1;%s;mss2;%s;mss3;%s;mss4;%s;mss5;%s;tm4;%s;tm5;%s;tm7;%s;oli8;%s",
	        _("Landsat-1 MSS"),
	        _("Landsat-2 MSS"),
	        _("Landsat-3 MSS"),
	        _("Landsat-4 MSS"),
	        _("Landsat-5 MSS"),
	        _("Landsat-4 TM"),
	        _("Landsat-5 TM"),
	        _("Landsat-7 ETM+"),
	        _("Landsat_8 OLI/TIRS"));
    sensor->descriptions = desc;
    sensor->required = NO;	/* perhaps YES for clarity */
    sensor->guisection = _("Metadata");

    metho = G_define_option();
    metho->key = "method";
    metho->type = TYPE_STRING;
    metho->required = NO;
    metho->options = "uncorrected,dos1,dos2,dos2b,dos3,dos4";
    metho->label = _("Atmospheric correction method");
    metho->description = _("Atmospheric correction method");
    metho->answer = "uncorrected";
    metho->guisection = _("Metadata");

    adate = G_define_option();
    adate->key = "date";
    adate->type = TYPE_STRING;
    adate->required = NO;
    adate->key_desc = "yyyy-mm-dd";
    adate->label = _("Image acquisition date (yyyy-mm-dd)");
    adate->description = _("Required only if 'metfile' not given");
    adate->guisection = _("Metadata");

    elev = G_define_option();
    elev->key = "sun_elevation";
    elev->type = TYPE_DOUBLE;
    elev->required = NO;
    elev->label = _("Sun elevation in degrees");
    elev->description = _("Required only if 'metfile' not given");
    elev->guisection = _("Metadata");

    pdate = G_define_option();
    pdate->key = "product_date";
    pdate->type = TYPE_STRING;
    pdate->required = NO;
    pdate->key_desc = "yyyy-mm-dd";
    pdate->label = _("Image creation date (yyyy-mm-dd)");
    pdate->description = _("Required only if 'metfile' not given");
    pdate->guisection = _("Metadata");

    bgain = G_define_option();
    bgain->key = "gain";
    bgain->type = TYPE_STRING;
    bgain->required = NO;
    bgain->label = _("Gain (H/L) of all Landsat ETM+ bands (1-5,61,62,7,8)");
    bgain->description = _("Required only if 'metfile' not given");
    bgain->guisection = _("Settings");

    perc = G_define_option();
    perc->key = "percent";
    perc->type = TYPE_DOUBLE;
    perc->required = NO;
    perc->label = _("Percent of solar radiance in path radiance");
    perc->description = _("Required only if 'method' is any DOS");
    perc->answer = "0.01";
    perc->guisection = _("Settings");

    dark = G_define_option();
    dark->key = "pixel";
    dark->type = TYPE_INTEGER;
    dark->required = NO;
    dark->label =
	_("Minimum pixels to consider digital number as dark object");
    dark->description = _("Required only if 'method' is any DOS");
    dark->answer = "1000";
    dark->guisection = _("Settings");

    atmo = G_define_option();
    atmo->key = "rayleigh";
    atmo->type = TYPE_DOUBLE;
    atmo->required = NO;
    atmo->label = _("Rayleigh atmosphere (diffuse sky irradiance)");	/* scattering coefficient? */
    atmo->description = _("Required only if 'method' is DOS3");
    atmo->answer = "0.0";
    atmo->guisection = _("Settings");

    lsatmet = G_define_option();
    lsatmet->key = "lsatmet";
    lsatmet->type = TYPE_STRING;
    lsatmet->required = NO;
    lsatmet->multiple = YES;
    lsatmet->label = _("return value stored for a given metadata");
    lsatmet->description = _("Required only if 'metfile' and -p given");
    lsatmet->options =
	"number,creation,date,sun_elev,sensor,bands,sunaz,time";
    desc = NULL;
    G_asprintf(&desc,
	       "number;%s;creation;%s;date;%s;sun_elev;%s;sensor;%s;bands;%s;sunaz;%s;time;%s",
	       _("Landsat Number"),
	       _("Creation timestamp"),
	       _("Date"),
	       _("Sun Elevation"),
	       _("Sensor"),
	       _("Bands count"), _("Sun Azimuth Angle"), _("Time"));
    lsatmet->descriptions = desc;
    lsatmet->guisection = _("Settings");

    oscale = G_define_option();
    oscale->key = "scale";
    oscale->type = TYPE_DOUBLE;
    oscale->answer = "1.0";
    oscale->required = NO;
    oscale->description = _("Scale factor for output");

    /* define the different flags */
    frad = G_define_flag();
    frad->key = 'r';
    frad->description =
	_("Output at-sensor radiance instead of reflectance for all bands");

    named = G_define_flag();
    named->key = 'n';
    named->description =
	_("Input raster maps use as extension the number of the band instead the code");

    print_meta = G_define_flag();
    print_meta->key = 'p';
    print_meta->description = _("Print output metadata info");

    /* options and afters parser */
    if (G_parser(argc, argv))
	exit(EXIT_FAILURE);


  /*****************************************
  * ---------- START --------------------
  * Stores options and flags to variables
  *****************************************/
    met = metfn->answer;
    inputname = input_prefix->answer;
    outputname = output_prefix->answer;
    sensorname = sensor->answer ? sensor->answer : "";

    overwrite = G_check_overwrite(argc, argv);

    Rast_get_window(&orig_cellhd);

    G_zero(&lsat, sizeof(lsat));

    if (adate->answer != NULL) {
	strncpy(lsat.date, adate->answer, 11);
	lsat.date[10] = '\0';
	if (strlen(lsat.date) != 10)
	    G_fatal_error(_("Illegal date format: [%s] (yyyy-mm-dd)"),
			  lsat.date);
    }

    if (pdate->answer != NULL) {
	strncpy(lsat.creation, pdate->answer, 11);
	lsat.creation[10] = '\0';
	if (strlen(lsat.creation) != 10)
	    G_fatal_error(_("Illegal date format: [%s] (yyyy-mm-dd)"),
			  lsat.creation);
    }

    lsat.sun_elev = elev->answer == NULL ? 0. : atof(elev->answer);

    percent = atof(perc->answer);
    pixel = atoi(dark->answer);
    rayleigh = atof(atmo->answer);
    scale = atof(oscale->answer);

    /*
     * Data from metadata file
     */
    lsat.flag = NOMETADATAFILE;	/* Unnecessary because G_zero filled, but for sanity */
    if (met != NULL) {
	lsat.flag = METADATAFILE;
	lsat_metadata(met, &lsat);
	if (print_meta->answer) {
	    char *lsatmeta;

	    if (lsatmet->answer == NULL) {
		G_fatal_error(_("Please use a metadata keyword with -p"));
	    }

	    for (i = 0; lsatmet->answers[i] != NULL; i++) {
		lsatmeta = lsatmet->answers[i];

		if (strcmp(lsatmeta, "number") == 0) {
		    fprintf(stdout, "number=%d\n", lsat.number);
		}
		if (strcmp(lsatmeta, "creation") == 0) {
		    fprintf(stdout, "creation=%s\n", lsat.creation);
		}
		if (strcmp(lsatmeta, "date") == 0) {
		    fprintf(stdout, "date=%s\n", lsat.date);
		}
		if (strcmp(lsatmeta, "sun_elev") == 0) {
		    fprintf(stdout, "sun_elev=%f\n", lsat.sun_elev);
		}
		if (strcmp(lsatmeta, "sunaz") == 0) {
		    fprintf(stdout, "sunaz=%f\n", lsat.sun_az);
		}
		if (strcmp(lsatmeta, "sensor") == 0) {
		    fprintf(stdout, "sensor=%s\n", lsat.sensor);
		}
		if (strcmp(lsatmeta, "bands") == 0) {
		    fprintf(stdout, "bands=%d\n", lsat.bands);
		}
		if (strcmp(lsatmet->answer, "time") == 0) {
		    fprintf(stdout, "%f\n", lsat.time);
		}
	    }
	    exit(EXIT_SUCCESS);
	}
	G_debug(1, "lsat.number = %d, lsat.sensor = [%s]",
		lsat.number, lsat.sensor);

	if (!lsat.sensor || lsat.number > 8 || lsat.number < 1)
	    G_fatal_error(_("Failed to identify satellite"));

	G_debug(1, "Landsat-%d %s with data set in metadata file [%s]",
		lsat.number, lsat.sensor, met);

	if (elev->answer != NULL) {
	    lsat.sun_elev = atof(elev->answer);
	    G_warning("Overwriting solar elevation of metadata file");
	}
    }
    /*
     * Data from command line
     */
    else if (adate->answer == NULL || elev->answer == NULL) {
	G_fatal_error(_("Lacking '%s' and/or '%s' for this satellite"),
		      adate->key, elev->key);
    }
    else {
	if (strcmp(sensorname, "tm7") == 0) {
	    if (bgain->answer == NULL || strlen(bgain->answer) != 9)
		G_fatal_error(_("Landsat-7 requires band gain with 9 (H/L) characters"));
	    set_ETM(&lsat, bgain->answer);
	}
	else if (strcmp(sensorname, "oli8") == 0)
	    set_OLI(&lsat);
	else if (strcmp(sensorname, "tm5") == 0)
	    set_TM5(&lsat);
	else if (strcmp(sensorname, "tm4") == 0)
	    set_TM4(&lsat);
	else if (strcmp(sensorname, "mss5") == 0)
	    set_MSS5(&lsat);
	else if (strcmp(sensorname, "mss4") == 0)
	    set_MSS4(&lsat);
	else if (strcmp(sensorname, "mss3") == 0)
	    set_MSS3(&lsat);
	else if (strcmp(sensorname, "mss2") == 0)
	    set_MSS2(&lsat);
	else if (strcmp(sensorname, "mss1") == 0)
	    set_MSS1(&lsat);
	else
	    G_fatal_error(_("Unknown satellite type (defined by '%s')"),
			  sensorname);
    }

	/*****************************************
	* ------------ PREPARATION --------------
	*****************************************/
    if (strcasecmp(metho->answer, "corrected") == 0)	/* deleted 2013 */
	method = CORRECTED;
    else if (strcasecmp(metho->answer, "dos1") == 0)
	method = DOS1;
    else if (strcasecmp(metho->answer, "dos2") == 0)
	method = DOS2;
    else if (strcasecmp(metho->answer, "dos2b") == 0)
	method = DOS2b;
    else if (strcasecmp(metho->answer, "dos3") == 0)
	method = DOS3;
    else if (strcasecmp(metho->answer, "dos4") == 0)
	method = DOS4;
    else
	method = UNCORRECTED;

    /*
       if (metho->answer[3] == '2') method = (metho->answer[4] == '\0') ? DOS2 : DOS2b;
       else if (metho->answer[3] == '1') method = DOS1;
       else if (metho->answer[3] == '3') method = DOS3;
       else if (metho->answer[3] == '4') method = DOS4;
       else method = UNCORRECTED;
     */

    for (i = 0; i < lsat.bands; i++) {
	dn_mode[i] = 0;
	dn_dark[i] = (int)lsat.band[i].qcalmin;
	dn_sat = (int)(0.90 * lsat.band[i].qcalmax);
	/* Begin: calculate dark pixel */
	if (method > DOS && !lsat.band[i].thermal) {
	    for (q = 0; q <= lsat.band[i].qcalmax; q++)
		hist[q] = 0L;

	    sprintf(band_in, "%s%d", inputname, lsat.band[i].code);
	    Rast_get_cellhd(band_in, "", &cellhd);
	    Rast_set_window(&cellhd);
	    if ((infd = Rast_open_old(band_in, "")) < 0)
		G_fatal_error(_("Unable to open raster map <%s>"), band_in);

	    in_data_type = Rast_get_map_type(infd);
	    if (in_data_type < 0)
		G_fatal_error(_("Unable to read data type of raster map <%s>"), band_in);
	    inrast = Rast_allocate_buf(in_data_type);

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

	    G_message("Calculating dark pixel of <%s>... ", band_in);
	    for (row = 0; row < nrows; row++) {
		Rast_get_row(infd, inrast, row, in_data_type);
		for (col = 0; col < ncols; col++) {
		    switch (in_data_type) {
		    case CELL_TYPE:
			ptr = (void *)((CELL *) inrast + col);
			q = (int)*((CELL *) ptr);
			break;
		    case FCELL_TYPE:
			ptr = (void *)((FCELL *) inrast + col);
			q = (int)*((FCELL *) ptr);
			break;
		    case DCELL_TYPE:
			ptr = (void *)((DCELL *) inrast + col);
			q = (int)*((DCELL *) ptr);
			break;
		    default:
			ptr = NULL;
			q = -1.;
		    }
		    if (!Rast_is_null_value(ptr, in_data_type) &&
			q >= lsat.band[i].qcalmin &&
			q <= lsat.band[i].qcalmax)
			hist[q]++;
		}
	    }
	    /* DN of dark object */
	    for (j = lsat.band[i].qcalmin; j <= lsat.band[i].qcalmax; j++) {
		if (hist[j] >= (unsigned int)pixel) {
		    dn_dark[i] = j;
		    break;
		}
	    }
	    /* Mode of DN (exclude potentially saturated) */
	    h_max = 0L;
	    for (j = lsat.band[i].qcalmin; j < dn_sat; j++) {
		/* G_debug(5, "%d-%ld", j, hist[j]); */
		if (hist[j] > h_max) {
		    h_max = hist[j];
		    dn_mode[i] = j;
		}
	    }
	    G_verbose_message
		("... DN = %.2d [%lu] : mode %.2d [%lu], excluding DN > %d",
		 dn_dark[i], hist[dn_dark[i]], dn_mode[i], hist[dn_mode[i]],
		 dn_sat);

	    G_free(inrast);
	    Rast_close(infd);
	}
	/* End: calculate dark pixel */

	/* Calculate transformation constants */
	lsat_bandctes(&lsat, i, method, percent, dn_dark[i], rayleigh);
    }

    /*
     * unnecessary or necessary with more checking as acquisition date,...
     * if (strlen(lsat.creation) == 0)
     * G_fatal_error(_("Unknown production date (defined by '%s')"), pdate->key);
     */

    if (G_verbose() > G_verbose_std()) {
	fprintf(stderr, "\n LANDSAT: %d SENSOR: %s\n", lsat.number,
		lsat.sensor);
	fprintf(stderr, " ACQUISITION DATE %s [production date %s]\n",
		lsat.date, lsat.creation);
	fprintf(stderr, "   Earth-sun distance    = %.8lf\n", lsat.dist_es);
	fprintf(stderr, "   Solar elevation angle = %.8lf\n", lsat.sun_elev);
	fprintf(stderr, "   Atmospheric correction: %s\n",
		(method == UNCORRECTED ? "UNCORRECTED" : metho->answer));
	if (method > DOS) {
	    fprintf(stderr,
		    "   Percent of solar irradiance in path radiance = %.4lf\n",
		    percent);
	}
	for (i = 0; i < lsat.bands; i++) {
	    fprintf(stderr, "-------------------\n");
	    fprintf(stderr, " BAND %d %s(code %d)\n", lsat.band[i].number,
		    (lsat.band[i].thermal ? "thermal " : ""),
		    lsat.band[i].code);
	    fprintf(stderr,
		    "   calibrated digital number (DN): %.1lf to %.1lf\n",
		    lsat.band[i].qcalmin, lsat.band[i].qcalmax);
	    fprintf(stderr, "   calibration constants (L): %.5lf to %.5lf\n",
		    lsat.band[i].lmin, lsat.band[i].lmax);
	    fprintf(stderr, "   at-%s radiance = %.8lf * DN + %.5lf\n",
		    (method > DOS ? "surface" : "sensor"), lsat.band[i].gain,
		    lsat.band[i].bias);
	    if (lsat.band[i].thermal) {
		fprintf(stderr,
			"   at-sensor temperature = %.5lf / log[(%.5lf / radiance) + 1.0]\n",
			lsat.band[i].K2, lsat.band[i].K1);
	    }
	    else {
		fprintf(stderr,
			"   mean solar exoatmospheric irradiance (ESUN): %.5lf\n",
			lsat.band[i].esun);
		fprintf(stderr, "   at-%s reflectance = radiance / %.5lf\n",
			(method > DOS ? "surface" : "sensor"),
			lsat.band[i].K1);
		if (method > DOS) {
		    fprintf(stderr,
			    "   the darkness DN with a least %d pixels is %d\n",
			    pixel, dn_dark[i]);
		    fprintf(stderr, "   the DN mode is %d\n", dn_mode[i]);
		}
	    }
	}
	fprintf(stderr, "-------------------\n");
	fflush(stderr);
    }

    /*****************************************
    * ------------ CALCULUS -----------------
    *****************************************/

    G_message(_("Calculating..."));
    for (i = 0; i < lsat.bands; i++) {
	sprintf(band_in, "%s%d", inputname,
		(named->answer ? lsat.band[i].number : lsat.band[i].code));
	sprintf(band_out, "%s%d", outputname, lsat.band[i].code);

	/* set same size as original band raster */
	Rast_get_cellhd(band_in, "", &cellhd);
	Rast_set_window(&cellhd);
	if ((infd = Rast_open_old(band_in, "")) < 0)
	    G_fatal_error(_("Unable to open raster map <%s>"), band_in);

	if (G_find_raster2(band_out, "")) {
	    if (overwrite) {
		G_warning(_("Raster map <%s> already exists and will be overwritten"),
			  band_out);
	    }
	    else {
		G_warning(_("Raster map <%s> exists. Skipping."), band_out);
		continue;
	    }
	}

	in_data_type = Rast_get_map_type(infd);
	if (in_data_type < 0)
	    G_fatal_error(_("Unable to read data type of raster map <%s>"), band_in);

	/* controlling, if we can write the raster */
	if (G_legal_filename(band_out) < 0)
	    G_fatal_error(_("<%s> is an illegal file name"), band_out);

	if ((outfd = Rast_open_new(band_out, DCELL_TYPE)) < 0)
	    G_fatal_error(_("Unable to create raster map <%s>"), band_out);

	/* allocate input and output buffer */
	inrast = Rast_allocate_buf(in_data_type);
	outrast = Rast_allocate_buf(DCELL_TYPE);

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

	G_important_message(_("Writing %s of <%s> to <%s>..."),
			    (frad->
			     answer ? _("radiance") : (lsat.band[i].
						       thermal) ?
			     _("temperature") : _("reflectance")), band_in,
			    band_out);
	for (row = 0; row < nrows; row++) {
	    G_percent(row, nrows, 2);

	    Rast_get_row(infd, inrast, row, in_data_type);
	    for (col = 0; col < ncols; col++) {
		switch (in_data_type) {
		case CELL_TYPE:
		    ptr = (void *)((CELL *) inrast + col);
		    qcal = (double)((CELL *) inrast)[col];
		    break;
		case FCELL_TYPE:
		    ptr = (void *)((FCELL *) inrast + col);
		    qcal = (double)((FCELL *) inrast)[col];
		    break;
		case DCELL_TYPE:
		    ptr = (void *)((DCELL *) inrast + col);
		    qcal = (double)((DCELL *) inrast)[col];
		    break;
		default:
		    ptr = NULL;
		    qcal = -1.;
		}
		if (Rast_is_null_value(ptr, in_data_type) ||
		    qcal < lsat.band[i].qcalmin) {
		    Rast_set_d_null_value((DCELL *) outrast + col, 1);
		}
		else {
		    rad = lsat_qcal2rad(qcal, &lsat.band[i]);
		    if (frad->answer) {
			ref = rad;
		    }
		    else {
			if (lsat.band[i].thermal) {
			    ref = lsat_rad2temp(rad, &lsat.band[i]);
			}
			else {
			    ref = lsat_rad2ref(rad, &lsat.band[i]) * scale;
			    if (ref < 0. && method > DOS)
				ref = 0.;
			}
		    }
		    ((DCELL *) outrast)[col] = ref;
		}
	    }
	    Rast_put_row(outfd, outrast, DCELL_TYPE);
	}
	G_percent(1, 1, 1);

	ref_mode = 0.;
	if (method > DOS && !lsat.band[i].thermal) {
	    ref_mode = lsat_qcal2rad(dn_mode[i], &lsat.band[i]);
	    ref_mode = lsat_rad2ref(ref_mode, &lsat.band[i]);
	}


	G_free(inrast);
	Rast_close(infd);
	G_free(outrast);
	Rast_close(outfd);


	/*
	 * needed?
	 * if (out_type != CELL_TYPE)
	 * G_quantize_fp_map_range(band_out, G_mapset(), 0., 360., 0,
	 * 360);
	 */

	/* set grey255 colortable */
	Rast_init_colors(&colors);
	Rast_read_fp_range(band_out, G_mapset(), &range);
	Rast_get_fp_range_min_max(&range, &min, &max);
	Rast_make_grey_scale_fp_colors(&colors, min, max);
	Rast_write_colors(band_out, G_mapset(), &colors);

	/* Initialize the 'history' structure with basic info */
	Rast_short_history(band_out, "raster", &history);
	Rast_append_format_history(&history,
				   " %s of Landsat-%d %s (method %s)",
				   (frad->
				    answer ? "Radiance" : (lsat.band[i].
							   thermal ?
							   "Temperature" :
							   "Reflectance")),
				   lsat.number, lsat.sensor, metho->answer);
	Rast_append_history(&history,
			    "-----------------------------------------------------------------");
	Rast_append_format_history(&history,
				   " Acquisition date (and time) ........... %s (%.4lf h)",
				   lsat.date, lsat.time);
	Rast_append_format_history(&history,
				   " Production date ....................... %s\n",
				   lsat.creation);
	Rast_append_format_history(&history,
				   " Earth-sun distance (d) ................ %.7lf",
				   lsat.dist_es);
	Rast_append_format_history(&history,
				   " Sun elevation (and azimuth) ........... %.5lf (%.5lf)",
				   lsat.sun_elev, lsat.sun_az);
	Rast_append_format_history(&history,
				   " Digital number (DN) range ............. %.0lf to %.0lf",
				   lsat.band[i].qcalmin,
				   lsat.band[i].qcalmax);
	Rast_append_format_history(&history,
				   " Calibration constants (Lmin to Lmax) .. %+.5lf to %+.5lf",
				   lsat.band[i].lmin, lsat.band[i].lmax);
	Rast_append_format_history(&history,
				   " DN to Radiance (gain and bias) ........ %+.5lf and %+.5lf",
				   lsat.band[i].gain, lsat.band[i].bias);
	if (lsat.band[i].thermal) {
	    Rast_append_format_history(&history,
				       " Temperature (K1 and K2) ............... %.3lf and %.3lf",
				       lsat.band[i].K1, lsat.band[i].K2);
	}
	else {
	    Rast_append_format_history(&history,
				       " Mean solar irradiance (ESUN) .......... %.3lf",
				       lsat.band[i].esun);
	    Rast_append_format_history(&history,
				       " Radiance to Reflectance (divide by) ... %+.5lf",
				       lsat.band[i].K1);
	    if (method > DOS) {
		Rast_append_format_history(&history, " ");
		Rast_append_format_history(&history,
					   " Dark object (%4d pixels) DN = ........ %d",
					   pixel, dn_dark[i]);
		Rast_append_format_history(&history,
					   " Mode in reflectance histogram ......... %.5lf",
					   ref_mode);
	    }
	}
	Rast_append_history(&history,
			    "------------------------------------------------------------------");

	Rast_command_history(&history);
	Rast_write_history(band_out, &history);

	if (lsat.band[i].thermal)
	    Rast_write_units(band_out, "Kelvin");
	else if (frad->answer)
	    Rast_write_units(band_out, "W/(m^2 sr um)");
	else
	    Rast_write_units(band_out, "unitless");

	/*  set raster timestamp from acq date? (see r.timestamp module)  */
    }
    Rast_set_window(&orig_cellhd);

    exit(EXIT_SUCCESS);
}