extract.py 11 KB

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