stds_export.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  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. 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(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. # Export unique maps only
  153. if name in exported_maps:
  154. continue
  155. if not layer:
  156. layer = 1
  157. if not end:
  158. end = start
  159. string = "%s:%s%s%s%s%s\n" % (name, layer, fs, start, fs, end)
  160. # Write the filename, the start_time and the end_time
  161. list_file.write(string)
  162. # Export the vector map with v.pack
  163. try:
  164. gscript.run_command("v.pack", input=name, flags="c")
  165. except CalledModuleError:
  166. shutil.rmtree(new_cwd)
  167. tar.close()
  168. gscript.fatal(_("Unable to export vector map <%s> with v.pack" %
  169. name))
  170. tar.add(name + ".pack")
  171. exported_maps[name] = name
  172. ############################################################################
  173. def _export_raster3d_maps(rows, tar, list_file, new_cwd, fs):
  174. for row in rows:
  175. name = row["name"]
  176. start = row["start_time"]
  177. end = row["end_time"]
  178. if not end:
  179. end = start
  180. string = "%s%s%s%s%s\n" % (name, fs, start, fs, end)
  181. # Write the filename, the start_time and the end_time
  182. list_file.write(string)
  183. # Export the raster 3d map with r3.pack
  184. try:
  185. gscript.run_command("r3.pack", input=name, flags="c")
  186. except CalledModuleError:
  187. shutil.rmtree(new_cwd)
  188. tar.close()
  189. gscript.fatal(_("Unable to export raster map <%s> with r3.pack" %
  190. name))
  191. tar.add(name + ".pack")
  192. ############################################################################
  193. def export_stds(input, output, compression, directory, where, format_="pack",
  194. type_="strds", datatype=None, **kwargs):
  195. """Export space time datasets as tar archive with optional compression
  196. This method should be used to export space time datasets
  197. of type raster and vector as tar archive that can be reimported
  198. with the method import_stds().
  199. :param input: The name of the space time dataset to export
  200. :param output: The name of the archive file
  201. :param compression: The compression of the archive file:
  202. - "no" no compression
  203. - "gzip" GNU zip compression
  204. - "bzip2" Bzip compression
  205. :param directory: The working directory used for extraction and packing
  206. :param where: The temporal WHERE SQL statement to select a subset
  207. of maps from the space time dataset
  208. :param format_: The export format:
  209. - "GTiff" Geotiff format, only for raster maps
  210. - "AAIGrid" Arc/Info ASCII Grid format, only for raster maps
  211. - "pack" The GRASS raster, 3D raster or vector Pack format,
  212. this is the default setting
  213. - "GML" GML file export format, only for vector maps,
  214. v.out.ogr export option
  215. :param type_: The space time dataset type
  216. - "strds" Space time raster dataset
  217. - "str3ds" Space time 3D raster dataset
  218. - "stvds" Space time vector dataset
  219. :param datatype: Force the output datatype for r.out.gdal
  220. """
  221. # Save current working directory path
  222. old_cwd = os.getcwd()
  223. # Create the temporary directory and jump into it
  224. new_cwd = tempfile.mkdtemp(dir=directory)
  225. os.chdir(new_cwd)
  226. if type_ == "strds":
  227. columns = "name,start_time,end_time,min,max,datatype"
  228. elif type_ == "stvds":
  229. columns = "name,start_time,end_time,layer"
  230. else:
  231. columns = "name,start_time,end_time"
  232. sp = open_old_stds(input, type_)
  233. rows = sp.get_registered_maps(columns, where, "start_time", None)
  234. if compression == "gzip":
  235. flag = "w:gz"
  236. elif compression == "bzip2":
  237. flag = "w:bz2"
  238. else:
  239. flag = "w:"
  240. # Open the tar archive to add the files
  241. tar = tarfile.open(tmp_tar_file_name, flag)
  242. list_file = open(list_file_name, "w")
  243. fs = "|"
  244. if rows:
  245. if type_ == "strds":
  246. if format_ == "GTiff" or format_ == "AAIGrid":
  247. _export_raster_maps_as_gdal(
  248. rows, tar, list_file, new_cwd, fs, format_, datatype,
  249. **kwargs)
  250. else:
  251. _export_raster_maps(rows, tar, list_file, new_cwd, fs)
  252. elif type_ == "stvds":
  253. if format_ == "GML":
  254. _export_vector_maps_as_gml(rows, tar, list_file, new_cwd, fs)
  255. else:
  256. _export_vector_maps(rows, tar, list_file, new_cwd, fs)
  257. elif type_ == "str3ds":
  258. _export_raster3d_maps(rows, tar, list_file, new_cwd, fs)
  259. list_file.close()
  260. # Write projection and metadata
  261. proj = gscript.read_command("g.proj", flags="j")
  262. proj_file = open(proj_file_name, "w")
  263. proj_file.write(proj)
  264. proj_file.close()
  265. init_file = open(init_file_name, "w")
  266. # Create the init string
  267. string = ""
  268. # This is optional, if not present strds will be assumed for backward
  269. # compatibility
  270. string += "%s=%s\n" % ("stds_type", sp.get_type())
  271. # This is optional, if not present gtiff will be assumed for
  272. # backward compatibility
  273. string += "%s=%s\n" % ("format", format_)
  274. string += "%s=%s\n" % ("temporal_type", sp.get_temporal_type())
  275. string += "%s=%s\n" % ("semantic_type", sp.get_semantic_type())
  276. if sp.is_time_relative():
  277. string += "%s=%s\n" % ("relative_time_unit",
  278. sp.get_relative_time_unit())
  279. # replace sp.metadata.get_number_of_maps() with len(rows)
  280. # sp.metadata.get_number_of_maps() doesn't work with where option
  281. string += "%s=%s\n" % ("number_of_maps", len(rows))
  282. north, south, east, west, top, bottom = sp.get_spatial_extent_as_tuple()
  283. string += "%s=%s\n" % ("north", north)
  284. string += "%s=%s\n" % ("south", south)
  285. string += "%s=%s\n" % ("east", east)
  286. string += "%s=%s\n" % ("west", west)
  287. init_file.write(string)
  288. init_file.close()
  289. metadata = gscript.read_command("t.info", type=type_, input=sp.get_id())
  290. metadata_file = open(metadata_file_name, "w")
  291. metadata_file.write(metadata)
  292. metadata_file.close()
  293. read_file = open(read_file_name, "w")
  294. if type_ == "strds":
  295. read_file.write("This space time raster dataset was exported with "
  296. "t.rast.export of GRASS GIS 7\n")
  297. elif type_ == "stvds":
  298. read_file.write("This space time vector dataset was exported with "
  299. "t.vect.export of GRASS GIS 7\n")
  300. elif type_ == "str3ds":
  301. read_file.write("This space time 3D raster dataset was exported "
  302. "with t.rast3d.export of GRASS GIS 7\n")
  303. read_file.write("\n")
  304. read_file.write("Files:\n")
  305. if type_ == "strds":
  306. if format_ == "GTiff":
  307. # 123456789012345678901234567890
  308. read_file.write(" *.tif -- GeoTIFF raster files\n")
  309. read_file.write(" *.color -- GRASS GIS raster color rules\n")
  310. elif format_ == "pack":
  311. read_file.write(" *.pack -- GRASS raster files packed with r.pack\n")
  312. elif type_ == "stvds":
  313. # 123456789012345678901234567890
  314. if format_ == "GML":
  315. read_file.write(" *.xml -- Vector GML files\n")
  316. else:
  317. read_file.write(" *.pack -- GRASS vector files packed with v.pack\n")
  318. elif type_ == "str3ds":
  319. read_file.write(" *.pack -- GRASS 3D raster files packed with r3.pack\n")
  320. read_file.write("%13s -- Projection information in PROJ.4 format\n" %
  321. (proj_file_name))
  322. read_file.write("%13s -- GRASS GIS space time %s dataset information\n" %
  323. (init_file_name, sp.get_new_map_instance(None).get_type()))
  324. read_file.write("%13s -- Time series file, lists all maps by name "
  325. "with interval\n" % (list_file_name))
  326. read_file.write(" time stamps in ISO-Format. Field separator is |\n")
  327. read_file.write("%13s -- The output of t.info\n" %
  328. (metadata_file_name))
  329. read_file.write("%13s -- This file\n" % (read_file_name))
  330. read_file.close()
  331. # Append the file list
  332. tar.add(list_file_name)
  333. tar.add(proj_file_name)
  334. tar.add(init_file_name)
  335. tar.add(read_file_name)
  336. tar.add(metadata_file_name)
  337. tar.close()
  338. os.chdir(old_cwd)
  339. # Move the archive to its destination
  340. shutil.move(os.path.join(new_cwd, tmp_tar_file_name), output)
  341. # Remove the temporary created working directory
  342. shutil.rmtree(new_cwd)