aggregation.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  1. """!@package grass.temporal
  2. @brief GRASS Python scripting module (temporal GIS functions)
  3. Temporal GIS related functions to be used in Python scripts.
  4. Usage:
  5. @code
  6. import grass.temporal as tgis
  7. tgis.aggregate_raster_maps(dataset, mapset, inputs, base, start, end,
  8. count, method, register_null, dbif)
  9. ...
  10. @endcode
  11. (C) 2012-2013 by the GRASS Development Team
  12. This program is free software under the GNU General Public
  13. License (>=v2). Read the file COPYING that comes with GRASS
  14. for details.
  15. @author Soeren Gebbert
  16. """
  17. from space_time_datasets import *
  18. import grass.script as gscript
  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() == 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 database, " \
  111. "use overwrite flag to overwrite"%({"name":new_map.get_name()})))
  112. return
  113. msgr.verbose(_("Computing aggregation of maps between %(st)s - %(end)s" % {
  114. 'st': str(start), 'end': str(end)}))
  115. # Create the r.series input file
  116. filename = gscript.tempfile(True)
  117. file = open(filename, 'w')
  118. for name in inputs:
  119. string = "%s\n" % (name)
  120. file.write(string)
  121. file.close()
  122. # Run r.series
  123. if len(inputs) > 1000 :
  124. ret = gscript.run_command("r.series", flags="z", file=filename,
  125. output=output, overwrite=gscript.overwrite(),
  126. method=method)
  127. else:
  128. ret = gscript.run_command("r.series", file=filename,
  129. output=output, overwrite=gscript.overwrite(),
  130. method=method)
  131. if ret != 0:
  132. dbif.close()
  133. msgr.fatal(_("Error occurred in r.series computation"))
  134. # Read the raster map data
  135. new_map.load()
  136. # In case of a null map continue, do not register null maps
  137. if new_map.metadata.get_min() is None and new_map.metadata.get_max() is None:
  138. if not register_null:
  139. gscript.run_command("g.remove", flags='f', type='rast', pattern=output)
  140. return None
  141. return new_map
  142. ##############################################################################
  143. def aggregate_by_topology(granularity_list, granularity, map_list, topo_list, basename, time_suffix,
  144. offset=0, method="average", nprocs=1, spatial=None, dbif=None,
  145. overwrite=False):
  146. """!Aggregate a list of raster input maps with r.series
  147. @param granularity_list A list of AbstractMapDataset objects.
  148. The temporal extents of the objects are used
  149. to build the spatio-temporal topology with the 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 (overwritten by time_suffix)
  159. @param method The aggregation method of r.series (average,min,max, ...)
  160. @param nprocs The number of processes used for parallel computation
  161. @param spatial This indicates if the spatial topology is created as well:
  162. spatial can be None (no spatial topology), "2D" using west, east,
  163. south, north or "3D" using west, east, south, north, bottom, top
  164. @param dbif The database interface to be used
  165. @param overwrite Overwrite existing raster maps
  166. @return A list of RasterDataset objects that contain the new map names and
  167. the temporal extent for map registration
  168. """
  169. import grass.pygrass.modules as pymod
  170. import copy
  171. msgr = get_tgis_message_interface()
  172. dbif, connected = init_dbif(dbif)
  173. topo_builder = SpatioTemporalTopologyBuilder()
  174. topo_builder.build(mapsA=granularity_list, mapsB=map_list, spatial=spatial)
  175. # The module queue for parallel execution
  176. process_queue = pymod.ParallelModuleQueue(int(nprocs))
  177. # Dummy process object that will be deep copied
  178. # and be put into the process queue
  179. r_series = pymod.Module("r.series", output="spam", method=[method],
  180. overwrite=overwrite, quiet=True, run_=False,
  181. finish_=False)
  182. g_copy = pymod.Module("g.copy", rast=['spam', 'spamspam'],
  183. quiet=True, run_=False, finish_=False)
  184. output_list = []
  185. count = 0
  186. for granule in granularity_list:
  187. msgr.percent(count, len(granularity_list), 1)
  188. count += 1
  189. aggregation_list = []
  190. if "equal" in topo_list and granule.equal:
  191. for map_layer in granule.equal:
  192. aggregation_list.append(map_layer.get_name())
  193. if "contains" in topo_list and granule.contains:
  194. for map_layer in granule.contains:
  195. aggregation_list.append(map_layer.get_name())
  196. if "during" in topo_list and granule.during:
  197. for map_layer in granule.during:
  198. aggregation_list.append(map_layer.get_name())
  199. if "starts" in topo_list and granule.starts:
  200. for map_layer in granule.starts:
  201. aggregation_list.append(map_layer.get_name())
  202. if "started" in topo_list and granule.started:
  203. for map_layer in granule.started:
  204. aggregation_list.append(map_layer.get_name())
  205. if "finishes" in topo_list and granule.finishes:
  206. for map_layer in granule.finishes:
  207. aggregation_list.append(map_layer.get_name())
  208. if "finished" in topo_list and granule.finished:
  209. for map_layer in granule.finished:
  210. aggregation_list.append(map_layer.get_name())
  211. if "overlaps" in topo_list and granule.overlaps:
  212. for map_layer in granule.overlaps:
  213. aggregation_list.append(map_layer.get_name())
  214. if "overlapped" in topo_list and granule.overlapped:
  215. for map_layer in granule.overlapped:
  216. aggregation_list.append(map_layer.get_name())
  217. if aggregation_list:
  218. msgr.verbose(_("Aggregating %(len)i raster maps from %(start)s to %(end)s") \
  219. %({"len":len(aggregation_list),
  220. "start":str(granule.temporal_extent.get_start_time()),
  221. "end":str(granule.temporal_extent.get_end_time())}))
  222. if granule.is_time_absolute() is True and time_suffix is True:
  223. suffix = create_suffix_from_datetime(granule.temporal_extent.get_start_time(),
  224. granularity)
  225. else:
  226. suffix = gscript.get_num_suffix(count + int(offset),
  227. len(granularity_list) + int(offset))
  228. output_name = "%s_%s"%(basename, suffix)
  229. map_layer = RasterDataset("%s@%s"%(output_name,
  230. get_current_mapset()))
  231. map_layer.set_temporal_extent(granule.get_temporal_extent())
  232. if map_layer.map_exists() is True and overwrite is False:
  233. msgr.fatal(_("Unable to perform aggregation. Output raster map <%(name)s> "\
  234. "exists and overwrite flag was not set"%({"name":output_name})))
  235. output_list.append(map_layer)
  236. if len(aggregation_list) > 1:
  237. # Create the r.series input file
  238. filename = gscript.tempfile(True)
  239. file = open(filename, 'w')
  240. for name in aggregation_list:
  241. string = "%s\n" % (name)
  242. file.write(string)
  243. file.close()
  244. mod = copy.deepcopy(r_series)
  245. mod(file=filename, output=output_name)
  246. if len(aggregation_list) > 1000 :
  247. mod(flags="z")
  248. process_queue.put(mod)
  249. else:
  250. mod = copy.deepcopy(g_copy)
  251. mod(rast=[aggregation_list[0], output_name])
  252. process_queue.put(mod)
  253. if connected:
  254. dbif.close()
  255. msgr.percent(1, 1, 1)
  256. return output_list