mapcalc.py 12 KB

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