aggregation.py 13 KB

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