stds_import.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  1. """
  2. Space time dataset import functions
  3. Usage:
  4. .. code-block:: python
  5. import grass.temporal as tgis
  6. input="/tmp/temp_1950_2012.tar.gz"
  7. output="temp_1950_2012"
  8. extrdir="/tmp"
  9. title="My new dataset"
  10. descr="May new shiny dataset"
  11. location=None
  12. link=True
  13. exp=True
  14. overr=False
  15. create=False
  16. tgis.import_stds(input, output, extrdir, title, descr, location,
  17. link, exp, overr, create, "strds")
  18. (C) 2012-2013 by the GRASS Development Team
  19. This program is free software under the GNU General Public
  20. License (>=v2). Read the file COPYING that comes with GRASS
  21. for details.
  22. :authors: Soeren Gebbert
  23. """
  24. import os
  25. import os.path
  26. import tarfile
  27. from space_time_datasets import *
  28. from register import *
  29. import factory
  30. from factory import *
  31. import grass.script as gscript
  32. proj_file_name = "proj.txt"
  33. init_file_name = "init.txt"
  34. list_file_name = "list.txt"
  35. # This global variable is for unique vector map export,
  36. # since single vector maps may have several layer
  37. # and therefore several attribute tables
  38. imported_maps = {}
  39. ############################################################################
  40. def _import_raster_maps_from_gdal(maplist, overr, exp, location, link, format_,
  41. set_current_region=False):
  42. impflags = ""
  43. if overr:
  44. impflags += "o"
  45. if exp or location:
  46. impflags += "e"
  47. for row in maplist:
  48. name = row["name"]
  49. if format_ == "GTiff":
  50. filename = row["filename"] + ".tif"
  51. elif format_ == "AAIGrid":
  52. filename = row["filename"] + ".asc"
  53. if not overr:
  54. impflags += "o"
  55. if link:
  56. ret = gscript.run_command("r.external", input=filename,
  57. output=name,
  58. flags=impflags,
  59. overwrite=gscript.overwrite())
  60. else:
  61. ret = gscript.run_command("r.in.gdal", input=filename,
  62. output=name,
  63. flags=impflags,
  64. overwrite=gscript.overwrite())
  65. if ret != 0:
  66. gscript.fatal(_("Unable to import/link raster map <%s> from file"
  67. " %s.") % (name, filename))
  68. # Set the color rules if present
  69. filename = row["filename"] + ".color"
  70. if os.path.isfile(filename):
  71. ret = gscript.run_command("r.colors", map=name,
  72. rules=filename,
  73. overwrite=gscript.overwrite())
  74. if ret != 0:
  75. gscript.fatal(_("Unable to set the color rules for "
  76. "raster map <%s>.") % name)
  77. # Set the computational region from the last map imported
  78. if set_current_region is True:
  79. gscript.run_command("g.region", rast=name)
  80. ############################################################################
  81. def _import_raster_maps(maplist, set_current_region=False):
  82. # We need to disable the projection check because of its
  83. # simple implementation
  84. impflags = "o"
  85. for row in maplist:
  86. name = row["name"]
  87. filename = row["filename"] + ".pack"
  88. ret = gscript.run_command("r.unpack", input=filename,
  89. output=name, flags=impflags,
  90. overwrite=gscript.overwrite(),
  91. verbose=True)
  92. if ret != 0:
  93. gscript.fatal(_("Unable to unpack raster map <%s> from file "
  94. "%s.") % (name, filename))
  95. # Set the computational region from the last map imported
  96. if set_current_region is True:
  97. gscript.run_command("g.region", rast=name)
  98. ############################################################################
  99. def _import_vector_maps_from_gml(maplist, overr, exp, location, link):
  100. impflags = "o"
  101. if exp or location:
  102. impflags += "e"
  103. for row in maplist:
  104. name = row["name"]
  105. filename = row["filename"] + ".xml"
  106. ret = gscript.run_command("v.in.ogr", dsn=filename,
  107. output=name, flags=impflags,
  108. overwrite=gscript.overwrite())
  109. if ret != 0:
  110. gscript.fatal(_("Unable to import vector map <%s> from file "
  111. "%s.") % (name, filename))
  112. ############################################################################
  113. def _import_vector_maps(maplist):
  114. # We need to disable the projection check because of its
  115. # simple implementation
  116. impflags = "o"
  117. for row in maplist:
  118. # Separate the name from the layer
  119. name = row["name"].split(":")[0]
  120. # Import only unique maps
  121. if name in imported_maps:
  122. continue
  123. filename = row["filename"] + ".pack"
  124. ret = gscript.run_command("v.unpack", input=filename,
  125. output=name, flags=impflags,
  126. overwrite=gscript.overwrite(),
  127. verbose=True)
  128. if ret != 0:
  129. gscript.fatal(_("Unable to unpack vector map <%s> from file "
  130. "%s.") % (name, filename))
  131. imported_maps[name] = name
  132. ############################################################################
  133. def import_stds(input, output, extrdir, title=None, descr=None, location=None,
  134. link=False, exp=False, overr=False, create=False,
  135. stds_type="strds", base=None, set_current_region=False):
  136. """Import space time datasets of type raster and vector
  137. :param input: Name of the input archive file
  138. :param output: The name of the output space time dataset
  139. :param extrdir: The extraction directory
  140. :param title: The title of the new created space time dataset
  141. :param descr: The description of the new created
  142. space time dataset
  143. :param location: The name of the location that should be created,
  144. maps are imported into this location
  145. :param link: Switch to link raster maps instead importing them
  146. :param exp: Extend location extents based on new dataset
  147. :param overr: Override projection (use location's projection)
  148. :param create: Create the location specified by the "location"
  149. parameter and exit.
  150. Do not import the space time datasets.
  151. :param stds_type: The type of the space time dataset that
  152. should be imported
  153. :param base: The base name of the new imported maps, it will be
  154. extended using a numerical index.
  155. """
  156. global raise_on_error
  157. old_state = gscript.raise_on_error
  158. gscript.set_raise_on_error(True)
  159. # Check if input file and extraction directory exits
  160. if not os.path.exists(input):
  161. gscript.fatal(_("Space time raster dataset archive <%s> not found")
  162. % input)
  163. if not create and not os.path.exists(extrdir):
  164. gscript.fatal(_("Extraction directory <%s> not found") % extrdir)
  165. tar = tarfile.open(name=input, mode='r')
  166. # Check for important files
  167. members = tar.getnames()
  168. if init_file_name not in members:
  169. gscript.fatal(_("Unable to find init file <%s>") % init_file_name)
  170. if list_file_name not in members:
  171. gscript.fatal(_("Unable to find list file <%s>") % list_file_name)
  172. if proj_file_name not in members:
  173. gscript.fatal(_("Unable to find projection file <%s>") % proj_file_name)
  174. tar.extractall(path=extrdir)
  175. tar.close()
  176. # We use a new list file name for map registration
  177. new_list_file_name = list_file_name + "_new"
  178. # Save current working directory path
  179. old_cwd = os.getcwd()
  180. # Switch into the data directory
  181. os.chdir(extrdir)
  182. # Check projection information
  183. if not location:
  184. temp_name = gscript.tempfile()
  185. temp_file = open(temp_name, "w")
  186. proj_name = os.path.abspath(proj_file_name)
  187. p = gscript.start_command("g.proj", flags="j", stdout=temp_file)
  188. p.communicate()
  189. temp_file.close()
  190. if not gscript.compare_key_value_text_files(temp_name, proj_name,
  191. sep="="):
  192. if overr:
  193. gscript.warning(_("Projection information does not match. "
  194. "Proceeding..."))
  195. else:
  196. diff = ''.join(gscript.diff_files(temp_name, proj_name))
  197. gscript.warning(_("Difference between PROJ_INFO file of "
  198. "imported map and of current location:"
  199. "\n{diff}").format(diff=diff))
  200. gscript.fatal(_("Projection information does not match. "
  201. "Aborting."))
  202. # Create a new location based on the projection information and switch
  203. # into it
  204. old_env = gscript.gisenv()
  205. if location:
  206. try:
  207. proj4_string = open(proj_file_name, 'r').read()
  208. gscript.create_location(dbase=old_env["GISDBASE"],
  209. location=location,
  210. proj4=proj4_string)
  211. # Just create a new location and return
  212. if create:
  213. os.chdir(old_cwd)
  214. return
  215. except Exception as e:
  216. gscript.fatal(_("Unable to create location %(l)s. Reason: %(e)s")
  217. % {'l': location, 'e': str(e)})
  218. # Switch to the new created location
  219. ret = gscript.run_command("g.mapset", mapset="PERMANENT",
  220. location=location,
  221. gisdbase=old_env["GISDBASE"])
  222. if ret != 0:
  223. gscript.fatal(_("Unable to switch to location %s") % location)
  224. # create default database connection
  225. ret = gscript.run_command("t.connect", flags="d")
  226. if ret != 0:
  227. gscript.fatal(_("Unable to create default temporal database "
  228. "in new location %s") % location)
  229. try:
  230. # Make sure the temporal database exists
  231. factory.init()
  232. fs = "|"
  233. maplist = []
  234. mapset = get_current_mapset()
  235. list_file = open(list_file_name, "r")
  236. new_list_file = open(new_list_file_name, "w")
  237. # get number of lines to correctly form the suffix
  238. max_count = -1
  239. for max_count, l in enumerate(list_file):
  240. pass
  241. max_count += 1
  242. list_file.seek(0)
  243. # Read the map list from file
  244. line_count = 0
  245. while True:
  246. line = list_file.readline()
  247. if not line:
  248. break
  249. line_list = line.split(fs)
  250. # The filename is actually the base name of the map
  251. # that must be extended by the file suffix
  252. filename = line_list[0].strip().split(":")[0]
  253. if base:
  254. mapname = "%s_%s" % (base, gscript.get_num_suffix(line_count + 1,
  255. max_count))
  256. mapid = "%s@%s" % (mapname, mapset)
  257. else:
  258. mapname = filename
  259. mapid = mapname + "@" + mapset
  260. row = {}
  261. row["filename"] = filename
  262. row["name"] = mapname
  263. row["id"] = mapid
  264. row["start"] = line_list[1].strip()
  265. row["end"] = line_list[2].strip()
  266. new_list_file.write("%s%s%s%s%s\n" % (mapname, fs, row["start"],
  267. fs, row["end"]))
  268. maplist.append(row)
  269. line_count += 1
  270. list_file.close()
  271. new_list_file.close()
  272. # Read the init file
  273. fs = "="
  274. init = {}
  275. init_file = open(init_file_name, "r")
  276. while True:
  277. line = init_file.readline()
  278. if not line:
  279. break
  280. kv = line.split(fs)
  281. init[kv[0]] = kv[1].strip()
  282. init_file.close()
  283. if "temporal_type" not in init or \
  284. "semantic_type" not in init or \
  285. "number_of_maps" not in init:
  286. gscript.fatal(_("Key words %(t)s, %(s)s or %(n)s not found in init"
  287. " file.") % {'t': "temporal_type",
  288. 's': "semantic_type",
  289. 'n': "number_of_maps"})
  290. if line_count != int(init["number_of_maps"]):
  291. gscript.fatal(_("Number of maps mismatch in init and list file."))
  292. format_ = "GTiff"
  293. type_ = "strds"
  294. if "stds_type" in init:
  295. type_ = init["stds_type"]
  296. if "format" in init:
  297. format_ = init["format"]
  298. if stds_type != type_:
  299. gscript.fatal(_("The archive file is of wrong space time dataset"
  300. " type"))
  301. # Check the existence of the files
  302. if format_ == "GTiff":
  303. for row in maplist:
  304. filename = row["filename"] + ".tif"
  305. if not os.path.exists(filename):
  306. gscript.fatal(_("Unable to find GeoTIFF raster file "
  307. "<%s> in archive.") % filename)
  308. elif format_ == "AAIGrid":
  309. for row in maplist:
  310. filename = row["filename"] + ".asc"
  311. if not os.path.exists(filename):
  312. gscript.fatal(_("Unable to find AAIGrid raster file "
  313. "<%s> in archive.") % filename)
  314. elif format_ == "GML":
  315. for row in maplist:
  316. filename = row["filename"] + ".xml"
  317. if not os.path.exists(filename):
  318. gscript.fatal(_("Unable to find GML vector file "
  319. "<%s> in archive.") % filename)
  320. elif format_ == "pack":
  321. for row in maplist:
  322. if type_ == "stvds":
  323. filename = str(row["filename"].split(":")[0]) + ".pack"
  324. else:
  325. filename = row["filename"] + ".pack"
  326. if not os.path.exists(filename):
  327. gscript.fatal(_("Unable to find GRASS package file "
  328. "<%s> in archive.") % filename)
  329. else:
  330. gscript.fatal(_("Unsupported input format"))
  331. # Check the space time dataset
  332. id = output + "@" + mapset
  333. sp = dataset_factory(type_, id)
  334. if sp.is_in_db() and gscript.overwrite() is False:
  335. gscript.fatal(_("Space time %(t)s dataset <%(sp)s> is already in"
  336. " the database. Use the overwrite flag.") %
  337. {'t': type_, 'sp': sp.get_id()})
  338. # Import the maps
  339. if type_ == "strds":
  340. if format_ == "GTiff" or format_ == "AAIGrid":
  341. _import_raster_maps_from_gdal(maplist, overr, exp, location,
  342. link, format_, set_current_region)
  343. if format_ == "pack":
  344. _import_raster_maps(maplist, set_current_region)
  345. elif type_ == "stvds":
  346. if format_ == "GML":
  347. _import_vector_maps_from_gml(
  348. maplist, overr, exp, location, link)
  349. if format_ == "pack":
  350. _import_vector_maps(maplist)
  351. # Create the space time dataset
  352. if sp.is_in_db() and gscript.overwrite() is True:
  353. gscript.info(_("Overwrite space time %(sp)s dataset "
  354. "<%(id)s> and unregister all maps.") %
  355. {'sp': sp.get_new_map_instance(None).get_type(),
  356. 'id': sp.get_id()})
  357. sp.delete()
  358. sp = sp.get_new_instance(id)
  359. temporal_type = init["temporal_type"]
  360. semantic_type = init["semantic_type"]
  361. relative_time_unit = None
  362. if temporal_type == "relative":
  363. if "relative_time_unit" not in init:
  364. gscript.fatal(_("Key word %s not found in init file.") %
  365. ("relative_time_unit"))
  366. relative_time_unit = init["relative_time_unit"]
  367. sp.set_relative_time_unit(relative_time_unit)
  368. gscript.verbose(_("Create space time %s dataset.") %
  369. sp.get_new_map_instance(None).get_type())
  370. sp.set_initial_values(temporal_type=temporal_type,
  371. semantic_type=semantic_type, title=title,
  372. description=descr)
  373. sp.insert()
  374. # register the maps
  375. fs = "|"
  376. register_maps_in_space_time_dataset(
  377. type=sp.get_new_map_instance(None).get_type(),
  378. name=output, file=new_list_file_name, start="file",
  379. end="file", unit=relative_time_unit, dbif=None, fs=fs,
  380. update_cmd_list=False)
  381. os.chdir(old_cwd)
  382. except:
  383. raise
  384. # Make sure the location is switched back correctly
  385. finally:
  386. if location:
  387. # Switch to the old location
  388. ret = gscript.run_command("g.mapset", mapset=old_env["MAPSET"],
  389. location=old_env["LOCATION_NAME"],
  390. gisdbase=old_env["GISDBASE"])
  391. gscript.set_raise_on_error(old_state)