extract.py 8.6 KB

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