stds_import.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  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) 2008-2011 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 shutil
  28. import os
  29. import os.path
  30. import tarfile
  31. import tempfile
  32. import time
  33. import filecmp
  34. from space_time_datasets_tools import *
  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_geotiff(maplist, overr, exp, location, link):
  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. filename = str(row["name"]) + ".tif"
  52. if link:
  53. ret = core.run_command("r.external", input=filename,
  54. output=name,
  55. flags=impflags,
  56. overwrite=core.overwrite())
  57. else:
  58. ret = core.run_command("r.in.gdal", input=filename,
  59. output=name,
  60. flags=impflags,
  61. overwrite=core.overwrite())
  62. if ret != 0:
  63. core.fatal(_("Unable to import/link raster map <%s>.") % name)
  64. # Set the color rules if present
  65. filename = str(row["name"]) + ".color"
  66. if os.path.isfile(filename):
  67. ret = core.run_command("r.colors", map=name,
  68. rules=filename,
  69. overwrite=core.overwrite())
  70. if ret != 0:
  71. core.fatal(_("Unable to set the color rules for "
  72. "raster map <%s>.") % name)
  73. ############################################################################
  74. def _import_raster_maps(maplist):
  75. # We need to disable the projection check because of its
  76. # simple implementation
  77. impflags = "o"
  78. for row in maplist:
  79. name = row["name"]
  80. filename = str(row["name"]) + ".pack"
  81. ret = core.run_command("r.unpack", input=filename,
  82. output=name,
  83. flags=impflags,
  84. overwrite=core.overwrite(),
  85. verbose=True)
  86. if ret != 0:
  87. core.fatal(_("Unable to unpack raster map <%s>.") % name)
  88. ############################################################################
  89. def _import_vector_maps_from_gml(maplist, overr, exp, location, link):
  90. impflags = "o"
  91. if exp or location:
  92. impflags += "e"
  93. for row in maplist:
  94. name = row["name"]
  95. filename = str(row["name"]) + ".xml"
  96. ret = core.run_command("v.in.ogr", dsn=filename,
  97. output=name,
  98. flags=impflags,
  99. overwrite=core.overwrite())
  100. if ret != 0:
  101. core.fatal(_("Unable to import vector map <%s>.") % name)
  102. ############################################################################
  103. def _import_vector_maps(maplist):
  104. # We need to disable the projection check because of its
  105. # simple implementation
  106. impflags = "o"
  107. for row in maplist:
  108. # Separate the name from the layer
  109. name = row["name"].split(":")[0]
  110. # Import only unique maps
  111. if name in imported_maps:
  112. continue
  113. filename = name + ".pack"
  114. ret = core.run_command("v.unpack", input=filename,
  115. output=name,
  116. flags=impflags,
  117. overwrite=core.overwrite(),
  118. verbose=True)
  119. if ret != 0:
  120. core.fatal(_("Unable to unpack vector map <%s>.") % name)
  121. imported_maps[name] = name
  122. ############################################################################
  123. def import_stds(
  124. input, output, extrdir, title=None, descr=None, location=None,
  125. link=False, exp=False, overr=False, create=False, stds_type="strds"):
  126. """!Import space time datasets of type raster and vector
  127. @param input: Name of the input archive file
  128. @param output: The name of the output space time dataset
  129. @param extrdir: The extraction directory
  130. @param title: The title of the new created space time dataset
  131. @param description: The description of the new created
  132. space time dataset
  133. @param location: The name of the location that should be created,
  134. maps are imported into this location
  135. @param link: Switch to link raster maps instead importing them
  136. @param exp: Extend location extents based on new dataset
  137. @param overr: Override projection (use location's projection)
  138. @param create: Create the location specified by the "location"
  139. parameter and exit.
  140. Do not import the space time datasets.
  141. @param stds_type: The type of the space time dataset that
  142. should be imported
  143. """
  144. core.set_raise_on_error(True)
  145. # Check if input file and extraction directory exits
  146. if not os.path.exists(input):
  147. core.fatal(_("Space time raster dataset archive <%s> not found")
  148. % input)
  149. if not create and not os.path.exists(extrdir):
  150. core.fatal(_("Extraction directory <%s> not found") % extrdir)
  151. tar = tarfile.open(name=input, mode='r')
  152. # Check for important files
  153. members = tar.getnames()
  154. if init_file_name not in members:
  155. core.fatal(_("Unable to find init file <%s>") % init_file_name)
  156. if list_file_name not in members:
  157. core.fatal(_("Unable to find list file <%s>") % list_file_name)
  158. if proj_file_name not in members:
  159. core.fatal(_("Unable to find projection file <%s>") % proj_file_name)
  160. tar.extractall(path=extrdir)
  161. tar.close()
  162. # Save current working directory path
  163. old_cwd = os.getcwd()
  164. # Switch into the data directory
  165. os.chdir(extrdir)
  166. # Check projection information
  167. if not location:
  168. temp_name = core.tempfile()
  169. temp_file = open(temp_name, "w")
  170. proj_name = os.path.abspath(proj_file_name)
  171. p = core.start_command("g.proj", flags="j", stdout=temp_file)
  172. p.communicate()
  173. temp_file.close()
  174. if not core.compare_key_value_text_files(temp_name, proj_name, sep="="):
  175. if overr:
  176. core.warning(_("Projection information does not match. "
  177. "Proceeding..."))
  178. else:
  179. core.fatal(_("Projection information does not match. Aborting."))
  180. # Create a new location based on the projection information and switch into it
  181. old_env = core.gisenv()
  182. if location:
  183. try:
  184. proj4_string = open(proj_file_name, 'r').read()
  185. core.create_location(dbase=old_env["GISDBASE"],
  186. location=location,
  187. proj4=proj4_string)
  188. # Just create a new location and return
  189. if create:
  190. os.chdir(old_cwd)
  191. return
  192. except Exception as e:
  193. core.fatal(_("Unable to create location %s. Reason: %s")
  194. % (location, str(e)))
  195. # Switch to the new created location
  196. ret = core.run_command("g.mapset", mapset="PERMANENT",
  197. location=location,
  198. gisdbase=old_env["GISDBASE"])
  199. if ret != 0:
  200. core.fatal(_("Unable to switch to location %s") % location)
  201. # create default database connection
  202. ret = core.run_command("t.connect", flags="d")
  203. if ret != 0:
  204. core.fatal(_("Unable to create default temporal database "
  205. "in new location %s") % location)
  206. try:
  207. # Make sure the temporal database exists
  208. create_temporal_database()
  209. fs = "|"
  210. maplist = []
  211. mapset = core.gisenv()["MAPSET"]
  212. list_file = open(list_file_name, "r")
  213. # Read the map list from file
  214. line_count = 0
  215. while True:
  216. line = list_file.readline()
  217. if not line:
  218. break
  219. line_list = line.split(fs)
  220. mapname = line_list[0].strip()
  221. mapid = mapname + "@" + mapset
  222. row = {}
  223. row["name"] = mapname
  224. row["id"] = mapid
  225. row["start"] = line_list[1].strip()
  226. row["end"] = line_list[2].strip()
  227. maplist.append(row)
  228. line_count += 1
  229. list_file.close()
  230. # Read the init file
  231. fs = "="
  232. init = {}
  233. init_file = open(init_file_name, "r")
  234. while True:
  235. line = init_file.readline()
  236. if not line:
  237. break
  238. kv = line.split(fs)
  239. init[kv[0]] = kv[1].strip()
  240. init_file.close()
  241. if "temporal_type" not in init or \
  242. "semantic_type" not in init or \
  243. "number_of_maps" not in init:
  244. core.fatal(_("Key words %s, %s or %s not found in init file.") %
  245. ("temporal_type", "semantic_type", "number_of_maps"))
  246. if line_count != int(init["number_of_maps"]):
  247. core.fatal(_("Number of maps mismatch in init and list file."))
  248. _format = "GTiff"
  249. _type = "strds"
  250. if "stds_type" in init:
  251. _type = init["stds_type"]
  252. if "format" in init:
  253. _format = init["format"]
  254. if stds_type != _type:
  255. core.fatal(_("The archive file is of wrong space time dataset type"))
  256. # Check the existence of the files
  257. if _format == "GTiff":
  258. for row in maplist:
  259. filename = str(row["name"]) + ".tif"
  260. if not os.path.exists(filename):
  261. core.fatal(_("Unable to find geotiff raster file "
  262. "<%s> in archive.") % filename)
  263. elif _format == "GML":
  264. for row in maplist:
  265. filename = str(row["name"]) + ".xml"
  266. if not os.path.exists(filename):
  267. core.fatal(_("Unable to find GML vector file "
  268. "<%s> in archive.") % filename)
  269. elif _format == "pack":
  270. for row in maplist:
  271. if _type == "stvds":
  272. filename = str(row["name"].split(":")[0]) + ".pack"
  273. else:
  274. filename = str(row["name"]) + ".pack"
  275. if not os.path.exists(filename):
  276. core.fatal(_("Unable to find GRASS package file "
  277. "<%s> in archive.") % filename)
  278. else:
  279. core.fatal(_("Unsupported input format"))
  280. # Check the space time dataset
  281. id = output + "@" + mapset
  282. sp = dataset_factory(_type, id)
  283. if sp.is_in_db() and core.overwrite() == False:
  284. core.fatal(_("Space time %s dataset <%s> is already in the "
  285. "database. Use the overwrite flag.") % \
  286. (_type, sp.get_id()))
  287. # Import the maps
  288. if _type == "strds":
  289. if _format == "GTiff":
  290. _import_raster_maps_from_geotiff(
  291. maplist, overr, exp, location, link)
  292. if _format == "pack":
  293. _import_raster_maps(maplist)
  294. elif _type == "stvds":
  295. if _format == "GML":
  296. _import_vector_maps_from_gml(
  297. maplist, overr, exp, location, link)
  298. if _format == "pack":
  299. _import_vector_maps(maplist)
  300. # Create the space time dataset
  301. if sp.is_in_db() and core.overwrite() == True:
  302. core.info(_("Overwrite space time %s dataset "
  303. "<%s> and unregister all maps.") % \
  304. (sp.get_new_map_instance(None).get_type(), sp.get_id()))
  305. sp.delete()
  306. sp = sp.get_new_instance(id)
  307. temporal_type = init["temporal_type"]
  308. semantic_type = init["semantic_type"]
  309. core.verbose(_("Create space time %s dataset.") %
  310. sp.get_new_map_instance(None).get_type())
  311. sp.set_initial_values(temporal_type=temporal_type,
  312. semantic_type=semantic_type, title=title,
  313. description=descr)
  314. sp.insert()
  315. # register the maps
  316. fs = "|"
  317. register_maps_in_space_time_dataset(
  318. type=sp.get_new_map_instance(None).get_type(),
  319. name=output, file=list_file_name, start="file",
  320. end="file", dbif=None, fs=fs)
  321. os.chdir(old_cwd)
  322. except:
  323. raise
  324. # Make sure the location is switched back correctly
  325. finally:
  326. if location:
  327. # Switch to the old location
  328. ret = core.run_command("g.mapset", mapset=old_env["MAPSET"],
  329. location=old_env["LOCATION_NAME"],
  330. gisdbase=old_env["GISDBASE"])