stds_export.py 14 KB

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