extract.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  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 extract_dataset(input, output, type, where, expression, base, nprocs=1,
  14. register_null=False, layer=1,
  15. vtype="point,line,boundary,centroid,area,face"):
  16. """!Extract a subset of a space time raster, raster3d or vector dataset
  17. A mapcalc expression can be provided to process the temporal extracted maps.
  18. Mapcalc expressions are supported for raster and raster3d maps.
  19. @param input The name of the input space time raster/raster3d dataset
  20. @param output The name of the extracted new space time raster/raster3d dataset
  21. @param type The type of the dataset: "raster", "raster3d" or vector
  22. @param where The temporal SQL WHERE statement for subset extraction
  23. @param expression The r(3).mapcalc expression or the v.extract where statement
  24. @param base The base name of the new created maps in case a mapclac
  25. expression is provided
  26. @param nprocs The number of parallel processes to be used for mapcalc processing
  27. @param register_null Set this number True to register empty maps
  28. (only raster and raster3d maps)
  29. @param layer The vector layer number to be used when no timestamped
  30. layer is present, default is 1
  31. @param vtype The feature type to be extracted for vector maps, default
  32. is point,line,boundary,centroid,area and face
  33. """
  34. # Check the parameters
  35. if expression and not base:
  36. core.fatal(_("You need to specify the base name of new created maps"))
  37. mapset = core.gisenv()["MAPSET"]
  38. if input.find("@") >= 0:
  39. id = input
  40. else:
  41. id = input + "@" + mapset
  42. if type == "raster":
  43. sp = space_time_raster_dataset(id)
  44. elif type == "raster3d":
  45. sp = space_time_raster3d_dataset(id)
  46. elif type == "vector":
  47. sp = space_time_vector_dataset(id)
  48. dummy = sp.get_new_map_instance(None)
  49. dbif = ()
  50. dbif.connect()
  51. if not sp.is_in_db(dbif):
  52. dbif.close()
  53. core.fatal(_("Space time %s dataset <%s> not found") % (type, id))
  54. if expression and not base:
  55. dbif.close()
  56. core.fatal(_("Please specify base="))
  57. sp.select(dbif)
  58. if output.find("@") >= 0:
  59. out_id = output
  60. else:
  61. out_id = output + "@" + mapset
  62. # The new space time dataset
  63. new_sp = sp.get_new_instance(out_id)
  64. if new_sp.is_in_db():
  65. if not core.overwrite():
  66. dbif.close()
  67. core.fatal(_("Space time %s dataset <%s> is already in database,"
  68. " use overwrite flag to overwrite") % (type, out_id))
  69. if type == "vector":
  70. rows = sp.get_registered_maps(
  71. "id,name,mapset,layer", where, "start_time", dbif)
  72. else:
  73. rows = sp.get_registered_maps("id", where, "start_time", dbif)
  74. new_maps = {}
  75. if rows:
  76. num_rows = len(rows)
  77. core.percent(0, num_rows, 1)
  78. # Run the mapcalc expression
  79. if expression:
  80. count = 0
  81. proc_count = 0
  82. proc_list = []
  83. for row in rows:
  84. count += 1
  85. core.percent(count, num_rows, 1)
  86. map_name = "%s_%i" % (base, count)
  87. # We need to modify the r(3).mapcalc expression
  88. if type != "vector":
  89. expr = "%s = %s" % (map_name, expression)
  90. expr = expr.replace(sp.base.get_map_id(), row["id"])
  91. expr = expr.replace(sp.base.get_name(), row["id"])
  92. # We need to build the id
  93. map_id = dummy.build_id(map_name, mapset)
  94. else:
  95. map_id = dummy.build_id(map_name, mapset, row["layer"])
  96. new_map = sp.get_new_map_instance(map_id)
  97. # Check if new map is in the temporal database
  98. if new_map.is_in_db(dbif):
  99. if core.overwrite():
  100. # Remove the existing temporal database entry
  101. new_map.delete(dbif)
  102. new_map = sp.get_new_map_instance(map_id)
  103. else:
  104. core.error(_("Map <%s> is already in temporal database,"
  105. " use overwrite flag to overwrite") %
  106. (new_map.get_map_id()))
  107. continue
  108. # Add process to the process list
  109. if type == "raster":
  110. core.verbose(_("Apply r.mapcalc expression: \"%s\"")
  111. % expr)
  112. proc_list.append(Process(target=run_mapcalc2d,
  113. args=(expr,)))
  114. elif type == "raster3d":
  115. core.verbose(_("Apply r3.mapcalc expression: \"%s\"")
  116. % expr)
  117. proc_list.append(Process(target=run_mapcalc3d,
  118. args=(expr,)))
  119. elif type == "vector":
  120. core.verbose(_("Apply v.extract where statement: \"%s\"")
  121. % expression)
  122. if row["layer"]:
  123. proc_list.append(Process(target=run_vector_extraction,
  124. args=(row["name"] + "@" + row["mapset"],
  125. map_name, row["layer"],
  126. vtype, expression)))
  127. else:
  128. proc_list.append(Process(target=run_vector_extraction,
  129. args=(row["name"] + "@" + row["mapset"],
  130. map_name, layer, vtype,
  131. expression)))
  132. proc_list[proc_count].start()
  133. proc_count += 1
  134. # Join processes if the maximum number of processes are reached or the end of the
  135. # loop is reached
  136. if proc_count == nprocs or proc_count == num_rows:
  137. proc_count = 0
  138. exitcodes = 0
  139. for proc in proc_list:
  140. proc.join()
  141. exitcodes += proc.exitcode
  142. if exitcodes != 0:
  143. dbif.close()
  144. core.fatal(_("Error while computation"))
  145. # Empty process list
  146. proc_list = []
  147. # Store the new maps
  148. new_maps[row["id"]] = new_map
  149. core.percent(0, num_rows, 1)
  150. # Insert the new space time dataset
  151. if new_sp.is_in_db(dbif):
  152. if core.overwrite():
  153. new_sp.delete(dbif)
  154. new_sp = sp.get_new_instance(out_id)
  155. temporal_type, semantic_type, title, description = sp.get_initial_values()
  156. new_sp.set_initial_values(
  157. temporal_type, semantic_type, title, description)
  158. new_sp.insert(dbif)
  159. # collect empty maps to remove them
  160. empty_maps = []
  161. # Register the maps in the database
  162. count = 0
  163. for row in rows:
  164. count += 1
  165. core.percent(count, num_rows, 1)
  166. old_map = sp.get_new_map_instance(row["id"])
  167. old_map.select(dbif)
  168. if expression:
  169. # Register the new maps
  170. if row["id"] in new_maps:
  171. new_map = new_maps[row["id"]]
  172. # Read the raster map data
  173. new_map.load()
  174. # In case of a empty map continue, do not register empty maps
  175. if type == "raster" or type == "raster3d":
  176. if new_map.metadata.get_min() is None and \
  177. new_map.metadata.get_max() is None:
  178. if not register_null:
  179. empty_maps.append(new_map)
  180. continue
  181. elif type == "vector":
  182. if new_map.metadata.get_primitives() == 0 or \
  183. new_map.metadata.get_primitives() is None:
  184. if not register_null:
  185. empty_maps.append(new_map)
  186. continue
  187. # Set the time stamp
  188. if old_map.is_time_absolute():
  189. start, end, tz = old_map.get_absolute_time()
  190. new_map.set_absolute_time(start, end, tz)
  191. else:
  192. start, end = old_map.get_relative_time()
  193. new_map.set_relative_time(start, end)
  194. # Insert map in temporal database
  195. new_map.insert(dbif)
  196. new_sp.register_map(new_map, dbif)
  197. else:
  198. new_sp.register_map(old_map, dbif)
  199. # Update the spatio-temporal extent and the metadata table entries
  200. new_sp.update_from_registered_maps(dbif)
  201. core.percent(num_rows, num_rows, 1)
  202. # Remove empty maps
  203. if len(empty_maps) > 0:
  204. names = ""
  205. count = 0
  206. for map in empty_maps:
  207. if count == 0:
  208. names += "%s" % (map.get_name())
  209. else:
  210. names += ",%s" % (map.get_name())
  211. count += 1
  212. if type == "raster":
  213. core.run_command("g.remove", rast=names, quiet=True)
  214. elif type == "raster3d":
  215. core.run_command("g.remove", rast3d=names, quiet=True)
  216. elif type == "vector":
  217. core.run_command("g.remove", vect=names, quiet=True)
  218. dbif.close()
  219. ###############################################################################
  220. def run_mapcalc2d(expr):
  221. """Helper function to run r.mapcalc in parallel"""
  222. return core.run_command("r.mapcalc", expression=expr,
  223. overwrite=core.overwrite(), quiet=True)
  224. def run_mapcalc3d(expr):
  225. """Helper function to run r3.mapcalc in parallel"""
  226. return core.run_command("r3.mapcalc", expression=expr,
  227. overwrite=core.overwrite(), quiet=True)
  228. def run_vector_extraction(input, output, layer, type, where):
  229. """Helper function to run r.mapcalc in parallel"""
  230. return core.run_command("v.extract", input=input, output=output,
  231. layer=layer, type=type, where=where,
  232. overwrite=core.overwrite(), quiet=True)