stds_export.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  1. """
  2. Export functions for space time datasets
  3. Usage:
  4. .. code-block:: python
  5. import grass.temporal as tgis
  6. input="temp_1950_2012@PERMANENT"
  7. output="/tmp/temp_1950_2012.tar.gz"
  8. compression="gzip"
  9. directory="/tmp"
  10. where=None
  11. format_="GTiff"
  12. type_="strds"
  13. tgis.export_stds(input, output, compression, directory, where, format_, type_)
  14. (C) 2012-2019 by the GRASS Development Team
  15. This program is free software under the GNU General Public
  16. License (>=v2). Read the file COPYING that comes with GRASS
  17. for details.
  18. :authors: Soeren Gebbert
  19. """
  20. import shutil
  21. import os
  22. import tarfile
  23. import tempfile
  24. import grass.script as gscript
  25. from grass.exceptions import CalledModuleError
  26. from .open_stds import open_old_stds
  27. proj_file_name = "proj.txt"
  28. init_file_name = "init.txt"
  29. metadata_file_name = "metadata.txt"
  30. read_file_name = "readme.txt"
  31. list_file_name = "list.txt"
  32. tmp_tar_file_name = "archive"
  33. # This global variable is for unique vector map export,
  34. # since single vector maps may have several layer
  35. # and therefore several attribute tables
  36. exported_maps = {}
  37. ############################################################################
  38. def _export_raster_maps_as_gdal(rows, tar, list_file, new_cwd, fs, format_,
  39. type_, **kwargs):
  40. kwargs = {key: value for key, value in kwargs.items() if value is not None}
  41. for row in rows:
  42. name = row["name"]
  43. start = row["start_time"]
  44. end = row["end_time"]
  45. max_val = row["max"]
  46. min_val = row["min"]
  47. datatype = row["datatype"]
  48. if not end:
  49. end = start
  50. string = "%s%s%s%s%s\n" % (name, fs, start, fs, end)
  51. # Write the filename, the start_time and the end_time
  52. list_file.write(string)
  53. try:
  54. if format_ == "GTiff":
  55. # Export the raster map with r.out.gdal as tif
  56. out_name = name + ".tif"
  57. if datatype == "CELL" and not type_:
  58. nodata = max_val + 1
  59. if nodata < 256 and min_val >= 0:
  60. gdal_type = "Byte"
  61. elif nodata < 65536 and min_val >= 0:
  62. gdal_type = "UInt16"
  63. elif min_val >= 0:
  64. gdal_type = "UInt32"
  65. else:
  66. gdal_type = "Int32"
  67. gscript.run_command("r.out.gdal", flags="c", input=name,
  68. output=out_name, nodata=nodata,
  69. type=gdal_type, format="GTiff",
  70. **kwargs)
  71. elif type_:
  72. gscript.run_command("r.out.gdal", flags="cf", input=name,
  73. output=out_name,
  74. type=type_, format="GTiff", **kwargs)
  75. else:
  76. gscript.run_command("r.out.gdal", flags="c",
  77. input=name, output=out_name,
  78. format="GTiff", **kwargs)
  79. elif format_ == "AAIGrid":
  80. # Export the raster map with r.out.gdal as Arc/Info ASCII Grid
  81. out_name = name + ".asc"
  82. gscript.run_command("r.out.gdal", flags="c", input=name,
  83. output=out_name, format="AAIGrid",
  84. **kwargs)
  85. except CalledModuleError:
  86. shutil.rmtree(new_cwd)
  87. tar.close()
  88. gscript.fatal(_("Unable to export raster map <%s>" % name))
  89. tar.add(out_name)
  90. # Export the color rules
  91. out_name = name + ".color"
  92. try:
  93. gscript.run_command("r.colors.out", map=name, rules=out_name)
  94. except CalledModuleError:
  95. shutil.rmtree(new_cwd)
  96. tar.close()
  97. gscript.fatal(_("Unable to export color rules for raster "
  98. "map <%s> r.out.gdal" % name))
  99. tar.add(out_name)
  100. ############################################################################
  101. def _export_raster_maps(rows, tar, list_file, new_cwd, fs):
  102. for row in rows:
  103. name = row["name"]
  104. start = row["start_time"]
  105. end = row["end_time"]
  106. if not end:
  107. end = start
  108. string = "%s%s%s%s%s\n" % (name, fs, start, fs, end)
  109. # Write the filename, the start_time and the end_time
  110. list_file.write(string)
  111. # Export the raster map with r.pack
  112. try:
  113. gscript.run_command("r.pack", input=name, flags="c")
  114. except CalledModuleError:
  115. shutil.rmtree(new_cwd)
  116. tar.close()
  117. gscript.fatal(_("Unable to export raster map <%s> with r.pack" %
  118. name))
  119. tar.add(name + ".pack")
  120. ############################################################################
  121. def _export_vector_maps_as_gml(rows, tar, list_file, new_cwd, fs):
  122. for row in rows:
  123. name = row["name"]
  124. start = row["start_time"]
  125. end = row["end_time"]
  126. layer = row["layer"]
  127. if not layer:
  128. layer = 1
  129. if not end:
  130. end = start
  131. string = "%s%s%s%s%s\n" % (name, fs, start, fs, end)
  132. # Write the filename, the start_time and the end_time
  133. list_file.write(string)
  134. # Export the vector map with v.out.ogr
  135. try:
  136. gscript.run_command("v.out.ogr", input=name, output=(name + ".xml"),
  137. layer=layer, format="GML")
  138. except CalledModuleError:
  139. shutil.rmtree(new_cwd)
  140. tar.close()
  141. gscript.fatal(_("Unable to export vector map <%s> as "
  142. "GML with v.out.ogr" % name))
  143. tar.add(name + ".xml")
  144. tar.add(name + ".xsd")
  145. ############################################################################
  146. def _export_vector_maps_as_gpkg(rows, tar, list_file, new_cwd, fs):
  147. for row in rows:
  148. name = row["name"]
  149. start = row["start_time"]
  150. end = row["end_time"]
  151. layer = row["layer"]
  152. if not layer:
  153. layer = 1
  154. if not end:
  155. end = start
  156. string = "%s%s%s%s%s\n" % (name, fs, start, fs, end)
  157. # Write the filename, the start_time and the end_time
  158. list_file.write(string)
  159. # Export the vector map with v.out.ogr
  160. try:
  161. gscript.run_command("v.out.ogr", input=name, output=(name + ".gpkg"),
  162. layer=layer, format="GPKG")
  163. except CalledModuleError:
  164. shutil.rmtree(new_cwd)
  165. tar.close()
  166. gscript.fatal(_("Unable to export vector map <%s> as "
  167. "GPKG with v.out.ogr" % name))
  168. tar.add(name + ".gpkg")
  169. ############################################################################
  170. def _export_vector_maps(rows, tar, list_file, new_cwd, fs):
  171. for row in rows:
  172. name = row["name"]
  173. start = row["start_time"]
  174. end = row["end_time"]
  175. layer = row["layer"]
  176. # Export unique maps only
  177. if name in exported_maps:
  178. continue
  179. if not layer:
  180. layer = 1
  181. if not end:
  182. end = start
  183. string = "%s:%s%s%s%s%s\n" % (name, layer, fs, start, fs, end)
  184. # Write the filename, the start_time and the end_time
  185. list_file.write(string)
  186. # Export the vector map with v.pack
  187. try:
  188. gscript.run_command("v.pack", input=name, flags="c")
  189. except CalledModuleError:
  190. shutil.rmtree(new_cwd)
  191. tar.close()
  192. gscript.fatal(_("Unable to export vector map <%s> with v.pack" %
  193. name))
  194. tar.add(name + ".pack")
  195. exported_maps[name] = name
  196. ############################################################################
  197. def _export_raster3d_maps(rows, tar, list_file, new_cwd, fs):
  198. for row in rows:
  199. name = row["name"]
  200. start = row["start_time"]
  201. end = row["end_time"]
  202. if not end:
  203. end = start
  204. string = "%s%s%s%s%s\n" % (name, fs, start, fs, end)
  205. # Write the filename, the start_time and the end_time
  206. list_file.write(string)
  207. # Export the raster 3d map with r3.pack
  208. try:
  209. gscript.run_command("r3.pack", input=name, flags="c")
  210. except CalledModuleError:
  211. shutil.rmtree(new_cwd)
  212. tar.close()
  213. gscript.fatal(_("Unable to export raster map <%s> with r3.pack" %
  214. name))
  215. tar.add(name + ".pack")
  216. ############################################################################
  217. def export_stds(input, output, compression, directory, where, format_="pack",
  218. type_="strds", datatype=None, **kwargs):
  219. """Export space time datasets as tar archive with optional compression
  220. This method should be used to export space time datasets
  221. of type raster and vector as tar archive that can be reimported
  222. with the method import_stds().
  223. :param input: The name of the space time dataset to export
  224. :param output: The name of the archive file
  225. :param compression: The compression of the archive file:
  226. - "no" no compression
  227. - "gzip" GNU zip compression
  228. - "bzip2" Bzip compression
  229. :param directory: The working directory used for extraction and packing
  230. :param where: The temporal WHERE SQL statement to select a subset
  231. of maps from the space time dataset
  232. :param format_: The export format:
  233. - "GTiff" Geotiff format, only for raster maps
  234. - "AAIGrid" Arc/Info ASCII Grid format, only for raster maps
  235. - "pack" The GRASS raster, 3D raster or vector Pack format,
  236. this is the default setting
  237. - "GML" GML file export format, only for vector maps,
  238. v.out.ogr export option
  239. - "GPKG" GPKG file export format, only for vector maps,
  240. v.out.ogr export option
  241. :param type_: The space time dataset type
  242. - "strds" Space time raster dataset
  243. - "str3ds" Space time 3D raster dataset
  244. - "stvds" Space time vector dataset
  245. :param datatype: Force the output datatype for r.out.gdal
  246. """
  247. # Save current working directory path
  248. old_cwd = os.getcwd()
  249. # Create the temporary directory and jump into it
  250. new_cwd = tempfile.mkdtemp(dir=directory)
  251. os.chdir(new_cwd)
  252. if type_ == "strds":
  253. columns = "name,start_time,end_time,min,max,datatype"
  254. elif type_ == "stvds":
  255. columns = "name,start_time,end_time,layer"
  256. else:
  257. columns = "name,start_time,end_time"
  258. sp = open_old_stds(input, type_)
  259. rows = sp.get_registered_maps(columns, where, "start_time", None)
  260. if compression == "gzip":
  261. flag = "w:gz"
  262. elif compression == "bzip2":
  263. flag = "w:bz2"
  264. else:
  265. flag = "w:"
  266. # Open the tar archive to add the files
  267. tar = tarfile.open(tmp_tar_file_name, flag)
  268. list_file = open(list_file_name, "w")
  269. fs = "|"
  270. if rows:
  271. if type_ == "strds":
  272. if format_ == "GTiff" or format_ == "AAIGrid":
  273. _export_raster_maps_as_gdal(
  274. rows, tar, list_file, new_cwd, fs, format_, datatype,
  275. **kwargs)
  276. else:
  277. _export_raster_maps(rows, tar, list_file, new_cwd, fs)
  278. elif type_ == "stvds":
  279. if format_ == "GML":
  280. _export_vector_maps_as_gml(rows, tar, list_file, new_cwd, fs)
  281. elif format_ == "GPKG":
  282. _export_vector_maps_as_gpkg(rows, tar, list_file, new_cwd, fs)
  283. else:
  284. _export_vector_maps(rows, tar, list_file, new_cwd, fs)
  285. elif type_ == "str3ds":
  286. _export_raster3d_maps(rows, tar, list_file, new_cwd, fs)
  287. list_file.close()
  288. # Write projection and metadata
  289. proj = gscript.read_command("g.proj", flags="j")
  290. proj_file = open(proj_file_name, "w")
  291. proj_file.write(proj)
  292. proj_file.close()
  293. init_file = open(init_file_name, "w")
  294. # Create the init string
  295. string = ""
  296. # This is optional, if not present strds will be assumed for backward
  297. # compatibility
  298. string += "%s=%s\n" % ("stds_type", sp.get_type())
  299. # This is optional, if not present gtiff will be assumed for
  300. # backward compatibility
  301. string += "%s=%s\n" % ("format", format_)
  302. string += "%s=%s\n" % ("temporal_type", sp.get_temporal_type())
  303. string += "%s=%s\n" % ("semantic_type", sp.get_semantic_type())
  304. if sp.is_time_relative():
  305. string += "%s=%s\n" % ("relative_time_unit",
  306. sp.get_relative_time_unit())
  307. # replace sp.metadata.get_number_of_maps() with len(rows)
  308. # sp.metadata.get_number_of_maps() doesn't work with where option
  309. string += "%s=%s\n" % ("number_of_maps", len(rows))
  310. north, south, east, west, top, bottom = sp.get_spatial_extent_as_tuple()
  311. string += "%s=%s\n" % ("north", north)
  312. string += "%s=%s\n" % ("south", south)
  313. string += "%s=%s\n" % ("east", east)
  314. string += "%s=%s\n" % ("west", west)
  315. init_file.write(string)
  316. init_file.close()
  317. metadata = gscript.read_command("t.info", type=type_, input=sp.get_id())
  318. metadata_file = open(metadata_file_name, "w")
  319. metadata_file.write(metadata)
  320. metadata_file.close()
  321. read_file = open(read_file_name, "w")
  322. if type_ == "strds":
  323. read_file.write("This space time raster dataset was exported with "
  324. "t.rast.export of GRASS GIS 7\n")
  325. elif type_ == "stvds":
  326. read_file.write("This space time vector dataset was exported with "
  327. "t.vect.export of GRASS GIS 7\n")
  328. elif type_ == "str3ds":
  329. read_file.write("This space time 3D raster dataset was exported "
  330. "with t.rast3d.export of GRASS GIS 7\n")
  331. read_file.write("\n")
  332. read_file.write("Files:\n")
  333. if type_ == "strds":
  334. if format_ == "GTiff":
  335. # 123456789012345678901234567890
  336. read_file.write(" *.tif -- GeoTIFF raster files\n")
  337. read_file.write(" *.color -- GRASS GIS raster color rules\n")
  338. elif format_ == "pack":
  339. read_file.write(" *.pack -- GRASS raster files packed with r.pack\n")
  340. elif type_ == "stvds":
  341. # 123456789012345678901234567890
  342. if format_ == "GML":
  343. read_file.write(" *.xml -- Vector GML files\n")
  344. else:
  345. read_file.write(" *.pack -- GRASS vector files packed with v.pack\n")
  346. elif type_ == "str3ds":
  347. read_file.write(" *.pack -- GRASS 3D raster files packed with r3.pack\n")
  348. read_file.write("%13s -- Projection information in PROJ.4 format\n" %
  349. (proj_file_name))
  350. read_file.write("%13s -- GRASS GIS space time %s dataset information\n" %
  351. (init_file_name, sp.get_new_map_instance(None).get_type()))
  352. read_file.write("%13s -- Time series file, lists all maps by name "
  353. "with interval\n" % (list_file_name))
  354. read_file.write(" time stamps in ISO-Format. Field separator is |\n")
  355. read_file.write("%13s -- The output of t.info\n" %
  356. (metadata_file_name))
  357. read_file.write("%13s -- This file\n" % (read_file_name))
  358. read_file.close()
  359. # Append the file list
  360. tar.add(list_file_name)
  361. tar.add(proj_file_name)
  362. tar.add(init_file_name)
  363. tar.add(read_file_name)
  364. tar.add(metadata_file_name)
  365. tar.close()
  366. os.chdir(old_cwd)
  367. # Move the archive to its destination
  368. shutil.move(os.path.join(new_cwd, tmp_tar_file_name), output)
  369. # Remove the temporary created working directory
  370. shutil.rmtree(new_cwd)