aggregation.py 14 KB

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