extract.py 8.5 KB

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