extract.py 11 KB

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