extract.py 11 KB

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