t.vect.observe.strds.py 10 KB

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