aggregation.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. """
  2. Aggregation methods for space time raster datasets
  3. Usage:
  4. .. code-block:: python
  5. import grass.temporal as tgis
  6. tgis.aggregate_raster_maps(dataset, mapset, inputs, base, start, end, count, method, register_null, dbif)
  7. (C) 2012-2013 by the GRASS Development Team
  8. This program is free software under the GNU General Public
  9. License (>=v2). Read the file COPYING that comes with GRASS
  10. for details.
  11. :author: Soeren Gebbert
  12. """
  13. from space_time_datasets import *
  14. import grass.script as gscript
  15. ###############################################################################
  16. def collect_map_names(sp, dbif, start, end, sampling):
  17. """Gather all maps from dataset using a specific sample method
  18. :param sp: The space time raster dataset to select aps from
  19. :param dbif: The temporal database interface to use
  20. :param start: The start time of the sample interval, may be relative or
  21. absolute
  22. :param end: The end time of the sample interval, may be relative or
  23. absolute
  24. :param sampling: The sampling methods to use
  25. """
  26. use_start = False
  27. use_during = False
  28. use_overlap = False
  29. use_contain = False
  30. use_equal = False
  31. use_follows = False
  32. use_precedes = False
  33. # Initialize the methods
  34. if sampling:
  35. for name in sampling.split(","):
  36. if name == "start":
  37. use_start = True
  38. if name == "during":
  39. use_during = True
  40. if name == "overlap":
  41. use_overlap = True
  42. if name == "contain":
  43. use_contain = True
  44. if name == "equal":
  45. use_equal = True
  46. if name == "follows":
  47. use_follows = True
  48. if name == "precedes":
  49. use_precedes = True
  50. else:
  51. use_start = True
  52. if sp.get_map_time() != "interval":
  53. use_start = True
  54. use_during = False
  55. use_overlap = False
  56. use_contain = False
  57. use_equal = False
  58. use_follows = False
  59. use_precedes = False
  60. where = create_temporal_relation_sql_where_statement(start, end,
  61. use_start,
  62. use_during,
  63. use_overlap,
  64. use_contain,
  65. use_equal,
  66. use_follows,
  67. use_precedes)
  68. rows = sp.get_registered_maps("id", where, "start_time", dbif)
  69. if not rows:
  70. return None
  71. names = []
  72. for row in rows:
  73. names.append(row["id"])
  74. return names
  75. ###############################################################################
  76. def aggregate_raster_maps(inputs, base, start, end, count, method,
  77. register_null, dbif, offset=0):
  78. """Aggregate a list of raster input maps with r.series
  79. :param inputs: The names of the raster maps to be aggregated
  80. :param base: The basename of the new created raster maps
  81. :param start: The start time of the sample interval, may be relative or
  82. absolute
  83. :param end: The end time of the sample interval, may be relative or
  84. absolute
  85. :param count: The number to be attached to the basename of the new
  86. created raster map
  87. :param method: The aggreation method to be used by r.series
  88. :param register_null: If true null maps will be registered in the space
  89. time raster dataset, if false not
  90. :param dbif: The temporal database interface to use
  91. :param offset: Offset to be added to the map counter to create the map ids
  92. """
  93. msgr = get_tgis_message_interface()
  94. msgr.verbose(_("Aggregating %s raster maps") % (len(inputs)))
  95. output = "%s_%i" % (base, int(offset) + count)
  96. mapset = get_current_mapset()
  97. map_id = output + "@" + mapset
  98. new_map = RasterDataset(map_id)
  99. # Check if new map is in the temporal database
  100. if new_map.is_in_db(dbif):
  101. if gscript.overwrite() is True:
  102. # Remove the existing temporal database entry
  103. new_map.delete(dbif)
  104. new_map = RasterDataset(map_id)
  105. else:
  106. msgr.error(_("Raster map <%(name)s> is already in temporal "
  107. "database, use overwrite flag to overwrite" %
  108. ({"name": new_map.get_name()})))
  109. return
  110. msgr.verbose(_("Computing aggregation of maps between %(st)s - %(end)s" % {
  111. 'st': str(start), 'end': str(end)}))
  112. # Create the r.series input file
  113. filename = gscript.tempfile(True)
  114. file = open(filename, 'w')
  115. for name in inputs:
  116. string = "%s\n" % (name)
  117. file.write(string)
  118. file.close()
  119. # Run r.series
  120. if len(inputs) > 1000:
  121. ret = gscript.run_command("r.series", flags="z", file=filename,
  122. output=output, overwrite=gscript.overwrite(),
  123. method=method)
  124. else:
  125. ret = gscript.run_command("r.series", file=filename,
  126. output=output, overwrite=gscript.overwrite(),
  127. method=method)
  128. if ret != 0:
  129. dbif.close()
  130. msgr.fatal(_("Error occurred in r.series computation"))
  131. # Read the raster map data
  132. new_map.load()
  133. # In case of a null map continue, do not register null maps
  134. if new_map.metadata.get_min() is None and \
  135. new_map.metadata.get_max() is None:
  136. if not register_null:
  137. gscript.run_command("g.remove", flags='f', type='rast',
  138. name=output)
  139. return None
  140. return new_map
  141. ##############################################################################
  142. def aggregate_by_topology(granularity_list, granularity, map_list, topo_list,
  143. basename, time_suffix, offset=0, method="average",
  144. nprocs=1, spatial=None, dbif=None, overwrite=False):
  145. """Aggregate a list of raster input maps with r.series
  146. :param granularity_list: A list of AbstractMapDataset objects.
  147. The temporal extents of the objects are used
  148. to build the spatio-temporal topology with the
  149. map list objects
  150. :param granularity: The granularity of the granularity list
  151. :param map_list: A list of RasterDataset objects that contain the raster
  152. maps that should be aggregated
  153. :param topo_list: A list of strings of topological relations that are
  154. used to select the raster maps for aggregation
  155. :param basename: The basename of the new generated raster maps
  156. :param time_suffix: Use the granularity truncated start time of the
  157. actual granule to create the suffix for the basename
  158. :param offset: Use a numerical offset for suffix generation
  159. (overwritten by time_suffix)
  160. :param method: The aggregation method of r.series (average,min,max, ...)
  161. :param nprocs: The number of processes used for parallel computation
  162. :param spatial: This indicates if the spatial topology is created as
  163. well: spatial can be None (no spatial topology), "2D"
  164. using west, east, south, north or "3D" using west,
  165. east, south, north, bottom, top
  166. :param dbif: The database interface to be used
  167. :param overwrite: Overwrite existing raster maps
  168. :return: A list of RasterDataset objects that contain the new map names
  169. and the temporal extent for map registration
  170. """
  171. import grass.pygrass.modules as pymod
  172. import copy
  173. msgr = get_tgis_message_interface()
  174. dbif, connected = init_dbif(dbif)
  175. topo_builder = SpatioTemporalTopologyBuilder()
  176. topo_builder.build(mapsA=granularity_list, mapsB=map_list, spatial=spatial)
  177. # The module queue for parallel execution
  178. process_queue = pymod.ParallelModuleQueue(int(nprocs))
  179. # Dummy process object that will be deep copied
  180. # and be put into the process queue
  181. r_series = pymod.Module("r.series", output="spam", method=[method],
  182. overwrite=overwrite, quiet=True, run_=False,
  183. finish_=False)
  184. g_copy = pymod.Module("g.copy", rast=['spam', 'spamspam'],
  185. quiet=True, run_=False, finish_=False)
  186. output_list = []
  187. count = 0
  188. for granule in granularity_list:
  189. msgr.percent(count, len(granularity_list), 1)
  190. count += 1
  191. aggregation_list = []
  192. if "equal" in topo_list and granule.equal:
  193. for map_layer in granule.equal:
  194. aggregation_list.append(map_layer.get_name())
  195. if "contains" in topo_list and granule.contains:
  196. for map_layer in granule.contains:
  197. aggregation_list.append(map_layer.get_name())
  198. if "during" in topo_list and granule.during:
  199. for map_layer in granule.during:
  200. aggregation_list.append(map_layer.get_name())
  201. if "starts" in topo_list and granule.starts:
  202. for map_layer in granule.starts:
  203. aggregation_list.append(map_layer.get_name())
  204. if "started" in topo_list and granule.started:
  205. for map_layer in granule.started:
  206. aggregation_list.append(map_layer.get_name())
  207. if "finishes" in topo_list and granule.finishes:
  208. for map_layer in granule.finishes:
  209. aggregation_list.append(map_layer.get_name())
  210. if "finished" in topo_list and granule.finished:
  211. for map_layer in granule.finished:
  212. aggregation_list.append(map_layer.get_name())
  213. if "overlaps" in topo_list and granule.overlaps:
  214. for map_layer in granule.overlaps:
  215. aggregation_list.append(map_layer.get_name())
  216. if "overlapped" in topo_list and granule.overlapped:
  217. for map_layer in granule.overlapped:
  218. aggregation_list.append(map_layer.get_name())
  219. if aggregation_list:
  220. msgr.verbose(_("Aggregating %(len)i raster maps from %(start)s to"
  221. " %(end)s") %({"len": len(aggregation_list),
  222. "start": str(granule.temporal_extent.get_start_time()),
  223. "end": str(granule.temporal_extent.get_end_time())}))
  224. if granule.is_time_absolute() is True and time_suffix is True:
  225. suffix = create_suffix_from_datetime(granule.temporal_extent.get_start_time(),
  226. granularity)
  227. else:
  228. suffix = gscript.get_num_suffix(count + int(offset),
  229. len(granularity_list) + int(offset))
  230. output_name = "%s_%s" % (basename, suffix)
  231. map_layer = RasterDataset("%s@%s" % (output_name,
  232. get_current_mapset()))
  233. map_layer.set_temporal_extent(granule.get_temporal_extent())
  234. if map_layer.map_exists() is True and overwrite is False:
  235. msgr.fatal(_("Unable to perform aggregation. Output raster "
  236. "map <%(name)s> exists and overwrite flag was "
  237. "not set" % ({"name": output_name})))
  238. output_list.append(map_layer)
  239. if len(aggregation_list) > 1:
  240. # Create the r.series input file
  241. filename = gscript.tempfile(True)
  242. file = open(filename, 'w')
  243. for name in aggregation_list:
  244. string = "%s\n" % (name)
  245. file.write(string)
  246. file.close()
  247. mod = copy.deepcopy(r_series)
  248. mod(file=filename, output=output_name)
  249. if len(aggregation_list) > 1000:
  250. mod(flags="z")
  251. process_queue.put(mod)
  252. else:
  253. mod = copy.deepcopy(g_copy)
  254. mod(rast=[aggregation_list[0], output_name])
  255. process_queue.put(mod)
  256. if connected:
  257. dbif.close()
  258. msgr.percent(1, 1, 1)
  259. return output_list