extract.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  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. Usage:
  5. @code
  6. import grass.temporal as tgis
  7. @endcode
  8. (C) 2008-2011 by the GRASS Development Team
  9. This program is free software under the GNU General Public
  10. License (>=v2). Read the file COPYING that comes with GRASS
  11. for details.
  12. @author Soeren Gebbert
  13. """
  14. from space_time_datasets import *
  15. from multiprocessing import Process
  16. ############################################################################
  17. def extract_dataset(input, output, type, where, expression, base, nprocs, register_null=False):
  18. """!Extract a subset of a space time raster or raster3d dataset
  19. A mapcalc expression can be provided to process the temporal extracted 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 dataset
  23. @param type The type of the dataset: "raster" or "raster3d"
  24. @param where The SQL WHERE statement for subset extraction
  25. @param expression The r(3).mapcalc expression
  26. @param base The base name of the new created maps in case a mapclac expression is provided
  27. @param nprocs The number of parallel processes to be used for mapcalc processing
  28. @param register_null Set this number True to register empty maps
  29. """
  30. mapset = core.gisenv()["MAPSET"]
  31. if input.find("@") >= 0:
  32. id = input
  33. else:
  34. id = input + "@" + mapset
  35. if type == "raster":
  36. sp = space_time_raster_dataset(id)
  37. else:
  38. sp = space_time_raster3d_dataset(id)
  39. dbif = sql_database_interface_connection()
  40. dbif.connect()
  41. if sp.is_in_db(dbif) == False:
  42. dbif.close()
  43. core.fatal(_("Space time %s dataset <%s> not found") % (type, id))
  44. if expression and not base:
  45. dbif.close()
  46. core.fatal(_("Please specify base="))
  47. sp.select(dbif)
  48. if output.find("@") >= 0:
  49. out_id = output
  50. else:
  51. out_id = output + "@" + mapset
  52. # The new space time dataset
  53. new_sp = sp.get_new_instance(out_id)
  54. if new_sp.is_in_db():
  55. if core.overwrite() == False:
  56. dbif.close()
  57. core.fatal(_("Space time %s dataset <%s> is already in database, use overwrite flag to overwrite") % (type, out_id))
  58. rows = sp.get_registered_maps("id", where, "start_time", dbif)
  59. new_maps = {}
  60. if rows:
  61. num_rows = len(rows)
  62. core.percent(0, num_rows, 1)
  63. # Run the mapcalc expression
  64. if expression:
  65. count = 0
  66. proc_count = 0
  67. proc_list = []
  68. for row in rows:
  69. count += 1
  70. core.percent(count, num_rows, 1)
  71. map_name = "%s_%i" % (base, count)
  72. expr = "%s = %s" % (map_name, expression)
  73. expr = expr.replace(sp.base.get_map_id(), row["id"])
  74. expr = expr.replace(sp.base.get_name(), row["id"])
  75. map_id = map_name + "@" + mapset
  76. new_map = sp.get_new_map_instance(map_id)
  77. # Check if new map is in the temporal database
  78. if new_map.is_in_db(dbif):
  79. if core.overwrite() == True:
  80. # Remove the existing temporal database entry
  81. new_map.delete(dbif)
  82. new_map = sp.get_new_map_instance(map_id)
  83. else:
  84. core.error(_("Map <%s> is already in temporal database, use overwrite flag to overwrite")%(new_map.get_map_id()))
  85. continue
  86. core.verbose(_("Apply mapcalc expression: \"%s\"") % expr)
  87. if type == "raster":
  88. proc_list.append(Process(target=run_mapcalc2d, args=(expr,)))
  89. else:
  90. proc_list.append(Process(target=run_mapcalc3d, args=(expr,)))
  91. proc_list[proc_count].start()
  92. proc_count += 1
  93. if proc_count == nprocs:
  94. proc_count = 0
  95. exitcodes = 0
  96. for proc in proc_list:
  97. proc.join()
  98. exitcodes += proc.exitcode
  99. if exitcodes != 0:
  100. dbif.close()
  101. core.fatal(_("Error while mapcalc computation"))
  102. # Empty proc list
  103. proc_list = []
  104. # Store the new maps
  105. new_maps[row["id"]] = new_map
  106. core.percent(0, num_rows, 1)
  107. # Insert the new space time dataset
  108. if new_sp.is_in_db(dbif):
  109. if core.overwrite() == True:
  110. new_sp.delete(dbif)
  111. new_sp = sp.get_new_instance(out_id)
  112. temporal_type, semantic_type, title, description = sp.get_initial_values()
  113. new_sp.set_initial_values(temporal_type, semantic_type, title, description)
  114. new_sp.insert(dbif)
  115. # Register the maps in the database
  116. count = 0
  117. for row in rows:
  118. count += 1
  119. core.percent(count, num_rows, 1)
  120. old_map = sp.get_new_map_instance(row["id"])
  121. old_map.select(dbif)
  122. if expression:
  123. # Register the new maps
  124. if new_maps.has_key(row["id"]):
  125. new_map = new_maps[row["id"]]
  126. # Read the raster map data
  127. new_map.load()
  128. # In case of a null map continue, do not register null maps
  129. if new_map.metadata.get_min() == None and new_map.metadata.get_max() == None:
  130. if not register_null:
  131. continue
  132. # Set the time stamp
  133. if old_map.is_time_absolute():
  134. start, end, tz = old_map.get_absolute_time()
  135. new_map.set_absolute_time(start, end, tz)
  136. else:
  137. start, end = old_map.get_relative_time()
  138. new_map.set_relative_time(start, end)
  139. # Insert map in temporal database
  140. new_map.insert(dbif)
  141. new_sp.register_map(new_map, dbif)
  142. else:
  143. new_sp.register_map(old_map, dbif)
  144. # Update the spatio-temporal extent and the metadata table entries
  145. new_sp.update_from_registered_maps(dbif)
  146. core.percent(num_rows, num_rows, 1)
  147. dbif.close()
  148. ###############################################################################
  149. def run_mapcalc2d(expr):
  150. """Helper function to run r.mapcalc in parallel"""
  151. return core.run_command("r.mapcalc", expression=expr, overwrite=core.overwrite(), quiet=True)
  152. def run_mapcalc3d(expr):
  153. """Helper function to run r3.mapcalc in parallel"""
  154. return core.run_command("r3.mapcalc", expression=expr, overwrite=core.overwrite(), quiet=True)