t.vect.observe.strds.py 10 KB

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