Ejemplo n.º 1
0
/** add points to the visibility graph
*/
void add_points(char **coor, struct Point **points, int *index_point)
{
    int i;
    double x, y;


    /* and defining the points */
    for (i = 0; coor[i] != NULL; i += 2) {
	G_scan_easting(coor[i], &x, G_projection());
	G_scan_northing(coor[i + 1], &y, G_projection());

	(*points)[*index_point].x = x;
	(*points)[*index_point].y = y;
	(*points)[*index_point].cat = -1;

	(*points)[*index_point].line1 = NULL;
	(*points)[*index_point].line2 = NULL;

	(*points)[*index_point].left_brother = NULL;
	(*points)[*index_point].right_brother = NULL;
	(*points)[*index_point].father = NULL;
	(*points)[*index_point].rightmost_son = NULL;

	(*index_point)++;

    }
}
Ejemplo n.º 2
0
int lookup_and_function_ptrs(SHORT nrows, SHORT ncols)
{
    double a, e2;		/* used to control geodetic distance calculations */

    if ((ll = (G_projection() == PROJECTION_LL))) {
	/* equivalent to G_begin_distance_calculations () */
	G_get_ellipsoid_parameters(&a, &e2);
	G_begin_geodesic_distance_l(nrows, a, e2);

	LL_lookup_tables(nrows, ncols);
	init_row_search = first_west_LL;
	comp_row_search = completed_row_LL;
	locate_neighbors = find_neighbors_LL;
	check_offset = offset_distance_LL;
	exhaust_row = exhaust_search_LL;
    }
    else {
	lookup_tables(nrows, ncols);
	init_row_search = first_west;
	comp_row_search = completed_row;
	locate_neighbors = find_neighbors;
	check_offset = offset_distance;
	exhaust_row = exhaust_search;
    }

    return 0;
}
Ejemplo n.º 3
0
/*!
  \brief Get units id for the current location
  
  \return units id
*/
int G_database_unit()
{
    int units;
    const char *name;
    
    units = G_projection_units(G_projection());
    
    if (units == U_UNDEFINED) {
	name = lookup_units("unit");
	if (!name)
	    return U_UNKNOWN;
	
	if (strcasecmp(name, "meter") == 0 || strcasecmp(name, "metre") == 0 
            || strcasecmp(name, "meters") == 0 || strcasecmp(name, "metres") == 0)
	    units = U_METERS;
	else if (strcasecmp(name, "kilometer") == 0 || strcasecmp(name, "kilometre") == 0
                 || strcasecmp(name, "kilometers") == 0 || strcasecmp(name, "kilometres") == 0)
	    units = U_KILOMETERS;
	else if (strcasecmp(name, "acre") == 0 || strcasecmp(name, "acres") == 0)
	    units = U_ACRES;
	else if (strcasecmp(name, "hectare") == 0 || strcasecmp(name, "hectares") == 0)
	    units = U_HECTARES;
	else if (strcasecmp(name, "mile") == 0 || strcasecmp(name, "miles") == 0)
	    units = U_MILES;
	else if (strcasecmp(name, "foot") == 0 || strcasecmp(name, "feet") == 0)
	    units = U_FEET;
	else if (strcasecmp(name, "foot_us") == 0 || strcasecmp(name, "foot_uss") == 0)
	    units = U_USFEET;
	else if (strcasecmp(name, "degree") == 0 || strcasecmp(name, "degrees") == 0)
	    units = U_DEGREES;
	else
	    units = U_UNKNOWN;
    }
    return units;
}
Ejemplo n.º 4
0
static int profile(int coords, const char *map, const char *nulls, char **line)
{
    double e1, n1, e2, n2;
    char buf[1024], profile[1024];
    const char *argv[7];
    int argc = 0;
    int n;
    int projection;

    projection = G_projection();

    argv[argc++] = "r.profile";

    if (coords)
	argv[argc++] = "-g";

    sprintf(buf, "input=%s", map);
    argv[argc++] = G_store(buf);

    argv[argc++] = "output=-";

    sprintf(buf, "null_value=%s", nulls);
    argv[argc++] = G_store(buf);

    strcpy(profile, "coordinates=");
    for (n = 0; line[n]; n += 4) {
	int err = parse_line("line", &line[n], &e1, &n1, &e2, &n2, projection);

	if (err) {
	    G_usage();
	    exit(EXIT_FAILURE);
	}

	if (n > 0)
	    strcat(profile, ",");
	G_format_easting(e1, buf, projection);
	strcat(profile, buf);

	G_format_northing(n1, buf, projection);
	strcat(profile, ",");
	strcat(profile, buf);

	G_format_easting(e2, buf, projection);
	strcat(profile, ",");
	strcat(profile, buf);

	G_format_northing(n2, buf, projection);
	strcat(profile, ",");
	strcat(profile, buf);
    }

    argv[argc++] = profile;

    argv[argc++] = NULL;

    G_verbose_message(_("End coordinate: %.15g, %.15g"), e2, n2);

    return G_vspawn_ex(argv[0], argv);
}
Ejemplo n.º 5
0
void print_shell(const struct Map_info *Map)
{
    if (Vect_maptype(Map) & (GV_FORMAT_OGR | GV_FORMAT_OGR_DIRECT)) {
	fprintf(stdout, "ogr_layer=%s\n",
		Vect_get_ogr_layer_name(Map));
	fprintf(stdout, "ogr_dsn=%s\n",
		Vect_get_ogr_dsn_name(Map));
    }
    else {
	fprintf(stdout, "name=%s\n",
		Vect_get_name(Map));
	fprintf(stdout, "mapset=%s\n",
		Vect_get_mapset(Map));
    }
    
    fprintf(stdout, "location=%s\n",
	    G_location());
    fprintf(stdout, "database=%s\n",
	    G_gisdbase());
    fprintf(stdout, "title=%s\n",
	    Vect_get_map_name(Map));
    fprintf(stdout, "scale=1:%d\n",
	    Vect_get_scale(Map));
    
    if (Vect_maptype(Map) & (GV_FORMAT_OGR | GV_FORMAT_OGR_DIRECT)) {	
	fprintf(stdout, "format=%s,%s\n",
		Vect_maptype_info(Map), Vect_get_ogr_format_info(Map));
    }
    else {
	fprintf(stdout, "format=%s\n",
		Vect_maptype_info(Map));
    }

    fprintf(stdout, "creator=%s\n",
	    Vect_get_person(Map));
    fprintf(stdout, "organization=%s\n",
	    Vect_get_organization(Map));
    fprintf(stdout, "source_date=%s\n",
	    Vect_get_map_date(Map));
    fprintf(stdout, "level=%d\n", 
	    Vect_level(Map));
    
    if (Vect_level(Map) > 0) {
	fprintf(stdout, "num_dblinks=%d\n",
		Vect_get_num_dblinks(Map));
    }

    fprintf(stdout, "projection=%s\n",
	    Vect_get_proj_name(Map));
    if (G_projection() == PROJECTION_UTM) {
	fprintf(stdout, "zone=%d\n",
		Vect_get_zone(Map));
    }
    fprintf(stdout, "digitization_threshold=%f\n",
	    Vect_get_thresh(Map));
    fprintf(stdout, "comment=%s\n",
	    Vect_get_comment(Map));
}
Ejemplo n.º 6
0
void G_shortest_way(double *east1, double *east2)
{
    if (G_projection() == PROJECTION_LL) {
	if (*east1 > *east2)
	    while ((*east1 - *east2) > 180)
		*east2 += 360;
	else if (*east2 > *east1)
	    while ((*east2 - *east1) > 180)
		*east1 += 360;
    }
}
Ejemplo n.º 7
0
/*!
  \brief Query cartographic projection for the current location
  
  Returns a pointer to a string which is a printable name for
  projection code <i>proj</i> (as returned by G_projection). Returns
  NULL if <i>proj</i> is not a valid projection.
  
  \return projection name
*/
const char *G_database_projection_name(void)
{
    int n;
    const char *name;

    switch (n = G_projection()) {
    case PROJECTION_XY:
    case PROJECTION_UTM:
    case PROJECTION_LL:
	return G_projection_name(n);
    }

    name = lookup_proj("name");
    if (!name)
	return _("Unknown projection");

    return name;
}
Ejemplo n.º 8
0
Archivo: proj3.c Proyecto: cran/GRASS
char *G_database_projection_name()
{
    int n;
    static char name[256];
    char *G__projection_name();

    switch(n=G_projection())
    {
    case PROJECTION_XY:
    case PROJECTION_UTM:
    case PROJECTION_LL:
    case PROJECTION_SP:
	return G__projection_name(n);
    }
    if(!lookup (PROJECTION_FILE, "name", name, sizeof(name)))
	strcpy (name, "Unknown projection");
    return name;
}
Ejemplo n.º 9
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.º 10
0
Archivo: proj3.c Proyecto: cran/GRASS
char *G_database_unit_name(int plural)
{
    int n;
    static char name[256];
    char *G__unit_name();

    switch(n=G_projection())
    {
    case PROJECTION_XY:
    case PROJECTION_UTM:
    case PROJECTION_LL:
    case PROJECTION_SP:
	return G__unit_name(G__projection_units(n), plural);
    }

    if(!lookup (UNIT_FILE, plural?"units":"unit", name, sizeof(name)))
	strcpy (name, plural ? "units" : "unit");
    return name;
}
Ejemplo n.º 11
0
/*!
   \brief Set constraint region

   Vect_read_next_line() will read only features inside of given
   region or features with overlapping bounding box. 

   \note Constraint is ignored for random access - Vect_read_line().

   \param Map pointer to Map_info struct
   \param n,s,e,w,t,b bbox definition (north, south, east, west, top, and bottom coordinates)
   
   \return 0 on success
   \return -1 on error (invalid region)
 */
int Vect_set_constraint_region(struct Map_info *Map,
			       double n, double s, double e, double w,
			       double t, double b)
{
    if (n <= s)
	return -1;
    if (e <= w)
	return -1;

    Map->constraint.region_flag = TRUE;
    Map->constraint.box.N = n;
    Map->constraint.box.S = s;
    Map->constraint.box.E = e;
    Map->constraint.box.W = w;
    Map->constraint.box.T = t;
    Map->constraint.box.B = b;
    Map->head.proj = G_projection();

    return 0;
}
Ejemplo n.º 12
0
int main(int argc, char **argv)
{
    interface(argc, argv);

    /* Make sure that the current projection is not lat/long */
    if ((G_projection() == PROJECTION_LL))
	G_fatal_error(_("Lat/Long locations are not supported by this module"));

    open_files();

    process();

    close_down();

    if (mparam == FEATURE) {
	write_cols();
	write_cats();
    }

    return 0;
}
Ejemplo n.º 13
0
/*!
  \brief Get units (localized) name for the current location
  
  Returns a string describing the database grid units. It returns a
  plural form (eg. 'feet') if <i>plural</i> is non-zero. Otherwise it
  returns a singular form (eg. 'foot').
  
  \param plural plural form if non-zero
  
  \return localized units name
*/
const char *G_database_unit_name(int plural)
{
    int units;
    const char *name;
    
    units = G_projection_units(G_projection());
    
    if (units == U_UNDEFINED) {
	name = lookup_units(plural ? "units" : "unit");
	if (!name)
	    return plural ? _("units") : _("unit");
	
	if (strcasecmp(name, "meter") == 0 || strcasecmp(name, "metre") == 0 
            || strcasecmp(name, "meters") == 0 || strcasecmp(name, "metres") == 0)
	    units = U_METERS;
	else if (strcasecmp(name, "kilometer") == 0 || strcasecmp(name, "kilometre") == 0
                 || strcasecmp(name, "kilometers") == 0 || strcasecmp(name, "kilometres") == 0)
	    units = U_KILOMETERS;
	else if (strcasecmp(name, "acre") == 0 || strcasecmp(name, "acres") == 0)
	    units = U_ACRES;
	else if (strcasecmp(name, "hectare") == 0 || strcasecmp(name, "hectares") == 0)
	    units = U_HECTARES;
	else if (strcasecmp(name, "mile") == 0 || strcasecmp(name, "miles") == 0)
	    units = U_MILES;
	else if (strcasecmp(name, "foot") == 0 || strcasecmp(name, "feet") == 0)
	    units = U_FEET;
	else if (strcasecmp(name, "foot_us") == 0 || strcasecmp(name, "foot_uss") == 0)
	    units = U_USFEET;
	else if (strcasecmp(name, "degree") == 0 || strcasecmp(name, "degrees") == 0)
	    units = U_DEGREES;
	else
	    units = U_UNKNOWN;
    }
    
    return G_get_units_name(units, plural, FALSE);
}
Ejemplo n.º 14
0
int main(int argc, char *argv[])
{
    int i, type, stat;
    int day, yr, Out_proj;
    int out_zone = 0;
    int overwrite;		/* overwrite output map */
    const char *mapset;
    const char *omap_name, *map_name, *iset_name, *iloc_name;
    struct pj_info info_in;
    struct pj_info info_out;
    const char *gbase;
    char date[40], mon[4];
    struct GModule *module;
    struct Option *omapopt, *mapopt, *isetopt, *ilocopt, *ibaseopt, *smax;
    struct Key_Value *in_proj_keys, *in_unit_keys;
    struct Key_Value *out_proj_keys, *out_unit_keys;
    struct line_pnts *Points, *Points2;
    struct line_cats *Cats;
    struct Map_info Map;
    struct Map_info Out_Map;
    struct bound_box src_box, tgt_box;
    int nowrap = 0, recommend_nowrap = 0;
    double lmax;
    struct
    {
	struct Flag *list;	/* list files in source location */
	struct Flag *transformz;	/* treat z as ellipsoidal height */
	struct Flag *wrap;		/* latlon output: wrap to 0,360 */
	struct Flag *no_topol;		/* do not build topology */
    } flag;

    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("vector"));
    G_add_keyword(_("projection"));
    G_add_keyword(_("transformation"));
    G_add_keyword(_("import"));
    module->description = _("Re-projects a vector map from one location to the current location.");

    /* set up the options and flags for the command line parser */

    ilocopt = G_define_standard_option(G_OPT_M_LOCATION);
    ilocopt->required = YES;
    ilocopt->label = _("Location containing input vector map");
    ilocopt->guisection = _("Source");
    
    isetopt = G_define_standard_option(G_OPT_M_MAPSET);
    isetopt->label = _("Mapset containing input vector map");
    isetopt->description = _("Default: name of current mapset");
    isetopt->guisection = _("Source");

    mapopt = G_define_standard_option(G_OPT_V_INPUT);
    mapopt->required = NO;
    mapopt->label = _("Name of input vector map to re-project");
    mapopt->description = NULL;
    mapopt->guisection = _("Source");
    
    ibaseopt = G_define_standard_option(G_OPT_M_DBASE);
    ibaseopt->label = _("Path to GRASS database of input location");
    
    smax = G_define_option();
    smax->key = "smax";
    smax->type = TYPE_DOUBLE;
    smax->required = NO;
    smax->answer = "10000";
    smax->label = _("Maximum segment length in meters in output vector map");
    smax->description = _("Increases accuracy of reprojected shapes, disable with smax=0");
    smax->guisection = _("Target");

    omapopt = G_define_standard_option(G_OPT_V_OUTPUT);
    omapopt->required = NO;
    omapopt->description = _("Name for output vector map (default: input)");
    omapopt->guisection = _("Target");

    flag.list = G_define_flag();
    flag.list->key = 'l';
    flag.list->description = _("List vector maps in input mapset and exit");

    flag.transformz = G_define_flag();
    flag.transformz->key = 'z';
    flag.transformz->description = _("3D vector maps only");
    flag.transformz->label =
	_("Assume z coordinate is ellipsoidal height and "
	  "transform if possible");
    flag.transformz->guisection = _("Target");

    flag.wrap = G_define_flag();
    flag.wrap->key = 'w';
    flag.wrap->description = _("Latlon output only, default is -180,180");
    flag.wrap->label =
	_("Disable wrapping to -180,180 for latlon output");
    flag.transformz->guisection = _("Target");

    flag.no_topol = G_define_flag();
    flag.no_topol->key = 'b';
    flag.no_topol->label = _("Do not build vector topology");
    flag.no_topol->description = _("Recommended for massive point projection");

    /* The parser checks if the map already exists in current mapset,
       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);

    /* start checking options and flags */
    /* set input vector map name and mapset */
    map_name = mapopt->answer;
    if (omapopt->answer)
	omap_name = omapopt->answer;
    else
	omap_name = map_name;
    if (omap_name && !flag.list->answer && !overwrite &&
	G_find_vector2(omap_name, G_mapset()))
	G_fatal_error(_("option <%s>: <%s> exists. To overwrite, use the --overwrite flag"), omapopt->key,
		      omap_name);
    if (isetopt->answer)
	iset_name = isetopt->answer;
    else
	iset_name = G_store(G_mapset());

    iloc_name = ilocopt->answer;

    if (ibaseopt->answer)
	gbase = ibaseopt->answer;
    else
	gbase = G_store(G_gisdbase());

    if (!ibaseopt->answer && strcmp(iloc_name, G_location()) == 0)
	G_fatal_error(_("Input and output locations can not be the same"));

    lmax = atof(smax->answer);
    if (lmax < 0)
	lmax = 0;

    Out_proj = G_projection();
    if (Out_proj == PROJECTION_LL && flag.wrap->answer)
	nowrap = 1;
    
    G_begin_distance_calculations();

    /* Change the location here and then come back */

    select_target_env();
    G_setenv_nogisrc("GISDBASE", gbase);
    G_setenv_nogisrc("LOCATION_NAME", iloc_name);
    stat = G_mapset_permissions(iset_name);
    
    if (stat >= 0) {		/* yes, we can access the mapset */
	/* if requested, list the vector maps in source location - MN 5/2001 */
	if (flag.list->answer) {
	    int i;
	    char **list;
	    G_verbose_message(_("Checking location <%s> mapset <%s>"),
			      iloc_name, iset_name);
	    list = G_list(G_ELEMENT_VECTOR, G_getenv_nofatal("GISDBASE"),
			  G_getenv_nofatal("LOCATION_NAME"), iset_name);
	    if (list[0]) {
		for (i = 0; list[i]; i++) {
		    fprintf(stdout, "%s\n", list[i]);
		}
		fflush(stdout);
	    }
	    else {
		G_important_message(_("No vector maps found"));
	    }
	    exit(EXIT_SUCCESS);	/* leave v.proj after listing */
	}

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

	G_setenv_nogisrc("MAPSET", iset_name);
	/* Make sure map is available */
	mapset = G_find_vector2(map_name, iset_name);
	if (mapset == NULL)
	    G_fatal_error(_("Vector map <%s> in location <%s> mapset <%s> not found"),
			  map_name, iloc_name, iset_name);

	 /*** Get projection info for input mapset ***/
	in_proj_keys = G_get_projinfo();
	if (in_proj_keys == NULL)
	    exit(EXIT_FAILURE);

	/* apparently the +over switch must be set in the input projection,
	 * not the output latlon projection */
	if (Out_proj == PROJECTION_LL && nowrap == 1)
	    G_set_key_value("+over", "defined", in_proj_keys);

	in_unit_keys = G_get_projunits();
	if (in_unit_keys == NULL)
	    exit(EXIT_FAILURE);

	if (pj_get_kv(&info_in, in_proj_keys, in_unit_keys) < 0)
	    exit(EXIT_FAILURE);

	Vect_set_open_level(1);
	G_debug(1, "Open old: location: %s mapset : %s", G_location_path(),
		G_mapset());
	if (Vect_open_old(&Map, map_name, mapset) < 0)
	    G_fatal_error(_("Unable to open vector map <%s>"), map_name);
    }
    else if (stat < 0)
    {				/* allow 0 (i.e. denied permission) */
	/* need to be able to read from others */
	if (stat == 0)
	    G_fatal_error(_("Mapset <%s> in input location <%s> - permission denied"),
			  iset_name, iloc_name);
	else
	    G_fatal_error(_("Mapset <%s> in input location <%s> not found"),
			  iset_name, iloc_name);
    }

    select_current_env();

    /****** get the output projection parameters ******/
    out_proj_keys = G_get_projinfo();
    if (out_proj_keys == NULL)
	exit(EXIT_FAILURE);

    out_unit_keys = G_get_projunits();
    if (out_unit_keys == NULL)
	exit(EXIT_FAILURE);

    if (pj_get_kv(&info_out, out_proj_keys, out_unit_keys) < 0)
	exit(EXIT_FAILURE);

    G_free_key_value(in_proj_keys);
    G_free_key_value(in_unit_keys);
    G_free_key_value(out_proj_keys);
    G_free_key_value(out_unit_keys);

    if (G_verbose() == G_verbose_max()) {
	pj_print_proj_params(&info_in, &info_out);
    }

    /* Initialize the Point / Cat structure */
    Points = Vect_new_line_struct();
    Points2 = Vect_new_line_struct();
    Cats = Vect_new_cats_struct();

    /* test if latlon wrapping to -180,180 should be disabled */
    if (Out_proj == PROJECTION_LL && nowrap == 0) {
	int first = 1, counter = 0;
	double x, y;
	
	/* Cycle through all lines */
	Vect_rewind(&Map);
	while (1) {
	    type = Vect_read_next_line(&Map, Points, Cats);	/* read line */
	    if (type == 0)
		continue;		/* Dead */

	    if (type == -1)
		G_fatal_error(_("Reading input vector map"));
	    if (type == -2)
		break;
		
	    if (first && Points->n_points > 0) {
		first = 0;
		src_box.E = src_box.W = Points->x[0];
		src_box.N = src_box.S = Points->y[0];
		src_box.T = src_box.B = Points->z[0];
	    }
	    for (i = 0; i < Points->n_points; i++) {
		if (src_box.E < Points->x[i])
		    src_box.E = Points->x[i];
		if (src_box.W > Points->x[i])
		    src_box.W = Points->x[i];
		if (src_box.N < Points->y[i])
		    src_box.N = Points->y[i];
		if (src_box.S > Points->y[i])
		    src_box.S = Points->y[i];
	    }
	    counter++;
	}
	if (counter == 0) {
	    G_warning(_("Input vector map <%s> is empty"), omap_name);
	    exit(EXIT_SUCCESS);
	}
	/* NW corner */
	x = src_box.W;
	y = src_box.N;
	if (pj_do_transform(1, &x, &y, NULL,
			    &info_in, &info_out) < 0) {
	    G_fatal_error(_("Error in pj_do_transform"));
	}
	tgt_box.E = x;
	tgt_box.W = x;
	tgt_box.N = y;
	tgt_box.S = y;
	/* SW corner */
	x = src_box.W;
	y = src_box.S;
	if (pj_do_transform(1, &x, &y, NULL,
			    &info_in, &info_out) < 0) {
	    G_fatal_error(_("Error in pj_do_transform"));
	}
	if (tgt_box.W > x)
	    tgt_box.W = x;
	if (tgt_box.E < x)
	    tgt_box.E = x;
	if (tgt_box.N < y)
	    tgt_box.N = y;
	if (tgt_box.S > y)
	    tgt_box.S = y;
	/* NE corner */
	x = src_box.E;
	y = src_box.N;
	if (pj_do_transform(1, &x, &y, NULL,
			    &info_in, &info_out) < 0) {
	    G_fatal_error(_("Error in pj_do_transform"));
	}
	if (tgt_box.W > x) {
	    tgt_box.E = x + 360;
	    recommend_nowrap = 1;
	}
	if (tgt_box.N < y)
	    tgt_box.N = y;
	if (tgt_box.S > y)
	    tgt_box.S = y;
	/* SE corner */
	x = src_box.E;
	y = src_box.S;
	if (pj_do_transform(1, &x, &y, NULL,
			    &info_in, &info_out) < 0) {
	    G_fatal_error(_("Error in pj_do_transform"));
	}
	if (tgt_box.W > x) {
	    if (tgt_box.E < x + 360)
		tgt_box.E = x + 360;
	    recommend_nowrap = 1;
	}
	if (tgt_box.N < y)
	    tgt_box.N = y;
	if (tgt_box.S > y)
	    tgt_box.S = y;
    }

    G_debug(1, "Open new: location: %s mapset : %s", G_location_path(),
	    G_mapset());

    if (Vect_open_new(&Out_Map, omap_name, Vect_is_3d(&Map)) < 0)
	G_fatal_error(_("Unable to create vector map <%s>"), omap_name);

    Vect_set_error_handler_io(NULL, &Out_Map); /* register standard i/o error handler */
    
    Vect_copy_head_data(&Map, &Out_Map);
    Vect_hist_copy(&Map, &Out_Map);
    Vect_hist_command(&Out_Map);

    out_zone = info_out.zone;
    Vect_set_zone(&Out_Map, out_zone);

    /* Read and write header info */
    sprintf(date, "%s", G_date());
    sscanf(date, "%*s%s%d%*s%d", mon, &day, &yr);
    if (yr < 2000)
	yr = yr - 1900;
    else
	yr = yr - 2000;
    sprintf(date, "%s %d %d", mon, day, yr);
    Vect_set_date(&Out_Map, date);

    /* line densification works only with vector topology */
    if (Map.format != GV_FORMAT_NATIVE)
	lmax = 0;

    /* Cycle through all lines */
    Vect_rewind(&Map);
    i = 0;
    G_message(_("Reprojecting primitives ..."));
    while (TRUE) {
	++i;
	G_progress(i, 1e3);
	type = Vect_read_next_line(&Map, Points, Cats);	/* read line */
	if (type == 0)
	    continue;		/* Dead */

	if (type == -1)
	    G_fatal_error(_("Reading input vector map"));
	if (type == -2)
	    break;

	Vect_line_prune(Points);
	if (lmax > 0 && (type & GV_LINES) && Points->n_points > 1) {
	    double x1, y1, z1, x2, y2, z2;
	    double dx, dy, dz;
	    double l;
	    int i, n;

	    Vect_reset_line(Points2);
	    for (i = 0; i < Points->n_points - 1; i++) {
		x1 = Points->x[i];
		y1 = Points->y[i];
		z1 = Points->z[i];
		n = i + 1;
		x2 = Points->x[n];
		y2 = Points->y[n];
		z2 = Points->z[n];

		dx = x2 - x1;
		dy = y2 - y1;
		dz = z2 - z1;

		if (pj_do_transform(1, &x1, &y1,
				    flag.transformz->answer ? &z1 : NULL,
				    &info_in, &info_out) < 0) {
		  G_fatal_error(_("Unable to re-project vector map <%s> from <%s>"),
				Vect_get_full_name(&Map), ilocopt->answer);
		}

		if (pj_do_transform(1, &x2, &y2,
				    flag.transformz->answer ? &z2 : NULL,
				    &info_in, &info_out) < 0) {
		  G_fatal_error(_("Unable to re-project vector map <%s> from <%s>"),
				Vect_get_full_name(&Map), ilocopt->answer);
		}

		Vect_append_point(Points2, x1, y1, z1);

		l = G_distance(x1, y1, x2, y2);

		if (l > lmax) {
		    int j;
		    double x, y, z;

		    x1 = Points->x[i];
		    y1 = Points->y[i];
		    z1 = Points->z[i];

		    n = ceil(l / lmax);

		    for (j = 1; j < n; j++) {
			x = x1 + dx * j / n;
			y = y1 + dy * j / n;
			z = z1 + dz * j / n;

			if (pj_do_transform(1, &x, &y,
					    flag.transformz->answer ? &z : NULL,
					    &info_in, &info_out) < 0) {
			  G_fatal_error(_("Unable to re-project vector map <%s> from <%s>"),
					Vect_get_full_name(&Map), ilocopt->answer);
			}
			Vect_append_point(Points2, x, y, z);
		    }
		}
	    }
	    Vect_append_point(Points2, x2, y2, z2);
	    Vect_write_line(&Out_Map, type, Points2, Cats);	/* write line */
	}
	else {
	    if (pj_do_transform(Points->n_points, Points->x, Points->y,
				flag.transformz->answer ? Points->z : NULL,
				&info_in, &info_out) < 0) {
	      G_fatal_error(_("Unable to re-project vector map <%s> from <%s>"),
			    Vect_get_full_name(&Map), ilocopt->answer);
	    }

	    Vect_write_line(&Out_Map, type, Points, Cats);	/* write line */
	}
    }				/* end lines section */
    G_progress(1, 1);

    /* Copy tables */
    if (Vect_copy_tables(&Map, &Out_Map, 0))
        G_warning(_("Failed to copy attribute table to output map"));

    Vect_close(&Map);

    if (!flag.no_topol->answer)
        Vect_build(&Out_Map);
    Vect_close(&Out_Map);

    if (recommend_nowrap)
	G_important_message(_("Try to disable wrapping to -180,180 "
			      "if topological errors occurred"));

    exit(EXIT_SUCCESS);
}
Ejemplo n.º 15
0
int main(int argc, char *argv[])
{
    struct Map_info In, Out;
    static struct line_pnts *Points;
    struct line_cats *Cats;
    struct GModule *module;	/* GRASS module for parsing arguments */
    struct Option *map_in, *map_out;
    struct Option *cat_opt, *field_opt, *where_opt, *abcol, *afcol;
    struct Option *iter_opt, *error_opt;
    struct Flag *geo_f, *add_f;
    int chcat, with_z;
    int layer, mask_type;
    struct varray *varray;
    dglGraph_s *graph;
    int i, geo, nnodes, nlines, j, max_cat;
    char buf[2000], *covered;

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

    /* initialize module */
    module = G_define_module();
    module->keywords = _("vector, network, centrality measures");
    module->description =
	_("Computes degree, centrality, betweeness, closeness and eigenvector "
	 "centrality measures in the network.");

    /* Define the different options as defined in gis.h */
    map_in = G_define_standard_option(G_OPT_V_INPUT);
    field_opt = G_define_standard_option(G_OPT_V_FIELD);

    map_out = G_define_standard_option(G_OPT_V_OUTPUT);

    cat_opt = G_define_standard_option(G_OPT_V_CATS);
    cat_opt->guisection = _("Selection");
    where_opt = G_define_standard_option(G_OPT_WHERE);
    where_opt->guisection = _("Selection");

    afcol = G_define_standard_option(G_OPT_COLUMN);
    afcol->key = "afcolumn";
    afcol->required = NO;
    afcol->description =
	_("Name of arc forward/both direction(s) cost column");
    afcol->guisection = _("Cost");

    abcol = G_define_standard_option(G_OPT_COLUMN);
    abcol->key = "abcolumn";
    abcol->required = NO;
    abcol->description = _("Name of arc backward direction cost column");
    abcol->guisection = _("Cost");

    deg_opt = G_define_standard_option(G_OPT_COLUMN);
    deg_opt->key = "degree";
    deg_opt->required = NO;
    deg_opt->description = _("Name of degree centrality column");
    deg_opt->guisection = _("Columns");

    close_opt = G_define_standard_option(G_OPT_COLUMN);
    close_opt->key = "closeness";
    close_opt->required = NO;
    close_opt->description = _("Name of closeness centrality column");
    close_opt->guisection = _("Columns");

    betw_opt = G_define_standard_option(G_OPT_COLUMN);
    betw_opt->key = "betweenness";
    betw_opt->required = NO;
    betw_opt->description = _("Name of betweenness centrality column");
    betw_opt->guisection = _("Columns");

    eigen_opt = G_define_standard_option(G_OPT_COLUMN);
    eigen_opt->key = "eigenvector";
    eigen_opt->required = NO;
    eigen_opt->description = _("Name of eigenvector centrality column");
    eigen_opt->guisection = _("Columns");

    iter_opt = G_define_option();
    iter_opt->key = "iterations";
    iter_opt->answer = "1000";
    iter_opt->type = TYPE_INTEGER;
    iter_opt->required = NO;
    iter_opt->description =
	_("Maximum number of iterations to compute eigenvector centrality");

    error_opt = G_define_option();
    error_opt->key = "error";
    error_opt->answer = "0.1";
    error_opt->type = TYPE_DOUBLE;
    error_opt->required = NO;
    error_opt->description =
	_("Cummulative error tolerance for eigenvector centrality");

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

    add_f = G_define_flag();
    add_f->key = 'a';
    add_f->description = _("Add points on nodes");

    /* options and flags parser */
    if (G_parser(argc, argv))
	exit(EXIT_FAILURE);
    /* TODO: make an option for this */
    mask_type = GV_LINE | GV_BOUNDARY;

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

    Vect_check_input_output_name(map_in->answer, map_out->answer,
				 GV_FATAL_EXIT);

    Vect_set_open_level(2);

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

    with_z = Vect_is_3d(&In);

    if (0 > Vect_open_new(&Out, map_out->answer, with_z)) {
	Vect_close(&In);
	G_fatal_error(_("Unable to create vector map <%s>"), map_out->answer);
    }


    if (geo_f->answer) {
	geo = 1;
	if (G_projection() != PROJECTION_LL)
	    G_warning(_("The current projection is not longitude-latitude"));
    }
    else
	geo = 0;

    /* parse filter option and select appropriate lines */
    layer = atoi(field_opt->answer);
    chcat =
	(NetA_initialise_varray
	 (&In, layer, mask_type, where_opt->answer, cat_opt->answer,
	  &varray) == 1);

    /* Create table */
    Fi = Vect_default_field_info(&Out, 1, NULL, GV_1TABLE);
    Vect_map_add_dblink(&Out, 1, NULL, Fi->table, "cat", Fi->database,
			Fi->driver);
    db_init_string(&sql);
    driver = db_start_driver_open_database(Fi->driver, Fi->database);
    if (driver == NULL)
	G_fatal_error(_("Unable to open database <%s> by driver <%s>"),
		      Fi->database, Fi->driver);

    db_init_string(&tmp);
    if (deg_opt->answer)
	append_string(&tmp, deg_opt->answer);
    if (close_opt->answer)
	append_string(&tmp, close_opt->answer);
    if (betw_opt->answer)
	append_string(&tmp, betw_opt->answer);
    if (eigen_opt->answer)
	append_string(&tmp, eigen_opt->answer);
    sprintf(buf,
	    "create table %s(cat integer%s)", Fi->table, db_get_string(&tmp));

    db_set_string(&sql, buf);
    G_debug(2, db_get_string(&sql));

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

    if (db_create_index2(driver, Fi->table, "cat") != DB_OK)
	G_warning(_("Cannot create index"));

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

    db_begin_transaction(driver);

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

    Vect_net_build_graph(&In, mask_type, atoi(field_opt->answer), 0,
			 afcol->answer, abcol->answer, NULL, geo, 0);
    graph = &(In.graph);
    nnodes = dglGet_NodeCount(graph);

    deg = closeness = betw = eigen = NULL;

    covered = (char *)G_calloc(nnodes + 1, sizeof(char));
    if (!covered)
	G_fatal_error(_("Out of memory"));

    if (deg_opt->answer) {
	deg = (double *)G_calloc(nnodes + 1, sizeof(double));
	if (!deg)
	    G_fatal_error(_("Out of memory"));
    }

    if (close_opt->answer) {
	closeness = (double *)G_calloc(nnodes + 1, sizeof(double));
	if (!closeness)
	    G_fatal_error(_("Out of memory"));
    }

    if (betw_opt->answer) {
	betw = (double *)G_calloc(nnodes + 1, sizeof(double));
	if (!betw)
	    G_fatal_error(_("Out of memory"));
    }

    if (eigen_opt->answer) {
	eigen = (double *)G_calloc(nnodes + 1, sizeof(double));
	if (!eigen)
	    G_fatal_error(_("Out of memory"));
    }


    if (deg_opt->answer) {
	G_message(_("Computing degree centrality measure"));
	NetA_degree_centrality(graph, deg);
    }
    if (betw_opt->answer || close_opt->answer) {
	G_message(_("Computing betweenness and/or closeness centrality measure"));
	NetA_betweenness_closeness(graph, betw, closeness);
	if (closeness)
	    for (i = 1; i <= nnodes; i++)
		closeness[i] /= (double)In.cost_multip;
    }
    if (eigen_opt->answer) {
	G_message(_("Computing eigenvector centrality measure"));
	NetA_eigenvector_centrality(graph, atoi(iter_opt->answer),
				    atof(error_opt->answer), eigen);
    }


    nlines = Vect_get_num_lines(&In);
    G_message(_("Writing data into the table..."));
    G_percent_reset();
    for (i = 1; i <= nlines; i++) {
	G_percent(i, nlines, 1);
	int type = Vect_read_line(&In, Points, Cats, i);

	if (type == GV_POINT && (!chcat || varray->c[i])) {
	    int cat, node;

	    if (!Vect_cat_get(Cats, layer, &cat))
		continue;
	    Vect_reset_cats(Cats);
	    Vect_cat_set(Cats, 1, cat);
	    Vect_write_line(&Out, type, Points, Cats);
	    Vect_get_line_nodes(&In, i, &node, NULL);
	    process_node(node, cat);
	    covered[node] = 1;
	}
    }

    if (add_f->answer && !chcat) {
	max_cat = 0;
	for (i = 1; i <= nlines; i++) {
	    Vect_read_line(&In, NULL, Cats, i);
	    for (j = 0; j < Cats->n_cats; j++)
		if (Cats->cat[j] > max_cat)
		    max_cat = Cats->cat[j];
	}
	max_cat++;
	for (i = 1; i <= nnodes; i++)
	    if (!covered[i]) {
		Vect_reset_cats(Cats);
		Vect_cat_set(Cats, 1, max_cat);
		NetA_add_point_on_node(&In, &Out, i, Cats);
		process_node(i, max_cat);
		max_cat++;
	    }

    }

    db_commit_transaction(driver);
    db_close_database_shutdown_driver(driver);

    G_free(covered);
    if (deg)
	G_free(deg);
    if (closeness)
	G_free(closeness);
    if (betw)
	G_free(betw);
    if (eigen)
	G_free(eigen);
    Vect_build(&Out);

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

    exit(EXIT_SUCCESS);
}
Ejemplo n.º 16
0
int read_scalebar(void)
{
    char buf[1024];
    char *key, *data;
    char ch;

    /* struct defined in decorate.h */
    sb.segment = 4;		/* four segments */
    sb.numbers = 1;		/* label each segment */
    sb.font = G_store("Helvetica");
    sb.fontsize = 8;
    sb.color = BLACK;		/* TODO: multi-color */
    sb.width = 1.;
    sb.length = -1.;
    sb.height = 0.1;		/* default height in inches */
    sb.x = PS.page_width / 2.;
    sb.y = 2.;
    sb.bgcolor = 1;		/* TODO: multi-color */
    sb.units = SB_UNITS_AUTO;   /* default to automatic based on value in PROJ_UNITS */


    while (input(2, buf, help)) {
	if (!key_data(buf, &key, &data))
	    continue;

	if (KEY("where")) {
	    if (sscanf(data, "%lf %lf", &sb.x, &sb.y) != 2) {
		error(key, data, "illegal where request");
	    }
	    else
		continue;
	}

	if (KEY("height")) {
	    if (sscanf(data, "%lf", &sb.height) != 1 || sb.height <= 0.) {
		error(key, data, "illegal height request");
	    }
	    else
		continue;
	}

	if (KEY("length")) {
	    if (sscanf(data, "%lf", &sb.length) != 1 || sb.length <= 0.) {
		error(key, data, "illegal length request");
	    }
	    else
		continue;
	}

	if (KEY("units")) {
	    G_strip(data);
	    if (strcmp(data, "auto") == 0) {
		sb.units = SB_UNITS_AUTO;
		continue;
	    }
	    else if (G_projection() == PROJECTION_XY) {
		error(key, data,
		  "Earth units not available in simple XY location");
	    }
	    else if (strcmp(data, "meters") == 0) {
		sb.units = SB_UNITS_METERS;
		continue;
	    }
	    else if (strcmp(data, "kilometers") == 0 || strcmp(data, "km") == 0) {
		sb.units = SB_UNITS_KM;
		continue;
	    }
	    else if (strcmp(data, "feet") == 0) {
		sb.units = SB_UNITS_FEET;
		continue;
	    }
	    else if (strcmp(data, "miles") == 0) {
		sb.units = SB_UNITS_MILES;
		continue;
	    }
	    else if (strcmp(data, "nautmiles") == 0 || strcmp(data, "nm") == 0) {
		sb.units = SB_UNITS_NMILES;
		continue;
	    }
	    else
		error(key, data, "illegal units request");
	}

	if (KEY("segment")) {
	    if (sscanf(data, "%d", &sb.segment) != 1 || sb.segment <= 0) {
		error(key, data, "illegal segment request");
	    }
	    else
		continue;
	}

	if (KEY("numbers")) {
	    if (sscanf(data, "%d", &sb.numbers) != 1 || sb.numbers <= 0) {
		error(key, data, "illegal numbers request");
	    }
	    else
		continue;
	}

	if (KEY("font")) {
	    get_font(data);
	    G_free(sb.font);
	    sb.font = G_store(data);
	    continue;
	}

	if (KEY("fontsize")) {
	    if (sscanf(data, "%d", &sb.fontsize) != 1 || sb.fontsize <= 0) {
		error(key, data, "illegal fontsize request");
	    }
	    else
		continue;
	}

	if (KEY("color"))
	{
	    sb.color = get_color_number(data);
	    if (sb.color < 0)
	    {
		sb.color = BLACK;
		error(key, data, "illegal color request");
	    }
	    continue;
	}

	if (KEY("background")) {
	    sb.bgcolor = yesno(key, data);
	    continue;
	}

	if (KEY("width")) {
	    sb.width = -1.;
	    ch = ' ';
	    if ((sscanf(data, "%lf%c", &sb.width, &ch) < 1) ||
		(sb.width < 0.)) {
		sb.width = 1.;
		error(key, data, "illegal grid width request");
	    }
	    if (ch == 'i')
		sb.width = sb.width * 72.0;
	    continue;
	}

	error(key, data, "illegal request (scalebar)");

    }

    return 0;

}
Ejemplo n.º 17
0
int main(int argc, char *argv[])
{
    struct Map_info in, out, vis;
    struct GModule *module;	/* GRASS module for parsing arguments */
    struct Option *input, *output;	/* The input map */
    struct Option *coor, *ovis;
    char *mapset;

    struct Point *points;
    struct Line *lines;
    int num_points, num_lines;
    int n = 0;



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

    /* initialize module */
    module = G_define_module();
    module->keywords = _("vector, path, visibility");
    module->description = _("Visibility graph construction.");

    /* define the arguments needed */
    input = G_define_standard_option(G_OPT_V_INPUT);
    output = G_define_standard_option(G_OPT_V_OUTPUT);

    coor = G_define_option();
    coor->key = "coordinate";
    coor->key_desc = "x,y";
    coor->type = TYPE_STRING;
    coor->required = NO;
    coor->multiple = YES;
    coor->description = _("One or more coordinates");

    ovis = G_define_option();
    ovis->key = "vis";
    ovis->type = TYPE_STRING;
    ovis->required = NO;
    ovis->description = _("Add points after computing the vis graph");

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

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

    Vect_set_open_level(2);

    mapset = G_find_vector2(input->answer, NULL);	/* finds the map */

    if (mapset == NULL)
	G_fatal_error("Vector map <%s> not found", input->answer);

    if (Vect_open_old(&in, input->answer, mapset) < 1)	/* opens the map */
	G_fatal_error(_("Unable to open vector map <%s>"),
		      G_fully_qualified_name(input->answer, mapset));

    if (Vect_open_new(&out, output->answer, WITHOUT_Z) < 0) {
	Vect_close(&in);
	G_fatal_error(_("Unable to create vector map <%s>"), output->answer);
    }

    if (ovis->answer != NULL) {
	mapset = G_find_vector2(ovis->answer, NULL);

	if (Vect_open_old(&vis, ovis->answer, mapset) < 1)
	    G_fatal_error(_("Unable to open vector map <%s>"),
			  G_fully_qualified_name(ovis->answer, mapset));

	if (Vect_copy_map_lines(&vis, &out) > 0)
	    G_fatal_error(_("Unable to copy elements from vector map <%s>"),
			  G_fully_qualified_name(ovis->answer, mapset));
    }


    if (G_projection() == PROJECTION_LL)
	G_warning(_("Lat-long projection"));


    /* counting how many points and lines we have to allocate */
    count(&in, &num_points, &num_lines);

    /* modify the number if we have new points to add */
    if (coor->answers != NULL)
	num_points += count_new(coor->answers);

    /* and allocate */
    points = G_malloc(num_points * sizeof(struct Point));
    lines = G_malloc(num_lines * sizeof(struct Line));

    /* and finally set the lines */
    load_lines(&in, &points, &num_points, &lines, &num_lines);

    if (coor->answers != NULL)
	add_points(coor->answers, &points, &num_points);

    if (ovis->answer == NULL)
	construct_visibility(points, num_points, lines, num_lines, &out);
    else
	visibility_points(points, num_points, lines, num_lines, &out, n);

    G_free(points);
    G_free(lines);

    Vect_build(&out);
    Vect_close(&out);
    Vect_close(&in);

    exit(EXIT_SUCCESS);
}
Ejemplo n.º 18
0
int G_get_3dview(const char *fname, const char *mapset, struct G_3dview *View)
{
    struct Cell_head curwin;
    FILE *fp;
    char buffer[80], keystring[24], boo[8], nbuf[128], ebuf[128];
    int lap, v_maj, v_min, wind_keys = 0, reqkeys = 0;
    int current = 0;		/* current version flag */

    mapset = G_find_file2("3d.view", fname, mapset);
    if (mapset != NULL) {
	if (NULL == (fp = G_fopen_old("3d.view", fname, mapset))) {
	    G_warning(_("Unable to open %s for reading"), fname);
	    return (-1);
	}

	G_get_set_window(&curwin);
	G_get_3dview_defaults(View, &curwin);

	if (NULL != fgets(buffer, 80, fp)) {
	    if (buffer[0] != '#') {	/* old d.3d format */
		rewind(fp);
		if (0 <= read_old_format(View, fp))
		    return (0);
		else
		    return (-1);
	    }
	    else {
		sscanf(buffer, "#%d.%d\n", &v_maj, &v_min);
		if (v_maj == vers_major && v_min == vers_minor)
		    current = 1;	/* same version */
	    }
	}

	while (NULL != fgets(buffer, 75, fp)) {
	    if (buffer[0] != '#') {

		sscanf(buffer, "%[^:]:", keystring);

		if (!strcmp(keystring, "PGM_ID")) {
		    sscanf(buffer, "%*s%s", (View->pgm_id));
		    continue;
		}
		if (!strcmp(keystring, "north")) {
		    sscanf(buffer, "%*s%lf", &(View->vwin.north));
		    ++wind_keys;
		    continue;
		}
		if (!strcmp(keystring, "south")) {
		    sscanf(buffer, "%*s%lf", &(View->vwin.south));
		    ++wind_keys;
		    continue;
		}
		if (!strcmp(keystring, "east")) {
		    sscanf(buffer, "%*s%lf", &(View->vwin.east));
		    ++wind_keys;
		    continue;
		}
		if (!strcmp(keystring, "west")) {
		    sscanf(buffer, "%*s%lf", &(View->vwin.west));
		    ++wind_keys;
		    continue;
		}
		if (!strcmp(keystring, "rows")) {
		    sscanf(buffer, "%*s%d", &(View->vwin.rows));
		    ++wind_keys;
		    continue;
		}
		if (!strcmp(keystring, "cols")) {
		    sscanf(buffer, "%*s%d", &(View->vwin.cols));
		    ++wind_keys;
		    continue;
		}
		if (!strcmp(keystring, "TO_EASTING")) {
		    sscanf(buffer, "%*s%f", &(View->from_to[1][0]));
		    ++reqkeys;
		    continue;
		}
		if (!strcmp(keystring, "TO_NORTHING")) {
		    sscanf(buffer, "%*s%f", &(View->from_to[1][1]));
		    ++reqkeys;
		    continue;
		}
		if (!strcmp(keystring, "TO_HEIGHT")) {
		    sscanf(buffer, "%*s%f", &(View->from_to[1][2]));
		    ++reqkeys;
		    continue;
		}
		if (!strcmp(keystring, "FROM_EASTING")) {
		    sscanf(buffer, "%*s%f", &(View->from_to[0][0]));
		    ++reqkeys;
		    continue;
		}
		if (!strcmp(keystring, "FROM_NORTHING")) {
		    sscanf(buffer, "%*s%f", &(View->from_to[0][1]));
		    ++reqkeys;
		    continue;
		}
		if (!strcmp(keystring, "FROM_HEIGHT")) {
		    sscanf(buffer, "%*s%f", &(View->from_to[0][2]));
		    ++reqkeys;
		    continue;
		}
		if (!strcmp(keystring, "Z_EXAG")) {
		    sscanf(buffer, "%*s%f", &(View->exag));
		    ++reqkeys;
		    continue;
		}
		if (!strcmp(keystring, "MESH_FREQ")) {
		    sscanf(buffer, "%*s%d", &(View->mesh_freq));
		    continue;
		}
		if (!strcmp(keystring, "POLY_RES")) {
		    sscanf(buffer, "%*s%d", &(View->poly_freq));
		    continue;
		}
		if (!strcmp(keystring, "DOAVG")) {
		    sscanf(buffer, "%*s%d", &(View->doavg));
		    continue;
		}
		if (!strcmp(keystring, "FIELD_VIEW")) {
		    sscanf(buffer, "%*s%f", &(View->fov));
		    ++reqkeys;
		    continue;
		}
		if (!strcmp(keystring, "TWIST")) {
		    sscanf(buffer, "%*s%f", &(View->twist));
		    continue;
		}
		if (!strcmp(keystring, "DISPLAY_TYPE")) {
		    sscanf(buffer, "%*s%d", &View->display_type);
		    continue;
		}
		if (!strcmp(keystring, "DOZERO")) {
		    sscanf(buffer, "%*s%s", boo);
		    View->dozero = get_bool(boo);
		    continue;
		}
		if (!strcmp(keystring, "COLORGRID")) {
		    sscanf(buffer, "%*s%s", boo);
		    View->colorgrid = get_bool(boo);
		    continue;
		}
		if (!strcmp(keystring, "FRINGE")) {
		    sscanf(buffer, "%*s%s", boo);
		    View->fringe = get_bool(boo);
		    continue;
		}
		if (!strcmp(keystring, "SHADING")) {
		    sscanf(buffer, "%*s%s", boo);
		    View->shading = get_bool(boo);
		    continue;
		}
		if (!strcmp(keystring, "BG_COL")) {
		    sscanf(buffer, "%*s%s", View->bg_col);
		    continue;
		}
		if (!strcmp(keystring, "GRID_COL")) {
		    sscanf(buffer, "%*s%s", View->grid_col);
		    continue;
		}
		if (!strcmp(keystring, "OTHER_COL")) {
		    sscanf(buffer, "%*s%s", View->other_col);
		    continue;
		}
		if (!strcmp(keystring, "SURFACEONLY")) {
		    sscanf(buffer, "%*s%s", boo);
		    View->surfonly = get_bool(boo);
		    continue;
		}
		if (!strcmp(keystring, "LIGHTS_ON")) {
		    sscanf(buffer, "%*s%s", boo);
		    View->lightson = get_bool(boo);
		    continue;
		}
		if (!strcmp(keystring, "LIGHTPOS")) {
		    sscanf(buffer, "%*s%f%f%f%f", &(View->lightpos[0]),
			   &(View->lightpos[1]), &(View->lightpos[2]),
			   &(View->lightpos[3]));
		    continue;
		}
		if (!strcmp(keystring, "LIGHTCOL")) {
		    sscanf(buffer, "%*s%f%f%f", &(View->lightcol[0]),
			   &(View->lightcol[1]), &(View->lightcol[2]));
		    continue;
		}
		if (!strcmp(keystring, "LIGHTAMBIENT")) {
		    sscanf(buffer, "%*s%f", &(View->ambient));
		    continue;
		}
		if (!strcmp(keystring, "SHINE")) {
		    sscanf(buffer, "%*s%f", &(View->shine));
		    continue;
		}
	    }
	}

	fclose(fp);

	if (reqkeys != REQ_KEYS)	/* required keys not found */
	    return (-1);

	/* fill rest of View->vwin */
	if (wind_keys == 6) {
	    View->vwin.ew_res = (View->vwin.east - View->vwin.west) /
		View->vwin.cols;
	    View->vwin.ns_res = (View->vwin.north - View->vwin.south) /
		View->vwin.rows;
	}
	else
	    return (0);		/* older format */

	if (!Suppress_warn) {
	    if (95 > (lap = compare_wind(&(View->vwin), &curwin))) {

		fprintf(stderr, _("GRASS window when view was saved:\n"));
		G_format_northing(View->vwin.north, nbuf, G_projection());
		fprintf(stderr, "north:   %s\n", nbuf);
		G_format_northing(View->vwin.south, nbuf, G_projection());
		fprintf(stderr, "south:   %s\n", nbuf);
		G_format_easting(View->vwin.east, ebuf, G_projection());
		fprintf(stderr, "east:    %s\n", ebuf);
		G_format_easting(View->vwin.west, ebuf, G_projection());
		fprintf(stderr, "west:    %s\n", ebuf);
		pr_winerr(lap, fname);
	    }
	}
    }
    else {
	G_warning(_("Unable to open %s for reading"), fname);
	return (-1);
    }

    if (current)
	return (2);

    return (1);
}
Ejemplo n.º 19
0
int main(int argc, char *argv[]) {
	struct GModule *module;
	struct {
		struct Option *input;
		struct Option *output;
		struct Option *null;
		struct Option *bytes;
		struct Option *order;
		struct Option *north;
		struct Option *south;
		struct Option *top;
		struct Option *bottom;
		struct Option *east;
		struct Option *west;
		struct Option *rows;
		struct Option *cols;
		struct Option *depths;
	} parm;
	struct {
		struct Flag *integer_in;
		struct Flag *sign;
		struct Flag *depth;
		struct Flag *row;
	} flag;
	const char *input;
	const char *output;
	int is_integer;
	int is_signed;
	int bytes;
	int order;
	int byte_swap;
	RASTER_MAP_TYPE map_type;
	off_t file_size;
	struct History history;
	off_t expected;
	/* Need to be allocated later */
	in_cell = NULL;

	G_gisinit(argv[0]);

	/* Set description */
	module = G_define_module();
	G_add_keyword(_("raster3d"));
	G_add_keyword(_("import"));
	G_add_keyword(_("voxel"));
	module->description =
			_("Imports a binary raster file into a GRASS 3D raster map.");

	parm.input = G_define_standard_option(G_OPT_F_BIN_INPUT);
	parm.input->description = _("Name of binary 3D raster file to be imported");

	parm.output = G_define_standard_option(G_OPT_R3_OUTPUT);

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

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

	parm.north = G_define_option();
	parm.north->key = "north";
	parm.north->type = TYPE_DOUBLE;
	parm.north->required = YES;
	parm.north->description =
			_("Northern limit of geographic region (outer edge)");
	parm.north->guisection = _("Bounds");

	parm.south = G_define_option();
	parm.south->key = "south";
	parm.south->type = TYPE_DOUBLE;
	parm.south->required = YES;
	parm.south->description =
			_("Southern limit of geographic region (outer edge)");
	parm.south->guisection = _("Bounds");

	parm.east = G_define_option();
	parm.east->key = "east";
	parm.east->type = TYPE_DOUBLE;
	parm.east->required = YES;
	parm.east->description =
			_("Eastern limit of geographic region (outer edge)");
	parm.east->guisection = _("Bounds");

	parm.west = G_define_option();
	parm.west->key = "west";
	parm.west->type = TYPE_DOUBLE;
	parm.west->required = YES;
	parm.west->description =
			_("Western limit of geographic region (outer edge)");
	parm.west->guisection = _("Bounds");

	parm.bottom = G_define_option();
	parm.bottom->key = "bottom";
	parm.bottom->type = TYPE_DOUBLE;
	parm.bottom->required = YES;
	parm.bottom->description =
			_("Bottom limit of geographic region (outer edge)");
	parm.bottom->guisection = _("Bounds");

	parm.top = G_define_option();
	parm.top->key = "top";
	parm.top->type = TYPE_DOUBLE;
	parm.top->required = YES;
	parm.top->description = _("Top limit of geographic region (outer edge)");
	parm.top->guisection = _("Bounds");

	parm.rows = G_define_option();
	parm.rows->key = "rows";
	parm.rows->type = TYPE_INTEGER;
	parm.rows->required = YES;
	parm.rows->description = _("Number of rows");
	parm.rows->guisection = _("Bounds");

	parm.cols = G_define_option();
	parm.cols->key = "cols";
	parm.cols->type = TYPE_INTEGER;
	parm.cols->required = YES;
	parm.cols->description = _("Number of columns");
	parm.cols->guisection = _("Bounds");

	parm.depths = G_define_option();
	parm.depths->key = "depths";
	parm.depths->type = TYPE_INTEGER;
	parm.depths->required = YES;
	parm.depths->description = _("Number of depths");
	parm.depths->guisection = _("Bounds");

	parm.null = G_define_option();
	parm.null->key = "null";
	parm.null->type = TYPE_DOUBLE;
	parm.null->required = NO;
	parm.null->description = _("Set Value to NULL");

	flag.row = G_define_flag();
	flag.row->key = 'r';
	flag.row->description = _("Switch the row order in output from "
			"north->south to south->north");

	flag.depth = G_define_flag();
	flag.depth->key = 'd';
	flag.depth->description = _("Switch the depth order in output "
			"from bottom->top to top->bottom");

	flag.integer_in = G_define_flag();
	flag.integer_in->key = 'i';
	flag.integer_in->description =
			_("Binary data is of type integer");

	flag.sign = G_define_flag();
	flag.sign->key = 's';
	flag.sign->description = _("Signed data (two's complement)");

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

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

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

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

	is_signed = !!flag.sign->answer;

	is_integer = 0;
	bytes = 8;

	if (parm.bytes->answer)
		bytes = atoi(parm.bytes->answer);

	if (!flag.integer_in->answer) {
		if (bytes && bytes < 4)
			G_fatal_error(
					_("bytes=%d; must be 4 or 8 in case of floating point input"),
					bytes);
		if (!bytes)
			bytes = 4;
	} else {
		is_integer = 1;
	}

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

	if (bytes != 1 && bytes != 2 && bytes != 4 && bytes != 8)
		G_fatal_error(_("bytes= must be 1, 2, 4 or 8"));

	region.zone = G_zone();
	region.proj = G_projection();
	region.rows = atoi(parm.rows->answer);
	region.cols = atoi(parm.cols->answer);
	region.depths = atoi(parm.depths->answer);
	region.top = atof(parm.top->answer);
	region.bottom = atof(parm.bottom->answer);

	if (!G_scan_northing(parm.north->answer, &region.north, region.proj))
		G_fatal_error(_("Illegal north coordinate <%s>"), parm.north->answer);
	if (!G_scan_northing(parm.south->answer, &region.south, region.proj))
		G_fatal_error(_("Illegal south coordinate <%s>"), parm.south->answer);
	if (!G_scan_easting(parm.east->answer, &region.east, region.proj))
		G_fatal_error(_("Illegal east coordinate <%s>"), parm.east->answer);
	if (!G_scan_easting(parm.west->answer, &region.west, region.proj))
		G_fatal_error(_("Illegal west coordinate <%s>"), parm.west->answer);

	Rast3d_adjust_region(&region);

	expected = (off_t) region.rows * region.cols * region.depths * bytes;

	fp = fopen(input, "rb");
	if (!fp)
		G_fatal_error(_("Unable to open <%s>"), input);

	/* Find File Size in Byte and Check against byte size */
	G_fseek(fp, 0, SEEK_END);
	file_size = G_ftell(fp);
	G_fseek(fp, 0, SEEK_SET);

	if (file_size != expected) {
		G_warning(_("File Size %lld ... Total Bytes %lld"),
				(long long int) file_size, (long long int) expected);
		G_fatal_error(_("Bytes do not match file size"));
	}

	map_type = (bytes > 4 ? DCELL_TYPE : FCELL_TYPE);

	if(is_integer && bytes >= 4)
		map_type = DCELL_TYPE;

	Rast3d_init_defaults();

	/*Open the new 3D raster map */
	map = Rast3d_open_new_opt_tile_size(output, RASTER3D_USE_CACHE_DEFAULT,
			&region, map_type, 32);

	if (map == NULL)
		G_fatal_error(_("Unable to open 3D raster map"));

	in_cell = G_malloc(bytes);

	bin_to_raster3d(parm.null->answer, map_type, is_integer, is_signed, bytes,
			byte_swap, flag.row->answer, flag.depth->answer);

	if (!Rast3d_close(map))
		G_fatal_error(_("Unable to close 3D raster map"));

	/* write input name to map history */
	Rast3d_read_history(output, G_mapset(), &history);
	Rast_set_history(&history, HIST_DATSRC_1, input);
	Rast3d_write_history(output, &history);

	fclose(fp);
	if (in_cell)
		G_free(in_cell);

	return EXIT_SUCCESS;
}
Ejemplo n.º 20
0
int main(int argc, char *argv[])
{
    int line_color;
    int text_color;
    double lon1, lat1, lon2, lat2;
    char *deftcolor;
    struct GModule *module;
    struct
    {
	struct Option *lcolor, *tcolor, *coor;
    } parm;

    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("display"));
    G_add_keyword(_("distance"));
    module->description =
	_("Displays a geodesic line, tracing the shortest distance "
	"between two geographic points along a great circle, in "
	"a longitude/latitude data set.");

    parm.coor = G_define_option();
    parm.coor->key = "coor";
    parm.coor->key_desc = "lon1,lat1,lon2,lat2";
    parm.coor->type = TYPE_STRING;
    parm.coor->required = YES;
    parm.coor->description = _("Starting and ending coordinates");

    parm.lcolor = G_define_option();
    parm.lcolor->key = "lcolor";
    parm.lcolor->type = TYPE_STRING;
    parm.lcolor->required = NO;
    parm.lcolor->description = _("Line color");
    parm.lcolor->gisprompt = "old_color,color,color";
    parm.lcolor->answer = DEFAULT_FG_COLOR;

    parm.tcolor = G_define_option();
    parm.tcolor->key = "tcolor";
    parm.tcolor->type = TYPE_STRING;
    parm.tcolor->required = NO;
    parm.tcolor->description = _("Text color or \"none\"");
    parm.tcolor->gisprompt = "old_color,color,color";

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


    if (G_projection() != PROJECTION_LL)
	G_fatal_error(_("Location is not %s"), G__projection_name(PROJECTION_LL));

    if (parm.coor->answers[0] == NULL)
	G_fatal_error(_("No coordinates given"));

    if (!G_scan_easting(parm.coor->answers[0], &lon1, G_projection()))
	G_fatal_error(_("%s - illegal longitude"), parm.coor->answers[0]);

    if (!G_scan_northing(parm.coor->answers[1], &lat1, G_projection()))
	G_fatal_error(_("%s - illegal longitude"), parm.coor->answers[1]);

    if (!G_scan_easting(parm.coor->answers[2], &lon2, G_projection()))
	G_fatal_error(_("%s - illegal longitude"), parm.coor->answers[2]);

    if (!G_scan_northing(parm.coor->answers[3], &lat2, G_projection()))
	G_fatal_error(_("%s - illegal longitude"), parm.coor->answers[3]);


    if (D_open_driver() != 0)
      	G_fatal_error(_("No graphics device selected. "
			"Use d.mon to select graphics device."));
    
    line_color = D_translate_color(parm.lcolor->answer);
    if (!line_color)
	line_color = D_translate_color(parm.lcolor->answer =
				       DEFAULT_FG_COLOR);

    if (strcmp(parm.lcolor->answer, DEFAULT_FG_COLOR) == 0)
	deftcolor = "red";
    else
	deftcolor = DEFAULT_FG_COLOR;

    if (parm.tcolor->answer == NULL)
	text_color = D_translate_color(deftcolor);
    else if (strcmp(parm.tcolor->answer, "none") == 0)
	text_color = -1;
    else
	text_color = D_translate_color(parm.tcolor->answer);

    plot(lon1, lat1, lon2, lat2, line_color, text_color);
    
    D_save_command(G_recreate_command());
    D_close_driver();

    exit(EXIT_SUCCESS);
}
Ejemplo n.º 21
0
int main(int argc, char **argv)
{
    char *mapname,		/* ptr to name of output layer  */
     *setname,			/* ptr to name of input mapset  */
     *ipolname;			/* name of interpolation method */

    int fdi,			/* input map file descriptor    */
      fdo,			/* output map file descriptor   */
      method,			/* position of method in table  */
      permissions,		/* mapset permissions           */
      cell_type,		/* output celltype              */
      cell_size,		/* size of a cell in bytes      */
      row, col,			/* counters                     */
      irows, icols,		/* original rows, cols          */
      orows, ocols, have_colors,	/* Input map has a colour table */
      overwrite,		/* Overwrite                    */
      curr_proj;		/* output projection (see gis.h) */

    void *obuffer,		/* buffer that holds one output row     */
     *obufptr;			/* column ptr in output buffer  */
    struct cache *ibuffer;	/* buffer that holds the input map      */
    func interpolate;		/* interpolation routine        */

    double xcoord1, xcoord2,	/* temporary x coordinates      */
      ycoord1, ycoord2,		/* temporary y coordinates      */
      col_idx,			/* column index in input matrix */
      row_idx,			/* row index in input matrix    */
      onorth, osouth,		/* save original border coords  */
      oeast, owest, inorth, isouth, ieast, iwest;
    char north_str[30], south_str[30], east_str[30], west_str[30];

    struct Colors colr;		/* Input map colour table       */
    struct History history;

    struct pj_info iproj,	/* input map proj parameters    */
      oproj;			/* output map proj parameters   */

    struct Key_Value *in_proj_info,	/* projection information of    */
     *in_unit_info,		/* input and output mapsets     */
     *out_proj_info, *out_unit_info;

    struct GModule *module;

    struct Flag *list,		/* list files in source location */
     *nocrop,			/* don't crop output map        */
     *print_bounds,		/* print output bounds and exit */
     *gprint_bounds;		/* same but print shell style	*/

    struct Option *imapset,	/* name of input mapset         */
     *inmap,			/* name of input layer          */
     *inlocation,		/* name of input location       */
     *outmap,			/* name of output layer         */
     *indbase,			/* name of input database       */
     *interpol,			/* interpolation method:
				   nearest neighbor, bilinear, cubic */
     *memory,			/* amount of memory for cache   */
     *res;			/* resolution of target map     */
    struct Cell_head incellhd,	/* cell header of input map     */
      outcellhd;		/* and output map               */


    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("raster"));
    G_add_keyword(_("projection"));
    G_add_keyword(_("transformation"));
    module->description =
	_("Re-projects a raster map from given location to the current location.");

    inmap = G_define_standard_option(G_OPT_R_INPUT);
    inmap->description = _("Name of input raster map to re-project");
    inmap->required = NO;
    inmap->guisection = _("Source");

    inlocation = G_define_option();
    inlocation->key = "location";
    inlocation->type = TYPE_STRING;
    inlocation->required = YES;
    inlocation->description = _("Location containing input raster map");
    inlocation->gisprompt = "old,location,location";
    inlocation->key_desc = "name";

    imapset = G_define_standard_option(G_OPT_M_MAPSET);
    imapset->label = _("Mapset containing input raster map");
    imapset->description = _("default: name of current mapset");
    imapset->guisection = _("Source");

    indbase = G_define_option();
    indbase->key = "dbase";
    indbase->type = TYPE_STRING;
    indbase->required = NO;
    indbase->description = _("Path to GRASS database of input location");
    indbase->gisprompt = "old,dbase,dbase";
    indbase->key_desc = "path";
    indbase->guisection = _("Source");

    outmap = G_define_standard_option(G_OPT_R_OUTPUT);
    outmap->required = NO;
    outmap->description = _("Name for output raster map (default: same as 'input')");
    outmap->guisection = _("Target");

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

    memory = G_define_option();
    memory->key = "memory";
    memory->type = TYPE_INTEGER;
    memory->required = NO;
    memory->description = _("Cache size (MiB)");

    res = G_define_option();
    res->key = "resolution";
    res->type = TYPE_DOUBLE;
    res->required = NO;
    res->description = _("Resolution of output raster map");
    res->guisection = _("Target");

    list = G_define_flag();
    list->key = 'l';
    list->description = _("List raster maps in input location and exit");

    nocrop = G_define_flag();
    nocrop->key = 'n';
    nocrop->description = _("Do not perform region cropping optimization");

    print_bounds = G_define_flag();
    print_bounds->key = 'p';
    print_bounds->description =
	_("Print input map's bounds in the current projection and exit");
    print_bounds->guisection = _("Target");
    
    gprint_bounds = G_define_flag();
    gprint_bounds->key = 'g';
    gprint_bounds->description =
	_("Print input map's bounds in the current projection and exit (shell style)");
    gprint_bounds->guisection = _("Target");

    /* The parser checks if the map already exists in current mapset,
       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);


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

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

    mapname = outmap->answer ? outmap->answer : inmap->answer;
    if (mapname && !list->answer && !overwrite &&
	G_find_raster(mapname, G_mapset()))
	G_fatal_error(_("option <%s>: <%s> exists."), "output", mapname);

    setname = imapset->answer ? imapset->answer : G_store(G_mapset());
    if (strcmp(inlocation->answer, G_location()) == 0 &&
        (!indbase->answer || strcmp(indbase->answer, G_gisdbase()) == 0))
#if 0
	G_fatal_error(_("Input and output locations can not be the same"));
#else
	G_warning(_("Input and output locations are the same"));
#endif
    G_get_window(&outcellhd);

    if(gprint_bounds->answer && !print_bounds->answer)
	print_bounds->answer = gprint_bounds->answer;
    curr_proj = G_projection();

    /* Get projection info for output mapset */
    if ((out_proj_info = G_get_projinfo()) == NULL)
	G_fatal_error(_("Unable to get projection info of output raster map"));

    if ((out_unit_info = G_get_projunits()) == NULL)
	G_fatal_error(_("Unable to get projection units of output raster map"));

    if (pj_get_kv(&oproj, out_proj_info, out_unit_info) < 0)
	G_fatal_error(_("Unable to get projection key values of output raster map"));

    /* Change the location           */
    G__create_alt_env();
    G__setenv("GISDBASE", indbase->answer ? indbase->answer : G_gisdbase());
    G__setenv("LOCATION_NAME", inlocation->answer);

    permissions = G__mapset_permissions(setname);
    if (permissions < 0)	/* can't access mapset       */
	G_fatal_error(_("Mapset <%s> in input location <%s> - %s"),
		      setname, inlocation->answer,
		      permissions == 0 ? _("permission denied")
		      : _("not found"));

    /* if requested, list the raster maps in source location - MN 5/2001 */
    if (list->answer) {
	int i;
	char **list;
	G_verbose_message(_("Checking location <%s> mapset <%s>"),
			  inlocation->answer, setname);
	list = G_list(G_ELEMENT_RASTER, G__getenv("GISDBASE"),
		      G__getenv("LOCATION_NAME"), setname);
	for (i = 0; list[i]; i++) {
	    fprintf(stdout, "%s\n", list[i]);
	}
	fflush(stdout);
	exit(EXIT_SUCCESS);	/* leave r.proj after listing */
    }

    if (!inmap->answer)
	G_fatal_error(_("Required parameter <%s> not set"), inmap->key);

    if (!G_find_raster(inmap->answer, setname))
	G_fatal_error(_("Raster map <%s> in location <%s> in mapset <%s> not found"),
		      inmap->answer, inlocation->answer, setname);

    /* Read input map colour table */
    have_colors = Rast_read_colors(inmap->answer, setname, &colr);

    /* Get projection info for input mapset */
    if ((in_proj_info = G_get_projinfo()) == NULL)
	G_fatal_error(_("Unable to get projection info of input map"));

    if ((in_unit_info = G_get_projunits()) == NULL)
	G_fatal_error(_("Unable to get projection units of input map"));

    if (pj_get_kv(&iproj, in_proj_info, in_unit_info) < 0)
	G_fatal_error(_("Unable to get projection key values of input map"));

    G_free_key_value(in_proj_info);
    G_free_key_value(in_unit_info);
    G_free_key_value(out_proj_info);
    G_free_key_value(out_unit_info);
    if (G_verbose() > G_verbose_std())
	pj_print_proj_params(&iproj, &oproj);

    /* this call causes r.proj to read the entire map into memeory */
    Rast_get_cellhd(inmap->answer, setname, &incellhd);

    Rast_set_input_window(&incellhd);

    if (G_projection() == PROJECTION_XY)
	G_fatal_error(_("Unable to work with unprojected data (xy location)"));

    /* Save default borders so we can show them later */
    inorth = incellhd.north;
    isouth = incellhd.south;
    ieast = incellhd.east;
    iwest = incellhd.west;
    irows = incellhd.rows;
    icols = incellhd.cols;

    onorth = outcellhd.north;
    osouth = outcellhd.south;
    oeast = outcellhd.east;
    owest = outcellhd.west;
    orows = outcellhd.rows;
    ocols = outcellhd.cols;


    if (print_bounds->answer) {
	G_message(_("Input map <%s@%s> in location <%s>:"),
	    inmap->answer, setname, inlocation->answer);

	if (pj_do_proj(&iwest, &isouth, &iproj, &oproj) < 0)
	    G_fatal_error(_("Error in pj_do_proj (projection of input coordinate pair)"));
	if (pj_do_proj(&ieast, &inorth, &iproj, &oproj) < 0)
	    G_fatal_error(_("Error in pj_do_proj (projection of input coordinate pair)"));

	G_format_northing(inorth, north_str, curr_proj);
	G_format_northing(isouth, south_str, curr_proj);
	G_format_easting(ieast, east_str, curr_proj);
	G_format_easting(iwest, west_str, curr_proj);

	if(gprint_bounds->answer) {
	    fprintf(stdout, "n=%s s=%s w=%s e=%s rows=%d cols=%d\n",
		north_str, south_str, west_str, east_str, irows, icols);
	}
	else {
	    fprintf(stdout, "Source cols: %d\n", icols);
	    fprintf(stdout, "Source rows: %d\n", irows);
	    fprintf(stdout, "Local north: %s\n",  north_str);
	    fprintf(stdout, "Local south: %s\n", south_str);
	    fprintf(stdout, "Local west: %s\n", west_str);
	    fprintf(stdout, "Local east: %s\n", east_str);
	}

	/* somehow approximate local ewres, nsres ?? (use 'g.region -m' on lat/lon side) */

	exit(EXIT_SUCCESS);
    }


    /* Cut non-overlapping parts of input map */
    if (!nocrop->answer)
	bordwalk(&outcellhd, &incellhd, &oproj, &iproj);

    /* Add 2 cells on each side for bilinear/cubic & future interpolation methods */
    /* (should probably be a factor based on input and output resolution) */
    incellhd.north += 2 * incellhd.ns_res;
    incellhd.east += 2 * incellhd.ew_res;
    incellhd.south -= 2 * incellhd.ns_res;
    incellhd.west -= 2 * incellhd.ew_res;
    if (incellhd.north > inorth)
	incellhd.north = inorth;
    if (incellhd.east > ieast)
	incellhd.east = ieast;
    if (incellhd.south < isouth)
	incellhd.south = isouth;
    if (incellhd.west < iwest)
	incellhd.west = iwest;

    Rast_set_input_window(&incellhd);

    /* And switch back to original location */

    G__switch_env();

    /* Adjust borders of output map */

    if (!nocrop->answer)
	bordwalk(&incellhd, &outcellhd, &iproj, &oproj);

#if 0
    outcellhd.west = outcellhd.south = HUGE_VAL;
    outcellhd.east = outcellhd.north = -HUGE_VAL;
    for (row = 0; row < incellhd.rows; row++) {
	ycoord1 = Rast_row_to_northing((double)(row + 0.5), &incellhd);
	for (col = 0; col < incellhd.cols; col++) {
	    xcoord1 = Rast_col_to_easting((double)(col + 0.5), &incellhd);
	    pj_do_proj(&xcoord1, &ycoord1, &iproj, &oproj);
	    if (xcoord1 > outcellhd.east)
		outcellhd.east = xcoord1;
	    if (ycoord1 > outcellhd.north)
		outcellhd.north = ycoord1;
	    if (xcoord1 < outcellhd.west)
		outcellhd.west = xcoord1;
	    if (ycoord1 < outcellhd.south)
		outcellhd.south = ycoord1;
	}
    }
#endif

    if (res->answer != NULL)	/* set user defined resolution */
	outcellhd.ns_res = outcellhd.ew_res = atof(res->answer);

    G_adjust_Cell_head(&outcellhd, 0, 0);
    Rast_set_output_window(&outcellhd);

    G_message(" ");
    G_message(_("Input:"));
    G_message(_("Cols: %d (%d)"), incellhd.cols, icols);
    G_message(_("Rows: %d (%d)"), incellhd.rows, irows);
    G_message(_("North: %f (%f)"), incellhd.north, inorth);
    G_message(_("South: %f (%f)"), incellhd.south, isouth);
    G_message(_("West: %f (%f)"), incellhd.west, iwest);
    G_message(_("East: %f (%f)"), incellhd.east, ieast);
    G_message(_("EW-res: %f"), incellhd.ew_res);
    G_message(_("NS-res: %f"), incellhd.ns_res);
    G_message(" ");

    G_message(_("Output:"));
    G_message(_("Cols: %d (%d)"), outcellhd.cols, ocols);
    G_message(_("Rows: %d (%d)"), outcellhd.rows, orows);
    G_message(_("North: %f (%f)"), outcellhd.north, onorth);
    G_message(_("South: %f (%f)"), outcellhd.south, osouth);
    G_message(_("West: %f (%f)"), outcellhd.west, owest);
    G_message(_("East: %f (%f)"), outcellhd.east, oeast);
    G_message(_("EW-res: %f"), outcellhd.ew_res);
    G_message(_("NS-res: %f"), outcellhd.ns_res);
    G_message(" ");

    /* open and read the relevant parts of the input map and close it */
    G__switch_env();
    Rast_set_input_window(&incellhd);
    fdi = Rast_open_old(inmap->answer, setname);
    cell_type = Rast_get_map_type(fdi);
    ibuffer = readcell(fdi, memory->answer);
    Rast_close(fdi);

    G__switch_env();
    Rast_set_output_window(&outcellhd);

    if (strcmp(interpol->answer, "nearest") == 0) {
	fdo = Rast_open_new(mapname, cell_type);
	obuffer = (CELL *) Rast_allocate_output_buf(cell_type);
    }
    else {
	fdo = Rast_open_fp_new(mapname);
	cell_type = FCELL_TYPE;
	obuffer = (FCELL *) Rast_allocate_output_buf(cell_type);
    }

    cell_size = Rast_cell_size(cell_type);

    xcoord1 = xcoord2 = outcellhd.west + (outcellhd.ew_res / 2);
    /**/ ycoord1 = ycoord2 = outcellhd.north - (outcellhd.ns_res / 2);
    /**/ G_important_message(_("Projecting..."));
    G_percent(0, outcellhd.rows, 2);

    for (row = 0; row < outcellhd.rows; row++) {
	obufptr = obuffer;

	for (col = 0; col < outcellhd.cols; col++) {
	    /* project coordinates in output matrix to       */
	    /* coordinates in input matrix                   */
	    if (pj_do_proj(&xcoord1, &ycoord1, &oproj, &iproj) < 0)
		Rast_set_null_value(obufptr, 1, cell_type);
	    else {
		/* convert to row/column indices of input matrix */
		col_idx = (xcoord1 - incellhd.west) / incellhd.ew_res;
		row_idx = (incellhd.north - ycoord1) / incellhd.ns_res;

		/* and resample data point               */
		interpolate(ibuffer, obufptr, cell_type,
			    &col_idx, &row_idx, &incellhd);
	    }

	    obufptr = G_incr_void_ptr(obufptr, cell_size);
	    xcoord2 += outcellhd.ew_res;
	    xcoord1 = xcoord2;
	    ycoord1 = ycoord2;
	}

	Rast_put_row(fdo, obuffer, cell_type);

	xcoord1 = xcoord2 = outcellhd.west + (outcellhd.ew_res / 2);
	ycoord2 -= outcellhd.ns_res;
	ycoord1 = ycoord2;
	G_percent(row, outcellhd.rows - 1, 2);
    }

    Rast_close(fdo);

    if (have_colors > 0) {
	Rast_write_colors(mapname, G_mapset(), &colr);
	Rast_free_colors(&colr);
    }

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

    G_done_msg(NULL);
    exit(EXIT_SUCCESS);
}
Ejemplo n.º 22
0
int get_item(FILE * fd, int *type, long *cat, double **x, double **y,
	     int *count, struct Categories *labels)
{
    static double *X = NULL;
    static double *Y = NULL;
    static int nalloc = 0;
    char buf[1024];
    char lbl[1024];
    char east[256], north[256];
    double e, n;
    long offset;

    *cat = 0;
    *count = 0;
    *type = 0;

    /* scan until we find the start of a new feature */
    while (G_getl2(buf, sizeof buf, fd)) {
	/* skip comments and blank lines */
	if ((*buf == '#') || (*buf == '\0'))
	    continue;

	G_strip(buf);
	if (*buf == 'A' || *buf == 'a') {
	    *type = 'A';
	    break;
	}
	if (*buf == 'L' || *buf == 'l') {
	    *type = 'L';
	    break;
	}
	if (*buf == 'P' || *buf == 'p') {
	    *type = 'P';
	    break;
	}
    }
    if (*type == 0)
	return 0;

    /* read the feature's data */
    while (1) {
	offset = G_ftell(fd);

	if (!G_getl2(buf, (sizeof buf) - 1, fd))
	    break;

	/* skip comments and blank lines */
	if ((*buf == '#') || (*buf == '\0'))
	    continue;

	G_strip(buf);

	/* if we've found the next feature, rewind to the start of it and complete */
	if (*buf == 'A' || *buf == 'a' ||
	    *buf == 'L' || *buf == 'l' || *buf == 'P' || *buf == 'p') {
	    G_fseek(fd, offset, 0);
	    break;
	}

	/* if we found a cat (and optionally a label), read them and continue to scan */
	if (*buf == '=') {
	    if (sscanf(buf + 1, "%ld", cat) != 1)
		continue;
	    /* probably change this as G_getl2() doesn't store the new line (?) */
	    if (sscanf(buf + 1, "%ld%[^\n]", cat, lbl) == 2) {
		G_strip(lbl);
		Rast_set_c_cat((CELL*) cat, (CELL *) cat, lbl, labels);
	    }
	    continue;
	}
	if (sscanf(buf, "%s %s", east, north) != 2) {
	    G_warning(_("Illegal coordinate <%s, %s>, skipping."), east, north);
	    continue;
	}

	if (!G_scan_northing(north, &n, G_projection())) {
	    G_warning(_("Illegal north coordinate <%s>, skipping."), north);
	    continue;
	}

	if (!G_scan_easting(east, &e, G_projection())) {
	    G_warning(_("Illegal east coordinate <%s>, skipping."), east);
	    continue;
	}

	if (*count >= nalloc) {
	    nalloc += 32;
	    X = (double *)G_realloc(X, nalloc * sizeof(double));
	    Y = (double *)G_realloc(Y, nalloc * sizeof(double));
	}
	X[*count] = e;
	Y[*count] = n;
	(*count)++;
    }
    *x = X;
    *y = Y;
    return 1;
}
Ejemplo n.º 23
0
int main(int argc, char *argv[])
{
    char *terrainmap, *seedmap, *lakemap, *mapset;
    int rows, cols, in_terran_fd, out_fd, lake_fd, row, col, pases, pass;
    int lastcount, curcount, start_col = 0, start_row = 0;
    double east, north, area = 0, volume = 0;
    FCELL **in_terran, **out_water, water_level, max_depth = 0, min_depth = 0;
    FCELL water_window[3][3];
    struct Option *tmap_opt, *smap_opt, *wlvl_opt, *lake_opt, *sdxy_opt;
    struct Flag *negative_flag, *overwrite_flag;
    struct GModule *module;
    struct Colors colr;
    struct Cell_head window;
    struct History history;

    G_gisinit(argv[0]);
    
    module = G_define_module();
    module->keywords = _("raster, hydrology");
    module->description = _("Fills lake at given point to given level.");

    tmap_opt = G_define_option();
    tmap_opt->key = "dem";
    tmap_opt->key_desc = "name";
    tmap_opt->description = _("Name of terrain raster map (DEM)");
    tmap_opt->type = TYPE_STRING;
    tmap_opt->gisprompt = "old,cell,raster";
    tmap_opt->required = YES;

    wlvl_opt = G_define_option();
    wlvl_opt->key = "wl";
    wlvl_opt->description = _("Water level");
    wlvl_opt->type = TYPE_DOUBLE;
    wlvl_opt->required = YES;

    lake_opt = G_define_option();
    lake_opt->key = "lake";
    lake_opt->key_desc = "name";
    lake_opt->description = _("Name for output raster map with lake");
    lake_opt->type = TYPE_STRING;
    lake_opt->gisprompt = "new,cell,raster";
    lake_opt->required = NO;

    sdxy_opt = G_define_option();
    sdxy_opt->key = "xy";
    sdxy_opt->description = _("Seed point coordinates");
    sdxy_opt->type = TYPE_DOUBLE;
    sdxy_opt->key_desc = "east,north";
    sdxy_opt->required = NO;
    sdxy_opt->multiple = NO;

    smap_opt = G_define_option();
    smap_opt->key = "seed";
    smap_opt->key_desc = "name";
    smap_opt->description =
	_("Name of raster map with given starting point(s) (at least 1 cell > 0)");
    smap_opt->type = TYPE_STRING;
    smap_opt->gisprompt = "old,cell,raster";
    smap_opt->required = NO;

    negative_flag = G_define_flag();
    negative_flag->key = 'n';
    negative_flag->description =
	_("Use negative depth values for lake raster map");

    overwrite_flag = G_define_flag();
    overwrite_flag->key = 'o';
    overwrite_flag->description =
	_("Overwrite seed map with result (lake) map");

    if (G_parser(argc, argv))	/* Returns 0 if successful, non-zero otherwise */
	exit(EXIT_FAILURE);

    if (smap_opt->answer && sdxy_opt->answer)
	G_fatal_error(_("Both seed map and coordinates cannot be specified"));

    if (!smap_opt->answer && !sdxy_opt->answer)
	G_fatal_error(_("Seed map or seed coordinates must be set!"));

    if (sdxy_opt->answer && !lake_opt->answer)
	G_fatal_error(_("Seed coordinates and output map lake= must be set!"));

    if (lake_opt->answer && overwrite_flag->answer)
	G_fatal_error(_("Both lake and overwrite cannot be specified"));

    if (!lake_opt->answer && !overwrite_flag->answer)
	G_fatal_error(_("Output lake map or overwrite flag must be set!"));

    terrainmap = tmap_opt->answer;
    seedmap = smap_opt->answer;
    sscanf(wlvl_opt->answer, "%f", &water_level);
    lakemap = lake_opt->answer;

    /* If lakemap is set, write to it, else is set overwrite flag and we should write to seedmap. */
    if (lakemap) {
	lake_fd = G_open_raster_new(lakemap, 1);
	if (lake_fd < 0)
	    G_fatal_error(_("Unable to create raster map <%s>"), lakemap);
    }

    rows = G_window_rows();
    cols = G_window_cols();

    /* If we use x,y as seed... */
    if (sdxy_opt->answer) {
	G_get_window(&window);
	east = window.east;
	north = window.north;

	G_scan_easting(sdxy_opt->answers[0], &east, G_projection());
	G_scan_northing(sdxy_opt->answers[1], &north, G_projection());
	start_col = (int)G_easting_to_col(east, &window);
	start_row = (int)G_northing_to_row(north, &window);

	if (start_row < 0 || start_row > rows ||
	    start_col < 0 || start_col > cols)
	    G_fatal_error(_("Seed point outside the current region"));
    }

    /* Open terran map */
    mapset = G_find_cell2(terrainmap, "");
    if (mapset == NULL)
	G_fatal_error(_("Raster map <%s> not found"), terrainmap);

    in_terran_fd = G_open_cell_old(terrainmap, mapset);
    if (in_terran_fd < 0)
	G_fatal_error(_("Unable to open raster map <%s>"),
		      G_fully_qualified_name(terrainmap, mapset));

    /* Open seed map */
    if (smap_opt->answer) {
	mapset = G_find_cell2(seedmap, "");
	if (mapset == NULL)
	    G_fatal_error(_("Raster map <%s> not found"), seedmap);

	out_fd = G_open_cell_old(seedmap, mapset);
	if (out_fd < 0)
	    G_fatal_error(_("Unable to open raster map <%s>"),
			  G_fully_qualified_name(seedmap, mapset));
    }

    /* Pointers to rows. Row = ptr to 'col' size array. */
    in_terran = (FCELL **) G_malloc(rows * sizeof(FCELL *));
    out_water = (FCELL **) G_malloc(rows * sizeof(FCELL *));
    if (in_terran == NULL || out_water == NULL)
	G_fatal_error(_("G_malloc: out of memory"));


    G_debug(1, "Loading maps...");
    /* foo_rows[row] == array with data (2d array). */
    for (row = 0; row < rows; row++) {
	in_terran[row] = (FCELL *) G_malloc(cols * sizeof(FCELL));
	out_water[row] = (FCELL *) G_calloc(cols, sizeof(FCELL));

	/* In newly created space load data from file. */
	if (G_get_f_raster_row(in_terran_fd, in_terran[row], row) != 1)
	    G_fatal_error(_("Unable to read raster map <%s> row %d"),
			  terrainmap, row);

	if (smap_opt->answer)
	    if (G_get_f_raster_row(out_fd, out_water[row], row) != 1)
		G_fatal_error(_("Unable to read raster map <%s> row %d"),
			      seedmap, row);

	G_percent(row + 1, rows, 5);
    }

    /* Set seed point */
    if (sdxy_opt->answer)
	/* Check is water level higher than seed point */
	if (in_terran[start_row][start_col] >= water_level)
	    G_fatal_error(_("Given water level at seed point is below earth surface. "
			   "Increase water level or move seed point."));
    out_water[start_row][start_col] = 1;

    /* Close seed map for reading. */
    if (smap_opt->answer)
	G_close_cell(out_fd);

    /* Open output map for writing. */
    if (lakemap) {
	out_fd = lake_fd;
    }
    else {
	out_fd = G_open_raster_new(seedmap, 1);
	if (out_fd < 0)
	    G_fatal_error(_("Unable to create raster map <%s>"), seedmap);
    }

    /* More pases are renudant. Real pases count is controled by altered cell count. */
    pases = (int)(rows * cols) / 2;

    G_debug(1,
	    "Starting lake filling at level of %8.4f in %d passes. Percent done:",
	    water_level, pases);

    lastcount = 0;

    for (pass = 0; pass < pases; pass++) {
	G_debug(3, "Pass: %d", pass);
	curcount = 0;
	/* Move from left upper corner to right lower corner. */
	for (row = 0; row < rows; row++) {
	    for (col = 0; col < cols; col++) {
		/* Loading water data into window. */
		load_window_values(out_water, water_window, rows, cols, row,
				   col);

		/* Cheking presence of water. */
		if (is_near_water(water_window) == 1) {
		    if (in_terran[row][col] < water_level) {
			out_water[row][col] =
			    water_level - in_terran[row][col];
			curcount++;
		    }
		    else {
			out_water[row][col] = 0;	/* Cell is higher than water level -> NULL. */
		    }
		}
	    }
	}
	if (curcount == lastcount)
	    break;		/* We done. */
	lastcount = curcount;
	curcount = 0;
	/* Move backwards - from lower right corner to upper left corner. */
	for (row = rows - 1; row >= 0; row--) {
	    for (col = cols - 1; col >= 0; col--) {
		load_window_values(out_water, water_window, rows, cols, row,
				   col);

		if (is_near_water(water_window) == 1) {
		    if (in_terran[row][col] < water_level) {
			out_water[row][col] =
			    water_level - in_terran[row][col];
			curcount++;
		    }
		    else {
			out_water[row][col] = 0;
		    }
		}
	    }
	}
	G_percent(pass + 1, pases, 10);
	if (curcount == lastcount)
	    break;		/* We done. */
	lastcount = curcount;
    }				/*pases */

    G_percent(pases, pases, 10);	/* Show 100%. */

    save_map(out_water, out_fd, rows, cols, negative_flag->answer, &min_depth,
	     &max_depth, &area, &volume);

    G_message(_("Lake depth from %f to %f"), min_depth, max_depth);
    G_message(_("Lake area %f square meters"), area);
    G_message(_("Lake volume %f cubic meters"), volume);
    G_warning(_("Volume is correct only if lake depth (terrain raster map) is in meters"));

    /* Close all files. Lake map gets written only now. */
    G_close_cell(in_terran_fd);
    G_close_cell(out_fd);

    /* Add blue color gradient from light bank to dark depth */
    G_init_colors(&colr);
    if (negative_flag->answer == 1) {
	G_add_f_raster_color_rule(&max_depth, 0, 240, 255,
				  &min_depth, 0, 50, 170, &colr);
    }
    else {
	G_add_f_raster_color_rule(&min_depth, 0, 240, 255,
				  &max_depth, 0, 50, 170, &colr);
    }

    if (G_write_colors(lakemap, G_mapset(), &colr) != 1)
	G_fatal_error(_("Unable to read color file of raster map <%s>"),
		      lakemap);

    G_short_history(lakemap, "raster", &history);
    G_command_history(&history);
    G_write_history(lakemap, &history);

    return EXIT_SUCCESS;
}
Ejemplo n.º 24
0
int main(int argc, char *argv[])
{
    struct GModule *module;
    struct Option *in_opt, *layer_opt, *out_opt, *length_opt, *units_opt, *vertices_opt;
    
    struct Map_info In, Out;
    struct line_pnts *Points, *Points2;
    struct line_cats *Cats;

    int line, nlines, layer;
    double length = -1;
    int vertices = 0;
    double (*line_length) ();
    int latlon = 0;

    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("vector"));
    G_add_keyword(_("geometry"));
    module->description = _("Splits vector lines to shorter segments.");
    
    in_opt = G_define_standard_option(G_OPT_V_INPUT);

    layer_opt = G_define_standard_option(G_OPT_V_FIELD_ALL);

    out_opt = G_define_standard_option(G_OPT_V_OUTPUT);
    
    length_opt = G_define_option();
    length_opt->key = "length";
    length_opt->type = TYPE_DOUBLE;
    length_opt->required = NO;
    length_opt->multiple = NO;
    length_opt->description = _("Maximum segment length");

    units_opt = G_define_option();
    units_opt->key = "units";
    units_opt->type = TYPE_STRING;
    units_opt->required = NO;
    units_opt->multiple = NO;
    units_opt->options = "meters,kilometers,feet,miles,nautmiles";
    units_opt->answer = "meters";
    units_opt->description = _("Length units");
    
    vertices_opt = G_define_option();
    vertices_opt->key = "vertices";
    vertices_opt->type = TYPE_INTEGER;
    vertices_opt->required = NO;
    vertices_opt->multiple = NO;
    vertices_opt->description = _("Maximum number of vertices in segment");
    
    if (G_parser(argc, argv))
	exit(EXIT_FAILURE);
    
    if ((length_opt->answer && vertices_opt->answer) ||
	!(length_opt->answer || vertices_opt->answer))
	G_fatal_error(_("Use either length or vertices"));

    line_length = NULL;

    if (length_opt->answer) {
	length = atof(length_opt->answer);
	if (length <= 0)
	    G_fatal_error(_("Length must be positive but is %g"), length);

	/* convert length to meters */
	if (strcmp(units_opt->answer, "meters") == 0)
	    /* do nothing */ ;
	else if (strcmp(units_opt->answer, "kilometers") == 0)
	    length *= FROM_KILOMETERS;
	else if (strcmp(units_opt->answer, "feet") == 0)
	    length *= FROM_FEET;
	else if (strcmp(units_opt->answer, "miles") == 0)
	    length *= FROM_MILES;
	else if (strcmp(units_opt->answer, "nautmiles") == 0)
	    length *= FROM_NAUTMILES;
	else
	    G_fatal_error(_("Unknown unit %s"), units_opt->answer); 

	/* set line length function */
	if ((latlon = (G_projection() == PROJECTION_LL)) == 1)
	    line_length = Vect_line_geodesic_length;
	else {
	    double factor;
	    
	    line_length = Vect_line_length;
	    
	    /* convert length to map units */
	    if ((factor = G_database_units_to_meters_factor()) == 0)
		G_fatal_error(_("Can not get projection units"));
	    else {
		/* meters to units */
		length = length / factor;
	    }
	}
	G_verbose_message(_("length in %s: %g"), (latlon ? "meters" : "map units"), length);
    }

    if (vertices_opt->answer) {
	vertices = atoi(vertices_opt->answer);
	if (vertices < 2)
	    G_fatal_error(_("Number of vertices must be at least 2"));
    }
    
    Vect_set_open_level(2);
    Vect_open_old2(&In, in_opt->answer, "", layer_opt->answer);
    layer = Vect_get_field_number(&In, layer_opt->answer);
    
    Vect_open_new(&Out, out_opt->answer, Vect_is_3d(&In));
    
    Vect_copy_head_data(&In, &Out);
    Vect_hist_copy(&In, &Out);
    Vect_hist_command(&Out);
    Vect_copy_tables(&In, &Out, layer);
    
    Points = Vect_new_line_struct();
    Points2 = Vect_new_line_struct();
    Cats = Vect_new_cats_struct();

    nlines = Vect_get_num_lines(&In);

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

	G_percent(line, nlines, 1);

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

	ltype = Vect_read_line(&In, Points, Cats, line);

	if (layer != -1 && !Vect_cat_get(Cats, layer, NULL))
	  continue;

	if (ltype & GV_LINES) {
	    if (length > 0) {
		double l, from, to, step;

		l = line_length(Points);

		if (l <= length) {
		    Vect_write_line(&Out, ltype, Points, Cats);
		}
		else {
		    int n, i;

		    n = ceil(l / length);
		    if (latlon)
			l = Vect_line_length(Points);

		    step = l / n;
		    from = 0.;

		    for (i = 0; i < n; i++) {
			int ret;
			double x, y, z;

			if (i == n - 1) {
			    to = l;	/* to be sure that it goes to end */
			}
			else {
			    to = from + step;
			}

			ret = Vect_line_segment(Points, from, to, Points2);
			if (ret == 0) {
			    G_warning(_("Unable to make line segment: %f - %f (line length = %f)"),
				      from, to, l);
			    continue;
			}

			/* To be sure that the coordinates are identical */
			if (i > 0) {
			    Points2->x[0] = x;
			    Points2->y[0] = y;
			    Points2->z[0] = z;
			}
			if (i == n - 1) {
			    Points2->x[Points2->n_points - 1] =
				Points->x[Points->n_points - 1];
			    Points2->y[Points2->n_points - 1] =
				Points->y[Points->n_points - 1];
			    Points2->z[Points2->n_points - 1] =
				Points->z[Points->n_points - 1];
			}

			Vect_write_line(&Out, ltype, Points2, Cats);

			/* last point */
			x = Points2->x[Points2->n_points - 1];
			y = Points2->y[Points2->n_points - 1];
			z = Points2->z[Points2->n_points - 1];

			from += step;
		    }
		}
	    }
	    else {
		int start = 0;	/* number of coordinates written */

		while (start < Points->n_points - 1) {
		    int i, v;

		    Vect_reset_line(Points2);
		    for (i = 0; i < vertices; i++) {
			v = start + i;
			if (v == Points->n_points)
			    break;

			Vect_append_point(Points2, Points->x[v], Points->y[v],
					  Points->z[v]);
		    }

		    Vect_write_line(&Out, ltype, Points2, Cats);

		    start = v;
		}
	    }
	}
	else {
	    Vect_write_line(&Out, ltype, Points, Cats);
	}
    }

    Vect_close(&In);
    Vect_build(&Out);
    Vect_close(&Out);
    
    exit(EXIT_SUCCESS);
}
Ejemplo n.º 25
0
void print_info(const struct Map_info *Map)
{
    int i;
    char line[100];
    char tmp1[100], tmp2[100];

    struct bound_box box;
    
    divider('+');
    if (Vect_maptype(Map) & (GV_FORMAT_OGR | GV_FORMAT_OGR_DIRECT)) {
	/* for OGR format print also datasource and layer */
	sprintf(line, "%-17s%s", _("OGR layer:"),
		Vect_get_ogr_layer_name(Map));
	printline(line);
	sprintf(line, "%-17s%s", _("OGR datasource:"),
		Vect_get_ogr_dsn_name(Map));
	printline(line);
    }
    else {
	sprintf(line, "%-17s%s", _("Name:"),
		Vect_get_name(Map));
	printline(line);
	sprintf(line, "%-17s%s", _("Mapset:"),
		Vect_get_mapset(Map));
	printline(line);
    }

    sprintf(line, "%-17s%s", _("Location:"),
	    G_location());
    printline(line);
    sprintf(line, "%-17s%s", _("Database:"),
	    G_gisdbase());
    printline(line);
    sprintf(line, "%-17s%s", _("Title:"),
	    Vect_get_map_name(Map));
    printline(line);
    sprintf(line, "%-17s1:%d", _("Map scale:"),
	    Vect_get_scale(Map));
    printline(line);
    
    if (Vect_maptype(Map) & (GV_FORMAT_OGR | GV_FORMAT_OGR_DIRECT)) {
	sprintf(line, "%-17s%s (%s)", _("Map format:"),
		Vect_maptype_info(Map), Vect_get_ogr_format_info(Map));
    }
    else {
	sprintf(line, "%-17s%s", _("Map format:"),
		Vect_maptype_info(Map));
    }
    
    printline(line);
    sprintf(line, "%-17s%s", _("Name of creator:"),
	    Vect_get_person(Map));
    printline(line);
    sprintf(line, "%-17s%s", _("Organization:"),
	    Vect_get_organization(Map));
    printline(line);
    sprintf(line, "%-17s%s", _("Source date:"),
	    Vect_get_map_date(Map));
    printline(line);
    
    divider('|');
    
    sprintf(line, "  %s: %s (%s: %i)",
	    _("Type of map"), _("vector"), _("level"), Vect_level(Map));
    
    printline(line);
    
    if (Vect_level(Map) > 0) {
	printline("");
	sprintf(line,
		"  %-24s%-9d       %-22s%-9d",
		_("Number of points:"), 
		Vect_get_num_primitives(Map, GV_POINT),
		_("Number of centroids:"),
		Vect_get_num_primitives(Map, GV_CENTROID));
	printline(line);
	sprintf(line,
		"  %-24s%-9d       %-22s%-9d",
		_("Number of lines:"),
		Vect_get_num_primitives(Map, GV_LINE),
		_("Number of boundaries:"),
		Vect_get_num_primitives(Map, GV_BOUNDARY));
	printline(line);
	sprintf(line,
		"  %-24s%-9d       %-22s%-9d",
		_("Number of areas:"),
		Vect_get_num_areas(Map),
		_("Number of islands:"),
		Vect_get_num_islands(Map));
	printline(line);
	if (Vect_is_3d(Map)) {
	    sprintf(line,
		    "  %-24s%-9d       %-22s%-9d",
		    _("Number of faces:"),
		    Vect_get_num_primitives(Map, GV_FACE),
		    _("Number of kernels:"),
		    Vect_get_num_primitives(Map, GV_KERNEL));
	    printline(line);
	    sprintf(line,
		    "  %-24s%-9d       %-22s%-9d",
		    _("Number of volumes:"),
		    Vect_get_num_volumes(Map),
		    _("Number of holes:"),
		    Vect_get_num_holes(Map));
	    printline(line);
	}
	printline("");
	
	sprintf(line, "  %-24s%s",
		_("Map is 3D:"),
		Vect_is_3d(Map) ? _("Yes") : _("No"));
	printline(line);
	sprintf(line, "  %-24s%-9d",
		_("Number of dblinks:"),
		Vect_get_num_dblinks(Map));
	printline(line);
    }
    
    printline("");
    /* this differs from r.info in that proj info IS taken from the map here, not the location settings */
    /* Vect_get_proj_name() and _zone() are typically unset?! */
    if (G_projection() == PROJECTION_UTM)
	sprintf(line, "  %s: %s (%s %d)",
		_("Projection:"),
		Vect_get_proj_name(Map),
		_("zone"), Vect_get_zone(Map));
    else
	sprintf(line, "  %s: %s",
		_("Projection"),
		Vect_get_proj_name(Map));
    
    printline(line);
    printline("");
    
    Vect_get_map_box(Map, &box);
    
    G_format_northing(box.N, tmp1, G_projection());
    G_format_northing(box.S, tmp2, G_projection());
    sprintf(line, "              %c: %17s    %c: %17s",
	    'N', tmp1, 'S', tmp2);
    printline(line);
    
    G_format_easting(box.E, tmp1, G_projection());
    G_format_easting(box.W, tmp2, G_projection());
    sprintf(line, "              %c: %17s    %c: %17s",
	    'E', tmp1, 'W', tmp2);
    printline(line);
    
    if (Vect_is_3d(Map)) {
	format_double(box.B, tmp1);
	format_double(box.T, tmp2);
	sprintf(line, "              %c: %17s    %c: %17s",
		'B', tmp1, 'T', tmp2);
	printline(line);
    }
    printline("");

    format_double(Vect_get_thresh(Map), tmp1);
    sprintf(line, "  %s: %s", _("Digitization threshold"), tmp1);
    printline(line);
    sprintf(line, "  %s:", _("Comment"));
    printline(line);
    sprintf(line, "    %s", Vect_get_comment(Map));
    printline(line);
    divider('+');
    fprintf(stdout, "\n");
}
Ejemplo n.º 26
0
int main(int argc, char **argv)
{
    struct Option *input_opt, *output_opt, *afield_opt, *nfield_opt,
	*tfield_opt, *tucfield_opt, *afcol, *abcol, *ncol, *type_opt;
    struct Option *max_dist, *file_opt;
    struct Flag *geo_f, *segments_f, *turntable_f;
    struct GModule *module;
    struct Map_info In, Out;
    int type, afield, nfield, tfield, tucfield, geo;
    double maxdist;

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

    module = G_define_module();
    G_add_keyword(_("vector"));
    G_add_keyword(_("network"));
    G_add_keyword(_("shortest path"));
    module->description = _("Finds shortest path on vector network.");

    input_opt = G_define_standard_option(G_OPT_V_INPUT);
    output_opt = G_define_standard_option(G_OPT_V_OUTPUT);

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

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

    nfield_opt = G_define_standard_option(G_OPT_V_FIELD);
    nfield_opt->key = "node_layer";
    nfield_opt->answer = "2";
    nfield_opt->required = YES;
    nfield_opt->label = _("Node layer");

    file_opt = G_define_standard_option(G_OPT_F_INPUT);
    file_opt->key = "file";
    file_opt->required = NO;
    file_opt->description = _("Name of file containing start and end points. "
			      "If not given, read from stdin");

    afcol = G_define_option();
    afcol->key = "arc_column";
    afcol->type = TYPE_STRING;
    afcol->required = NO;
    afcol->description = _("Arc forward/both direction(s) cost column (number)");
    afcol->guisection = _("Cost");

    abcol = G_define_option();
    abcol->key = "arc_backward_column";
    abcol->type = TYPE_STRING;
    abcol->required = NO;
    abcol->description = _("Arc backward direction cost column (number)");
    abcol->guisection = _("Cost");

    ncol = G_define_option();
    ncol->key = "node_column";
    ncol->type = TYPE_STRING;
    ncol->required = NO;
    ncol->description = _("Node cost column (number)");
    ncol->guisection = _("Cost");

    max_dist = G_define_option();
    max_dist->key = "dmax";
    max_dist->type = TYPE_DOUBLE;
    max_dist->required = NO;
    max_dist->answer = "1000";
    max_dist->label = _("Maximum distance to the network");
    max_dist->description = _("If start/end are given as coordinates. "
			      "If start/end point is outside this threshold, "
			      "the path is not found "
			      "and error message is printed. To speed up the process, keep this "
			      "value as low as possible.");

    turntable_f = G_define_flag();
    turntable_f->key = 't';
    turntable_f->description = _("Use turntable");
    turntable_f->guisection = _("Turntable");

    tfield_opt = G_define_standard_option(G_OPT_V_FIELD);
    tfield_opt->key = "turn_layer";
    tfield_opt->answer = "3";
    tfield_opt->label = _("Layer with turntable");
    tfield_opt->description =
	_("Relevant only with -t flag");
    tfield_opt->guisection = _("Turntable");

    tucfield_opt = G_define_standard_option(G_OPT_V_FIELD);
    tucfield_opt->key = "turn_cat_layer";
    tucfield_opt->answer = "4";
    tucfield_opt->label = _("Layer with unique categories used in turntable");
    tucfield_opt->description =
	_("Relevant only with -t flag");
    tucfield_opt->guisection = _("Turntable");

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

    segments_f = G_define_flag();
    segments_f->key = 's';
    segments_f->description = _("Write output as original input segments, "
				"not each path as one line.");

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

    type = Vect_option_to_types(type_opt);
    maxdist = atof(max_dist->answer);

    if (geo_f->answer) {
	geo = 1;
	if (G_projection() != PROJECTION_LL)
	    G_warning(_("The current projection is not longitude-latitude"));
    }
    else
	geo = 0;

    Vect_check_input_output_name(input_opt->answer, output_opt->answer,
				 G_FATAL_EXIT);

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

    afield = Vect_get_field_number(&In, afield_opt->answer);
    nfield = Vect_get_field_number(&In, nfield_opt->answer);
    tfield = Vect_get_field_number(&In, tfield_opt->answer);
    tucfield = Vect_get_field_number(&In, tucfield_opt->answer);

    if (1 > Vect_open_new(&Out, output_opt->answer, Vect_is_3d(&In))) {
	Vect_close(&In);
	G_fatal_error(_("Unable to create vector map <%s>"),
		      output_opt->answer);
    }
    Vect_hist_command(&Out);

    if (turntable_f->answer)
	Vect_net_ttb_build_graph(&In, type, afield, nfield, tfield, tucfield,
				 afcol->answer, abcol->answer, ncol->answer,
				 geo, 0);
    else
	Vect_net_build_graph(&In, type, afield, nfield, afcol->answer,
			     abcol->answer, ncol->answer, geo, 0);

    path(&In, &Out, file_opt->answer, nfield, maxdist, segments_f->answer,
	 tucfield, turntable_f->answer);

    Vect_close(&In);

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

    exit(EXIT_SUCCESS);
}
Ejemplo n.º 27
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.º 28
0
int G_site_put_new(FILE * fptr, Site * s, int has_cat)

/* Writes a site to file open on fptr. */
{
    char ebuf[MAX_SITE_STRING], nbuf[MAX_SITE_STRING];
    char xbuf[MAX_SITE_STRING], buf[MAX_SITE_LEN];
    static int format_double();
    int fmt, i, j, k;
    int G_format_northing(), G_format_easting(), G_projection();

    fmt = G_projection();

    G_format_northing(s->north, nbuf, fmt);
    G_format_easting(s->east, ebuf, fmt);
    sprintf(buf, "%s|%s|", ebuf, nbuf);
    for (i = 0; i < s->dim_alloc; ++i) {
	format_double(s->dim[i], nbuf);
	sprintf(xbuf, "%s|", nbuf);
	strcat(buf, xbuf);
    }

    if (has_cat) {
	switch (s->cattype) {
	case CELL_TYPE:
	    sprintf(xbuf, "#%d ", s->ccat);
	    strcat(buf, xbuf);
	    break;
	case FCELL_TYPE:
	    sprintf(xbuf, "#%g ", s->fcat);
	    strcat(buf, xbuf);
	    break;
	case DCELL_TYPE:
	    sprintf(xbuf, "#%g ", s->dcat);
	    strcat(buf, xbuf);
	    break;
	}
    }
    else {			/* no cat there, so data in plain x,y,z format will be imported   12/99 MN */

	/* we create a #cat entry in site_list from the current site number 11/99 */
	sprintf(xbuf, "#%d ", loop);
	loop++;
	strcat(buf, xbuf);
    }

    /* now import attributes */
    for (i = 0; i < s->dbl_alloc; ++i) {
	format_double(s->dbl_att[i], nbuf);
	sprintf(xbuf, "%%%s ", nbuf);
	strcat(buf, xbuf);
    }

    for (i = 0; i < s->str_alloc; ++i) {
	if (strlen(s->str_att[i]) != 0) {
	    /* escape double quotes */
	    j = k = 0;
	    if (G_index(s->str_att[i], DQUOTE) != (char *)NULL) {
		while (!isnull(s->str_att[i][j])) {
		    if (isquote(s->str_att[i][j])) {
			xbuf[k++] = BSLASH;
			xbuf[k++] = DQUOTE;
		    }
		    else if (isbslash(s->str_att[i][j])) {
			xbuf[k++] = BSLASH;
			xbuf[k++] = BSLASH;
		    }
		    else
			xbuf[k++] = s->str_att[i][j];
		    j++;
		}
		xbuf[k] = (char)NULL;
	    }
	    else
		strcpy(xbuf, s->str_att[i]);

	    strcpy(s->str_att[i], xbuf);

	    if (G_index(s->str_att[i], SPACE) != (char *)NULL)
		sprintf(xbuf, "@\"%s\" ", s->str_att[i]);
	    else
		sprintf(xbuf, "@%s ", s->str_att[i]);

	    strcat(buf, xbuf);
	}
    }
    fprintf(fptr, "%s\n", buf);
    return 0;
}
Ejemplo n.º 29
0
Archivo: main.c Proyecto: caomw/grass
int main(int argc, char *argv[])
{
    char *name, *outfile;
    const char *unit;
    int unit_id;
    double factor;
    int fd, projection;
    FILE *fp, *coor_fp;
    double res;
    char *null_string;
    char ebuf[256], nbuf[256], label[512], formatbuff[256];
    char b1[100], b2[100];
    int n;
    int havefirst = FALSE;
    int coords = 0, i, k = -1;
    double e1, e2, n1, n2;
    RASTER_MAP_TYPE data_type;
    struct Cell_head window;
    struct
    {
	struct Option *opt1, *profile, *res, *output, *null_str, *coord_file, *units;
	struct Flag *g, *c, *m;
    }
    parm;
    struct GModule *module;

    G_gisinit(argv[0]);

    /* Set description */
    module = G_define_module();
    G_add_keyword(_("raster"));
    G_add_keyword(_("profile"));
    module->description =
	_("Outputs the raster map layer values lying on user-defined line(s).");

    parm.opt1 = G_define_standard_option(G_OPT_R_INPUT);

    parm.output = G_define_standard_option(G_OPT_F_OUTPUT);
    parm.output->required = NO;
    parm.output->answer = "-";
    parm.output->description =
	_("Name of file for output (use output=- for stdout)");

    parm.profile = G_define_standard_option(G_OPT_M_COORDS);
    parm.profile->required = NO;
    parm.profile->multiple = YES;
    parm.profile->description = _("Profile coordinate pairs");

    parm.coord_file = G_define_standard_option(G_OPT_F_INPUT);
    parm.coord_file->key = "file";
    parm.coord_file->required = NO;
    parm.coord_file->label =
	_("Name of input file containing coordinate pairs");
    parm.coord_file->description =
	_("Use instead of the 'coordinates' option. "
	  "\"-\" reads from stdin.");

    parm.res = G_define_option();
    parm.res->key = "resolution";
    parm.res->type = TYPE_DOUBLE;
    parm.res->required = NO;
    parm.res->description =
	_("Resolution along profile (default = current region resolution)");

    parm.null_str = G_define_option();
    parm.null_str->key = "null";
    parm.null_str->type = TYPE_STRING;
    parm.null_str->required = NO;
    parm.null_str->answer = "*";
    parm.null_str->description = _("Character to represent no data cell");

    parm.g = G_define_flag();
    parm.g->key = 'g';
    parm.g->description =
	_("Output easting and northing in first two columns of four column output");

    parm.c = G_define_flag();
    parm.c->key = 'c';
    parm.c->description =
	_("Output RRR:GGG:BBB color values for each profile point");

    parm.units = G_define_standard_option(G_OPT_M_UNITS);
    parm.units->options = "meters,kilometers,feet,miles";
    parm.units->label = parm.units->description;
    parm.units->description = _("If units are not specified, current location units are used. "
                                "Meters are used by default in geographic (latlon) locations.");

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

    clr = 0;
    if (parm.c->answer)
	clr = 1;		/* color output */

    null_string = parm.null_str->answer;

    if ((parm.profile->answer && parm.coord_file->answer) ||
	(!parm.profile->answer && !parm.coord_file->answer))
	G_fatal_error(_("Either use profile option or coordinate_file "
			" option, but not both"));

    G_get_window(&window);
    projection = G_projection();

    /* get conversion factor and units name */
    if (parm.units->answer) {
        unit_id = G_units(parm.units->answer);
        factor = 1. / G_meters_to_units_factor(unit_id);
        unit = G_get_units_name(unit_id, 1, 0);
    }
    /* keep meters in case of latlon */
    else if (projection == PROJECTION_LL) {
        factor = 1;
        unit = "meters";
    } 
    else {
        /* get conversion factor to current units */
        unit = G_database_unit_name(1);
        factor = G_database_units_to_meters_factor();
    }

    if (parm.res->answer) {
	res = atof(parm.res->answer);
	/* Catch bad resolution ? */
	if (res <= 0)
	    G_fatal_error(_("Illegal resolution %g [%s]"), res / factor, unit);
    }
    else {
	/* Do average of EW and NS res */
	res = (window.ew_res + window.ns_res) / 2;
    }

    G_message(_("Using resolution: %g [%s]"), res / factor, unit);

    G_begin_distance_calculations();

    /* Open Input File for reading */
    /* Get Input Name */
    name = parm.opt1->answer;
    if (parm.g->answer)
	coords = 1;

    /* Open Raster File */
    fd = Rast_open_old(name, "");

    /* initialize color structure */
    if (clr)
	Rast_read_colors(name, "", &colors);

    /* Open ASCII file for output or stdout */
    outfile = parm.output->answer;

    if ((strcmp("-", outfile)) == 0) {
	fp = stdout;
    }
    else if (NULL == (fp = fopen(outfile, "w")))
	G_fatal_error(_("Unable to open file <%s>"), outfile);

    /* Get Raster Type */
    data_type = Rast_get_map_type(fd);
    /* Done with file */

    /* Show message giving output format */
    G_message(_("Output columns:"));
    if (coords == 1)
	sprintf(formatbuff,
		_("Easting, Northing, Along track dist. [%s], Elevation"), unit);
    else
	sprintf(formatbuff, _("Along track dist. [%s], Elevation"), unit);
    if (clr)
	strcat(formatbuff, _(" RGB color"));
    G_message(formatbuff);

    /* Get Profile Start Coords */
    if (parm.coord_file->answer) {
	if (strcmp("-", parm.coord_file->answer) == 0)
	    coor_fp = stdin;
	else
	    coor_fp = fopen(parm.coord_file->answer, "r");

	if (coor_fp == NULL)
	    G_fatal_error(_("Could not open <%s>"), parm.coord_file->answer);


	for (n = 1; input(b1, ebuf, b2, nbuf, label, coor_fp); n++) {
	    G_debug(4, "stdin line %d: ebuf=[%s]  nbuf=[%s]", n, ebuf, nbuf);
	    if (!G_scan_easting(ebuf, &e2, G_projection()) ||
		!G_scan_northing(nbuf, &n2, G_projection()))
		G_fatal_error(_("Invalid coordinates %s %s"), ebuf, nbuf);

	    if (havefirst)
		do_profile(e1, e2, n1, n2, coords, res, fd, data_type,
			   fp, null_string, unit, factor);
	    e1 = e2;
	    n1 = n2;
	    havefirst = TRUE;
	}

	if (coor_fp != stdin)
	    fclose(coor_fp);
    }
    else {
	/* Coords given on the Command Line using the profile= option */
	for (i = 0; parm.profile->answers[i]; i += 2) {
	    /* Test for number coordinate pairs */
	    k = i;
	}

	if (k == 0) {
	    /* Only one coordinate pair supplied */
	    G_scan_easting(parm.profile->answers[0], &e1, G_projection());
	    G_scan_northing(parm.profile->answers[1], &n1, G_projection());
	    e2 = e1;
	    n2 = n1;

	    /* Get profile info */
	    do_profile(e1, e2, n1, n2, coords, res, fd, data_type, fp,
		       null_string, unit, factor);
	}
	else {
	    for (i = 0; i <= k - 2; i += 2) {
		G_scan_easting(parm.profile->answers[i], &e1, G_projection());
		G_scan_northing(parm.profile->answers[i + 1], &n1,
				G_projection());
		G_scan_easting(parm.profile->answers[i + 2], &e2,
			       G_projection());
		G_scan_northing(parm.profile->answers[i + 3], &n2,
				G_projection());

		/* Get profile info */
		do_profile(e1, e2, n1, n2, coords, res, fd, data_type,
			   fp, null_string, unit, factor);

	    }
	}
    }

    Rast_close(fd);
    fclose(fp);

    if (clr)
	Rast_free_colors(&colors);

    exit(EXIT_SUCCESS);
}				/* Done with main */
Ejemplo n.º 30
0
int main(int argc, char *argv[])
{

    struct GModule *module;
    struct Option *coord, *out_file, *min, *max, *mult;
    struct Flag *flag;
    int *int_buf;
    struct Cell_head w;
    struct History history;
    int cellfile;
    double east, north, pt[2], cur[2], row, col, fmult;
    double fmin, fmax;
    int binary;

    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("raster"));
    G_add_keyword(_("buffer"));
    G_add_keyword(_("geometry"));
    G_add_keyword(_("circle"));
    module->description =
	_("Creates a raster map containing concentric "
	  "rings around a given point.");

    out_file = G_define_standard_option(G_OPT_R_OUTPUT);

    coord = G_define_standard_option(G_OPT_M_COORDS);
    coord->required = YES;
    coord->description = _("The coordinate of the center (east,north)");

    min = G_define_option();
    min->key = "min";
    min->type = TYPE_DOUBLE;
    min->required = NO;
    min->description = _("Minimum radius for ring/circle map (in meters)");

    max = G_define_option();
    max->key = "max";
    max->type = TYPE_DOUBLE;
    max->required = NO;
    max->description = _("Maximum radius for ring/circle map (in meters)");

    mult = G_define_option();
    mult->key = "multiplier";
    mult->type = TYPE_DOUBLE;
    mult->required = NO;
    mult->description = _("Data value multiplier");

    flag = G_define_flag();
    flag->key = 'b';
    flag->description = _("Generate binary raster map");

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

    G_scan_easting(coord->answers[0], &east, G_projection());
    G_scan_northing(coord->answers[1], &north, G_projection());
    pt[0] = east;
    pt[1] = north;

    fmult = 1.0;

    if (min->answer)
	sscanf(min->answer, "%lf", &fmin);
    else
	fmin = 0;

    if (max->answer)
	sscanf(max->answer, "%lf", &fmax);
    else
	fmax = HUGE_VAL;

    if (fmin > fmax)
	G_fatal_error(_("Please specify a radius in which min < max"));

    if (mult->answer)
	if (1 != sscanf(mult->answer, "%lf", &fmult))
	    fmult = 1.0;

    /* nonsense test */
    if (flag->answer && (!min->answer && !max->answer))
	G_fatal_error(_("Please specify min and/or max radius when "
			"using the binary flag"));

    if (flag->answer)
	binary = 1;		/* generate binary pattern only, useful for MASK */
    else
	binary = 0;

    G_get_set_window(&w);

    cellfile = Rast_open_c_new(out_file->answer);

    int_buf = (int *)G_malloc(w.cols * sizeof(int));
    {
	int c;

	for (row = 0; row < w.rows; row++) {
	    G_percent(row, w.rows, 2);
	    cur[1] = Rast_row_to_northing(row + 0.5, &w);
	    for (col = 0; col < w.cols; col++) {
		c = col;
		cur[0] = Rast_col_to_easting(col + 0.5, &w);
		int_buf[c] =
		    (int)(distance(pt, cur, fmin, fmax, binary) * fmult);
		if (int_buf[c] == 0)
		    Rast_set_null_value(&int_buf[c], 1, CELL_TYPE);
	    }
	    Rast_put_row(cellfile, int_buf, CELL_TYPE);

	}
    }
    G_free(int_buf);
    Rast_close(cellfile);
    Rast_short_history(out_file->answer, "raster", &history);
    Rast_command_history(&history);
    Rast_write_history(out_file->answer, &history);

    G_done_msg(_("Raster map <%s> created."),
	       out_file->answer);
    
    return (EXIT_SUCCESS);
}