1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397
|
#!/usr/bin/env python3
############################################################################
#
# MODULE: v.import
#
# AUTHOR(S): Markus Metz
#
# PURPOSE: Import and reproject vector data on the fly
#
# COPYRIGHT: (C) 2015 by GRASS development team
#
# This program is free software under the GNU General
# Public License (>=v2). Read the file COPYING that
# comes with GRASS for details.
#
#############################################################################
# %module
# % description: Imports vector data into a GRASS vector map using OGR library and reprojects on the fly.
# % keyword: vector
# % keyword: import
# % keyword: projection
# %end
# %option
# % key: input
# % type: string
# % required: yes
# % description: Name of OGR datasource to be imported
# % gisprompt: old,datasource,datasource
# % guisection: Input
# %end
# %option
# % key: layer
# % type: string
# % multiple: yes
# % description: OGR layer name. If not given, all available layers are imported
# % guisection: Input
# % gisprompt: old,datasource_layer,datasource_layer
# %end
# %option G_OPT_V_OUTPUT
# % description: Name for output vector map (default: input)
# % required: no
# % guisection: Output
# %end
# %option
# % key: extent
# % type: string
# % options: input,region
# % answer: input
# % description: Output vector map extent
# % descriptions: input;extent of input map;region;extent of current region
# % guisection: Output
# %end
# %option
# % key: encoding
# % type: string
# % label: Encoding value for attribute data
# % descriptions: Overrides encoding interpretation, useful when importing ESRI Shapefile
# % guisection: Output
# %end
# %option
# % key: snap
# % type: double
# % label: Snapping threshold for boundaries (map units)
# % description: A suitable threshold is estimated during import
# % answer: -1
# % guisection: Output
# %end
# %option
# % key: epsg
# % type: integer
# % options: 1-1000000
# % guisection: Input SRS
# % description: EPSG projection code
# %end
# %option
# % key: datum_trans
# % type: integer
# % options: -1-100
# % guisection: Input SRS
# % label: Index number of datum transform parameters
# % description: -1 to list available datum transform parameters
# %end
# %flag
# % key: f
# % description: List supported OGR formats and exit
# % suppress_required: yes
# %end
# %flag
# % key: l
# % description: List available OGR layers in data source and exit
# %end
# %flag
# % key: o
# % label: Override projection check (use current project's CRS)
# % description: Assume that the dataset has the same coordinate reference system (CRS) as the current project
# %end
import sys
import os
import atexit
import xml.etree.ElementTree as ET # only needed for GDAL version < 2.4.1
import re # only needed for GDAL version < 2.4.1
import grass.script as grass
from grass.exceptions import CalledModuleError
# initialize global vars
TMPLOC = None
SRCGISRC = None
TGTGISRC = None
GISDBASE = None
def cleanup():
if TGTGISRC:
os.environ["GISRC"] = str(TGTGISRC)
# remove temp location
if TMPLOC:
grass.try_rmdir(os.path.join(GISDBASE, TMPLOC))
if SRCGISRC:
grass.try_remove(SRCGISRC)
def gdal_version():
"""Returns the GDAL version as tuple"""
version = grass.parse_command("g.version", flags="reg")["gdal"]
return version
def GDAL_COMPUTE_VERSION(maj, min, rev):
return (maj) * 1000000 + (min) * 10000 + (rev) * 100
def is_projection_matching(OGRdatasource, layer):
"""Returns True if current location projection
matches dataset projection, otherwise False"""
try:
grass.run_command(
"v.in.ogr", input=OGRdatasource, layer=layer, flags="j", quiet=True
)
return True
except CalledModuleError:
return False
def fix_gfsfile(input):
"""Fixes the gfs file of an gml file by adding the SRSName
:param input: gml file name to import with v.import
:type input: str
"""
# get srs string from gml file
gmltree = ET.parse(input)
gmlroot = gmltree.getroot()
gmlstring = ET.tostring(gmlroot).decode("utf-8")
srs_str = re.search(r"srsname=\"(.*?)\"", gmlstring.lower()).groups()[0]
# set srs string in gfs file
gml = os.path.basename(input).split(".")[-1]
gfsfile = input.replace(gml, "gfs")
if os.path.isfile(gfsfile):
tree = ET.parse(gfsfile)
root = tree.getroot()
gfsstring = ET.tostring(root).decode("utf-8")
if "srsname" not in gfsstring.lower():
for featClass in root.findall("GMLFeatureClass"):
ET.SubElement(featClass, "SRSName").text = srs_str
tree.write(gfsfile)
def main():
global TMPLOC, SRCGISRC, TGTGISRC, GISDBASE
overwrite = grass.overwrite()
# list formats and exit
if flags["f"]:
grass.run_command("v.in.ogr", flags="f")
return 0
# list layers and exit
if flags["l"]:
try:
grass.run_command("v.in.ogr", flags="l", input=options["input"])
except CalledModuleError:
return 1
return 0
OGRdatasource = options["input"]
output = options["output"]
layers = options["layer"]
vflags = ""
if options["extent"] == "region":
vflags += "r"
if flags["o"]:
vflags += "o"
vopts = {}
if options["encoding"]:
vopts["encoding"] = options["encoding"]
if options["datum_trans"] and options["datum_trans"] == "-1":
# list datum transform parameters
if not options["epsg"]:
grass.fatal(_("Missing value for parameter <%s>") % "epsg")
return grass.run_command(
"g.proj", epsg=options["epsg"], datum_trans=options["datum_trans"]
)
if layers:
vopts["layer"] = layers
if output:
vopts["output"] = output
vopts["snap"] = options["snap"]
# try v.in.ogr directly
if flags["o"] or is_projection_matching(OGRdatasource, layers):
try:
grass.run_command(
"v.in.ogr",
input=OGRdatasource,
flags=vflags,
overwrite=overwrite,
**vopts,
)
grass.message(
_("Input <%s> successfully imported without reprojection")
% OGRdatasource
)
return 0
except CalledModuleError:
grass.fatal(_("Unable to import <%s>") % OGRdatasource)
grassenv = grass.gisenv()
tgtloc = grassenv["LOCATION_NAME"]
# make sure target is not xy
if grass.parse_command("g.proj", flags="g")["name"] == "xy_location_unprojected":
grass.fatal(
_("Coordinate reference system not available for current project <%s>")
% tgtloc
)
tgtmapset = grassenv["MAPSET"]
GISDBASE = grassenv["GISDBASE"]
TGTGISRC = os.environ["GISRC"]
SRCGISRC = grass.tempfile()
TMPLOC = grass.append_node_pid("tmp_v_import_location")
f = open(SRCGISRC, "w")
f.write("MAPSET: PERMANENT\n")
f.write("GISDBASE: %s\n" % GISDBASE)
f.write("LOCATION_NAME: %s\n" % TMPLOC)
f.write("GUI: text\n")
f.close()
tgtsrs = grass.read_command("g.proj", flags="j", quiet=True)
# create temp location from input without import
grass.verbose(_("Creating temporary project for <%s>...") % OGRdatasource)
try:
if OGRdatasource.lower().endswith("gml"):
try:
from osgeo import gdal
except:
grass.fatal(
_(
"Unable to load GDAL Python bindings (requires package "
"'python-gdal' being installed)"
)
)
if int(gdal.VersionInfo("VERSION_NUM")) < GDAL_COMPUTE_VERSION(2, 4, 1):
fix_gfsfile(OGRdatasource)
grass.run_command(
"v.in.ogr",
input=OGRdatasource,
project=TMPLOC,
flags="i",
quiet=True,
overwrite=overwrite,
**vopts,
)
except CalledModuleError:
grass.fatal(
_("Unable to create project from OGR datasource <%s>") % OGRdatasource
)
# switch to temp location
os.environ["GISRC"] = str(SRCGISRC)
if options["epsg"]: # force given EPSG
kwargs = {}
if options["datum_trans"]:
kwargs["datum_trans"] = options["datum_trans"]
grass.run_command("g.proj", flags="c", epsg=options["epsg"], **kwargs)
# print projection at verbose level
grass.verbose(grass.read_command("g.proj", flags="p").rstrip(os.linesep))
# make sure input is not xy
if grass.parse_command("g.proj", flags="g")["name"] == "xy_location_unprojected":
grass.fatal(
_("Coordinate reference system not available for input <%s>")
% OGRdatasource
)
if options["extent"] == "region":
# switch to target location
os.environ["GISRC"] = str(TGTGISRC)
# v.in.region in tgt
vreg = grass.append_node_pid("tmp_v_import_region")
grass.run_command("v.in.region", output=vreg, quiet=True)
# reproject to src
# switch to temp location
os.environ["GISRC"] = str(SRCGISRC)
try:
grass.run_command(
"v.proj",
input=vreg,
output=vreg,
project=tgtloc,
mapset=tgtmapset,
quiet=True,
overwrite=overwrite,
)
except CalledModuleError:
grass.fatal(_("Unable to reproject to source project"))
# set region from region vector
grass.run_command("g.region", res="1")
grass.run_command("g.region", vector=vreg)
# import into temp location
grass.message(_("Importing <%s> ...") % OGRdatasource)
try:
if OGRdatasource.lower().endswith("gml"):
try:
from osgeo import gdal
except:
grass.fatal(
_(
"Unable to load GDAL Python bindings (requires package "
"'python-gdal' being installed)"
)
)
if int(gdal.VersionInfo("VERSION_NUM")) < GDAL_COMPUTE_VERSION(2, 4, 1):
fix_gfsfile(OGRdatasource)
grass.run_command(
"v.in.ogr", input=OGRdatasource, flags=vflags, overwrite=overwrite, **vopts
)
except CalledModuleError:
grass.fatal(_("Unable to import OGR datasource <%s>") % OGRdatasource)
# if output is not define check source mapset
if not output:
output = grass.list_grouped("vector")["PERMANENT"][0]
# switch to target location
os.environ["GISRC"] = str(TGTGISRC)
# check if map exists
if (
not grass.overwrite()
and grass.find_file(output, element="vector", mapset=".")["mapset"]
):
grass.fatal(_("option <%s>: <%s> exists.") % ("output", output))
if options["extent"] == "region":
grass.run_command("g.remove", type="vector", name=vreg, flags="f", quiet=True)
# v.proj
grass.message(_("Reprojecting <%s>...") % output)
try:
grass.run_command(
"v.proj",
project=TMPLOC,
mapset="PERMANENT",
input=output,
overwrite=overwrite,
)
except CalledModuleError:
grass.fatal(_("Unable to to reproject vector <%s>") % output)
return 0
if __name__ == "__main__":
options, flags = grass.parser()
atexit.register(cleanup)
sys.exit(main())
|