stds_import.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  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. import grass.script as gscript
  35. proj_file_name = "proj.txt"
  36. init_file_name = "init.txt"
  37. list_file_name = "list.txt"
  38. # This global variable is for unique vector map export,
  39. # since single vector maps may have several layer
  40. # and therefore several attribute tables
  41. imported_maps = {}
  42. ############################################################################
  43. def _import_raster_maps_from_gdal(maplist, overr, exp, location, link, format_,
  44. set_current_region=False):
  45. impflags = ""
  46. if overr:
  47. impflags += "o"
  48. if exp or location:
  49. impflags += "e"
  50. for row in maplist:
  51. name = row["name"]
  52. if format_ == "GTiff":
  53. filename = row["filename"] + ".tif"
  54. elif format_=="AAIGrid":
  55. filename = row["filename"] + ".asc"
  56. if not overr:
  57. impflags += "o"
  58. if link:
  59. ret = gscript.run_command("r.external", input=filename,
  60. output=name,
  61. flags=impflags,
  62. overwrite=gscript.overwrite())
  63. else:
  64. ret = gscript.run_command("r.in.gdal", input=filename,
  65. output=name,
  66. flags=impflags,
  67. overwrite=gscript.overwrite())
  68. if ret != 0:
  69. gscript.fatal(_("Unable to import/link raster map <%s> from file %s.") %(name,
  70. filename))
  71. # Set the color rules if present
  72. filename = row["filename"] + ".color"
  73. if os.path.isfile(filename):
  74. ret = gscript.run_command("r.colors", map=name,
  75. rules=filename,
  76. overwrite=gscript.overwrite())
  77. if ret != 0:
  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", rast=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. ret = gscript.run_command("r.unpack", input=filename,
  92. output=name,
  93. flags=impflags,
  94. overwrite=gscript.overwrite(),
  95. verbose=True)
  96. if ret != 0:
  97. gscript.fatal(_("Unable to unpack raster map <%s> from file %s.") % (name,
  98. filename))
  99. # Set the computational region from the last map imported
  100. if set_current_region is True:
  101. gscript.run_command("g.region", rast=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. ret = gscript.run_command("v.in.ogr", dsn=filename,
  111. output=name,
  112. flags=impflags,
  113. overwrite=gscript.overwrite())
  114. if ret != 0:
  115. gscript.fatal(_("Unable to import vector map <%s> from file %s.") % (name,
  116. 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. ret = gscript.run_command("v.unpack", input=filename,
  130. output=name,
  131. flags=impflags,
  132. overwrite=gscript.overwrite(),
  133. verbose=True)
  134. if ret != 0:
  135. gscript.fatal(_("Unable to unpack vector map <%s> from file %s.") % (name,
  136. filename))
  137. imported_maps[name] = name
  138. ############################################################################
  139. def import_stds(input, output, extrdir, title=None, descr=None, location=None,
  140. link=False, exp=False, overr=False, create=False, stds_type="strds",
  141. 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 extrdir 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 extended
  160. 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(extrdir):
  170. gscript.fatal(_("Extraction directory <%s> not found") % extrdir)
  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=extrdir)
  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(extrdir)
  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, sep="="):
  197. if overr:
  198. gscript.warning(_("Projection information does not match. "
  199. "Proceeding..."))
  200. else:
  201. diff = ''.join(gscript.diff_files(temp_name, proj_name))
  202. gscript.warning(_("Difference between PROJ_INFO file of imported map "
  203. "and of current location:\n{diff}").format(diff=diff))
  204. gscript.fatal(_("Projection information does not match. Aborting."))
  205. # Create a new location based on the projection information and switch
  206. # into it
  207. old_env = gscript.gisenv()
  208. if location:
  209. try:
  210. proj4_string = open(proj_file_name, 'r').read()
  211. gscript.create_location(dbase=old_env["GISDBASE"],
  212. location=location,
  213. proj4=proj4_string)
  214. # Just create a new location and return
  215. if create:
  216. os.chdir(old_cwd)
  217. return
  218. except Exception as e:
  219. gscript.fatal(_("Unable to create location %(l)s. Reason: %(e)s")
  220. % {'l': location, 'e': str(e)})
  221. # Switch to the new created location
  222. ret = gscript.run_command("g.mapset", mapset="PERMANENT",
  223. location=location,
  224. gisdbase=old_env["GISDBASE"])
  225. if ret != 0:
  226. gscript.fatal(_("Unable to switch to location %s") % location)
  227. # create default database connection
  228. ret = gscript.run_command("t.connect", flags="d")
  229. if ret != 0:
  230. gscript.fatal(_("Unable to create default temporal database "
  231. "in new location %s") % location)
  232. try:
  233. # Make sure the temporal database exists
  234. factory.init()
  235. fs = "|"
  236. maplist = []
  237. mapset = get_current_mapset()
  238. list_file = open(list_file_name, "r")
  239. new_list_file = open(new_list_file_name, "w")
  240. # get number of lines to correctly form the suffix
  241. max_count = -1
  242. for max_count, l in enumerate(list_file):
  243. pass
  244. max_count += 1
  245. list_file.seek(0)
  246. # Read the map list from file
  247. line_count = 0
  248. while True:
  249. line = list_file.readline()
  250. if not line:
  251. break
  252. line_list = line.split(fs)
  253. # The filename is actually the base name of the map
  254. # that must be extended by the file suffix
  255. filename = line_list[0].strip().split(":")[0]
  256. if base:
  257. mapname = "%s_%s" % (base, gscript.get_num_suffix(line_count + 1, max_count))
  258. mapid= "%s@%s"%(mapname, mapset)
  259. else:
  260. mapname = filename
  261. mapid = mapname + "@" + mapset
  262. row = {}
  263. row["filename"] = filename
  264. row["name"] = mapname
  265. row["id"] = mapid
  266. row["start"] = line_list[1].strip()
  267. row["end"] = line_list[2].strip()
  268. new_list_file.write("%s%s%s%s%s\n"%(mapname,fs, row["start"],
  269. fs, row["end"]))
  270. maplist.append(row)
  271. line_count += 1
  272. list_file.close()
  273. new_list_file.close()
  274. # Read the init file
  275. fs = "="
  276. init = {}
  277. init_file = open(init_file_name, "r")
  278. while True:
  279. line = init_file.readline()
  280. if not line:
  281. break
  282. kv = line.split(fs)
  283. init[kv[0]] = kv[1].strip()
  284. init_file.close()
  285. if "temporal_type" not in init or \
  286. "semantic_type" not in init or \
  287. "number_of_maps" not in init:
  288. gscript.fatal(_("Key words %(t)s, %(s)s or %(n)s not found in init"
  289. " file.") % {'t': "temporal_type",
  290. 's': "semantic_type",
  291. 'n': "number_of_maps"})
  292. if line_count != int(init["number_of_maps"]):
  293. gscript.fatal(_("Number of maps mismatch in init and list file."))
  294. format_ = "GTiff"
  295. type_ = "strds"
  296. if "stds_type" in init:
  297. type_ = init["stds_type"]
  298. if "format" in init:
  299. format_ = init["format"]
  300. if stds_type != type_:
  301. gscript.fatal(_("The archive file is of wrong space time dataset type"))
  302. # Check the existence of the files
  303. if format_ == "GTiff":
  304. for row in maplist:
  305. filename = row["filename"] + ".tif"
  306. if not os.path.exists(filename):
  307. gscript.fatal(_("Unable to find GeoTIFF raster file "
  308. "<%s> in archive.") % filename)
  309. elif format_ == "AAIGrid":
  310. for row in maplist:
  311. filename = row["filename"] + ".asc"
  312. if not os.path.exists(filename):
  313. gscript.fatal(_("Unable to find AAIGrid raster file "
  314. "<%s> in archive.") % filename)
  315. elif format_ == "GML":
  316. for row in maplist:
  317. filename = row["filename"] + ".xml"
  318. if not os.path.exists(filename):
  319. gscript.fatal(_("Unable to find GML vector file "
  320. "<%s> in archive.") % filename)
  321. elif format_ == "pack":
  322. for row in maplist:
  323. if type_ == "stvds":
  324. filename = str(row["filename"].split(":")[0]) + ".pack"
  325. else:
  326. filename = row["filename"] + ".pack"
  327. if not os.path.exists(filename):
  328. gscript.fatal(_("Unable to find GRASS package file "
  329. "<%s> in archive.") % filename)
  330. else:
  331. gscript.fatal(_("Unsupported input format"))
  332. # Check the space time dataset
  333. id = output + "@" + mapset
  334. sp = dataset_factory(type_, id)
  335. if sp.is_in_db() and gscript.overwrite() == False:
  336. gscript.fatal(_("Space time %(t)s dataset <%(sp)s> is already in the "
  337. "database. Use the overwrite flag.") % {'t': type_,
  338. 'sp': sp.get_id()})
  339. # Import the maps
  340. if type_ == "strds":
  341. if format_ == "GTiff" or format_ == "AAIGrid":
  342. _import_raster_maps_from_gdal(maplist, overr, exp, location,
  343. link, format_, set_current_region)
  344. if format_ == "pack":
  345. _import_raster_maps(maplist, set_current_region)
  346. elif type_ == "stvds":
  347. if format_ == "GML":
  348. _import_vector_maps_from_gml(
  349. maplist, overr, exp, location, link)
  350. if format_ == "pack":
  351. _import_vector_maps(maplist)
  352. # Create the space time dataset
  353. if sp.is_in_db() and gscript.overwrite() == True:
  354. gscript.info(_("Overwrite space time %(sp)s dataset "
  355. "<%(id)s> and unregister all maps.") % {
  356. 'sp': sp.get_new_map_instance(None).get_type(),
  357. 'id': sp.get_id()})
  358. sp.delete()
  359. sp = sp.get_new_instance(id)
  360. temporal_type = init["temporal_type"]
  361. semantic_type = init["semantic_type"]
  362. relative_time_unit = None
  363. if temporal_type == "relative":
  364. if "relative_time_unit" not in init:
  365. gscript.fatal(_("Key word %s not found in init file.") % ("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)