extract.py 10 KB

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