stds_export.py 13 KB

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