t.vect.observe.strds.py 11 KB

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