t.vect.observe.strds.py 10 KB

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