aggregation.py 12 KB

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