mapcalc.py 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  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. @endcode
  8. (C) 2008-2011 by the GRASS Development Team
  9. This program is free software under the GNU General Public
  10. License (>=v2). Read the file COPYING that comes with GRASS
  11. for details.
  12. @author Soeren Gebbert
  13. """
  14. from space_time_datasets import *
  15. from multiprocessing import Process
  16. ############################################################################
  17. def dataset_mapcalculator(inputs, output, type, expression, base, method, nprocs=1, register_null=False, spatial=False):
  18. """!Perform map-calculations of maps from different space time raster/raster3d datasets, using
  19. a specific sampling method to select temporal related maps.
  20. A mapcalc expression can be provided to process the temporal extracted maps.
  21. Mapcalc expressions are supported for raster and raster3d maps.
  22. @param input The name of the input space time raster/raster3d dataset
  23. @param output The name of the extracted new space time raster/raster3d dataset
  24. @param type The type of the dataset: "raster" or "raster3d"
  25. @param method The method to be used for temporal sampling
  26. @param expression The r(3).mapcalc expression
  27. @param base The base name of the new created maps in case a mapclac expression is provided
  28. @param nprocs The number of parallel processes to be used for mapcalc processing
  29. @param register_null Set this number True to register empty maps
  30. @param spatial Check spatial overlap
  31. """
  32. # We need a database interface for fast computation
  33. dbif = sql_database_interface_connection()
  34. dbif.connect()
  35. mapset = core.gisenv()["MAPSET"]
  36. input_name_list = inputs.split(",")
  37. # Process the first input
  38. if input_name_list[0].find("@") >= 0:
  39. id = input_name_list[0]
  40. else:
  41. id = input_name_list[0] + "@" + mapset
  42. if type == "raster":
  43. first_input = space_time_raster_dataset(id)
  44. else:
  45. first_input = space_time_raster3d_dataset(id)
  46. if first_input.is_in_db(dbif) == False:
  47. dbif.close()
  48. core.fatal(_("Space time %s dataset <%s> not found") % (type, id))
  49. # Fill the object with data from the temporal database
  50. first_input.select(dbif)
  51. # All additional inputs in reverse sorted order to avoid wrong name substitution
  52. input_name_list = input_name_list[1:]
  53. input_name_list.sort()
  54. input_name_list.reverse()
  55. input_list = []
  56. for input in input_name_list:
  57. if input.find("@") >= 0:
  58. id = input
  59. else:
  60. id = input + "@" + mapset
  61. sp = first_input.get_new_instance(id)
  62. if sp.is_in_db(dbif) == False:
  63. dbif.close()
  64. core.fatal(_("Space time %s dataset <%s> not found in temporal database") % (type, id))
  65. sp.select(dbif)
  66. input_list.append(copy.copy(sp))
  67. # Create the new space time dataset
  68. if output.find("@") >= 0:
  69. out_id = output
  70. else:
  71. out_id = output + "@" + mapset
  72. new_sp = first_input.get_new_instance(out_id)
  73. # Check if in database
  74. if new_sp.is_in_db(dbif):
  75. if core.overwrite() == False:
  76. dbif.close()
  77. core.fatal(_("Space time %s dataset <%s> is already in database, use overwrite flag to overwrite") % (type, out_id))
  78. # Sample all inputs by the first input and create a sample matrix
  79. if spatial:
  80. core.message(_("Start spatio-temporal sampling"))
  81. else:
  82. core.message(_("Start temporal sampling"))
  83. map_matrix = []
  84. id_list = []
  85. sample_map_list = []
  86. # First entry is the first dataset id
  87. id_list.append(first_input.get_name())
  88. if len(input_list) > 0:
  89. has_samples = False
  90. for dataset in input_list:
  91. list = dataset.sample_by_dataset(stds=first_input, method=method, spatial=spatial, dbif=dbif)
  92. # In case samples are not found
  93. if not list and len(list) == 0:
  94. dbif.close()
  95. core.message(_("No samples found for map calculation"))
  96. return 0
  97. # The fist entries are the samples
  98. map_name_list = []
  99. if has_samples == False:
  100. for entry in list:
  101. granule = entry["granule"]
  102. # Do not consider gaps
  103. if granule.get_id() == None:
  104. continue
  105. sample_map_list.append(granule)
  106. map_name_list.append(granule.get_name())
  107. # Attach the map names
  108. map_matrix.append(copy.copy(map_name_list))
  109. has_samples = True
  110. map_name_list = []
  111. for entry in list:
  112. maplist = entry["samples"]
  113. granule = entry["granule"]
  114. # Do not consider gaps in the sampler
  115. if granule.get_id() == None:
  116. continue
  117. if len(maplist) > 1:
  118. core.warning(_("Found more than a single map in a sample granule. "\
  119. "Only the first map is used for computation. "\
  120. "Use t.rast.aggregate.ds to create synchronous raster datasets."))
  121. # Store all maps! This includes non existent maps, identified by id == None
  122. map_name_list.append(maplist[0].get_name())
  123. # Attach the map names
  124. map_matrix.append(copy.copy(map_name_list))
  125. id_list.append(dataset.get_name())
  126. else:
  127. list = first_input.get_registered_maps_as_objects(dbif=dbif)
  128. if list == None:
  129. dbif.close()
  130. core.message(_("No maps in input dataset"))
  131. return 0
  132. map_name_list = []
  133. for map in list:
  134. map_name_list.append(map.get_name())
  135. sample_map_list.append(map)
  136. # Attach the map names
  137. map_matrix.append(copy.copy(map_name_list))
  138. # Needed for map registration
  139. map_list = []
  140. if len(map_matrix) > 0:
  141. core.message(_("Start mapcalc computation"))
  142. count = 0
  143. # Get the number of samples
  144. num = len(map_matrix[0])
  145. # Parallel processing
  146. proc_list = []
  147. proc_count = 0
  148. # For all samples
  149. for i in range(num):
  150. count += 1
  151. core.percent(count, num, 1)
  152. # Create the r.mapcalc statement for the current time step
  153. map_name = "%s_%i" % (base, count)
  154. expr = "%s = %s" % (map_name, expression)
  155. # Check that all maps are in the sample
  156. valid_maps = True
  157. # Replace all dataset names with their map names of the current time step
  158. for j in range(len(map_matrix)):
  159. if map_matrix[j][i] == None:
  160. valid_maps = False
  161. break
  162. # Substitute the dataset name with the map name
  163. expr = expr.replace(id_list[j], map_matrix[j][i])
  164. # Proceed with the next sample
  165. if valid_maps == False:
  166. continue
  167. # Create the new map id and check if the map is already in the database
  168. map_id = map_name + "@" + mapset
  169. new_map = first_input.get_new_map_instance(map_id)
  170. # Check if new map is in the temporal database
  171. if new_map.is_in_db(dbif):
  172. if core.overwrite() == True:
  173. # Remove the existing temporal database entry
  174. new_map.delete(dbif)
  175. new_map = first_input.get_new_map_instance(map_id)
  176. else:
  177. core.error(_("Map <%s> is already in temporal database, use overwrite flag to overwrite"))
  178. continue
  179. # Set the time stamp
  180. if sample_map_list[i].is_time_absolute():
  181. start, end, tz = sample_map_list[i].get_absolute_time()
  182. new_map.set_absolute_time(start, end, tz)
  183. else:
  184. start, end = sample_map_list[i].get_relative_time()
  185. new_map.set_relative_time(start, end)
  186. map_list.append(new_map)
  187. # Start the parallel r.mapcalc computation
  188. core.verbose(_("Apply mapcalc expression: \"%s\"") % expr)
  189. if type == "raster":
  190. proc_list.append(Process(target=run_mapcalc2d, args=(expr,)))
  191. else:
  192. proc_list.append(Process(target=run_mapcalc3d, args=(expr,)))
  193. proc_list[proc_count].start()
  194. proc_count += 1
  195. if proc_count == nprocs:
  196. proc_count = 0
  197. exitcodes = 0
  198. for proc in proc_list:
  199. proc.join()
  200. exitcodes += proc.exitcode
  201. if exitcodes != 0:
  202. dbif.close()
  203. core.fatal(_("Error while mapcalc computation"))
  204. # Empty process list
  205. proc_list = []
  206. # Register the new maps in the output space time dataset
  207. core.message(_("Start map registration in temporal database"))
  208. # Overwrite an existing dataset if requested
  209. if new_sp.is_in_db(dbif):
  210. if core.overwrite() == True:
  211. new_sp.delete(dbif)
  212. new_sp = first_input.get_new_instance(out_id)
  213. # Copy the ids from the first input
  214. temporal_type, semantic_type, title, description = first_input.get_initial_values()
  215. new_sp.set_initial_values(temporal_type, semantic_type, title, description)
  216. # Insert the dataset in the temporal database
  217. new_sp.insert(dbif)
  218. count = 0
  219. # Insert maps in the temporal database and in the new space time dataset
  220. for new_map in map_list:
  221. count += 1
  222. core.percent(count, num, 1)
  223. # Read the map data
  224. new_map.load()
  225. # In case of a null map continue, do not register null maps
  226. if new_map.metadata.get_min() == None and new_map.metadata.get_max() == None:
  227. if not register_null:
  228. continue
  229. # Insert map in temporal database
  230. new_map.insert(dbif)
  231. new_sp.register_map(new_map, dbif)
  232. # Update the spatio-temporal extent and the metadata table entries
  233. new_sp.update_from_registered_maps(dbif)
  234. core.percent(1, 1, 1)
  235. dbif.close()
  236. ###############################################################################
  237. def run_mapcalc2d(expr):
  238. """Helper function to run r.mapcalc in parallel"""
  239. return core.run_command("r.mapcalc", expression=expr, overwrite=core.overwrite(), quiet=True)
  240. ###############################################################################
  241. def run_mapcalc3d(expr):
  242. """Helper function to run r3.mapcalc in parallel"""
  243. return core.run_command("r3.mapcalc", expression=expr, overwrite=core.overwrite(), quiet=True)