t.vect.observe.strds.py 10 KB

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