stds_export.py 15 KB

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