extract.py 10 KB

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