t.vect.observe.strds.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. ############################################################################
  4. #
  5. # MODULE: t.vect.observe.strds
  6. # AUTHOR(S): Soeren Gebbert
  7. #
  8. # PURPOSE: Observe specific locations in a space time raster dataset over a period of time using vector points
  9. # COPYRIGHT: (C) 2011-2017 by the GRASS Development Team
  10. #
  11. # This program is free software; you can redistribute it and/or modify
  12. # it under the terms of the GNU General Public License as published by
  13. # the Free Software Foundation; either version 2 of the License, or
  14. # (at your option) any later version.
  15. #
  16. # This program is distributed in the hope that it will be useful,
  17. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. # GNU General Public License for more details.
  20. #
  21. #############################################################################
  22. #%module
  23. #% description: Observes specific locations in a space time raster dataset over a period of time using vector points.
  24. #% keyword: temporal
  25. #% keyword: sampling
  26. #% keyword: vector
  27. #% keyword: time
  28. #%end
  29. #%option G_OPT_V_INPUT
  30. #%end
  31. #%option G_OPT_STRDS_INPUTS
  32. #% key: strds
  33. #%end
  34. #%option G_OPT_STVDS_OUTPUT
  35. #%end
  36. #%option G_OPT_V_OUTPUT
  37. #% key: vector_output
  38. #% description: Name of the new created vector map that stores the sampled values in different layers
  39. #%end
  40. #%option
  41. #% key: columns
  42. #% type: string
  43. #% description: Names of the vector columns to be created and to store sampled raster values, one name for each STRDS
  44. #% required: yes
  45. #% multiple: yes
  46. #%end
  47. #%option G_OPT_DB_WHERE
  48. #%end
  49. import grass.script as grass
  50. import grass.script.raster as raster
  51. from grass.exceptions import CalledModuleError
  52. ############################################################################
  53. class Sample(object):
  54. def __init__(self, start = None, end = None, raster_names = None):
  55. self.start = start
  56. self.end = end
  57. if raster_names != None:
  58. self.raster_names = raster_names
  59. else:
  60. self.raster_names = []
  61. def __str__(self):
  62. return "Start: %s\nEnd: %s\nNames: %s\n"%(str(self.start), str(self.end), str(self.raster_names))
  63. ############################################################################
  64. def main():
  65. #lazy imports
  66. import grass.temporal as tgis
  67. # Get the options
  68. input = options["input"]
  69. output = options["output"]
  70. vector_output = options["vector_output"]
  71. strds = options["strds"]
  72. where = options["where"]
  73. columns = options["columns"]
  74. if where == "" or where == " " or where == "\n":
  75. where = None
  76. overwrite = grass.overwrite()
  77. # Check the number of sample strds and the number of columns
  78. strds_names = strds.split(",")
  79. column_names = columns.split(",")
  80. if len(strds_names) != len(column_names):
  81. grass.fatal(_("The number of columns must be equal to the number of space time raster datasets"))
  82. # Make sure the temporal database exists
  83. tgis.init()
  84. # We need a database interface
  85. dbif = tgis.SQLDatabaseInterfaceConnection()
  86. dbif.connect()
  87. mapset = grass.encode(grass.gisenv()["MAPSET"])
  88. out_sp = tgis.check_new_stds(output, "stvds", dbif, overwrite)
  89. samples = []
  90. first_strds = tgis.open_old_stds(strds_names[0], "strds", dbif)
  91. # Single space time raster dataset
  92. if len(strds_names) == 1:
  93. rows = first_strds.get_registered_maps(
  94. columns="name,mapset,start_time,end_time",
  95. order="start_time", dbif=dbif)
  96. if not rows:
  97. dbif.close()
  98. grass.fatal(_("Space time raster dataset <%s> is empty") %
  99. out_sp.get_id())
  100. for row in rows:
  101. start = row["start_time"]
  102. end = row["end_time"]
  103. raster_maps = [row["name"] + "@" + row["mapset"],]
  104. s = Sample(start, end, raster_maps)
  105. samples.append(s)
  106. else:
  107. # Multiple space time raster datasets
  108. for name in strds_names[1:]:
  109. dataset = tgis.open_old_stds(name, "strds", dbif)
  110. if dataset.get_temporal_type() != first_strds.get_temporal_type():
  111. grass.fatal(_("Temporal type of space time raster datasets must be equal\n"
  112. "<%(a)s> of type %(type_a)s do not match <%(b)s> of type %(type_b)s"%\
  113. {"a":first_strds.get_id(),
  114. "type_a":first_strds.get_temporal_type(),
  115. "b":dataset.get_id(),
  116. "type_b":dataset.get_temporal_type()}))
  117. mapmatrizes = tgis.sample_stds_by_stds_topology("strds", "strds", strds_names,
  118. strds_names[0], False, None,
  119. "equal", False, False)
  120. for i in range(len(mapmatrizes[0])):
  121. isvalid = True
  122. mapname_list = []
  123. for mapmatrix in mapmatrizes:
  124. entry = mapmatrix[i]
  125. if entry["samples"]:
  126. sample = entry["samples"][0]
  127. name = sample.get_id()
  128. if name is None:
  129. isvalid = False
  130. break
  131. else:
  132. mapname_list.append(name)
  133. if isvalid:
  134. entry = mapmatrizes[0][i]
  135. map = entry["granule"]
  136. start, end = map.get_temporal_extent_as_tuple()
  137. s = Sample(start, end, mapname_list)
  138. samples.append(s)
  139. num_samples = len(samples)
  140. # Get the layer and database connections of the input vector
  141. vector_db = grass.vector.vector_db(input)
  142. # We copy the vector table and create the new layers
  143. if vector_db:
  144. # Use the first layer to copy the categories from
  145. layers = "1,"
  146. else:
  147. layers = ""
  148. first = True
  149. for layer in range(num_samples):
  150. layer += 1
  151. # Skip existing layer
  152. if vector_db and layer in vector_db and \
  153. vector_db[layer]["layer"] == layer:
  154. continue
  155. if first:
  156. layers += "%i" % (layer)
  157. first = False
  158. else:
  159. layers += ",%i" % (layer)
  160. vectmap = vector_output
  161. # We create a new vector map using the categories of the original map
  162. try:
  163. grass.run_command("v.category", input=input, layer=layers,
  164. output=vectmap, option="transfer",
  165. overwrite=overwrite)
  166. except CalledModuleError:
  167. grass.fatal(_("Unable to create new layers for vector map <%s>")
  168. % (vectmap))
  169. title = _("Observaion of space time raster dataset(s) <%s>") % (strds)
  170. description= _("Observation of space time raster dataset(s) <%s>"
  171. " with vector map <%s>") % (strds, input)
  172. # Create the output space time vector dataset
  173. out_sp = tgis.open_new_stds(output, "stvds",
  174. first_strds.get_temporal_type(),
  175. title, description,
  176. first_strds.get_semantic_type(),
  177. dbif, overwrite)
  178. dummy = out_sp.get_new_map_instance(None)
  179. # Sample the space time raster dataset with the vector
  180. # map at specific layer with v.what.rast
  181. count = 1
  182. for sample in samples:
  183. raster_names = sample.raster_names
  184. if len(raster_names) != len(column_names):
  185. grass.fatal(_("The number of raster maps in a granule must "
  186. "be equal to the number of column names"))
  187. # Create the columns creation string
  188. columns_string = ""
  189. for name, column in zip(raster_names, column_names):
  190. # The column is by default double precision
  191. coltype = "DOUBLE PRECISION"
  192. # Get raster map type
  193. raster_map = tgis.RasterDataset(name)
  194. raster_map.load()
  195. if raster_map.metadata.get_datatype() == "CELL":
  196. coltype = "INT"
  197. tmp_string = "%s %s,"%(column, coltype)
  198. columns_string += tmp_string
  199. # Remove last comma
  200. columns_string = columns_string[0:len(columns_string) - 1]
  201. # Try to add a column
  202. if vector_db and count in vector_db and vector_db[count]["table"]:
  203. try:
  204. grass.run_command("v.db.addcolumn", map=vectmap,
  205. layer=count, column=columns_string,
  206. overwrite=overwrite)
  207. except CalledModuleError:
  208. dbif.close()
  209. grass.fatal(_("Unable to add column %s to vector map <%s> "
  210. "with layer %i") % (columns_string, vectmap, count))
  211. else:
  212. # Try to add a new table
  213. grass.message("Add table to layer %i" % (count))
  214. try:
  215. grass.run_command("v.db.addtable", map=vectmap, layer=count,
  216. columns=columns_string, overwrite=overwrite)
  217. except CalledModuleError:
  218. dbif.close()
  219. grass.fatal(_("Unable to add table to vector map "
  220. "<%s> with layer %i") % (vectmap, count))
  221. # Call v.what.rast for each raster map
  222. for name, column in zip(raster_names, column_names):
  223. try:
  224. grass.run_command("v.what.rast", map=vectmap,
  225. layer=count, raster=name,
  226. column=column, where=where)
  227. except CalledModuleError:
  228. dbif.close()
  229. grass.fatal(_("Unable to run v.what.rast for vector map <%s> "
  230. "with layer %i and raster map <%s>") % \
  231. (vectmap, count, str(raster_names)))
  232. vect = out_sp.get_new_map_instance(dummy.build_id(vectmap,
  233. mapset, str(count)))
  234. vect.load()
  235. start = sample.start
  236. end = sample.end
  237. if out_sp.is_time_absolute():
  238. vect.set_absolute_time(start, end)
  239. else:
  240. vect.set_relative_time(
  241. start, end, first_strds.get_relative_time_unit())
  242. if vect.is_in_db(dbif):
  243. vect.update_all(dbif)
  244. else:
  245. vect.insert(dbif)
  246. out_sp.register_map(vect, dbif)
  247. count += 1
  248. out_sp.update_from_registered_maps(dbif)
  249. dbif.close()
  250. if __name__ == "__main__":
  251. options, flags = grass.parser()
  252. main()