aggregation.py 13 KB

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