v.what.strds.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. #!/usr/bin/env python3
  2. ############################################################################
  3. #
  4. # MODULE: v.what.strds
  5. # AUTHOR(S): Luca delucchi
  6. #
  7. # PURPOSE: Uploads space time raster dataset values at positions of vector points to the table
  8. # COPYRIGHT: (C) 2013 by the GRASS Development Team
  9. #
  10. # This program is free software under the GNU General Public
  11. # License (version 2). Read the file COPYING that comes with GRASS
  12. # for details.
  13. #
  14. #############################################################################
  15. # %module
  16. # % description: Uploads space time raster dataset values at positions of vector points to the table.
  17. # % keyword: vector
  18. # % keyword: temporal
  19. # % keyword: sampling
  20. # % keyword: position
  21. # % keyword: querying
  22. # % keyword: attribute table
  23. # % keyword: time
  24. # %end
  25. # %option G_OPT_V_INPUT
  26. # %end
  27. # %option G_OPT_STRDS_INPUTS
  28. # % key: strds
  29. # %end
  30. # %option G_OPT_V_OUTPUT
  31. # % required: no
  32. # %end
  33. # %option G_OPT_DB_WHERE
  34. # %end
  35. # %option G_OPT_T_WHERE
  36. # % key: t_where
  37. # %end
  38. # %flag
  39. # % key: u
  40. # % label: Update attribute table of input vector map
  41. # % description: Instead of creating a new vector map update the attribute table with value(s)
  42. # %end
  43. import grass.script as grass
  44. from grass.exceptions import CalledModuleError
  45. ############################################################################
  46. class Sample(object):
  47. def __init__(
  48. self, start=None, end=None, raster_names=None, strds_name=None, granularity=None
  49. ):
  50. self.start = start
  51. self.end = end
  52. if raster_names is not None:
  53. self.raster_names = raster_names
  54. else:
  55. self.raster_names = []
  56. self.strds_name = strds_name
  57. self.granu = granularity
  58. def __str__(self):
  59. return "Start: %s\nEnd: %s\nNames: %s\n" % (
  60. str(self.start),
  61. str(self.end),
  62. str(self.raster_names),
  63. )
  64. def printDay(self, date="start"):
  65. output = ""
  66. if date == "start":
  67. output = str(self.start).split(" ")[0].replace("-", "_")
  68. elif date == "end":
  69. output = str(self.end).split(" ")[0].replace("-", "_")
  70. else:
  71. grass.fatal(
  72. "The values accepted by printDay in Sample are:" " 'start', 'end'"
  73. )
  74. if self.granu:
  75. if self.granu.find("minute") != -1 or self.granu.find("second") != -1:
  76. output += "_" + str(self.start).split(" ")[1].replace(":", "_")
  77. return output
  78. ############################################################################
  79. def main():
  80. # lazy imports
  81. import grass.temporal as tgis
  82. from grass.pygrass.utils import copy as gcopy
  83. from grass.pygrass.messages import Messenger
  84. from grass.pygrass.vector import Vector
  85. # Get the options
  86. input = options["input"]
  87. output = options["output"]
  88. strds = options["strds"]
  89. where = options["where"]
  90. tempwhere = options["t_where"]
  91. if output and flags["u"]:
  92. grass.fatal(_("Cannot combine 'output' option and 'u' flag"))
  93. elif not output and not flags["u"]:
  94. grass.fatal(_("'output' option or 'u' flag must be given"))
  95. elif not output and flags["u"]:
  96. grass.warning(
  97. _("Attribute table of vector {name} will be updated...").format(name=input)
  98. )
  99. if where == "" or where == " " or where == "\n":
  100. where = None
  101. overwrite = grass.overwrite()
  102. quiet = True
  103. if grass.verbosity() > 2:
  104. quiet = False
  105. # Check the number of sample strds and the number of columns
  106. strds_names = strds.split(",")
  107. # Make sure the temporal database exists
  108. tgis.init()
  109. # We need a database interface
  110. dbif = tgis.SQLDatabaseInterfaceConnection()
  111. dbif.connect()
  112. samples = []
  113. first_strds = tgis.open_old_stds(strds_names[0], "strds", dbif)
  114. # Single space time raster dataset
  115. if len(strds_names) == 1:
  116. granu = first_strds.get_granularity()
  117. rows = first_strds.get_registered_maps(
  118. "name,mapset,start_time,end_time", tempwhere, "start_time", dbif
  119. )
  120. if not rows:
  121. dbif.close()
  122. grass.fatal(
  123. _("Space time raster dataset <%s> is empty") % first_strds.get_id()
  124. )
  125. for row in rows:
  126. start = row["start_time"]
  127. end = row["end_time"]
  128. raster_maps = [
  129. row["name"] + "@" + row["mapset"],
  130. ]
  131. s = Sample(start, end, raster_maps, first_strds.get_name(), granu)
  132. samples.append(s)
  133. else:
  134. # Multiple space time raster datasets
  135. for name in strds_names[1:]:
  136. dataset = tgis.open_old_stds(name, "strds", dbif)
  137. if dataset.get_temporal_type() != first_strds.get_temporal_type():
  138. grass.fatal(
  139. _(
  140. "Temporal type of space time raster "
  141. "datasets must be equal\n<%(a)s> of type "
  142. "%(type_a)s do not match <%(b)s> of type "
  143. "%(type_b)s"
  144. % {
  145. "a": first_strds.get_id(),
  146. "type_a": first_strds.get_temporal_type(),
  147. "b": dataset.get_id(),
  148. "type_b": dataset.get_temporal_type(),
  149. }
  150. )
  151. )
  152. mapmatrizes = tgis.sample_stds_by_stds_topology(
  153. "strds",
  154. "strds",
  155. strds_names,
  156. strds_names[0],
  157. False,
  158. None,
  159. "equal",
  160. False,
  161. False,
  162. )
  163. # TODO check granularity for multiple STRDS
  164. for i in range(len(mapmatrizes[0])):
  165. isvalid = True
  166. mapname_list = []
  167. for mapmatrix in mapmatrizes:
  168. entry = mapmatrix[i]
  169. if entry["samples"]:
  170. sample = entry["samples"][0]
  171. name = sample.get_id()
  172. if name is None:
  173. isvalid = False
  174. break
  175. else:
  176. mapname_list.append(name)
  177. if isvalid:
  178. entry = mapmatrizes[0][i]
  179. map = entry["granule"]
  180. start, end = map.get_temporal_extent_as_tuple()
  181. s = Sample(start, end, mapname_list, name)
  182. samples.append(s)
  183. # Get the layer and database connections of the input vector
  184. if output:
  185. gcopy(input, output, "vector")
  186. else:
  187. output = input
  188. msgr = Messenger()
  189. perc_curr = 0
  190. perc_tot = len(samples)
  191. pymap = Vector(output)
  192. try:
  193. pymap.open("r")
  194. except:
  195. dbif.close()
  196. grass.fatal(_("Unable to create vector map <%s>" % output))
  197. if len(pymap.dblinks) == 0:
  198. try:
  199. pymap.close()
  200. grass.run_command("v.db.addtable", map=output)
  201. except CalledModuleError:
  202. dbif.close()
  203. grass.fatal(_("Unable to add table <%s> to vector map <%s>" % output))
  204. if pymap.is_open():
  205. pymap.close()
  206. for sample in samples:
  207. raster_names = sample.raster_names
  208. # Call v.what.rast for each raster map
  209. for name in raster_names:
  210. coltype = "DOUBLE PRECISION"
  211. # Get raster map type
  212. raster_map = tgis.RasterDataset(name)
  213. raster_map.load()
  214. if raster_map.metadata.get_datatype() == "CELL":
  215. coltype = "INT"
  216. day = sample.printDay()
  217. column_name = "%s_%s" % (sample.strds_name, day)
  218. column_string = "%s %s" % (column_name, coltype)
  219. column_string.replace(".", "_")
  220. try:
  221. grass.run_command(
  222. "v.db.addcolumn",
  223. map=output,
  224. column=column_string,
  225. overwrite=overwrite,
  226. )
  227. except CalledModuleError:
  228. dbif.close()
  229. grass.fatal(
  230. _("Unable to add column %s to vector map " "<%s> ")
  231. % (column_string, output)
  232. )
  233. try:
  234. grass.run_command(
  235. "v.what.rast",
  236. map=output,
  237. raster=name,
  238. column=column_name,
  239. where=where,
  240. quiet=quiet,
  241. )
  242. except CalledModuleError:
  243. dbif.close()
  244. grass.fatal(
  245. _(
  246. "Unable to run v.what.rast for vector map"
  247. " <%s> and raster map <%s>"
  248. )
  249. % (output, str(raster_names))
  250. )
  251. msgr.percent(perc_curr, perc_tot, 1)
  252. perc_curr += 1
  253. dbif.close()
  254. if __name__ == "__main__":
  255. options, flags = grass.parser()
  256. main()