Ejemplo n.º 1
0
int intro(void)
{
    G_message(_("%s provides a text-based user-interface to the %s program."),
	      G_program_name(), NON_NAME);
    G_message(_("%s also allows the user to prepare a report of map layers for each"),
	      G_program_name());
    G_message(_("watershed basin determined in %s.\n"), NON_NAME);

    G_message(_("%s will help the user determine which options to use for the"),
	      G_program_name());
    G_message(_("%s program.  %s will then ask for map layers that will be"),
	      NON_NAME, G_program_name());
    G_message(_("divided by basin. %s will then run %s and create the report."),
	      G_program_name(), NON_NAME);

    return (0);
}
Ejemplo n.º 2
0
void die(char *a, char *b)
{
    char *message;

    G_asprintf(&message, "%s: %s %s", G_program_name(), a, b);
    G_fatal_error(message);

    return;
}
Ejemplo n.º 3
0
void G_done_msg(const char *msg, ...)
{
    char buffer[2000];
    va_list ap;

    va_start(ap, msg);
    vsprintf(buffer, msg, ap);
    va_end(ap);

    G_message(_("%s complete. %s"), G_program_name(), buffer);
}
Ejemplo n.º 4
0
static int set_login(const char *driver, const char *database, const char *user,
                     const char *password, const char *host, const char *port,
                     int overwrite)
{
    int i, found;
    LOGIN login;

    G_debug(3, "db_set_login(): drv=[%s] db=[%s] usr=[%s] pwd=[%s] host=[%s] port=[%s]",
	    driver, database, user, password, host, port);

    init_login(&login);

    if (read_file(&login) == -1)
	return DB_FAILED;

    found = FALSE;
    for (i = 0; i < login.n; i++) {
	if (strcmp(login.data[i].driver, driver) == 0 &&
	    strcmp(login.data[i].database, database) == 0) {
	    if (user)
		login.data[i].user = G_store(user);
	    else
		login.data[i].user = G_store("");

	    if (password)
		login.data[i].password = G_store(password);
	    else
		login.data[i].password = G_store("");

	    found = TRUE;
	    break;
	}
    }

    if (found) {
        if (overwrite)
            G_warning(_("DB connection <%s/%s> already exists and will be overwritten"),
                      driver, database ? database : "");
        else
            G_fatal_error(_("DB connection <%s/%s> already exists. "
                            "Re-run '%s' with '--%s' flag to overwrite existing settings."),
                          driver, database ? database : "", G_program_name(), "overwrite");
    }
    
    if (!found)
	add_login(&login, driver, database, user, password, host, port, -1);
    else
        add_login(&login, driver, database, user, password, host, port, i);

    if (write_file(&login) == -1)
	return DB_FAILED;

    return DB_OK;
}
Ejemplo n.º 5
0
/*
 * update_rast_history - Update a history file.  Some of the digit file 
 * information is placed in the history file.
 */
void update_rast_history(struct parms *parm)
{
    struct History hist;

    /* write command line to history */
    Rast_short_history(parm->outrast->answer, "raster", &hist);
    Rast_append_format_history(&hist, "%s version %.2f", G_program_name(), APP_VERSION);
    Rast_append_format_history(&hist, "stream width: %.2f", parm->swidth * 2);
    Rast_format_history(&hist, HIST_DATSRC_1, "raster elevation file: %s", parm->inrast->answer);
    Rast_format_history(&hist, HIST_DATSRC_2, "vector stream file: %s", parm->invect->answer);
    Rast_command_history(&hist);
    Rast_write_history(parm->outrast->answer, &hist);
}
Ejemplo n.º 6
0
void print_wkt(int esristyle, int dontprettify)
{
    char *outwkt;

    if (check_xy(FALSE))
	return;

    outwkt = GPJ_grass_to_wkt(projinfo, projunits, esristyle,
			      !(dontprettify));
    if (outwkt != NULL) {
	fprintf(stdout, "%s\n", outwkt);
	G_free(outwkt);
    }
    else
	G_warning(_("%s: Unable to convert to WKT"), G_program_name());

    return;
}
Ejemplo n.º 7
0
Archivo: main.c Proyecto: caomw/grass
int main(int argc, char **argv)
{
    struct GModule *module;
    struct
    {
	struct Option *input;
	struct Option *output;
    } params;

    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("raster"));
    G_add_keyword(_("hydrology"));
    module->description =
	_("Creates a topographic index raster map from an elevation raster map.");

    params.input = G_define_standard_option(G_OPT_R_ELEV);
    params.input->key = "input";

    params.output = G_define_standard_option(G_OPT_R_OUTPUT);
    params.output->description = _("Name for output topographic index raster map");

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

    /* Make sure that the current projection is not lat/long */
    if ((G_projection() == PROJECTION_LL))
	G_fatal_error(_("Lat/Long location is not supported by %s. Please reproject map first."),
		      G_program_name());

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

    G_get_window(&window);

    read_cells();
    initialize();
    calculate_atanb();
    write_cells();

    exit(EXIT_SUCCESS);
}
Ejemplo n.º 8
0
int renumber(int in, int out)
{
    CELL *cell, *c;
    int row, col;

    cell = Rast_allocate_c_buf();

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

    return 0;
}
Ejemplo n.º 9
0
/*!
  \brief Print module usage description in HTML format.
*/
void G__usage_html(void)
{
    struct Option *opt;
    struct Flag *flag;
    const char *type;
    int new_prompt = 0;

    new_prompt = G__uses_new_gisprompt();

    if (!st->pgm_name)		/* v.dave && r.michael */
	st->pgm_name = G_program_name();
    if (!st->pgm_name)
	st->pgm_name = "??";

    fprintf(stdout,
	    "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n");
    fprintf(stdout, "<html>\n<head>\n");
    fprintf(stdout, "<title>GRASS GIS manual: %s</title>\n", st->pgm_name);
    fprintf(stdout,
	    "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\">\n");
    fprintf(stdout,
	    "<link rel=\"stylesheet\" href=\"grassdocs.css\" type=\"text/css\">\n");
    fprintf(stdout, "</head>\n");
    fprintf(stdout, "<body bgcolor=\"white\">\n\n");
    fprintf(stdout,
	    "<img src=\"grass_logo.png\" alt=\"GRASS logo\"><hr align=center size=6 noshade>\n\n");
    fprintf(stdout, "<h2>%s</h2>\n", _("NAME"));
    fprintf(stdout, "<em><b>%s</b></em> ", st->pgm_name);

    if (st->module_info.label || st->module_info.description)
	fprintf(stdout, " - ");

    if (st->module_info.label)
	fprintf(stdout, "%s<BR>\n", st->module_info.label);

    if (st->module_info.description)
	fprintf(stdout, "%s\n", st->module_info.description);


    fprintf(stdout, "<h2>%s</h2>\n", _("KEYWORDS"));
    if (st->module_info.keywords) {
	G__print_keywords(stdout, NULL);
	fprintf(stdout, "\n");
    }
    fprintf(stdout, "<h2>%s</h2>\n", _("SYNOPSIS"));
    fprintf(stdout, "<b>%s</b><br>\n", st->pgm_name);
    fprintf(stdout, "<b>%s help</b><br>\n", st->pgm_name);

    fprintf(stdout, "<b>%s</b>", st->pgm_name);



    /* print short version first */
    if (st->n_flags) {
	flag = &st->first_flag;
	fprintf(stdout, " [-<b>");
	while (flag != NULL) {
	    fprintf(stdout, "%c", flag->key);
	    flag = flag->next_flag;
	}
	fprintf(stdout, "</b>] ");
    }
    else
	fprintf(stdout, " ");

    if (st->n_opts) {
	opt = &st->first_option;

	while (opt != NULL) {
	    if (opt->key_desc != NULL)
		type = opt->key_desc;
	    else
		switch (opt->type) {
		case TYPE_INTEGER:
		    type = "integer";
		    break;
		case TYPE_DOUBLE:
		    type = "float";
		    break;
		case TYPE_STRING:
		    type = "string";
		    break;
		default:
		    type = "string";
		    break;
		}
	    if (!opt->required)
		fprintf(stdout, " [");
	    fprintf(stdout, "<b>%s</b>=<em>%s</em>", opt->key, type);
	    if (opt->multiple) {
		fprintf(stdout, "[,<i>%s</i>,...]", type);
	    }
	    if (!opt->required)
		fprintf(stdout, "] ");

	    opt = opt->next_opt;
	    fprintf(stdout, " ");
	}
    }
    if (new_prompt)
	fprintf(stdout, " [--<b>overwrite</b>] ");

    fprintf(stdout, " [--<b>verbose</b>] ");
    fprintf(stdout, " [--<b>quiet</b>] ");

    fprintf(stdout, "\n");


    /* now long version */
    fprintf(stdout, "\n");
    if (st->n_flags || new_prompt) {
	flag = &st->first_flag;
	fprintf(stdout, "<h3>%s:</h3>\n", _("Flags"));
	fprintf(stdout, "<DL>\n");
	while (st->n_flags && flag != NULL) {
	    fprintf(stdout, "<DT><b>-%c</b></DT>\n", flag->key);

	    if (flag->label) {
		fprintf(stdout, "<DD>");
		fprintf(stdout, "%s", flag->label);
		fprintf(stdout, "</DD>\n");
	    }

	    if (flag->description) {
		fprintf(stdout, "<DD>");
		fprintf(stdout, "%s", flag->description);
		fprintf(stdout, "</DD>\n");
	    }

	    flag = flag->next_flag;
	    fprintf(stdout, "\n");
	}
	if (new_prompt) {
	    fprintf(stdout, "<DT><b>--overwrite</b></DT>\n");
	    fprintf(stdout, "<DD>%s</DD>\n",
		    _("Allow output files to overwrite existing files"));
	}

	fprintf(stdout, "<DT><b>--verbose</b></DT>\n");
	fprintf(stdout, "<DD>%s</DD>\n", _("Verbose module output"));

	fprintf(stdout, "<DT><b>--quiet</b></DT>\n");
	fprintf(stdout, "<DD>%s</DD>\n", _("Quiet module output"));

	fprintf(stdout, "</DL>\n");
    }

    fprintf(stdout, "\n");
    if (st->n_opts) {
	opt = &st->first_option;
	fprintf(stdout, "<h3>%s:</h3>\n", _("Parameters"));
	fprintf(stdout, "<DL>\n");

	while (opt != NULL) {
	    /* TODO: make this a enumeration type? */
	    if (opt->key_desc != NULL)
		type = opt->key_desc;
	    else
		switch (opt->type) {
		case TYPE_INTEGER:
		    type = "integer";
		    break;
		case TYPE_DOUBLE:
		    type = "float";
		    break;
		case TYPE_STRING:
		    type = "string";
		    break;
		default:
		    type = "string";
		    break;
		}
	    fprintf(stdout, "<DT><b>%s</b>=<em>%s", opt->key, type);
	    if (opt->multiple) {
		fprintf(stdout, "[,<i>%s</i>,...]", type);
	    }
	    fprintf(stdout, "</em></DT>\n");

	    if (opt->label) {
		fprintf(stdout, "<DD>");
		print_escaped_for_html(stdout, opt->label);
		fprintf(stdout, "</DD>\n");
	    }
	    if (opt->description) {
		fprintf(stdout, "<DD>");
		print_escaped_for_html(stdout, opt->description);
		fprintf(stdout, "</DD>\n");
	    }

	    if (opt->options) {
		fprintf(stdout, "<DD>%s: <em>", _("Options"));
		print_escaped_for_html(stdout, opt->options);
		fprintf(stdout, "</em></DD>\n");
	    }

	    if (opt->def) {
		fprintf(stdout, "<DD>%s: <em>", _("Default"));
		print_escaped_for_html(stdout, opt->def);
		fprintf(stdout, "</em></DD>\n");
	    }

	    if (opt->descs) {
		int i = 0;

		while (opt->opts[i]) {
		    if (opt->descs[i]) {
			fprintf(stdout, "<DD><b>");
			print_escaped_for_html(stdout, opt->opts[i]);
			fprintf(stdout, "</b>: ");
			print_escaped_for_html(stdout, opt->descs[i]);
			fprintf(stdout, "</DD>\n");
		    }
		    i++;
		}
	    }

	    opt = opt->next_opt;
	    fprintf(stdout, "\n");
	}
	fprintf(stdout, "</DL>\n");
    }

    fprintf(stdout, "</body>\n</html>\n");
}
Ejemplo n.º 10
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;
}
Ejemplo n.º 11
0
void G__wps_print_process_description(void)
{
    struct Option *opt;
    struct Flag *flag;
    char *type;
    char *s, *top;
    const char *value = NULL;
    int i;
    char *encoding;
    int new_prompt = 0;
    int store = 1;
    int status = 1;
    const char *identifier = NULL;
    const char *title = NULL;
    const char *abstract = NULL;
    const char **keywords = NULL;
    int data_type, is_input, is_output;
    int num_raster_inputs = 0, num_raster_outputs = 0;
    int num_vector_inputs = 0, num_vector_outputs = 0;
    int num_strds_inputs = 0, num_strds_outputs = 0;
    int num_stvds_inputs = 0, num_stvds_outputs = 0;
    int min = 0, max = 0;
    int num_keywords = 0;
    int found_output = 0;
    int is_tuple; /* Checks the key_descr for comma separated values */
    int num_tuples; /* Counts the "," in key_descr */

    new_prompt = G__uses_new_gisprompt();

    /* gettext converts strings to encoding returned by nl_langinfo(CODESET) */

#if defined(HAVE_LANGINFO_H)
    encoding = nl_langinfo(CODESET);
    if (!encoding || strlen(encoding) == 0) {
	encoding = "UTF-8";
    }
#elif defined(__MINGW32__) && defined(USE_NLS)
    encoding = locale_charset();
    if (!encoding || strlen(encoding) == 0) {
	encoding = "UTF-8";
    }
#else
    encoding = "UTF-8";
#endif

    if (!st->pgm_name)
	st->pgm_name = G_program_name();
    if (!st->pgm_name)
	st->pgm_name = "??";

    /* the identifier of the process is the module name */
    identifier = st->pgm_name;

    if (st->module_info.description) {
        title = st->module_info.description;
        abstract = st->module_info.description;
    }

    if (st->module_info.keywords) {
        keywords = st->module_info.keywords;
        num_keywords = st->n_keys;
    }

    wps_print_process_descriptions_begin();
    /* store and status are supported as default. The WPS server should change this if necessary */
    wps_print_process_description_begin(store, status, identifier, title, abstract, keywords, num_keywords);
    wps_print_data_inputs_begin();

    /* Print the bounding box element with all the coordinate reference systems, which are supported by grass*/
    /* Currently Disabled! A list of all proj4 supported EPSG coordinate reference systems must be implemented*/
    if(1 == 0)
        wps_print_bounding_box_data();

    /* We parse only the inputs at the beginning */
    if (st->n_opts) {
	opt = &st->first_option;
	while (opt != NULL) {

            identifier = NULL;
            title = NULL;
            abstract = NULL;
            keywords = NULL;
            num_keywords = 0;
            value = NULL;
            is_input = 1;
            is_output = 0;
	    is_tuple = 0;
	    num_tuples = 0;
            data_type = TYPE_OTHER;

	    /* Check the gisprompt */
	    if (opt->gisprompt) {
		const char *atts[] = { "age", "element", "prompt", NULL };
		top = G_calloc(strlen(opt->gisprompt) + 1, 1);
		strcpy(top, opt->gisprompt);
		s = strtok(top, ",");
		for (i = 0; s != NULL && atts[i] != NULL; i++) {

                    char *token = G_store(s);

                    /* we print only input parameter, sort out the output parameter */
                    if(strcmp(token, "new") == 0) {
                        is_input = 0;
                        is_output = 1;
                    }
                    if(strcmp(token, "raster") == 0)
                    {
                        data_type = TYPE_RASTER;
                        /* Count the raster inputs and outputs for default option creation */
                        if(is_input == 1)
                            num_raster_inputs++;
                        if(is_output == 1)
                            num_raster_outputs++;
                    }
                    if(strcmp(token, "vector") == 0)
                    {
                        data_type = TYPE_VECTOR;
			if(is_input == 1)
                            num_vector_inputs++;
                        if(is_output == 1)
                            num_vector_outputs++;
                    }
		    /* Modules may have different types of space time datasets as inputs */
                    if(strcmp(token, "stds") == 0)
                    {
                        data_type = TYPE_STDS;
                    }
                    if(strcmp(token, "strds") == 0)
                    {
                        data_type = TYPE_STRDS;
                        if(is_input == 1)
                            num_strds_inputs++;
                        if(is_output == 1)
                            num_strds_outputs++;
                    }
                    if(strcmp(token, "stvds") == 0)
                    {
                        data_type = TYPE_STVDS;
                        if(is_input == 1)
                            num_stvds_inputs++;
                        if(is_output == 1)
                            num_stvds_outputs++;
                    }
                    if(strcmp(token, "file") == 0)
                    {
                        data_type = TYPE_PLAIN_TEXT;
                    }
                    s = strtok(NULL, ",");
                    G_free(token);
		}
		G_free(top);
	    }

	    /* Check the key description */
	    if (opt->key_desc) {
		top = G_calloc(strlen(opt->key_desc) + 1, 1);
		strcpy(top, opt->key_desc);
		s = strtok(top, ",");
		/* Count comma's */
                for (i = 0; s != NULL; i++) {
                    num_tuples++;
                    s = strtok(NULL, ",");
		}
                if(num_tuples > 1)
                    is_tuple = 1;
                
		G_free(top);
	    }
            /* We have an input option */
            if(is_input == 1)
            {
                switch (opt->type) {
                case TYPE_INTEGER:
                    type = "integer";
                    break;
                case TYPE_DOUBLE:
                    type = "float";
                    break;
                case TYPE_STRING:
                    type = "string";
                    break;
                default:
                    type = "string";
                    break;
                }

                identifier = opt->key;

                if(opt->required == YES) {
                    if(is_tuple)
                        min = num_tuples;
                    else
                        min = 1;
                } else {
                    min = 0;
                }

                if(opt->multiple == YES) {
                    max = 1024;
                } else {
                    if(is_tuple)
                        max = num_tuples;
                    else
                        max = 1;
                }
                
                if(opt->label) {
                    title = opt->label;
		}
                if (opt->description) {
		    if(!opt->label)
			title = opt->description;
		    else
			abstract = opt->description;
                }
                if (opt->def) {
                    value = opt->def;
                }
                if (opt->options) {
                    /* TODO:
                     * add something like
                     *       <range min="xxx" max="xxx"/>
                     * to <values> */
                    i = 0;
                    while (opt->opts[i]) {
                        i++;
                    }
                    keywords = opt->opts;
                    num_keywords = i;
                }
                if(data_type == TYPE_RASTER || data_type == TYPE_VECTOR || 
		   data_type == TYPE_STRDS  || data_type == TYPE_STVDS  || 
		   data_type == TYPE_STDS || data_type == TYPE_PLAIN_TEXT)
                {
                    /* 2048 is the maximum size of the map in mega bytes */
                    wps_print_complex_input(min, max, identifier, title, abstract, 2048, data_type);
                }
                else
                {
                    /* The keyword array is missused for options, type means the type of the value (integer, float ... )*/
                    wps_print_literal_input_output(WPS_INPUT, min, max, identifier, title, 
						    abstract, type, 0, keywords, num_keywords, value, TYPE_OTHER);
                }
            }
	    opt = opt->next_opt;
	}
    }

    /* Flags are always input options and can be false or true (boolean) */
    if (st->n_flags) {
	flag = &st->first_flag;
	while (flag != NULL) {

            /* The identifier is the flag "-x" */
            char* ident = (char*)G_calloc(3, sizeof(char));
            ident[0] = '-';
            ident[1] = flag->key;
            ident[2] = '\0';
            title = NULL;
            abstract = NULL;

	    if (flag->description) {
                title = flag->description;
                abstract = flag->description;
	    }
            const char *val[] = {"true","false"};
            wps_print_literal_input_output(WPS_INPUT, 0, 1, ident, title, NULL, "boolean", 0, val, 2, "false", TYPE_OTHER);
	    flag = flag->next_flag;
	}
    }

    /* We have two default options, which define the resolution of the created mapset */
    if(num_raster_inputs > 0 || num_raster_outputs > 0 || num_strds_inputs > 0 || num_strds_outputs > 0) {
        wps_print_literal_input_output(WPS_INPUT, 0, 1, "grass_resolution_ns", "Resolution of the mapset in north-south direction in meters or degrees",
            "This parameter defines the north-south resolution of the mapset in meter or degrees, which should be used to process the input and output raster data. To enable this setting, you need to specify north-south and east-west resolution.",
            "float", 1, NULL, 0, NULL, TYPE_OTHER);
        wps_print_literal_input_output(WPS_INPUT, 0, 1, "grass_resolution_ew", "Resolution of the mapset in east-west direction in meters or degrees",
            "This parameter defines the east-west resolution of the mapset in meters or degrees, which should be used to process the input and output raster data.  To enable this setting, you need to specify north-south and east-west resolution.",
            "float", 1, NULL, 0, NULL, TYPE_OTHER);
    }
    /* In case multi band raster maps should be imported, the band number must be provided */
    if(num_raster_inputs > 0)
        wps_print_literal_input_output(WPS_INPUT, 0, 1, "grass_band_number", "Band to select for processing (default is all bands)",
            "This parameter defines band number of the input raster files which should be processed. As default all bands are processed and used as single and multiple inputs for raster modules.",
            "integer", 0, NULL, 0, NULL, TYPE_OTHER);

    /* End of inputs */
    wps_print_data_inputs_end();
    /* Start of the outputs */
    wps_print_process_outputs_begin();

    found_output = 0;

    /*parse the output. only raster maps, vector maps, space time raster and vector datasets plus stdout are supported */
    if (st->n_opts) {
	opt = &st->first_option;
	while (opt != NULL) {

            identifier = NULL;
            title = NULL;
            abstract = NULL;
            value = NULL;
            is_output = 0;
            data_type = TYPE_OTHER;

	    if (opt->gisprompt) {
		const char *atts[] = { "age", "element", "prompt", NULL };
		top = G_calloc(strlen(opt->gisprompt) + 1, 1);
		strcpy(top, opt->gisprompt);
		s = strtok(top, ",");
		for (i = 0; s != NULL && atts[i] != NULL; i++) {

                    char *token = G_store(s);

                    /* we print only the output parameter */
                    if(strcmp(token, "new") == 0)
                        is_output = 1;
                    if(strcmp(token, "raster") == 0)
                    {
                        data_type = TYPE_RASTER;
                    }
                    if(strcmp(token, "vector") == 0)
                    {
                        data_type = TYPE_VECTOR;
                    }
                    if(strcmp(token, "stds") == 0)
                    {
                        data_type = TYPE_STDS;
                    }
                    if(strcmp(token, "strds") == 0)
                    {
                        data_type = TYPE_STRDS;
                    }
                    if(strcmp(token, "stvds") == 0)
                    {
                        data_type = TYPE_STVDS;
                    }
                    if(strcmp(token, "file") == 0)
                    {
                        data_type = TYPE_PLAIN_TEXT;
                    }
                    s = strtok(NULL, ",");
                    G_free(token);
		}
		G_free(top);
	    }
            /* Only single module output is supported!! */
            if(is_output == 1)
            {
		if(opt->multiple == YES)
		    G_warning(_("Multiple outputs are not supported by WPS 1.0.0"));
                identifier = opt->key;
 
                if(opt->label) {
                    title = opt->label;
		}
                if (opt->description) {
		    if(!opt->label)
			title = opt->description;
		    else
			abstract = opt->description;
		}

                if(data_type == TYPE_RASTER || data_type == TYPE_VECTOR || 
		   data_type == TYPE_STRDS  || data_type == TYPE_STVDS || 
		   data_type == TYPE_STDS  || data_type == TYPE_PLAIN_TEXT) {
                    wps_print_complex_output(identifier, title, abstract, data_type);
                    found_output = 1;
                }
            }
	    opt = opt->next_opt;
	}
        /* we assume the computatuon output on stdout, if no raster/vector output was found*/
        if(found_output == 0)
            wps_print_complex_output("stdout", "Module output on stdout", "The output of the module written to stdout", TYPE_PLAIN_TEXT);
    }

    wps_print_process_outputs_end();
    wps_print_process_description_end();
    wps_print_process_descriptions_end();
}
Ejemplo n.º 12
0
static void usage(FILE *fp, int markers)
{
    struct Option *opt;
    struct Flag *flag;
    char item[256];
    const char *key_desc;
    int maxlen;
    int len, n;
    int new_prompt = 0;

    new_prompt = G__uses_new_gisprompt();

    if (!st->pgm_name)		/* v.dave && r.michael */
	st->pgm_name = G_program_name();
    if (!st->pgm_name)
	st->pgm_name = "??";

    if (st->module_info.label || st->module_info.description) {
	fprintf(fp, "\n");
	if (markers)
	    fprintf(fp, "{{{DESCRIPTION}}}\n");
	fprintf(fp, "%s\n", _("Description:"));
	if (st->module_info.label)
	    fprintf(fp, " %s\n", st->module_info.label);
	if (st->module_info.description)
	    fprintf(fp, " %s\n", st->module_info.description);
    }
    if (st->module_info.keywords) {
	fprintf(fp, "\n");
	if (markers)
	    fprintf(fp, "{{{KEYWORDS}}}\n");
	fprintf(fp, "%s\n ", _("Keywords:"));
	G__print_keywords(fp, NULL);
	fprintf(fp, "\n");
    }

    fprintf(fp, "\n");
    if (markers)
	fprintf(fp, "{{{USAGE}}}\n");
    fprintf(fp, "%s\n ", _("Usage:"));

    len = show(fp, st->pgm_name, 1);

    /* Print flags */

    if (st->n_flags) {
	item[0] = ' ';
	item[1] = '[';
	item[2] = '-';
	flag = &st->first_flag;
	for (n = 3; flag != NULL; n++, flag = flag->next_flag)
	    item[n] = flag->key;
	item[n++] = ']';
	item[n] = 0;
	len = show(fp, item, len);
    }

    maxlen = 0;
    if (st->n_opts) {
	opt = &st->first_option;
	while (opt != NULL) {
	    if (opt->key_desc != NULL)
		key_desc = opt->key_desc;
	    else if (opt->type == TYPE_STRING)
		key_desc = "string";
	    else
		key_desc = "value";

	    if (!opt->key) {
		fprintf(stderr, "\n%s\n", _("ERROR: Option key not defined"));
		exit(EXIT_FAILURE);
	    }
	    n = strlen(opt->key);
	    if (n > maxlen)
		maxlen = n;

	    strcpy(item, " ");
	    if (!opt->required)
		strcat(item, "[");
	    strcat(item, opt->key);
	    strcat(item, "=");
	    strcat(item, key_desc);
	    if (opt->multiple) {
		strcat(item, "[,");
		strcat(item, key_desc);
		strcat(item, ",...]");
	    }
	    if (!opt->required)
		strcat(item, "]");

	    len = show(fp, item, len);

	    opt = opt->next_opt;
	}
    }
    if (new_prompt) {
	strcpy(item, " [--overwrite]");
	len = show(fp, item, len);
    }

    strcpy(item, " [--help]");
    len = show(fp, item, len);

    strcpy(item, " [--verbose]");
    len = show(fp, item, len);

    strcpy(item, " [--quiet]");
    len = show(fp, item, len);

    strcpy(item, " [--ui]");
    len = show(fp, item, len);

    fprintf(fp, "\n");

    /* Print help info for flags */

    fprintf(fp, "\n");
    if (markers)
	fprintf(fp, "{{{FLAGS}}}\n");
    fprintf(fp, "%s\n", _("Flags:"));

    if (st->n_flags) {
	flag = &st->first_flag;
	while (flag != NULL) {
	    fprintf(fp, "  -%c   ", flag->key);

	    if (flag->label) {
		fprintf(fp, "%s\n", flag->label);
		if (flag->description)
		    fprintf(fp, "        %s\n", flag->description);

	    }
	    else if (flag->description) {
		fprintf(fp, "%s\n", flag->description);
	    }

	    flag = flag->next_flag;
	}
    }

    if (new_prompt)
	fprintf(fp, " --o   %s\n",
		_("Allow output files to overwrite existing files"));

    fprintf(fp, " --h   %s\n", _("Print usage summary"));
    fprintf(fp, " --v   %s\n", _("Verbose module output"));
    fprintf(fp, " --q   %s\n", _("Quiet module output"));
    fprintf(fp, " --qq  %s\n", _("Super quiet module output"));
    fprintf(fp, " --ui  %s\n", _("Force launching GUI dialog"));
    
    /* Print help info for options */

    if (st->n_opts) {
	fprintf(fp, "\n");
	if (markers)
	    fprintf(fp, "{{{PARAMETERS}}}\n");
	fprintf(fp, "%s\n", _("Parameters:"));
	opt = &st->first_option;
	while (opt != NULL) {
	    fprintf(fp, "  %*s   ", maxlen, opt->key);

	    if (opt->label) {
		fprintf(fp, "%s\n", opt->label);
		if (opt->description) {
		    fprintf(fp, "  %*s    %s\n",
			    maxlen, " ", opt->description);
		}
	    }
	    else if (opt->description) {
		fprintf(fp, "%s\n", opt->description);
	    }

	    if (opt->options)
		show_options(fp, maxlen, opt->options);
	    /*
	       fprintf (fp, "  %*s   options: %s\n", maxlen, " ",
	       _(opt->options)) ;
	     */
	    if (opt->def)
		fprintf(fp, _("  %*s   default: %s\n"), maxlen, " ",
			opt->def);

	    if (opt->descs) {
		int i = 0;

		while (opt->opts[i]) {
		    if (opt->descs[i])
			fprintf(fp, "  %*s    %s: %s\n",
				maxlen, " ", opt->opts[i], opt->descs[i]);

		    i++;
		}
	    }

	    opt = opt->next_opt;
	}
    }
}
Ejemplo n.º 13
0
/*!
  \brief Print module usage description in XML format.
*/
void G__usage_xml(void)
{
    struct Option *opt;
    struct Flag *flag;
    char *type;
    char *s, *top;
    int i;
    const char *encoding;
    int new_prompt = 0;

    new_prompt = G__uses_new_gisprompt();

    /* gettext converts strings to encoding returned by nl_langinfo(CODESET) */

#if defined(HAVE_LANGINFO_H)
    encoding = nl_langinfo(CODESET);
#elif defined(__MINGW32__) && defined(USE_NLS)
    encoding = locale_charset();
#endif

    if (!encoding || strlen(encoding) == 0)
	encoding = "UTF-8";

#ifdef HAVE_ICONV_H
    src_enc = encoding;
    encoding = "UTF-8";
#endif

    if (!st->pgm_name)		/* v.dave && r.michael */
	st->pgm_name = G_program_name();
    if (!st->pgm_name)
	st->pgm_name = "??";

    fprintf(stdout, "<?xml version=\"1.0\" encoding=\"%s\"?>\n", encoding);
    fprintf(stdout, "<!DOCTYPE task SYSTEM \"grass-interface.dtd\">\n");

    fprintf(stdout, "<task name=\"%s\">\n", st->pgm_name);

    if (st->module_info.label) {
	fprintf(stdout, "\t<label>\n\t\t");
	print_escaped_for_xml(stdout, st->module_info.label);
	fprintf(stdout, "\n\t</label>\n");
    }

    if (st->module_info.description) {
	fprintf(stdout, "\t<description>\n\t\t");
	print_escaped_for_xml(stdout, st->module_info.description);
	fprintf(stdout, "\n\t</description>\n");
    }

    if (st->module_info.keywords) {
	fprintf(stdout, "\t<keywords>\n\t\t");
	G__print_keywords(stdout, print_escaped_for_xml);
	fprintf(stdout, "\n\t</keywords>\n");
    }

	/***** Don't use parameter-groups for now.  We'll reimplement this later
	 ***** when we have a concept of several mutually exclusive option
	 ***** groups
	if (st->n_opts || st->n_flags)
		fprintf(stdout, "\t<parameter-group>\n");
	 *****
	 *****
	 *****/

    if (st->n_opts) {
	opt = &st->first_option;
	while (opt != NULL) {
	    /* TODO: make this a enumeration type? */
	    switch (opt->type) {
	    case TYPE_INTEGER:
		type = "integer";
		break;
	    case TYPE_DOUBLE:
		type = "float";
		break;
	    case TYPE_STRING:
		type = "string";
		break;
	    default:
		type = "string";
		break;
	    }
	    fprintf(stdout, "\t<parameter "
		    "name=\"%s\" "
		    "type=\"%s\" "
		    "required=\"%s\" "
		    "multiple=\"%s\">\n",
		    opt->key,
		    type,
		    opt->required == YES ? "yes" : "no",
		    opt->multiple == YES ? "yes" : "no");

	    if (opt->label) {
		fprintf(stdout, "\t\t<label>\n\t\t\t");
		print_escaped_for_xml(stdout, opt->label);
		fprintf(stdout, "\n\t\t</label>\n");
	    }

	    if (opt->description) {
		fprintf(stdout, "\t\t<description>\n\t\t\t");
		print_escaped_for_xml(stdout, opt->description);
		fprintf(stdout, "\n\t\t</description>\n");
	    }

	    if (opt->key_desc) {
		fprintf(stdout, "\t\t<keydesc>\n");
		top = G_calloc(strlen(opt->key_desc) + 1, 1);
		strcpy(top, opt->key_desc);
		s = strtok(top, ",");
		for (i = 1; s != NULL; i++) {
		    fprintf(stdout, "\t\t\t<item order=\"%d\">", i);
		    print_escaped_for_xml(stdout, s);
		    fprintf(stdout, "</item>\n");
		    s = strtok(NULL, ",");
		}
		fprintf(stdout, "\t\t</keydesc>\n");
		G_free(top);
	    }

	    if (opt->gisprompt) {
		const char *atts[] = { "age", "element", "prompt", NULL };
		top = G_calloc(strlen(opt->gisprompt) + 1, 1);
		strcpy(top, opt->gisprompt);
		s = strtok(top, ",");
		fprintf(stdout, "\t\t<gisprompt ");
		for (i = 0; s != NULL && atts[i] != NULL; i++) {
		    fprintf(stdout, "%s=\"%s\" ", atts[i], s);
		    s = strtok(NULL, ",");
		}
		fprintf(stdout, "/>\n");
		G_free(top);
	    }

	    if (opt->def) {
		fprintf(stdout, "\t\t<default>\n\t\t\t");
		print_escaped_for_xml(stdout, opt->def);
		fprintf(stdout, "\n\t\t</default>\n");
	    }

	    if (opt->options) {
		/* TODO:
		 * add something like
		 *       <range min="xxx" max="xxx"/>
		 * to <values> */
		i = 0;
		fprintf(stdout, "\t\t<values>\n");
		while (opt->opts[i]) {
		    fprintf(stdout, "\t\t\t<value>\n");
		    fprintf(stdout, "\t\t\t\t<name>");
		    print_escaped_for_xml(stdout, opt->opts[i]);
		    fprintf(stdout, "</name>\n");
		    if (opt->descs && opt->opts[i] && opt->descs[i]) {
			fprintf(stdout, "\t\t\t\t<description>");
			print_escaped_for_xml(stdout, opt->descs[i]);
			fprintf(stdout, "</description>\n");
		    }
		    fprintf(stdout, "\t\t\t</value>\n");
		    i++;
		}
		fprintf(stdout, "\t\t</values>\n");
	    }
	    if (opt->guisection) {
		fprintf(stdout, "\t\t<guisection>\n\t\t\t");
		print_escaped_for_xml(stdout, opt->guisection);
		fprintf(stdout, "\n\t\t</guisection>\n");
	    }
	    if (opt->guidependency) {
		fprintf(stdout, "\t\t<guidependency>\n\t\t\t");
		print_escaped_for_xml(stdout, opt->guidependency);
		fprintf(stdout, "\n\t\t</guidependency>\n");
	    }
	    /* TODO:
	     * - key_desc?
	     * - there surely are some more. which ones?
	     */

	    opt = opt->next_opt;
	    fprintf(stdout, "\t</parameter>\n");
	}
    }


    if (st->n_flags) {
	flag = &st->first_flag;
	while (flag != NULL) {
	    fprintf(stdout, "\t<flag name=\"%c\">\n", flag->key);

	    if (flag->label) {
		fprintf(stdout, "\t\t<label>\n\t\t\t");
		print_escaped_for_xml(stdout, flag->label);
		fprintf(stdout, "\n\t\t</label>\n");
	    }

	    if (flag->suppress_required)
		fprintf(stdout, "\t\t<suppress_required/>\n");

	    if (flag->description) {
		fprintf(stdout, "\t\t<description>\n\t\t\t");
		print_escaped_for_xml(stdout, flag->description);
		fprintf(stdout, "\n\t\t</description>\n");
	    }
	    if (flag->guisection) {
		fprintf(stdout, " \t\t<guisection>\n\t\t\t");
		print_escaped_for_xml(stdout, flag->guisection);
		fprintf(stdout, "\n\t\t</guisection>\n");
	    }
	    flag = flag->next_flag;
	    fprintf(stdout, "\t</flag>\n");
	}
    }

	/***** Don't use parameter-groups for now.  We'll reimplement this later
	 ***** when we have a concept of several mutually exclusive option
	 ***** groups
	if (st->n_opts || st->n_flags)
		fprintf(stdout, "\t</parameter-group>\n");
	 *****
	 *****
	 *****/

    if (new_prompt) {
	/* overwrite */
	fprintf(stdout, "\t<flag name=\"%s\">\n", "overwrite");
	fprintf(stdout, "\t\t<description>\n\t\t\t");
	print_escaped_for_xml(stdout,
			      _("Allow output files to overwrite existing files"));
	fprintf(stdout, "\n\t\t</description>\n");
	fprintf(stdout, "\t</flag>\n");
    }

    /* verbose */
    fprintf(stdout, "\t<flag name=\"%s\">\n", "verbose");
    fprintf(stdout, "\t\t<description>\n\t\t\t");
    print_escaped_for_xml(stdout, _("Verbose module output"));
    fprintf(stdout, "\n\t\t</description>\n");
    fprintf(stdout, "\t</flag>\n");

    /* quiet */
    fprintf(stdout, "\t<flag name=\"%s\">\n", "quiet");
    fprintf(stdout, "\t\t<description>\n\t\t\t");
    print_escaped_for_xml(stdout, _("Quiet module output"));
    fprintf(stdout, "\n\t\t</description>\n");
    fprintf(stdout, "\t</flag>\n");

    fprintf(stdout, "</task>\n");
}
Ejemplo n.º 14
0
int main(int argc, char *argv[])
{
    int fd[NFILES];
    int outfd;
    int i;
    const char *name;
    const char *output;
    const char *mapset;
    int non_zero;
    struct Range range;
    CELL ncats, max_cats;
    int primary;
    struct Categories pcats;
    struct Colors pcolr;
    char buf[1024];
    CELL result;
    struct GModule *module;
    struct
    {
	struct Option *input, *output;
    } parm;
    struct
    {
	struct Flag *z;
    } flag;

    G_gisinit(argv[0]);

    /* Define the different options */

    module = G_define_module();
    G_add_keyword(_("raster"));
    G_add_keyword(_("statistics"));
    module->description =
	_("Creates a cross product of the category values from "
	  "multiple raster map layers.");

    parm.input = G_define_option();
    parm.input->key = "input";
    parm.input->type = TYPE_STRING;
    parm.input->required = YES;
    parm.input->multiple = YES;
    parm.input->gisprompt = "old,cell,raster";
    sprintf(buf, _("Names of 2-%d input raster maps"), NFILES);
    parm.input->description = G_store(buf);

    parm.output = G_define_standard_option(G_OPT_R_OUTPUT);

    /* Define the different flags */

    flag.z = G_define_flag();
    flag.z->key = 'z';
    flag.z->description = _("Non-zero data only");

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

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

    nfiles = 0;
    non_zero = flag.z->answer;

    for (nfiles = 0; (name = parm.input->answers[nfiles]); nfiles++) {
	if (nfiles >= NFILES)
	    G_fatal_error(_("More than %d files not allowed"), NFILES);
	mapset = G_find_raster2(name, "");
	if (!mapset)
	    G_fatal_error(_("Raster map <%s> not found"), name);
	names[nfiles] = name;
	fd[nfiles] = Rast_open_old(name, mapset);
	Rast_read_range(name, mapset, &range);
	ncats = range.max - range.min;

	if (nfiles == 0 || ncats > max_cats) {
	    primary = nfiles;
	    max_cats = ncats;
	}
    }

    if (nfiles <= 1)
	G_fatal_error(_("Must specify 2 or more input maps"));
    output = parm.output->answer;
    outfd = Rast_open_c_new(output);

    sprintf(buf, "Cross of %s", names[0]);
    for (i = 1; i < nfiles - 1; i++) {
	strcat(buf, ", ");
	strcat(buf, names[i]);
    }
    strcat(buf, " and ");
    strcat(buf, names[i]);
    Rast_init_cats(buf, &pcats);

    /* first step is cross product, but un-ordered */
    result = cross(fd, non_zero, primary, outfd);

    /* print message STEP mesage */
    G_message(_("%s: STEP 2 ..."), G_program_name());

    /* now close all files */
    for (i = 0; i < nfiles; i++)
	Rast_close(fd[i]);
    Rast_close(outfd);

    if (result <= 0)
	exit(0);


    /* build the renumbering/reclass and the new cats file */
    qsort(reclass, result + 1, sizeof(RECLASS), cmp);
    table = (CELL *) G_calloc(result + 1, sizeof(CELL));
    for (i = 0; i < nfiles; i++) {
	mapset = G_find_raster2(names[i], "");
	Rast_read_cats(names[i], mapset, &labels[i]);
    }

    for (ncats = 0; ncats <= result; ncats++) {
	table[reclass[ncats].result] = ncats;
	set_cat(ncats, reclass[ncats].cat, &pcats);
    }

    for (i = 0; i < nfiles; i++)
	Rast_free_cats(&labels[i]);

    /* reopen the output cell for reading and for writing */
    fd[0] = Rast_open_old(output, G_mapset());
    outfd = Rast_open_c_new(output);

    renumber(fd[0], outfd);

    G_message(_("Creating support files for <%s>..."), output);
    Rast_close(fd[0]);
    Rast_close(outfd);
    Rast_write_cats(output, &pcats);
    Rast_free_cats(&pcats);
    if (result > 0) {
	Rast_make_random_colors(&pcolr, (CELL) 1, result);
	Rast_write_colors(output, G_mapset(), &pcolr);
    }

    G_message(_("%ld categories"), (long)result);
    exit(EXIT_SUCCESS);
}
Ejemplo n.º 15
0
void write_points(const char *fname, DATA *d, DPOINT *where, double *est,
	int n_outfl) {

	static FILE *f = NULL;
#ifdef HAVE_LIBGIS
	static Site *site = NULL;
	static int dim = 2;
	int i;
#endif 

	if (! grass()) {
		if (where == NULL) {
			if (fname != NULL) {
				f = efopen(fname, "w");
				write_ascii_header(f, d, n_outfl);
			} else
				efclose(f);
		} else {
			if (f == NULL)
				ErrMsg(ER_NULL, "write_points(): f");
			output_line(f, d, where, est, n_outfl);
		}
	} else {
#ifdef HAVE_LIBGIS
		if (where == NULL) {
			if (fname != NULL) { /* initialize: */
				DUMP("opening grass sites list\n");
				if (d->mode & Z_BIT_SET)
					dim++;
				if ((f = G_sites_open_new((char *) fname)) == NULL)
					G_fatal_error("%s: cannot open sites file %f for writing\n",
						G_program_name());
				site = G_site_new_struct(CELL_TYPE, dim, 0, n_outfl);
			} else { /* close: */
				DUMP("closing grass sites list\n");
				fclose(f);
				dim = 2;
				G_site_free_struct(site);
				site = NULL;
			}
		} else {
			assert(site != NULL);
			assert(d != NULL);
			/* fill site: */
			site->east = where->x;
			site->north = where->y;
			if (d->mode & Z_BIT_SET)
				site->dim[0] = where->z;
			if (d->mode & S_BIT_SET)
				site->ccat = where->u.stratum + strata_min;
			else
				site->ccat = GET_INDEX(where) + 1;
			for (i = 0; i < n_outfl; i++) {
				if (is_mv_double(&(est[i]))) {
					site->dbl_att[i] = -9999.0;
					if (DEBUG_DUMP)
						printlog(" [%d]:mv ", i);
				} else {
					site->dbl_att[i] = est[i];
					if (DEBUG_DUMP)
						printlog(" value[%d]: %g ", i, site->dbl_att[i]);
				}
			}
			if (DEBUG_DUMP)
				printlog("\n");
			G_site_put(f, site);
		}
#else 
		ErrMsg(ER_IMPOSVAL, "gstat/grass error: libgis() not linked");
#endif 
	}
}
Ejemplo n.º 16
0
int main(int argc, char *argv[])
{
    struct GModule *module;
    struct _param {
        struct Option *dsn, *out, *layer, *spat, *where,
                   *min_area;
        struct Option *snap, *type, *outloc, *cnames;
    } param;
    struct _flag {
        struct Flag *list, *tlist, *no_clean, *z, *notab,
                   *region;
        struct Flag *over, *extend, *formats, *tolower, *no_import;
    } flag;

    int i, j, layer, arg_s_num, nogeom, ncnames;
    float xmin, ymin, xmax, ymax;
    int ncols = 0, type;
    double min_area, snap;
    char buf[2000], namebuf[2000], tempvect[GNAME_MAX];
    char *separator;

    struct Key_Value *loc_proj_info, *loc_proj_units;
    struct Key_Value *proj_info, *proj_units;
    struct Cell_head cellhd, loc_wind, cur_wind;
    char error_msg[8192];

    /* Vector */
    struct Map_info Map, Tmp, *Out;
    int cat;

    /* Attributes */
    struct field_info *Fi;
    dbDriver *driver;
    dbString sql, strval;
    int dim, with_z;

    /* OGR */
    OGRDataSourceH Ogr_ds;
    OGRLayerH Ogr_layer;
    OGRFieldDefnH Ogr_field;
    char *Ogr_fieldname;
    OGRFieldType Ogr_ftype;
    OGRFeatureH Ogr_feature;
    OGRFeatureDefnH Ogr_featuredefn;
    OGRGeometryH Ogr_geometry, Ogr_oRing, poSpatialFilter;
    OGRSpatialReferenceH Ogr_projection;
    OGREnvelope oExt;
    OGRwkbGeometryType Ogr_geom_type;

    int OFTIntegerListlength;

    char *output;
    char **layer_names;		/* names of layers to be imported */
    int *layers;		/* layer indexes */
    int nlayers;		/* number of layers to import */
    char **available_layer_names;	/* names of layers to be imported */
    int navailable_layers;
    int layer_id;
    unsigned int n_features, feature_count;
    int overwrite;
    double area_size;
    int use_tmp_vect;

    xmin = ymin = xmax = ymax = 0.0;
    loc_proj_info = loc_proj_units = NULL;
    Ogr_ds = Ogr_oRing = poSpatialFilter = NULL;
    OFTIntegerListlength = 40;	/* hack due to limitation in OGR */
    area_size = 0.0;
    use_tmp_vect = FALSE;

    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("vector"));
    G_add_keyword(_("import"));
    module->description = _("Converts vector data into a GRASS vector map using OGR library.");

    param.dsn = G_define_option();
    param.dsn->key = "dsn";
    param.dsn->type = TYPE_STRING;
    param.dsn->required =YES;
    param.dsn->label = _("OGR datasource name");
    param.dsn->description = _("Examples:\n"
                               "\t\tESRI Shapefile: directory containing shapefiles\n"
                               "\t\tMapInfo File: directory containing mapinfo files");

    param.layer = G_define_option();
    param.layer->key = "layer";
    param.layer->type = TYPE_STRING;
    param.layer->required = NO;
    param.layer->multiple = YES;
    param.layer->label =
        _("OGR layer name. If not given, all available layers are imported");
    param.layer->description =
        _("Examples:\n" "\t\tESRI Shapefile: shapefile name\n"
          "\t\tMapInfo File: mapinfo file name");
    param.layer->guisection = _("Selection");

    param.out = G_define_standard_option(G_OPT_V_OUTPUT);
    param.out->required = NO;
    param.out->guisection = _("Output");

    param.spat = G_define_option();
    param.spat->key = "spatial";
    param.spat->type = TYPE_DOUBLE;
    param.spat->multiple = YES;
    param.spat->required = NO;
    param.spat->key_desc = "xmin,ymin,xmax,ymax";
    param.spat->label = _("Import subregion only");
    param.spat->guisection = _("Selection");
    param.spat->description =
        _("Format: xmin,ymin,xmax,ymax - usually W,S,E,N");

    param.where = G_define_standard_option(G_OPT_DB_WHERE);
    param.where->guisection = _("Selection");

    param.min_area = G_define_option();
    param.min_area->key = "min_area";
    param.min_area->type = TYPE_DOUBLE;
    param.min_area->required = NO;
    param.min_area->answer = "0.0001";
    param.min_area->label =
        _("Minimum size of area to be imported (square units)");
    param.min_area->guisection = _("Selection");
    param.min_area->description = _("Smaller areas and "
                                    "islands are ignored. Should be greater than snap^2");

    param.type = G_define_standard_option(G_OPT_V_TYPE);
    param.type->options = "point,line,boundary,centroid";
    param.type->answer = "";
    param.type->description = _("Optionally change default input type");
    param.type->descriptions =
        _("point;import area centroids as points;"
          "line;import area boundaries as lines;"
          "boundary;import lines as area boundaries;"
          "centroid;import points as centroids");
    param.type->guisection = _("Selection");

    param.snap = G_define_option();
    param.snap->key = "snap";
    param.snap->type = TYPE_DOUBLE;
    param.snap->required = NO;
    param.snap->answer = "-1";
    param.snap->label = _("Snapping threshold for boundaries");
    param.snap->description = _("'-1' for no snap");

    param.outloc = G_define_option();
    param.outloc->key = "location";
    param.outloc->type = TYPE_STRING;
    param.outloc->required = NO;
    param.outloc->description = _("Name for new location to create");
    param.outloc->key_desc = "name";

    param.cnames = G_define_option();
    param.cnames->key = "cnames";
    param.cnames->type = TYPE_STRING;
    param.cnames->required = NO;
    param.cnames->multiple = YES;
    param.cnames->description =
        _("List of column names to be used instead of original names, "
          "first is used for category column");
    param.cnames->guisection = _("Attributes");

    flag.list = G_define_flag();
    flag.list->key = 'l';
    flag.list->description = _("List available OGR layers in data source and exit");
    flag.list->suppress_required = YES;
    flag.list->guisection = _("Print");

    flag.tlist = G_define_flag();
    flag.tlist->key = 'a';
    flag.tlist->description = _("List available OGR layers including feature types "
                                "in data source and exit");
    flag.tlist->suppress_required = YES;
    flag.tlist->guisection = _("Print");

    flag.formats = G_define_flag();
    flag.formats->key = 'f';
    flag.formats->description = _("List supported formats and exit");
    flag.formats->suppress_required = YES;
    flag.formats->guisection = _("Print");

    /* if using -c, you lose topological information ! */
    flag.no_clean = G_define_flag();
    flag.no_clean->key = 'c';
    flag.no_clean->description = _("Do not clean polygons (not recommended)");
    flag.no_clean->guisection = _("Output");

    flag.z = G_define_flag();
    flag.z->key = 'z';
    flag.z->description = _("Create 3D output");
    flag.z->guisection = _("Output");

    flag.notab = G_define_flag();
    flag.notab->key = 't';
    flag.notab->description = _("Do not create attribute table");
    flag.notab->guisection = _("Attributes");

    flag.over = G_define_flag();
    flag.over->key = 'o';
    flag.over->description =
        _("Override dataset projection (use location's projection)");

    flag.region = G_define_flag();
    flag.region->key = 'r';
    flag.region->guisection = _("Selection");
    flag.region->description = _("Limit import to the current region");

    flag.extend = G_define_flag();
    flag.extend->key = 'e';
    flag.extend->description =
        _("Extend location extents based on new dataset");

    flag.tolower = G_define_flag();
    flag.tolower->key = 'w';
    flag.tolower->description =
        _("Change column names to lowercase characters");
    flag.tolower->guisection = _("Attributes");

    flag.no_import = G_define_flag();
    flag.no_import->key = 'i';
    flag.no_import->description =
        _("Create the location specified by the \"location\" parameter and exit."
          " Do not import the vector data.");

    /* The parser checks if the map already exists in current mapset, this is
     * wrong if location options is used, so we switch out the check and do it
     * in the module after the parser */
    overwrite = G_check_overwrite(argc, argv);

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

    G_begin_polygon_area_calculations();	/* Used in geom() */

    OGRRegisterAll();

    /* list supported formats */
    if (flag.formats->answer) {
        int iDriver;

        G_message(_("Available OGR Drivers:"));

        for (iDriver = 0; iDriver < OGRGetDriverCount(); iDriver++) {
            OGRSFDriverH poDriver = OGRGetDriver(iDriver);
            const char *pszRWFlag;

            if (OGR_Dr_TestCapability(poDriver, ODrCCreateDataSource))
                pszRWFlag = "rw";
            else
                pszRWFlag = "ro";

            fprintf(stdout, " %s (%s): %s\n",
                    OGR_Dr_GetName(poDriver),
                    pszRWFlag, OGR_Dr_GetName(poDriver));
        }
        exit(EXIT_SUCCESS);
    }

    if (param.dsn->answer == NULL) {
        G_fatal_error(_("Required parameter <%s> not set"), param.dsn->key);
    }

    min_area = atof(param.min_area->answer);
    snap = atof(param.snap->answer);
    type = Vect_option_to_types(param.type);

    ncnames = 0;
    if (param.cnames->answers) {
        i = 0;
        while (param.cnames->answers[i++]) {
            ncnames++;
        }
    }

    /* Open OGR DSN */
    Ogr_ds = NULL;
    if (strlen(param.dsn->answer) > 0)
        Ogr_ds = OGROpen(param.dsn->answer, FALSE, NULL);

    if (Ogr_ds == NULL)
        G_fatal_error(_("Unable to open data source <%s>"), param.dsn->answer);

    /* Make a list of available layers */
    navailable_layers = OGR_DS_GetLayerCount(Ogr_ds);
    available_layer_names =
        (char **)G_malloc(navailable_layers * sizeof(char *));

    if (flag.list->answer || flag.tlist->answer)
        G_message(_("Data source <%s> (format '%s') contains %d layers:"),
                  param.dsn->answer,
                  OGR_Dr_GetName(OGR_DS_GetDriver(Ogr_ds)), navailable_layers);
    for (i = 0; i < navailable_layers; i++) {
        Ogr_layer = OGR_DS_GetLayer(Ogr_ds, i);
        Ogr_featuredefn = OGR_L_GetLayerDefn(Ogr_layer);
        Ogr_geom_type = OGR_FD_GetGeomType(Ogr_featuredefn);

        available_layer_names[i] =
            G_store((char *)OGR_FD_GetName(Ogr_featuredefn));

        if (flag.tlist->answer)
            fprintf(stdout, "%s (%s)\n", available_layer_names[i],
                    OGRGeometryTypeToName(Ogr_geom_type));
        else if (flag.list->answer)
            fprintf(stdout, "%s\n", available_layer_names[i]);
    }
    if (flag.list->answer || flag.tlist->answer) {
        fflush(stdout);
        exit(EXIT_SUCCESS);
    }

    /* Make a list of layers to be imported */
    if (param.layer->answer) {	/* From option */
        nlayers = 0;
        while (param.layer->answers[nlayers])
            nlayers++;

        layer_names = (char **)G_malloc(nlayers * sizeof(char *));
        layers = (int *)G_malloc(nlayers * sizeof(int));

        for (i = 0; i < nlayers; i++) {
            layer_names[i] = G_store(param.layer->answers[i]);
            /* Find it in the source */
            layers[i] = -1;
            for (j = 0; j < navailable_layers; j++) {
                if (strcmp(available_layer_names[j], layer_names[i]) == 0) {
                    layers[i] = j;
                    break;
                }
            }
            if (layers[i] == -1)
                G_fatal_error(_("Layer <%s> not available"), layer_names[i]);
        }
    }
    else {			/* use list of all layers */
        nlayers = navailable_layers;
        layer_names = available_layer_names;
        layers = (int *)G_malloc(nlayers * sizeof(int));
        for (i = 0; i < nlayers; i++)
            layers[i] = i;
    }

    if (param.out->answer) {
        output = G_store(param.out->answer);
    }
    else {
        if (nlayers < 1)
            G_fatal_error(_("No OGR layers available"));
        output = G_store(layer_names[0]);
        G_message(_("All available OGR layers will be imported into vector map <%s>"), output);
    }

    if (!param.outloc->answer) {	/* Check if the map exists */
        if (G_find_vector2(output, G_mapset()) && !overwrite)
            G_fatal_error(_("Vector map <%s> already exists"),
                          output);
    }

    /* Get first imported layer to use for extents and projection check */
    Ogr_layer = OGR_DS_GetLayer(Ogr_ds, layers[0]);

    if (flag.region->answer) {
        if (param.spat->answer)
            G_fatal_error(_("Select either the current region flag or the spatial option, not both"));

        G_get_window(&cur_wind);
        xmin = cur_wind.west;
        xmax = cur_wind.east;
        ymin = cur_wind.south;
        ymax = cur_wind.north;
    }
    if (param.spat->answer) {
        /* See as reference: gdal/ogr/ogr_capi_test.c */

        /* cut out a piece of the map */
        /* order: xmin,ymin,xmax,ymax */
        arg_s_num = 0;
        i = 0;
        while (param.spat->answers[i]) {
            if (i == 0)
                xmin = atof(param.spat->answers[i]);
            if (i == 1)
                ymin = atof(param.spat->answers[i]);
            if (i == 2)
                xmax = atof(param.spat->answers[i]);
            if (i == 3)
                ymax = atof(param.spat->answers[i]);
            arg_s_num++;
            i++;
        }
        if (arg_s_num != 4)
            G_fatal_error(_("4 parameters required for 'spatial' parameter"));
    }
    if (param.spat->answer || flag.region->answer) {
        G_debug(2, "cut out with boundaries: xmin:%f ymin:%f xmax:%f ymax:%f",
                xmin, ymin, xmax, ymax);

        /* in theory this could be an irregular polygon */
        poSpatialFilter = OGR_G_CreateGeometry(wkbPolygon);
        Ogr_oRing = OGR_G_CreateGeometry(wkbLinearRing);
        OGR_G_AddPoint(Ogr_oRing, xmin, ymin, 0.0);
        OGR_G_AddPoint(Ogr_oRing, xmin, ymax, 0.0);
        OGR_G_AddPoint(Ogr_oRing, xmax, ymax, 0.0);
        OGR_G_AddPoint(Ogr_oRing, xmax, ymin, 0.0);
        OGR_G_AddPoint(Ogr_oRing, xmin, ymin, 0.0);
        OGR_G_AddGeometryDirectly(poSpatialFilter, Ogr_oRing);

        OGR_L_SetSpatialFilter(Ogr_layer, poSpatialFilter);
    }

    if (param.where->answer) {
        /* select by attribute */
        OGR_L_SetAttributeFilter(Ogr_layer, param.where->answer);
    }

    /* fetch boundaries */
    if ((OGR_L_GetExtent(Ogr_layer, &oExt, 1)) == OGRERR_NONE) {
        G_get_window(&cellhd);
        cellhd.north = oExt.MaxY;
        cellhd.south = oExt.MinY;
        cellhd.west = oExt.MinX;
        cellhd.east = oExt.MaxX;
        cellhd.rows = 20;	/* TODO - calculate useful values */
        cellhd.cols = 20;
        cellhd.ns_res = (cellhd.north - cellhd.south) / cellhd.rows;
        cellhd.ew_res = (cellhd.east - cellhd.west) / cellhd.cols;
    }
    else {
        cellhd.north = 1.;
        cellhd.south = 0.;
        cellhd.west = 0.;
        cellhd.east = 1.;
        cellhd.top = 1.;
        cellhd.bottom = 1.;
        cellhd.rows = 1;
        cellhd.rows3 = 1;
        cellhd.cols = 1;
        cellhd.cols3 = 1;
        cellhd.depths = 1;
        cellhd.ns_res = 1.;
        cellhd.ns_res3 = 1.;
        cellhd.ew_res = 1.;
        cellhd.ew_res3 = 1.;
        cellhd.tb_res = 1.;
    }

    /* suppress boundary splitting ? */
    if (flag.no_clean->answer) {
        split_distance = -1.;
    }
    else {
        split_distance = 0.;
        area_size =
            sqrt((cellhd.east - cellhd.west) * (cellhd.north - cellhd.south));
    }

    /* Fetch input map projection in GRASS form. */
    proj_info = NULL;
    proj_units = NULL;
    Ogr_projection = OGR_L_GetSpatialRef(Ogr_layer);	/* should not be freed later */

    /* Do we need to create a new location? */
    if (param.outloc->answer != NULL) {
        /* Convert projection information non-interactively as we can't
         * assume the user has a terminal open */
        if (GPJ_osr_to_grass(&cellhd, &proj_info,
                             &proj_units, Ogr_projection, 0) < 0) {
            G_fatal_error(_("Unable to convert input map projection to GRASS "
                            "format; cannot create new location."));
        }
        else {
            G_make_location(param.outloc->answer, &cellhd,
                            proj_info, proj_units, NULL);
            G_message(_("Location <%s> created"), param.outloc->answer);
        }

        /* If the i flag is set, clean up? and exit here */
        if(flag.no_import->answer)
        {
            exit(EXIT_SUCCESS);
        }
    }
    else {
        int err = 0;

        /* Projection only required for checking so convert non-interactively */
        if (GPJ_osr_to_grass(&cellhd, &proj_info,
                             &proj_units, Ogr_projection, 0) < 0)
            G_warning(_("Unable to convert input map projection information to "
                        "GRASS format for checking"));

        /* Does the projection of the current location match the dataset? */
        /* G_get_window seems to be unreliable if the location has been changed */
        G__get_window(&loc_wind, "", "DEFAULT_WIND", "PERMANENT");
        /* fetch LOCATION PROJ info */
        if (loc_wind.proj != PROJECTION_XY) {
            loc_proj_info = G_get_projinfo();
            loc_proj_units = G_get_projunits();
        }

        if (flag.over->answer) {
            cellhd.proj = loc_wind.proj;
            cellhd.zone = loc_wind.zone;
            G_message(_("Over-riding projection check"));
        }
        else if (loc_wind.proj != cellhd.proj
                 || (err =
                         G_compare_projections(loc_proj_info, loc_proj_units,
                                               proj_info, proj_units)) != TRUE) {
            int i_value;

            strcpy(error_msg,
                   _("Projection of dataset does not"
                     " appear to match current location.\n\n"));

            /* TODO: output this info sorted by key: */
            if (loc_wind.proj != cellhd.proj || err != -2) {
                if (loc_proj_info != NULL) {
                    strcat(error_msg, _("GRASS LOCATION PROJ_INFO is:\n"));
                    for (i_value = 0; i_value < loc_proj_info->nitems;
                            i_value++)
                        sprintf(error_msg + strlen(error_msg), "%s: %s\n",
                                loc_proj_info->key[i_value],
                                loc_proj_info->value[i_value]);
                    strcat(error_msg, "\n");
                }

                if (proj_info != NULL) {
                    strcat(error_msg, _("Import dataset PROJ_INFO is:\n"));
                    for (i_value = 0; i_value < proj_info->nitems; i_value++)
                        sprintf(error_msg + strlen(error_msg), "%s: %s\n",
                                proj_info->key[i_value],
                                proj_info->value[i_value]);
                }
                else {
                    strcat(error_msg, _("Import dataset PROJ_INFO is:\n"));
                    if (cellhd.proj == PROJECTION_XY)
                        sprintf(error_msg + strlen(error_msg),
                                "Dataset proj = %d (unreferenced/unknown)\n",
                                cellhd.proj);
                    else if (cellhd.proj == PROJECTION_LL)
                        sprintf(error_msg + strlen(error_msg),
                                "Dataset proj = %d (lat/long)\n",
                                cellhd.proj);
                    else if (cellhd.proj == PROJECTION_UTM)
                        sprintf(error_msg + strlen(error_msg),
                                "Dataset proj = %d (UTM), zone = %d\n",
                                cellhd.proj, cellhd.zone);
                    else if (cellhd.proj == PROJECTION_SP)
                        sprintf(error_msg + strlen(error_msg),
                                "Dataset proj = %d (State Plane), zone = %d\n",
                                cellhd.proj, cellhd.zone);
                    else
                        sprintf(error_msg + strlen(error_msg),
                                "Dataset proj = %d (unknown), zone = %d\n",
                                cellhd.proj, cellhd.zone);
                }
            }
            else {
                if (loc_proj_units != NULL) {
                    strcat(error_msg, "GRASS LOCATION PROJ_UNITS is:\n");
                    for (i_value = 0; i_value < loc_proj_units->nitems;
                            i_value++)
                        sprintf(error_msg + strlen(error_msg), "%s: %s\n",
                                loc_proj_units->key[i_value],
                                loc_proj_units->value[i_value]);
                    strcat(error_msg, "\n");
                }

                if (proj_units != NULL) {
                    strcat(error_msg, "Import dataset PROJ_UNITS is:\n");
                    for (i_value = 0; i_value < proj_units->nitems; i_value++)
                        sprintf(error_msg + strlen(error_msg), "%s: %s\n",
                                proj_units->key[i_value],
                                proj_units->value[i_value]);
                }
            }
            sprintf(error_msg + strlen(error_msg),
                    _("\nYou can use the -o flag to %s to override this projection check.\n"),
                    G_program_name());
            strcat(error_msg,
                   _("Consider generating a new location with 'location' parameter"
                     " from input data set.\n"));
            G_fatal_error(error_msg);
        }
        else {
            G_message(_("Projection of input dataset and current location "
                        "appear to match"));
        }
    }

    db_init_string(&sql);
    db_init_string(&strval);

    /* open output vector */
    /* strip any @mapset from vector output name */
    G_find_vector(output, G_mapset());
    Vect_open_new(&Map, output, flag.z->answer != 0);
    Out = &Map;

    n_polygon_boundaries = 0;
    if (!flag.no_clean->answer) {
        /* check if we need a tmp vector */

        /* estimate distance for boundary splitting --> */
        for (layer = 0; layer < nlayers; layer++) {
            layer_id = layers[layer];

            Ogr_layer = OGR_DS_GetLayer(Ogr_ds, layer_id);
            Ogr_featuredefn = OGR_L_GetLayerDefn(Ogr_layer);

            n_features = feature_count = 0;

            n_features = OGR_L_GetFeatureCount(Ogr_layer, 1);
            OGR_L_ResetReading(Ogr_layer);

            /* count polygons and isles */
            G_message(_("Counting polygons for %d features (OGR layer <%s>)..."),
                      n_features, layer_names[layer]);
            while ((Ogr_feature = OGR_L_GetNextFeature(Ogr_layer)) != NULL) {
                G_percent(feature_count++, n_features, 1);	/* show something happens */
                /* Geometry */
                Ogr_geometry = OGR_F_GetGeometryRef(Ogr_feature);
                if (Ogr_geometry != NULL) {
                    poly_count(Ogr_geometry, (type & GV_BOUNDARY));
                }
                OGR_F_Destroy(Ogr_feature);
            }
        }

        G_debug(1, "n polygon boundaries: %d", n_polygon_boundaries);
        if (n_polygon_boundaries > 50) {
            split_distance =
                area_size / log(n_polygon_boundaries);
            /* divisor is the handle: increase divisor to decrease split_distance */
            split_distance = split_distance / 5.;
            G_debug(1, "root of area size: %f", area_size);
            G_verbose_message(_("Boundary splitting distance in map units: %G"),
                              split_distance);
        }
        /* <-- estimate distance for boundary splitting */

        use_tmp_vect = n_polygon_boundaries > 0;

        if (use_tmp_vect) {
            /* open temporary vector, do the work in the temporary vector
             * at the end copy alive lines to output vector
             * in case of polygons this reduces the coor file size by a factor of 2 to 5
             * only needed when cleaning polygons */
            sprintf(tempvect, "%s_tmp", output);
            G_verbose_message(_("Using temporary vector <%s>"), tempvect);
            Vect_open_new(&Tmp, tempvect, flag.z->answer != 0);
            Out = &Tmp;
        }
    }

    Vect_hist_command(&Map);

    /* Points and lines are written immediately with categories. Boundaries of polygons are
     * written to the vector then cleaned and centroids are calculated for all areas in cleaan vector.
     * Then second pass through finds all centroids in each polygon feature and adds its category
     * to the centroid. The result is that one centroids may have 0, 1 ore more categories
     * of one ore more (more input layers) fields. */
    with_z = 0;
    for (layer = 0; layer < nlayers; layer++) {
        layer_id = layers[layer];

        Ogr_layer = OGR_DS_GetLayer(Ogr_ds, layer_id);
        Ogr_featuredefn = OGR_L_GetLayerDefn(Ogr_layer);

        /* Add DB link */
        if (!flag.notab->answer) {
            char *cat_col_name = GV_KEY_COLUMN;

            if (nlayers == 1) {	/* one layer only */
                Fi = Vect_default_field_info(&Map, layer + 1, NULL,
                                             GV_1TABLE);
            }
            else {
                Fi = Vect_default_field_info(&Map, layer + 1, NULL,
                                             GV_MTABLE);
            }

            if (ncnames > 0) {
                cat_col_name = param.cnames->answers[0];
            }
            Vect_map_add_dblink(&Map, layer + 1, layer_names[layer], Fi->table,
                                cat_col_name, Fi->database, Fi->driver);

            ncols = OGR_FD_GetFieldCount(Ogr_featuredefn);
            G_debug(2, "%d columns", ncols);

            /* Create table */
            sprintf(buf, "create table %s (%s integer", Fi->table,
                    cat_col_name);
            db_set_string(&sql, buf);
            for (i = 0; i < ncols; i++) {

                Ogr_field = OGR_FD_GetFieldDefn(Ogr_featuredefn, i);
                Ogr_ftype = OGR_Fld_GetType(Ogr_field);

                G_debug(3, "Ogr_ftype: %i", Ogr_ftype);	/* look up below */

                if (i < ncnames - 1) {
                    Ogr_fieldname = G_store(param.cnames->answers[i + 1]);
                }
                else {
                    /* Change column names to [A-Za-z][A-Za-z0-9_]* */
                    Ogr_fieldname = G_store(OGR_Fld_GetNameRef(Ogr_field));
                    G_debug(3, "Ogr_fieldname: '%s'", Ogr_fieldname);

                    G_str_to_sql(Ogr_fieldname);

                    G_debug(3, "Ogr_fieldname: '%s'", Ogr_fieldname);

                }

                /* avoid that we get the 'cat' column twice */
                if (strcmp(Ogr_fieldname, GV_KEY_COLUMN) == 0) {
                    sprintf(namebuf, "%s_", Ogr_fieldname);
                    Ogr_fieldname = G_store(namebuf);
                }

                /* captial column names are a pain in SQL */
                if (flag.tolower->answer)
                    G_str_to_lower(Ogr_fieldname);

                if (strcmp(OGR_Fld_GetNameRef(Ogr_field), Ogr_fieldname) != 0) {
                    G_warning(_("Column name changed: '%s' -> '%s'"),
                              OGR_Fld_GetNameRef(Ogr_field), Ogr_fieldname);
                }

                /** Simple 32bit integer                     OFTInteger = 0        **/

                /** List of 32bit integers                   OFTIntegerList = 1    **/

                /** Double Precision floating point          OFTReal = 2           **/

                /** List of doubles                          OFTRealList = 3       **/

                /** String of ASCII chars                    OFTString = 4         **/

                /** Array of strings                         OFTStringList = 5     **/

                /** Double byte string (unsupported)         OFTWideString = 6     **/

                /** List of wide strings (unsupported)       OFTWideStringList = 7 **/

                /** Raw Binary data (unsupported)            OFTBinary = 8         **/

                /**                                          OFTDate = 9           **/

                /**                                          OFTTime = 10          **/

                /**                                          OFTDateTime = 11      **/


                if (Ogr_ftype == OFTInteger) {
                    sprintf(buf, ", %s integer", Ogr_fieldname);
                }
                else if (Ogr_ftype == OFTIntegerList) {
                    /* hack: treat as string */
                    sprintf(buf, ", %s varchar ( %d )", Ogr_fieldname,
                            OFTIntegerListlength);
                    G_warning(_("Writing column <%s> with fixed length %d chars (may be truncated)"),
                              Ogr_fieldname, OFTIntegerListlength);
                }
                else if (Ogr_ftype == OFTReal) {
                    sprintf(buf, ", %s double precision", Ogr_fieldname);
#if GDAL_VERSION_NUM >= 1320
                }
                else if (Ogr_ftype == OFTDate) {
                    sprintf(buf, ", %s date", Ogr_fieldname);
                }
                else if (Ogr_ftype == OFTTime) {
                    sprintf(buf, ", %s time", Ogr_fieldname);
                }
                else if (Ogr_ftype == OFTDateTime) {
                    sprintf(buf, ", %s datetime", Ogr_fieldname);
#endif
                }
                else if (Ogr_ftype == OFTString) {
                    int fwidth;

                    fwidth = OGR_Fld_GetWidth(Ogr_field);
                    /* TODO: read all records first and find the longest string length */
                    if (fwidth == 0) {
                        G_warning(_("Width for column %s set to 255 (was not specified by OGR), "
                                    "some strings may be truncated!"),
                                  Ogr_fieldname);
                        fwidth = 255;
                    }
                    sprintf(buf, ", %s varchar ( %d )", Ogr_fieldname,
                            fwidth);
                }
                else if (Ogr_ftype == OFTStringList) {
                    /* hack: treat as string */
                    sprintf(buf, ", %s varchar ( %d )", Ogr_fieldname,
                            OFTIntegerListlength);
                    G_warning(_("Writing column %s with fixed length %d chars (may be truncated)"),
                              Ogr_fieldname, OFTIntegerListlength);
                }
                else {
                    G_warning(_("Column type not supported (%s)"),
                              Ogr_fieldname);
                    buf[0] = 0;
                }
                db_append_string(&sql, buf);
                G_free(Ogr_fieldname);
            }
            db_append_string(&sql, ")");
            G_debug(3, db_get_string(&sql));

            driver =
                db_start_driver_open_database(Fi->driver,
                                              Vect_subst_var(Fi->database,
                                                      &Map));
            if (driver == NULL) {
                G_fatal_error(_("Unable open database <%s> by driver <%s>"),
                              Vect_subst_var(Fi->database, &Map), Fi->driver);
            }

            if (db_execute_immediate(driver, &sql) != DB_OK) {
                db_close_database(driver);
                db_shutdown_driver(driver);
                G_fatal_error(_("Unable to create table: '%s'"),
                              db_get_string(&sql));
            }

            if (db_create_index2(driver, Fi->table, cat_col_name) != DB_OK)
                G_warning(_("Unable to create index for table <%s>, key <%s>"),
                          Fi->table, cat_col_name);

            if (db_grant_on_table
                    (driver, Fi->table, DB_PRIV_SELECT,
                     DB_GROUP | DB_PUBLIC) != DB_OK)
                G_fatal_error(_("Unable to grant privileges on table <%s>"),
                              Fi->table);

            db_begin_transaction(driver);
        }

        /* Import feature */
        cat = 1;
        nogeom = 0;
        OGR_L_ResetReading(Ogr_layer);
        n_features = feature_count = 0;

        n_features = OGR_L_GetFeatureCount(Ogr_layer, 1);

        G_important_message(_("Importing %d features (OGR layer <%s>)..."),
                            n_features, layer_names[layer]);
        while ((Ogr_feature = OGR_L_GetNextFeature(Ogr_layer)) != NULL) {
            G_percent(feature_count++, n_features, 1);	/* show something happens */
            /* Geometry */
            Ogr_geometry = OGR_F_GetGeometryRef(Ogr_feature);
            if (Ogr_geometry == NULL) {
                nogeom++;
            }
            else {
                dim = OGR_G_GetCoordinateDimension(Ogr_geometry);
                if (dim > 2)
                    with_z = 1;

                geom(Ogr_geometry, Out, layer + 1, cat, min_area, type,
                     flag.no_clean->answer);
            }

            /* Attributes */
            if (!flag.notab->answer) {
                sprintf(buf, "insert into %s values ( %d", Fi->table, cat);
                db_set_string(&sql, buf);
                for (i = 0; i < ncols; i++) {
                    Ogr_field = OGR_FD_GetFieldDefn(Ogr_featuredefn, i);
                    Ogr_ftype = OGR_Fld_GetType(Ogr_field);
                    if (OGR_F_IsFieldSet(Ogr_feature, i)) {
                        if (Ogr_ftype == OFTInteger || Ogr_ftype == OFTReal) {
                            sprintf(buf, ", %s",
                                    OGR_F_GetFieldAsString(Ogr_feature, i));
#if GDAL_VERSION_NUM >= 1320
                            /* should we use OGR_F_GetFieldAsDateTime() here ? */
                        }
                        else if (Ogr_ftype == OFTDate || Ogr_ftype == OFTTime
                                 || Ogr_ftype == OFTDateTime) {
                            char *newbuf;

                            db_set_string(&strval, (char *)
                                          OGR_F_GetFieldAsString(Ogr_feature,
                                                                 i));
                            db_double_quote_string(&strval);
                            sprintf(buf, ", '%s'", db_get_string(&strval));
                            newbuf = G_str_replace(buf, "/", "-");	/* fix 2001/10/21 to 2001-10-21 */
                            sprintf(buf, "%s", newbuf);
#endif
                        }
                        else if (Ogr_ftype == OFTString ||
                                 Ogr_ftype == OFTIntegerList) {
                            db_set_string(&strval, (char *)
                                          OGR_F_GetFieldAsString(Ogr_feature,
                                                                 i));
                            db_double_quote_string(&strval);
                            sprintf(buf, ", '%s'", db_get_string(&strval));
                        }

                    }
                    else {
                        /* G_warning (_("Column value not set" )); */
                        if (Ogr_ftype == OFTInteger || Ogr_ftype == OFTReal) {
                            sprintf(buf, ", NULL");
#if GDAL_VERSION_NUM >= 1320
                        }
                        else if (Ogr_ftype == OFTString ||
                                 Ogr_ftype == OFTIntegerList ||
                                 Ogr_ftype == OFTDate) {
#else
                        }
                        else if (Ogr_ftype == OFTString ||
                                 Ogr_ftype == OFTIntegerList) {
#endif
                            sprintf(buf, ", ''");
                        }
                    }
                    db_append_string(&sql, buf);
                }
                db_append_string(&sql, " )");
                G_debug(3, db_get_string(&sql));

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

            OGR_F_Destroy(Ogr_feature);
            cat++;
        }
        G_percent(1, 1, 1);	/* finish it */

        if (!flag.notab->answer) {
            db_commit_transaction(driver);
            db_close_database_shutdown_driver(driver);
        }

        if (nogeom > 0)
            G_warning(_("%d %s without geometry"), nogeom,
                      nogeom == 1 ? "feature" : "features");
    }


    separator = "-----------------------------------------------------";
    G_message("%s", separator);

    if (use_tmp_vect) {
        /* TODO: is it necessary to build here? probably not, consumes time */
        /* GV_BUILD_BASE is sufficient to toggle boundary cleaning */
        Vect_build_partial(&Tmp, GV_BUILD_BASE);
    }

    if (use_tmp_vect && !flag.no_clean->answer &&
            Vect_get_num_primitives(Out, GV_BOUNDARY) > 0) {
        int ret, centr, ncentr, otype, n_overlaps, n_nocat;
        CENTR *Centr;
        struct spatial_index si;
        double x, y, total_area, overlap_area, nocat_area;
        struct bound_box box;
        struct line_pnts *Points;
        int nmodif;

        Points = Vect_new_line_struct();

        G_message("%s", separator);

        G_warning(_("Cleaning polygons, result is not guaranteed!"));

        if (snap >= 0) {
            G_message("%s", separator);
            G_message(_("Snapping boundaries (threshold = %.3e)..."), snap);
            Vect_snap_lines(&Tmp, GV_BOUNDARY, snap, NULL);
        }

        /* It is not to clean to snap centroids, but I have seen data with 2 duplicate polygons
         * (as far as decimal places were printed) and centroids were not identical */
        /* Disabled, because overlapping polygons result in many duplicate centroids anyway */
        /*
           fprintf ( stderr, separator );
           fprintf ( stderr, "Snap centroids (threshold 0.000001):\n" );
           Vect_snap_lines ( &Map, GV_CENTROID, 0.000001, NULL, stderr );
         */

        G_message("%s", separator);
        G_message(_("Breaking polygons..."));
        Vect_break_polygons(&Tmp, GV_BOUNDARY, NULL);

        /* It is important to remove also duplicate centroids in case of duplicate input polygons */
        G_message("%s", separator);
        G_message(_("Removing duplicates..."));
        Vect_remove_duplicates(&Tmp, GV_BOUNDARY | GV_CENTROID, NULL);

        /* in non-pathological cases, the bulk of the cleaning is now done */

        /* Vect_clean_small_angles_at_nodes() can change the geometry so that new intersections
         * are created. We must call Vect_break_lines(), Vect_remove_duplicates()
         * and Vect_clean_small_angles_at_nodes() until no more small angles are found */
        do {
            G_message("%s", separator);
            G_message(_("Breaking boundaries..."));
            Vect_break_lines(&Tmp, GV_BOUNDARY, NULL);

            G_message("%s", separator);
            G_message(_("Removing duplicates..."));
            Vect_remove_duplicates(&Tmp, GV_BOUNDARY, NULL);

            G_message("%s", separator);
            G_message(_("Cleaning boundaries at nodes..."));
            nmodif =
                Vect_clean_small_angles_at_nodes(&Tmp, GV_BOUNDARY, NULL);
        } while (nmodif > 0);

        /* merge boundaries */
        G_message("%s", separator);
        G_message(_("Merging boundaries..."));
        Vect_merge_lines(&Tmp, GV_BOUNDARY, NULL, NULL);

        G_message("%s", separator);
        if (type & GV_BOUNDARY) {	/* that means lines were converted to boundaries */
            G_message(_("Changing boundary dangles to lines..."));
            Vect_chtype_dangles(&Tmp, -1.0, NULL);
        }
        else {
            G_message(_("Removing dangles..."));
            Vect_remove_dangles(&Tmp, GV_BOUNDARY, -1.0, NULL);
        }

        G_message("%s", separator);
        if (type & GV_BOUNDARY) {
            G_message(_("Changing boundary bridges to lines..."));
            Vect_chtype_bridges(&Tmp, NULL);
        }
        else {
            G_message(_("Removing bridges..."));
            Vect_remove_bridges(&Tmp, NULL);
        }

        /* Boundaries are hopefully clean, build areas */
        G_message("%s", separator);
        Vect_build_partial(&Tmp, GV_BUILD_ATTACH_ISLES);

        /* Calculate new centroids for all areas, centroids have the same id as area */
        ncentr = Vect_get_num_areas(&Tmp);
        G_debug(3, "%d centroids/areas", ncentr);

        Centr = (CENTR *) G_calloc(ncentr + 1, sizeof(CENTR));
        Vect_spatial_index_init(&si, 0);
        for (centr = 1; centr <= ncentr; centr++) {
            Centr[centr].valid = 0;
            Centr[centr].cats = Vect_new_cats_struct();
            ret = Vect_get_point_in_area(&Tmp, centr, &x, &y);
            if (ret < 0) {
                G_warning(_("Unable to calculate area centroid"));
                continue;
            }

            Centr[centr].x = x;
            Centr[centr].y = y;
            Centr[centr].valid = 1;
            box.N = box.S = y;
            box.E = box.W = x;
            box.T = box.B = 0;
            Vect_spatial_index_add_item(&si, centr, &box);
        }

        /* Go through all layers and find centroids for each polygon */
        for (layer = 0; layer < nlayers; layer++) {
            G_message("%s", separator);
            G_message(_("Finding centroids for OGR layer <%s>..."), layer_names[layer]);
            layer_id = layers[layer];
            Ogr_layer = OGR_DS_GetLayer(Ogr_ds, layer_id);
            n_features = OGR_L_GetFeatureCount(Ogr_layer, 1);
            OGR_L_ResetReading(Ogr_layer);

            cat = 0;		/* field = layer + 1 */
            G_percent(cat, n_features, 2);
            while ((Ogr_feature = OGR_L_GetNextFeature(Ogr_layer)) != NULL) {
                cat++;
                G_percent(cat, n_features, 2);
                /* Geometry */
                Ogr_geometry = OGR_F_GetGeometryRef(Ogr_feature);
                if (Ogr_geometry != NULL) {
                    centroid(Ogr_geometry, Centr, &si, layer + 1, cat,
                             min_area, type);
                }

                OGR_F_Destroy(Ogr_feature);
            }
        }

        /* Write centroids */
        G_message("%s", separator);
        G_message(_("Writing centroids..."));

        n_overlaps = n_nocat = 0;
        total_area = overlap_area = nocat_area = 0.0;
        for (centr = 1; centr <= ncentr; centr++) {
            double area;

            G_percent(centr, ncentr, 2);

            area = Vect_get_area_area(&Tmp, centr);
            total_area += area;

            if (!(Centr[centr].valid)) {
                continue;
            }

            if (Centr[centr].cats->n_cats == 0) {
                nocat_area += area;
                n_nocat++;
                continue;
            }

            if (Centr[centr].cats->n_cats > 1) {
                Vect_cat_set(Centr[centr].cats, nlayers + 1,
                             Centr[centr].cats->n_cats);
                overlap_area += area;
                n_overlaps++;
            }

            Vect_reset_line(Points);
            Vect_append_point(Points, Centr[centr].x, Centr[centr].y, 0.0);
            if (type & GV_POINT)
                otype = GV_POINT;
            else
                otype = GV_CENTROID;
            Vect_write_line(&Tmp, otype, Points, Centr[centr].cats);
        }
        if (Centr)
            G_free(Centr);

        Vect_spatial_index_destroy(&si);

        if (n_overlaps > 0) {
            G_warning(_("%d areas represent more (overlapping) features, because polygons overlap "
                        "in input layer(s). Such areas are linked to more than 1 row in attribute table. "
                        "The number of features for those areas is stored as category in layer %d"),
                      n_overlaps, nlayers + 1);
        }

        G_message("%s", separator);

        Vect_hist_write(&Map, separator);
        Vect_hist_write(&Map, "\n");
        sprintf(buf, _("%d input polygons\n"), n_polygons);
        G_message(_("%d input polygons"), n_polygons);
        Vect_hist_write(&Map, buf);

        sprintf(buf, _("Total area: %G (%d areas)\n"), total_area, ncentr);
        G_message(_("Total area: %G (%d areas)"), total_area, ncentr);
        Vect_hist_write(&Map, buf);

        sprintf(buf, _("Overlapping area: %G (%d areas)\n"), overlap_area,
                n_overlaps);
        G_message(_("Overlapping area: %G (%d areas)"), overlap_area,
                  n_overlaps);
        Vect_hist_write(&Map, buf);

        sprintf(buf, _("Area without category: %G (%d areas)\n"), nocat_area,
                n_nocat);
        G_message(_("Area without category: %G (%d areas)"), nocat_area,
                  n_nocat);
        Vect_hist_write(&Map, buf);
        G_message("%s", separator);
    }

    /* needed?
     * OGR_DS_Destroy( Ogr_ds );
     */

    if (use_tmp_vect) {
        /* Copy temporary vector to output vector */
        Vect_copy_map_lines(&Tmp, &Map);
        /* release memory occupied by topo, we may need that memory for main output */
        Vect_set_release_support(&Tmp);
        Vect_close(&Tmp);
        Vect_delete(tempvect);
    }

    Vect_build(&Map);
    Vect_close(&Map);

    /* -------------------------------------------------------------------- */
    /*      Extend current window based on dataset.                         */
    /* -------------------------------------------------------------------- */
    if (flag.extend->answer) {
        G_get_default_window(&loc_wind);

        loc_wind.north = MAX(loc_wind.north, cellhd.north);
        loc_wind.south = MIN(loc_wind.south, cellhd.south);
        loc_wind.west = MIN(loc_wind.west, cellhd.west);
        loc_wind.east = MAX(loc_wind.east, cellhd.east);

        loc_wind.rows = (int)ceil((loc_wind.north - loc_wind.south)
                                  / loc_wind.ns_res);
        loc_wind.south = loc_wind.north - loc_wind.rows * loc_wind.ns_res;

        loc_wind.cols = (int)ceil((loc_wind.east - loc_wind.west)
                                  / loc_wind.ew_res);
        loc_wind.east = loc_wind.west + loc_wind.cols * loc_wind.ew_res;

        G__put_window(&loc_wind, "../PERMANENT", "DEFAULT_WIND");
    }

    if (with_z && !flag.z->answer)
        G_warning(_("Input data contains 3D features. Created vector is 2D only, "
                    "use -z flag to import 3D vector."));

    exit(EXIT_SUCCESS);
}
Ejemplo n.º 17
0
/* ************************************************************************* */
int main(int argc, char *argv[])
{
    struct GModule *module = NULL;
    N_gwflow_data2d *data = NULL;
    N_geom_data *geom = NULL;
    N_les *les = NULL;
    N_les_callback_2d *call = NULL;
    double *tmp_vect = NULL;
    struct Cell_head region;
    double error, sor, max_norm = 0, tmp;
    int maxit, i, inner_count = 0;
    char *solver;
    int x, y, stat;
    N_gradient_field_2d *field = NULL;
    N_array_2d *xcomp = NULL;
    N_array_2d *ycomp = NULL;
    char *buff = NULL;
    int with_river = 0, with_drain = 0;

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

    module = G_define_module();
    module->keywords = _("raster, hydrology");
    module->description =
	_("Numerical calculation program for transient, confined and unconfined groundwater flow in two dimensions.");

    /* Get parameters from user */
    set_params();

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

    /* Make sure that the current projection is not lat/long */
    if ((G_projection() == PROJECTION_LL))
	G_fatal_error(_("Lat/Long location is not supported by %s. Please reproject map first."),
		      G_program_name());

    /*Check the river  parameters */
    if (param.river_leak->answer == NULL && param.river_bed->answer == NULL &&
	param.river_head->answer == NULL) {
	with_river = 0;
    }
    else if (param.river_leak->answer != NULL &&
	     param.river_bed->answer != NULL &&
	     param.river_head->answer != NULL) {
	with_river = 1;
    }
    else {
	G_fatal_error
	    (_("Please provide river_head, river_leak and river_bed maps"));
    }

    /*Check the drainage parameters */
    if (param.drain_leak->answer == NULL && param.drain_bed->answer == NULL) {
	with_drain = 0;
    }
    else if (param.drain_leak->answer != NULL &&
	     param.drain_bed->answer != NULL) {
	with_drain = 1;
    }
    else {
	G_fatal_error(_("Please provide drain_head and drain_leak maps"));
    }

    /*Set the maximum iterations */
    sscanf(param.maxit->answer, "%i", &(maxit));
    /*Set the calculation error break criteria */
    sscanf(param.error->answer, "%lf", &(error));
    sscanf(param.sor->answer, "%lf", &(sor));
    /*set the solver */
    solver = param.solver->answer;

    if (strcmp(solver, N_SOLVER_DIRECT_LU) == 0 && param.sparse->answer)
	G_fatal_error(_("The direct LU solver do not work with sparse matrices"));
    if (strcmp(solver, N_SOLVER_DIRECT_GAUSS) == 0 && param.sparse->answer)
	G_fatal_error(_("The direct Gauss solver do not work with sparse matrices"));
    if (strcmp(solver, N_SOLVER_DIRECT_CHOLESKY) == 0 && param.sparse->answer)
	G_fatal_error(_("The direct cholesky solver do not work with sparse matrices"));

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

    /*allocate the geometry structure  for geometry and area calculation */
    geom = N_init_geom_data_2d(&region, geom);

    /*Set the function callback to the groundwater flow function */
    call = N_alloc_les_callback_2d();
    N_set_les_callback_2d_func(call, (*N_callback_gwflow_2d));	/*gwflow 2d */

    /*Allocate the groundwater flow data structure */
    data =
	N_alloc_gwflow_data2d(geom->cols, geom->rows, with_river, with_drain);

    /* set the groundwater type */
    if (param.type->answer) {
	if (strncmp("unconfined", param.type->answer, 10) == 0) {
	    data->gwtype = N_GW_UNCONFINED;
	}
	else {
	    data->gwtype = N_GW_CONFINED;
	}
    }

    /*Set the calculation time */
    sscanf(param.dt->answer, "%lf", &(data->dt));
    G_message("Calculation time: %g", data->dt);

    /*read all input maps into the memory and take care of the
     * null values.*/
    N_read_rast_to_array_2d(param.phead->answer, data->phead);
    N_convert_array_2d_null_to_zero(data->phead);
    N_copy_array_2d(data->phead, data->phead_start);
    N_read_rast_to_array_2d(param.status->answer, data->status);
    N_convert_array_2d_null_to_zero(data->status);
    N_read_rast_to_array_2d(param.hc_x->answer, data->hc_x);
    N_convert_array_2d_null_to_zero(data->hc_x);
    N_read_rast_to_array_2d(param.hc_y->answer, data->hc_y);
    N_convert_array_2d_null_to_zero(data->hc_y);
    N_read_rast_to_array_2d(param.s->answer, data->s);
    N_convert_array_2d_null_to_zero(data->s);
    N_read_rast_to_array_2d(param.top->answer, data->top);
    N_convert_array_2d_null_to_zero(data->top);
    N_read_rast_to_array_2d(param.bottom->answer, data->bottom);
    N_convert_array_2d_null_to_zero(data->bottom);

    /*river is optional */
    if (with_river) {
	N_read_rast_to_array_2d(param.river_bed->answer, data->river_bed);
	N_read_rast_to_array_2d(param.river_head->answer, data->river_head);
	N_read_rast_to_array_2d(param.river_leak->answer, data->river_leak);
	N_convert_array_2d_null_to_zero(data->river_bed);
	N_convert_array_2d_null_to_zero(data->river_head);
	N_convert_array_2d_null_to_zero(data->river_leak);
    }

    /*drainage is optional */
    if (with_drain) {
	N_read_rast_to_array_2d(param.drain_bed->answer, data->drain_bed);
	N_read_rast_to_array_2d(param.drain_leak->answer, data->drain_leak);
	N_convert_array_2d_null_to_zero(data->drain_bed);
	N_convert_array_2d_null_to_zero(data->drain_leak);
    }

    /*Recharge is optional */
    if (param.r->answer) {
	N_read_rast_to_array_2d(param.r->answer, data->r);
	N_convert_array_2d_null_to_zero(data->r);
    }

    /*Sources or sinks are optional */
    if (param.q->answer) {
        N_read_rast_to_array_2d(param.q->answer, data->q);
        N_convert_array_2d_null_to_zero(data->q);
    }

    /* Set the inactive values to zero, to assure a no flow boundary */
    for (y = 0; y < geom->rows; y++) {
	for (x = 0; x < geom->cols; x++) {
	    stat = N_get_array_2d_c_value(data->status, x, y);
	    if (stat == N_CELL_INACTIVE) {	/*only inactive cells */
		N_put_array_2d_d_value(data->hc_x, x, y, 0);
		N_put_array_2d_d_value(data->hc_y, x, y, 0);
		N_put_array_2d_d_value(data->s, x, y, 0);
		N_put_array_2d_d_value(data->q, x, y, 0);
	    }
	}
    }

    /*assemble the linear equation system  and solve it */
    les = create_solve_les(geom, data, call, solver, maxit, error, sor);

    /* copy the result into the phead array for output or unconfined calculation */
    copy_result(data->status, data->phead_start, les->x, &region,
		data->phead);
    N_convert_array_2d_null_to_zero(data->phead);

  /****************************************************/
    /*explicite calculation of free groundwater surface */

  /****************************************************/
    if (data->gwtype == N_GW_UNCONFINED) {
	/* allocate memory and copy the result into a new temporal vector */
	if (!(tmp_vect = (double *)calloc(les->rows, sizeof(double))))
	    G_fatal_error(_("Out of memory"));

	/*copy data */
	for (i = 0; i < les->rows; i++)
	    tmp_vect[i] = les->x[i];

	/*count the number of inner iterations */
	inner_count = 0;

	do {
	    G_message(_("Calculation of unconfined groundwater flow loop %i\n"),
		      inner_count + 1);

	    /* we will allocate a new les for each loop */
	    if (les)
		N_free_les(les);

	    /*assemble the linear equation system  and solve it */
	    les =
		create_solve_les(geom, data, call, solver, maxit, error, sor);

	    /*calculate the maximum norm of the groundwater height difference */
	    tmp = 0;
	    max_norm = 0;
	    for (i = 0; i < les->rows; i++) {
		tmp = fabs(les->x[i] - tmp_vect[i]);
		if (max_norm < tmp)
		    max_norm = tmp;

		/*copy the result */
		tmp_vect[i] = les->x[i];
	    }

	    G_message(_("Maximum difference between this and last increment: %g"),
		      max_norm);

	    /* copy the result into the phead array */
	    copy_result(data->status, data->phead_start, les->x, &region,
			data->phead);
	    N_convert_array_2d_null_to_zero(data->phead);
	     /**/ inner_count++;
	}
	while (max_norm > 0.01 && inner_count < 50);

	if (tmp_vect)
	    free(tmp_vect);
    }

    /*write the result to the output file */
    N_write_array_2d_to_rast(data->phead, param.output->answer);

    /*release the memory */
    if (les)
	N_free_les(les);

    /*Compute the the velocity field if required and write the result into three rast maps */
    if (param.vector->answer) {
	field =
	    N_compute_gradient_field_2d(data->phead, data->hc_x, data->hc_y,
					geom, NULL);

	xcomp = N_alloc_array_2d(geom->cols, geom->rows, 1, DCELL_TYPE);
	ycomp = N_alloc_array_2d(geom->cols, geom->rows, 1, DCELL_TYPE);

	N_compute_gradient_field_components_2d(field, xcomp, ycomp);

	G_asprintf(&buff, "%s_x", param.vector->answer);
	N_write_array_2d_to_rast(xcomp, buff);
	G_asprintf(&buff, "%s_y", param.vector->answer);
	N_write_array_2d_to_rast(ycomp, buff);
	if (buff)
	    G_free(buff);

	if (xcomp)
	    N_free_array_2d(xcomp);
	if (ycomp)
	    N_free_array_2d(ycomp);
	if (field)
	    N_free_gradient_field_2d(field);
    }

    if (data)
	N_free_gwflow_data2d(data);
    if (geom)
	N_free_geom_data(geom);
    if (call)
	G_free(call);

    return (EXIT_SUCCESS);
}
Ejemplo n.º 18
0
/*!
  \brief Generate script-like output
*/
void G__script(void)
{
    FILE *fp = stdout;
    char *type;

    fprintf(fp,
	    "############################################################################\n");
    fprintf(fp, "#\n");
    fprintf(fp, "# MODULE:       %s_wrapper\n", G_program_name());
    fprintf(fp, "# AUTHOR(S):    %s\n", G_whoami());
    fprintf(fp, "# PURPOSE:      \n");
    fprintf(fp, "# COPYRIGHT:    (C) %s by %s, and The GRASS Development Team\n",
	    GRASS_VERSION_DATE, G_whoami());
    fprintf(fp, "#\n");
    fprintf(fp,
	    "#  This program is free software; you can redistribute it and/or modify\n");
    fprintf(fp,
	    "#  it under the terms of the GNU General Public License as published by\n");
    fprintf(fp,
	    "#  the Free Software Foundation; either version 2 of the License, or\n");
    fprintf(fp, "#  (at your option) any later version.\n");
    fprintf(fp, "#\n");
    fprintf(fp,
	    "#  This program is distributed in the hope that it will be useful,\n");
    fprintf(fp,
	    "#  but WITHOUT ANY WARRANTY; without even the implied warranty of\n");
    fprintf(fp,
	    "#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n");
    fprintf(fp, "#  GNU General Public License for more details.\n");
    fprintf(fp, "#\n");
    fprintf(fp,
	    "############################################################################\n\n");

    fprintf(fp, "#%%module\n");
    if (st->module_info.label)
	fprintf(fp, "#%% label: %s\n", st->module_info.label);
    if (st->module_info.description)
	fprintf(fp, "#%% description: %s\n", st->module_info.description);
    if (st->module_info.keywords) {
	fprintf(fp, "#%% keywords: ");
	G__print_keywords(fp, NULL);
	fprintf(fp, "\n");
    }
    fprintf(fp, "#%%end\n");

    if (st->n_flags) {
	struct Flag *flag;

	for (flag = &st->first_flag; flag; flag = flag->next_flag) {
	    fprintf(fp, "#%%flag\n");
	    fprintf(fp, "#%% key: %c\n", flag->key);
	    if (flag->suppress_required)
		fprintf(fp, "#%% suppress_required: yes\n");
	    if (flag->label)
		fprintf(fp, "#%% label: %s\n", flag->label);
	    if (flag->description)
		fprintf(fp, "#%% description: %s\n", flag->description);
	    if (flag->guisection)
		fprintf(fp, "#%% guisection: %s\n", flag->guisection);
	    fprintf(fp, "#%%end\n");
	}
    }

    if (st->n_opts) {
	struct Option *opt;

	for (opt = &st->first_option; opt; opt = opt->next_opt) {
	    switch (opt->type) {
	    case TYPE_INTEGER:
		type = "integer";
		break;
	    case TYPE_DOUBLE:
		type = "double";
		break;
	    case TYPE_STRING:
		type = "string";
		break;
	    default:
		type = "string";
		break;
	    }

	    fprintf(fp, "#%%option\n");
	    fprintf(fp, "#%% key: %s\n", opt->key);
	    fprintf(fp, "#%% type: %s\n", type);
	    fprintf(fp, "#%% required: %s\n", opt->required ? "yes" : "no");
	    fprintf(fp, "#%% multiple: %s\n", opt->multiple ? "yes" : "no");
	    if (opt->options)
		fprintf(fp, "#%% options: %s\n", opt->options);
	    if (opt->key_desc)
		fprintf(fp, "#%% key_desc: %s\n", opt->key_desc);
	    if (opt->label)
		fprintf(fp, "#%% label: %s\n", opt->label);
	    if (opt->description)
		fprintf(fp, "#%% description: %s\n", opt->description);
	    if (opt->descriptions)
		fprintf(fp, "#%% descriptions: %s\n", opt->descriptions);
	    if (opt->answer)
		fprintf(fp, "#%% answer: %s\n", opt->answer);
	    if (opt->gisprompt)
		fprintf(fp, "#%% gisprompt: %s\n", opt->gisprompt);
	    if (opt->guisection)
		fprintf(fp, "#%% guisection: %s\n", opt->guisection);
	    if (opt->guidependency)
		fprintf(fp, "#%% guidependency: %s\n", opt->guidependency);
	    fprintf(fp, "#%%end\n");
	}
    }
}
Ejemplo n.º 19
0
/* ************************************************************************* */
int main(int argc, char *argv[])
{
    struct GModule *module = NULL;
    N_solute_transport_data2d *data = NULL;
    N_geom_data *geom = NULL;
    N_les *les = NULL;
    N_les_callback_2d *call = NULL;
    struct Cell_head region;
    double error, sor;
    char *solver;
    int x, y, stat, i, maxit = 1;
    double loops = 1;
    N_array_2d *xcomp = NULL;
    N_array_2d *ycomp = NULL;
    N_array_2d *hc_x = NULL;
    N_array_2d *hc_y = NULL;
    N_array_2d *phead = NULL;

    double time_step, cfl, length, time_loops, time_sum;

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

    module = G_define_module();
    G_add_keyword(_("raster"));
    G_add_keyword(_("hydrology"));
    G_add_keyword(_("solute transport"));
    module->description =
	_("Numerical calculation program for transient, confined and unconfined "
            "solute transport in two dimensions");

    /* Get parameters from user */
    set_params();

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

    /* Make sure that the current projection is not lat/long */
    if ((G_projection() == PROJECTION_LL))
	G_fatal_error(_("Lat/Long location is not supported by %s. Please reproject map first."),
		      G_program_name());
    
    /*Set the maximum iterations */
    sscanf(param.maxit->answer, "%i", &(maxit));
    /*Set the calculation error break criteria */
    sscanf(param.error->answer, "%lf", &(error));
    sscanf(param.sor->answer, "%lf", &(sor));
    /*number of loops*/
    sscanf(param.loops->answer, "%lf", &(loops));    
    /*Set the solver */
    solver = param.solver->answer;

    if (strcmp(solver, G_MATH_SOLVER_DIRECT_LU) == 0 && !param.full_les->answer)
	G_fatal_error(_("The direct LU solver do not work with sparse matrices"));
    if (strcmp(solver, G_MATH_SOLVER_DIRECT_GAUSS) == 0 && !param.full_les->answer)
	G_fatal_error(_("The direct Gauss solver do not work with sparse matrices"));


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

    /*allocate the geometry structure for geometry and area calculation */
    geom = N_init_geom_data_2d(&region, geom);

    /*Set the function callback to the groundwater flow function */
    call = N_alloc_les_callback_2d();
    N_set_les_callback_2d_func(call, (*N_callback_solute_transport_2d));	/*solute_transport 2d */

    /*Allocate the groundwater flow data structure */
    data = N_alloc_solute_transport_data2d(geom->cols, geom->rows);

    /*Set the stabilizing scheme*/
    if (strncmp("full", param.stab->answer, 4) == 0) {
        data->stab = N_UPWIND_FULL;
    }
    if (strncmp("exp", param.stab->answer, 3) == 0) {
        data->stab = N_UPWIND_EXP;
    }
 
    /*the dispersivity lengths*/
    sscanf(param.al->answer, "%lf", &(data->al));
    sscanf(param.at->answer, "%lf", &(data->at));

    /*Set the calculation time */
    sscanf(param.dt->answer, "%lf", &(data->dt));

    /*read all input maps into the memory and take care of the
     * null values.*/
    N_read_rast_to_array_2d(param.c->answer, data->c);
    N_convert_array_2d_null_to_zero(data->c);
    N_read_rast_to_array_2d(param.c->answer, data->c_start);
    N_convert_array_2d_null_to_zero(data->c_start);
    N_read_rast_to_array_2d(param.status->answer, data->status);
    N_convert_array_2d_null_to_zero(data->status);
    N_read_rast_to_array_2d(param.diff_x->answer, data->diff_x);
    N_convert_array_2d_null_to_zero(data->diff_x);
    N_read_rast_to_array_2d(param.diff_y->answer, data->diff_y);
    N_convert_array_2d_null_to_zero(data->diff_y);
    N_read_rast_to_array_2d(param.q->answer, data->q);
    N_convert_array_2d_null_to_zero(data->q);
    N_read_rast_to_array_2d(param.nf->answer, data->nf);
    N_convert_array_2d_null_to_zero(data->nf);
    N_read_rast_to_array_2d(param.cs->answer, data->cs);
    N_convert_array_2d_null_to_zero(data->cs);
    N_read_rast_to_array_2d(param.top->answer, data->top);
    N_convert_array_2d_null_to_zero(data->top);
    N_read_rast_to_array_2d(param.bottom->answer, data->bottom);
    N_convert_array_2d_null_to_zero(data->bottom);
    N_read_rast_to_array_2d(param.r->answer, data->R);
    N_convert_array_2d_null_to_zero(data->R);

    if(param.cin->answer) {
      N_read_rast_to_array_2d(param.cin->answer, data->cin);
      N_convert_array_2d_null_to_zero(data->cin);
    }

    /*initiate the values for velocity calculation*/
    hc_x = N_alloc_array_2d(geom->cols, geom->rows, 1, DCELL_TYPE);
    hc_x = N_read_rast_to_array_2d(param.hc_x->answer, hc_x);
    N_convert_array_2d_null_to_zero(hc_x);
    hc_y = N_alloc_array_2d(geom->cols, geom->rows, 1, DCELL_TYPE);
    hc_y = N_read_rast_to_array_2d(param.hc_y->answer, hc_y);
    N_convert_array_2d_null_to_zero(hc_y);
    phead = N_alloc_array_2d(geom->cols, geom->rows, 1, DCELL_TYPE);
    phead = N_read_rast_to_array_2d(param.phead->answer, phead);
    N_convert_array_2d_null_to_zero(phead);

    /* Set the inactive values to zero, to assure a no flow boundary */
    for (y = 0; y < geom->rows; y++) {
	for (x = 0; x < geom->cols; x++) {
	    stat = (int)N_get_array_2d_d_value(data->status, x, y);
	    if (stat == N_CELL_INACTIVE) {	/*only inactive cells */
		N_put_array_2d_d_value(data->diff_x, x, y, 0);
		N_put_array_2d_d_value(data->diff_y, x, y, 0);
		N_put_array_2d_d_value(data->cs, x, y, 0);
		N_put_array_2d_d_value(data->q, x, y, 0);
	    }
	}
    }

    /*compute the velocities */
    N_math_array_2d(hc_x, data->nf, hc_x, N_ARRAY_DIV);
    N_math_array_2d(hc_y, data->nf, hc_y, N_ARRAY_DIV);
    N_compute_gradient_field_2d(phead, hc_x, hc_y, geom, data->grad);

    /*Now compute the dispersivity tensor*/
    N_calc_solute_transport_disptensor_2d(data);

    /***************************************/
    /*the Courant-Friedrichs-Lewy criteria */
    /*Compute the correct time step */
    if (geom->dx > geom->dy)
	length = geom->dx;
    else
	length = geom->dy;

    if (fabs(data->grad->max) > fabs(data->grad->min)) {
	cfl = (double)data->dt * fabs(data->grad->max) / length;
	time_step = 1*length / fabs(data->grad->max);
    }
    else {
	cfl = (double)data->dt * fabs(data->grad->min) / length;
	time_step = 1*length / fabs(data->grad->min);
    }

    G_message(_("The Courant-Friedrichs-Lewy criteria is %g it should be within [0:1]"), cfl);
    G_message(_("The largest stable time step is %g"), time_step);

    /*Set the number of inner loops and the time step*/
    if (data->dt > time_step && param.cfl->answer) {
	/*safe the user time step */
	time_sum = data->dt;
	time_loops = data->dt / time_step;
	time_loops = floor(time_loops) + 1;
	data->dt = data->dt / time_loops;
	G_message(_("Number of inner loops is %g"), time_loops);
	G_message(_("Time step for each loop %g"), data->dt);
    }
    else {
        if(data->dt > time_step)
	    G_warning(_("The time step is to large: %gs. The largest time step should be of size %gs."), data->dt, time_step);

	time_loops = loops;
	data->dt = data->dt / loops;
    }

    N_free_array_2d(phead);
    N_free_array_2d(hc_x);
    N_free_array_2d(hc_y);

     /*Compute for each time step*/
     for (i = 0; i < time_loops; i++) {
	 G_message(_("Time step %i with time sum %g"), i + 1, (i + 1)*data->dt);

	/*assemble the linear equation system  and solve it */
	les = create_solve_les(geom, data, call, solver, maxit, error, sor);

	/* copy the result into the c array for output */
	copy_result(data->status, data->c_start, les->x, &region, data->c, 1);
	N_convert_array_2d_null_to_zero(data->c_start);

        if (les)
	    N_free_les(les);

	/*Set the start array*/
	N_copy_array_2d(data->c, data->c_start);
	/*Set the transmission boundary*/
	N_calc_solute_transport_transmission_2d(data);

    }

    /*write the result to the output file */
    N_write_array_2d_to_rast(data->c, param.output->answer);

    /*Compute the the velocity field if required and write the result into three rast maps */
    if (param.vector_x->answer || param.vector_y->answer) {
	xcomp = N_alloc_array_2d(geom->cols, geom->rows, 1, DCELL_TYPE);
	ycomp = N_alloc_array_2d(geom->cols, geom->rows, 1, DCELL_TYPE);

	N_compute_gradient_field_components_2d(data->grad, xcomp, ycomp);

        if (param.vector_x->answer)
            N_write_array_2d_to_rast(xcomp, param.vector_x->answer);
        if (param.vector_y->answer)
            N_write_array_2d_to_rast(ycomp, param.vector_y->answer);

	if (xcomp)
	    N_free_array_2d(xcomp);
	if (ycomp)
	    N_free_array_2d(ycomp);
    }


    if (data)
	N_free_solute_transport_data2d(data);
    if (geom)
	N_free_geom_data(geom);
    if (call)
	G_free(call);

    return (EXIT_SUCCESS);
}
Ejemplo n.º 20
0
int main(int argc, char *argv[])
{
    struct GModule *module;
    struct {
        struct Option *input, *output, *zshift, *height, *elevation, *hcolumn,
            *type, *field, *cats, *where, *interp, *scale, *null;
    } opt;
    struct {
        struct Flag *trace;
    } flag;
    
    struct Map_info In, Out;
    struct line_pnts *Points;
    struct line_cats *Cats;
    struct bound_box map_box;

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

    opt.input = G_define_standard_option(G_OPT_V_INPUT);

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

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

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

    opt.output = G_define_standard_option(G_OPT_V_OUTPUT);

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

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

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

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

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

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

    G_gisinit(argv[0]);

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

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

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

    only_type = Vect_option_to_types(opt.type);

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

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

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

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

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

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

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

    Vect_set_error_handler_io(&In, &Out);

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

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

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

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

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

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

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

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

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

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

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

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

	    Vect_get_area_points(&In, area, Points);

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

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

    }

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

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

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

	    if (!(type & only_type))
		continue;

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

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

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

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

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

    Vect_get_map_box(&Out, &map_box);

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

    Vect_destroy_line_struct(Points);
    Vect_destroy_cats_struct(Cats);

    G_done_msg("T: %f B: %f.", map_box.T, map_box.B);
    
    exit(EXIT_SUCCESS);
}
Ejemplo n.º 21
0
/*!
  \brief Print module usage description in HTML format.
*/
void G__usage_html(void)
{
    struct Option *opt;
    struct Flag *flag;
    const char *type;
    int new_prompt = 0;

    new_prompt = G__uses_new_gisprompt();

    if (!st->pgm_name)		/* v.dave && r.michael */
	st->pgm_name = G_program_name();
    if (!st->pgm_name)
	st->pgm_name = "??";

    fprintf(stdout,
	    "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n");
    fprintf(stdout, "<html>\n<head>\n");
    fprintf(stdout, "<title>GRASS GIS manual: %s</title>\n", st->pgm_name);
    fprintf(stdout,
	    "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\">\n");
    fprintf(stdout,
	    "<link rel=\"stylesheet\" href=\"grassdocs.css\" type=\"text/css\">\n");
    fprintf(stdout, "</head>\n");
    fprintf(stdout, "<body bgcolor=\"white\">\n");
    fprintf(stdout, "<div id=\"container\">\n\n");
    fprintf(stdout,
	    "<a href=\"index.html\"><img src=\"grass_logo.png\" alt=\"GRASS logo\"></a>\n");
    fprintf(stdout, "<hr class=\"header\">\n\n");
    fprintf(stdout, "<h2>%s</h2>\n", _("NAME"));
    fprintf(stdout, "<em><b>%s</b></em> ", st->pgm_name);

    if (st->module_info.label || st->module_info.description)
	fprintf(stdout, " - ");

    if (st->module_info.label)
	fprintf(stdout, "%s<BR>\n", st->module_info.label);

    if (st->module_info.description)
	fprintf(stdout, "%s\n", st->module_info.description);


    fprintf(stdout, "<h2>%s</h2>\n", _("KEYWORDS"));
    if (st->module_info.keywords) {
	G__print_keywords(stdout, print_escaped_for_html_keywords);
	fprintf(stdout, "\n");
    }
    fprintf(stdout, "<h2>%s</h2>\n", _("SYNOPSIS"));
    fprintf(stdout, "<div id=\"name\"><b>%s</b><br></div>\n", st->pgm_name);
    fprintf(stdout, "<b>%s --help</b><br>\n", st->pgm_name);

    fprintf(stdout, "<div id=\"synopsis\"><b>%s</b>", st->pgm_name);

    /* print short version first */
    if (st->n_flags) {
	flag = &st->first_flag;
	fprintf(stdout, " [-<b>");
	while (flag != NULL) {
	    fprintf(stdout, "%c", flag->key);
	    flag = flag->next_flag;
	}
	fprintf(stdout, "</b>] ");
    }
    else
	fprintf(stdout, " ");

    if (st->n_opts) {
	opt = &st->first_option;

	while (opt != NULL) {
	    if (opt->key_desc != NULL)
		type = opt->key_desc;
	    else
		switch (opt->type) {
		case TYPE_INTEGER:
		    type = "integer";
		    break;
		case TYPE_DOUBLE:
		    type = "float";
		    break;
		case TYPE_STRING:
		    type = "string";
		    break;
		default:
		    type = "string";
		    break;
		}
	    if (!opt->required)
		fprintf(stdout, " [");
	    fprintf(stdout, "<b>%s</b>=<em>%s</em>", opt->key, type);
	    if (opt->multiple) {
		fprintf(stdout, "[,<i>%s</i>,...]", type);
	    }
	    if (!opt->required)
		fprintf(stdout, "] ");

	    opt = opt->next_opt;
	    fprintf(stdout, " ");
	}
    }
    if (new_prompt)
	fprintf(stdout, " [--<b>overwrite</b>] ");

    fprintf(stdout, " [--<b>help</b>] ");
    fprintf(stdout, " [--<b>verbose</b>] ");
    fprintf(stdout, " [--<b>quiet</b>] ");
    fprintf(stdout, " [--<b>ui</b>] ");
    
    fprintf(stdout, "\n</div>\n");

    /* now long version */
    fprintf(stdout, "\n");
    fprintf(stdout, "<div id=\"flags\">\n");
    fprintf(stdout, "<h3>%s:</h3>\n", _("Flags"));
    fprintf(stdout, "<dl>\n");
    if (st->n_flags) {
	flag = &st->first_flag;
	while (st->n_flags && flag != NULL) {
	    fprintf(stdout, "<dt><b>-%c</b></dt>\n", flag->key);

	    if (flag->label) {
		fprintf(stdout, "<dd>");
		fprintf(stdout, "%s", flag->label);
		fprintf(stdout, "</dd>\n");
	    }

	    if (flag->description) {
		fprintf(stdout, "<dd>");
		fprintf(stdout, "%s", flag->description);
		fprintf(stdout, "</dd>\n");
	    }

	    flag = flag->next_flag;
	    fprintf(stdout, "\n");
	}
    }
    if (new_prompt) {
	fprintf(stdout, "<dt><b>--overwrite</b></dt>\n");
	fprintf(stdout, "<dd>%s</dd>\n",
		_("Allow output files to overwrite existing files"));
    }
    /* these flags are always available */
    fprintf(stdout, "<dt><b>--help</b></dt>\n");
    fprintf(stdout, "<dd>%s</dd>\n", _("Print usage summary"));

    fprintf(stdout, "<dt><b>--verbose</b></dt>\n");
    fprintf(stdout, "<dd>%s</dd>\n", _("Verbose module output"));

    fprintf(stdout, "<dt><b>--quiet</b></dt>\n");
    fprintf(stdout, "<dd>%s</dd>\n", _("Quiet module output"));

    fprintf(stdout, "<dt><b>--ui</b></dt>\n");
    fprintf(stdout, "<dd>%s</dd>\n", _("Force launching GUI dialog"));

    fprintf(stdout, "</dl>\n");
    fprintf(stdout, "</div>\n");

    fprintf(stdout, "\n");
    fprintf(stdout, "<div id=\"parameters\">\n");
    if (st->n_opts) {
	opt = &st->first_option;
	fprintf(stdout, "<h3>%s:</h3>\n", _("Parameters"));
	fprintf(stdout, "<dl>\n");

	while (opt != NULL) {
	    /* TODO: make this a enumeration type? */
	    if (opt->key_desc != NULL)
		type = opt->key_desc;
	    else
		switch (opt->type) {
		case TYPE_INTEGER:
		    type = "integer";
		    break;
		case TYPE_DOUBLE:
		    type = "float";
		    break;
		case TYPE_STRING:
		    type = "string";
		    break;
		default:
		    type = "string";
		    break;
		}
	    fprintf(stdout, "<dt><b>%s</b>=<em>%s", opt->key, type);
	    if (opt->multiple) {
		fprintf(stdout, "[,<i>%s</i>,...]", type);
	    }
	    fprintf(stdout, "</em>");
	    if (opt->required) {
		fprintf(stdout, "&nbsp;<b>[required]</b>");
	    }
	    fprintf(stdout, "</dt>\n");

	    if (opt->label) {
		fprintf(stdout, "<dd>");
		print_escaped_for_html(stdout, opt->label);
		fprintf(stdout, "</dd>\n");
	    }
	    if (opt->description) {
		fprintf(stdout, "<dd>");
		print_escaped_for_html(stdout, opt->description);
		fprintf(stdout, "</dd>\n");
	    }

	    if (opt->options) {
		fprintf(stdout, "<dd>%s: <em>", _("Options"));
		print_escaped_for_html_options(stdout, opt->options);
		fprintf(stdout, "</em></dd>\n");
	    }

	    if (opt->def) {
		fprintf(stdout, "<dd>%s: <em>", _("Default"));
		print_escaped_for_html(stdout, opt->def);
		fprintf(stdout, "</em></dd>\n");
	    }

	    if (opt->descs) {
		int i = 0;
                
		while (opt->opts[i]) {
		    if (opt->descs[i]) {
			fprintf(stdout, "<dd><b>");
                        if (opt->gisprompt) {
                            char *thumbnails = NULL;
                            
                            if (strcmp(opt->gisprompt,
                                       "old,colortable,colortable") == 0)
                                thumbnails = "colortables";
                            else if (strcmp(opt->gisprompt,
                                            "old,barscale,barscale") == 0)
                                thumbnails = "barscales";
                            
                            if (thumbnails)
                                fprintf(stdout, "<img width=\"80\" height=\"12\" "
                                        "src=\"%s/%s.png\" alt=\"%s\">",
                                        thumbnails, opt->opts[i], opt->opts[i]);
                        }
			print_escaped_for_html(stdout, opt->opts[i]);
			fprintf(stdout, "</b>: ");
			print_escaped_for_html(stdout, opt->descs[i]);
			fprintf(stdout, "</dd>\n");
		    }
		    i++;
		}
	    }

	    opt = opt->next_opt;
	    fprintf(stdout, "\n");
	}
	fprintf(stdout, "</dl>\n");
    }
    fprintf(stdout, "</div>\n");

    fprintf(stdout, "</body>\n</html>\n");
}
Ejemplo n.º 22
0
int main(int argc, char **argv)
{
    struct GModule *module;
    struct opts opt;
    struct Map_info In, Out;
    BOUND_BOX box;
    int field, type;
    int ret;
    
    G_gisinit(argv[0]);

    module = G_define_module();
    module->keywords = _("vector, transformation, 3D");
    module->description =
	_("Performs transformation of 2D vector features to 3D.");

    parse_args(&opt);

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

    field = atoi(opt.field->answer);
    type = Vect_option_to_types(opt.type);

    if (!opt.reverse->answer) {
	if ((!opt.height->answer && !opt.column->answer) ||
	    (opt.height->answer && opt.column->answer)) {
	    G_fatal_error(_("Either '%s' or '%s' parameter have to be used"),
			  opt.height->key, opt.column->key);
	}
    }
    else {
	if (opt.height->answer) {
	    G_warning(_("Parameters '%s' ignored"), opt.height->key);
	}
    }

    if (opt.reverse->answer && opt.table->answer) {
	G_fatal_error(_("Attribute table required"));
    }

    Vect_check_input_output_name(opt.input->answer, opt.output->answer,
				 GV_FATAL_EXIT);

    /* open input vector, topology not needed */
    Vect_set_open_level(1);
    if (Vect_open_old(&In, opt.input->answer, "") < 1)
	G_fatal_error(_("Unable to open vector map <%s>"), opt.input->answer);

    if (opt.reverse->answer && !Vect_is_3d(&In)) {
	Vect_close(&In);
	G_fatal_error(_("Vector map <%s> is 2D"), opt.input->answer);
    }

    if (!opt.reverse->answer && Vect_is_3d(&In)) {
	Vect_close(&In);
	G_fatal_error(_("Vector map <%s> is 3D"), opt.input->answer);
    }

    /* create output vector */
    Vect_set_open_level(2);
    if (Vect_open_new(&Out, opt.output->answer,
		      opt.reverse->answer ? WITHOUT_Z : WITH_Z) == -1)
	G_fatal_error(_("Unable to create vector map <%s>"),
		      opt.output->answer);

    /* copy history & header */
    Vect_hist_copy(&In, &Out);
    Vect_hist_command(&Out);
    Vect_copy_head_data(&In, &Out);

    if (opt.reverse->answer && !opt.table->answer) {
	G_message(_("Copying attributes..."));
	if (Vect_copy_tables(&In, &Out, 0) == -1) {
	    G_warning(_("Unable to copy attributes"));
	}
    }

    G_message(_("Transforming features..."));
    ret = 0;
    if (opt.reverse->answer) {
	/* 3d -> 2d */
	ret = trans3d(&In, &Out, type, field, opt.column->answer);
    }
    else {
	/* 2d -> 3d */
	double height = 0.;

	if (opt.height->answer) {
	    height = atof(opt.height->answer);
	}
	ret = trans2d(&In, &Out, type, height, field, opt.column->answer);
    }

    if (ret < 0) {
	Vect_close(&In);
	Vect_close(&Out);
	Vect_delete(opt.output->answer);
	G_fatal_error(_("%s failed"), G_program_name());
    }

    if (!opt.reverse->answer && !opt.table->answer) {
	G_message(_("Copying attributes..."));
	if (Vect_copy_tables(&In, &Out, 0) == -1) {
	    G_warning(_("Unable to copy attributes"));
	}
    }

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

    if (!opt.reverse->answer) {
	Vect_get_map_box(&Out, &box);
	G_message(_("Vertical extent of vector map <%s>: B: %f T: %f"),
		  opt.output->answer, box.B, box.T);
    }

    Vect_close(&Out);

    exit(EXIT_SUCCESS);
}
Ejemplo n.º 23
0
int main(int argc, char *argv[])
{
    int fd, maskfd;
    CELL *cell, *mask;
    struct Cell_head window;
    int row, col;
    double north, east;
    double dx, dy;
    double maxdist, dist;
    double sum1, sum2;
    int i, n, max;
    struct GModule *module;
    struct History history;
    struct
    {
	struct Option *input, *npoints, *output;
    } parm;

    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("raster"));
    G_add_keyword(_("surface"));
    G_add_keyword(_("interpolation"));
    G_add_keyword(_("IDW"));
    module->description = _("Surface generation program.");

    parm.input = G_define_standard_option(G_OPT_R_INPUT);

    parm.output = G_define_standard_option(G_OPT_R_OUTPUT);

    parm.npoints = G_define_option();
    parm.npoints->key = "npoints";
    parm.npoints->key_desc = "count";
    parm.npoints->type = TYPE_INTEGER;
    parm.npoints->required = NO;
    parm.npoints->description = _("Number of interpolation points");
    parm.npoints->answer = "12";

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

    /* Make sure that the current projection is not lat/long */
    if ((G_projection() == PROJECTION_LL))
	G_fatal_error(_("Lat/long databases not supported by r.surf.idw2. Use r.surf.idw instead!"));

    if (sscanf(parm.npoints->answer, "%d", &search_points) != 1 ||
	search_points < 1)
	G_fatal_error(_("%s=%s - illegal number of interpolation points"),
		      parm.npoints->key, parm.npoints->answer);

    list = (struct Point *)G_calloc(search_points, sizeof(struct Point));

    /* read the elevation points from the input raster map */
    read_cell(parm.input->answer);

    if (npoints == 0)
	G_fatal_error(_("%s: no data points found"), G_program_name());
    nsearch = npoints < search_points ? npoints : search_points;

    /* get the window, allocate buffers, etc. */
    G_get_set_window(&window);

    cell = Rast_allocate_c_buf();

    if ((maskfd = Rast_maskfd()) >= 0)
	mask = Rast_allocate_c_buf();
    else
	mask = NULL;

    fd = Rast_open_c_new(parm.output->answer);

    G_message(_("Interpolating raster map <%s>... %d rows... "),
	      parm.output->answer, window.rows);

    north = window.north - window.ns_res / 2.0;
    for (row = 0; row < window.rows; row++) {
	G_percent(row, window.rows, 2);

	if (mask)
	    Rast_get_c_row(maskfd, mask, row);

	north += window.ns_res;
	east = window.west - window.ew_res / 2.0;
	for (col = 0; col < window.cols; col++) {
	    east += window.ew_res;
	    /* don't interpolate outside of the mask */
	    if (mask && mask[col] == 0) {
		cell[col] = 0;
		continue;
	    }
	    /* fill list with first nsearch points */
	    for (i = 0; i < nsearch; i++) {
		dy = points[i].north - north;
		dx = points[i].east - east;
		list[i].dist = dy * dy + dx * dx;
		list[i].z = points[i].z;
	    }
	    /* find the maximum distance */
	    maxdist = list[max = 0].dist;
	    for (n = 1; n < nsearch; n++) {
		if (maxdist < list[n].dist)
		    maxdist = list[max = n].dist;
	    }
	    /* go thru rest of the points now */
	    for (; i < npoints; i++) {
		dy = points[i].north - north;
		dx = points[i].east - east;
		dist = dy * dy + dx * dx;

		if (dist < maxdist) {
		    /* replace the largest dist */
		    list[max].z = points[i].z;
		    list[max].dist = dist;
		    maxdist = list[max = 0].dist;
		    for (n = 1; n < nsearch; n++) {
			if (maxdist < list[n].dist)
			    maxdist = list[max = n].dist;
		    }
		}
	    }

	    /* interpolate */
	    sum1 = 0.0;
	    sum2 = 0.0;
	    for (n = 0; n < nsearch; n++) {
		if ((dist = list[n].dist)) {
		    sum1 += list[n].z / dist;
		    sum2 += 1.0 / dist;
		}
		else {
		    sum1 = list[n].z;
		    sum2 = 1.0;
		    break;
		}
	    }
	    cell[col] = (CELL) (sum1 / sum2 + 0.5);
	}

	Rast_put_row(fd, cell, CELL_TYPE);
    }

    G_free(points);
    G_free(cell);
    Rast_close(fd);

    /* writing history file */
    Rast_short_history(parm.output->answer, "raster", &history);
    Rast_command_history(&history);
    Rast_write_history(parm.output->answer, &history);
    G_done_msg(" ");

    exit(EXIT_SUCCESS);
}