extract.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. """
  2. Extract functions for space time raster, 3d raster and vector datasets
  3. (C) 2012-2013 by the GRASS Development Team
  4. This program is free software under the GNU General Public
  5. License (>=v2). Read the file COPYING that comes with GRASS
  6. for details.
  7. :authors: Soeren Gebbert
  8. """
  9. from grass.script.utils import get_num_suffix
  10. from space_time_datasets import *
  11. from open_stds import *
  12. from multiprocessing import Process
  13. import grass.script as gscript
  14. ############################################################################
  15. def extract_dataset(input, output, type, where, expression, base, nprocs=1,
  16. register_null=False, layer=1,
  17. vtype="point,line,boundary,centroid,area,face"):
  18. """Extract a subset of a space time raster, raster3d or vector dataset
  19. A mapcalc expression can be provided to process the temporal extracted
  20. maps.
  21. Mapcalc expressions are supported for raster and raster3d maps.
  22. :param input: The name of the input space time raster/raster3d dataset
  23. :param output: The name of the extracted new space time raster/raster3d
  24. dataset
  25. :param type: The type of the dataset: "raster", "raster3d" or vector
  26. :param where: The temporal SQL WHERE statement for subset extraction
  27. :param expression: The r(3).mapcalc expression or the v.extract where
  28. statement
  29. :param base: The base name of the new created maps in case a mapclac
  30. expression is provided
  31. :param nprocs: The number of parallel processes to be used for mapcalc
  32. processing
  33. :param register_null: Set this number True to register empty maps
  34. (only raster and raster3d maps)
  35. :param layer: The vector layer number to be used when no timestamped
  36. layer is present, default is 1
  37. :param vtype: The feature type to be extracted for vector maps, default
  38. is point,line,boundary,centroid,area and face
  39. """
  40. # Check the parameters
  41. msgr = get_tgis_message_interface()
  42. if expression and not base:
  43. msgr.fatal(_("You need to specify the base name of new created maps"))
  44. mapset = get_current_mapset()
  45. dbif = SQLDatabaseInterfaceConnection()
  46. dbif.connect()
  47. sp = open_old_stds(input, type, dbif)
  48. # Check the new stds
  49. new_sp = check_new_stds(output, type, dbif, gscript.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 = "{base}_{suffix}".format(base=base,
  69. suffix=get_num_suffix(count,
  70. num_rows))
  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,
  80. row["layer"])
  81. new_map = sp.get_new_map_instance(map_id)
  82. # Check if new map is in the temporal database
  83. if new_map.is_in_db(dbif):
  84. if gscript.overwrite():
  85. # Remove the existing temporal database entry
  86. new_map.delete(dbif)
  87. new_map = sp.get_new_map_instance(map_id)
  88. else:
  89. msgr.error(_("Map <%s> is already in temporal database"
  90. ", use overwrite flag to overwrite") %
  91. (new_map.get_map_id()))
  92. continue
  93. # Add process to the process list
  94. if type == "raster":
  95. msgr.verbose(_("Applying r.mapcalc expression: \"%s\"")
  96. % expr)
  97. proc_list.append(Process(target=run_mapcalc2d,
  98. args=(expr,)))
  99. elif type == "raster3d":
  100. msgr.verbose(_("Applying r3.mapcalc expression: \"%s\"")
  101. % expr)
  102. proc_list.append(Process(target=run_mapcalc3d,
  103. args=(expr,)))
  104. elif type == "vector":
  105. msgr.verbose(_("Applying v.extract where statement: \"%s\"")
  106. % expression)
  107. if row["layer"]:
  108. proc_list.append(Process(target=run_vector_extraction,
  109. args=(row["name"] + "@" +
  110. row["mapset"], map_name,
  111. row["layer"], vtype,
  112. expression)))
  113. else:
  114. proc_list.append(Process(target=run_vector_extraction,
  115. args=(row["name"] + "@" +
  116. row["mapset"], map_name,
  117. layer, vtype,
  118. expression)))
  119. proc_list[proc_count].start()
  120. proc_count += 1
  121. # Join processes if the maximum number of processes are
  122. # reached or the end of the loop is reached
  123. if proc_count == nprocs or count == num_rows:
  124. proc_count = 0
  125. exitcodes = 0
  126. for proc in proc_list:
  127. proc.join()
  128. exitcodes += proc.exitcode
  129. if exitcodes != 0:
  130. dbif.close()
  131. msgr.fatal(_("Error in computation process"))
  132. # Empty process list
  133. proc_list = []
  134. # Store the new maps
  135. new_maps[row["id"]] = new_map
  136. msgr.percent(0, num_rows, 1)
  137. temporal_type, semantic_type, title, description = sp.get_initial_values()
  138. new_sp = open_new_stds(output, type, sp.get_temporal_type(), title.
  139. description, semantic_type, dbif,
  140. gscript.overwrite())
  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. msgr.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. new_map.set_temporal_extent(old_map.get_temporal_extent())
  173. # Insert map in temporal database
  174. new_map.insert(dbif)
  175. new_sp.register_map(new_map, dbif)
  176. else:
  177. new_sp.register_map(old_map, dbif)
  178. # Update the spatio-temporal extent and the metadata table entries
  179. new_sp.update_from_registered_maps(dbif)
  180. msgr.percent(num_rows, num_rows, 1)
  181. # Remove empty maps
  182. if len(empty_maps) > 0:
  183. names = ""
  184. count = 0
  185. for map in empty_maps:
  186. if count == 0:
  187. names += "%s" % (map.get_name())
  188. else:
  189. names += ",%s" % (map.get_name())
  190. count += 1
  191. if type == "raster":
  192. gscript.run_command("g.remove", flags='f', type='rast',
  193. pattern=names, quiet=True)
  194. elif type == "raster3d":
  195. gscript.run_command("g.remove", flags='f', type='rast3d',
  196. pattern=names, quiet=True)
  197. elif type == "vector":
  198. gscript.run_command("g.remove", flags='f', type='vect',
  199. pattern=names, quiet=True)
  200. dbif.close()
  201. ###############################################################################
  202. def run_mapcalc2d(expr):
  203. """Helper function to run r.mapcalc in parallel"""
  204. exit(gscript.run_command("r.mapcalc", expression=expr,
  205. overwrite=gscript.overwrite(), quiet=True))
  206. def run_mapcalc3d(expr):
  207. """Helper function to run r3.mapcalc in parallel"""
  208. exit(gscript.run_command("r3.mapcalc", expression=expr,
  209. overwrite=gscript.overwrite(), quiet=True))
  210. def run_vector_extraction(input, output, layer, type, where):
  211. """Helper function to run r.mapcalc in parallel"""
  212. exit(gscript.run_command("v.extract", input=input, output=output,
  213. layer=layer, type=type, where=where,
  214. overwrite=gscript.overwrite(), quiet=True))