v.what.strds.py 8.8 KB

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