stds_export.py 14 KB

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