stds_import.py 18 KB

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