stds_import.py 17 KB

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