abstract_map_dataset.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  1. # -*- coding: utf-8 -*-
  2. """!@package grass.temporal
  3. @brief GRASS Python scripting module (temporal GIS functions)
  4. Temporal GIS related functions to be used in temporal GIS Python library package.
  5. Usage:
  6. @code
  7. import grass.temporal as tgis
  8. ...
  9. @endcode
  10. (C) 2008-2011 by the GRASS Development Team
  11. This program is free software under the GNU General Public
  12. License (>=v2). Read the file COPYING that comes with GRASS
  13. for details.
  14. @author Soeren Gebbert
  15. """
  16. from abstract_dataset import *
  17. from datetime_math import *
  18. ###############################################################################
  19. class abstract_map_dataset(abstract_dataset):
  20. """!This is the base class for all maps (raster, vector, raster3d)
  21. providing additional function to set the valid time and the spatial extent.
  22. """
  23. def get_new_stds_instance(self, ident):
  24. """!Return a new space time dataset instance in which maps are stored with the type of this class
  25. @param ident: The identifier of the dataset
  26. """
  27. raise IOError("This method must be implemented in the subclasses")
  28. def get_stds_register(self):
  29. """!Return the space time dataset register table name in which stds are listed in which this map is registered"""
  30. raise IOError("This method must be implemented in the subclasses")
  31. def set_stds_register(self, name):
  32. """!Set the space time dataset register table name.
  33. This table stores all space time datasets in which this map is registered.
  34. @param ident: The name of the register table
  35. """
  36. raise IOError("This method must be implemented in the subclasses")
  37. def get_timestamp_module_name(self):
  38. """!Return the name of the C-module to set the time stamp in the file system"""
  39. raise IOError("This method must be implemented in the subclasses")
  40. def load(self):
  41. """!Load the content of this object from map files"""
  42. raise IOError("This method must be implemented in the subclasses")
  43. def check_resolution_with_current_region(self):
  44. """!Check if the raster or voxel resolution is finer than the current resolution
  45. Return "finer" in case the raster/voxel resolution is finer than the current region
  46. Return "coarser" in case the raster/voxel resolution is coarser than the current region
  47. Vector maps are alwyas finer than the current region
  48. """
  49. raise IOError("This method must be implemented in the subclasses")
  50. def get_map_id(self):
  51. """!Return the map id. The map id is the unique map identifier in grass and must not be equal to the
  52. primary key identifier (id) of the map in the database. Since vector maps may have layer information,
  53. the unique id is a combination of name, layer and mapset.
  54. Use get_map_id() every time your need to access the grass map in the file system but not to identify
  55. map information in the temporal database.
  56. """
  57. return self.base.get_map_id()
  58. def build_id(self, name, mapset, layer=None):
  59. """!Convenient method to build the unique identifier
  60. Existing layer and mapset definitions in the name string will be reused
  61. @param return the id of the vector map as name(:layer)@mapset while layer is optional
  62. """
  63. # Check if the name includes any mapset
  64. if name.find("@") >= 0:
  65. name, mapset = name.split("@")[0]
  66. # Check for layer number in map name
  67. if name.find(":") >= 0:
  68. name, layer = name.split(":")
  69. if layer:
  70. return "%s:%s@%s"%(name, layer, mapset)
  71. else:
  72. return "%s@%s"%(name, mapset)
  73. def get_layer(self):
  74. """!Return the layer of the map or None in case no layer is defined"""
  75. return self.base.get_layer()
  76. def print_info(self):
  77. """!Print information about this class in human readable style"""
  78. if self.get_type() == "raster":
  79. # 1 2 3 4 5 6 7
  80. # 0123456789012345678901234567890123456789012345678901234567890123456789012345678
  81. print ""
  82. print " +-------------------- Raster Dataset ----------------------------------------+"
  83. if self.get_type() == "raster3d":
  84. # 1 2 3 4 5 6 7
  85. # 0123456789012345678901234567890123456789012345678901234567890123456789012345678
  86. print ""
  87. print " +-------------------- Raster3d Dataset --------------------------------------+"
  88. if self.get_type() == "vector":
  89. # 1 2 3 4 5 6 7
  90. # 0123456789012345678901234567890123456789012345678901234567890123456789012345678
  91. print ""
  92. print " +-------------------- Vector Dataset ----------------------------------------+"
  93. print " | |"
  94. self.base.print_info()
  95. if self.is_time_absolute():
  96. self.absolute_time.print_info()
  97. if self.is_time_relative():
  98. self.relative_time.print_info()
  99. self.spatial_extent.print_info()
  100. self.metadata.print_info()
  101. datasets = self.get_registered_datasets()
  102. count = 0
  103. string = ""
  104. if datasets:
  105. for ds in datasets:
  106. if count == 0:
  107. string += ds["id"]
  108. else:
  109. string += ",%s" % ds["id"]
  110. count += 1
  111. if count > 2:
  112. string += " | ............................ "
  113. print " | Registered datasets ........ " + string
  114. print " +----------------------------------------------------------------------------+"
  115. def print_shell_info(self):
  116. """!Print information about this class in shell style"""
  117. self.base.print_shell_info()
  118. if self.is_time_absolute():
  119. self.absolute_time.print_shell_info()
  120. if self.is_time_relative():
  121. self.relative_time.print_shell_info()
  122. self.spatial_extent.print_shell_info()
  123. self.metadata.print_shell_info()
  124. datasets = self.get_registered_datasets()
  125. count = 0
  126. string = ""
  127. for ds in datasets:
  128. if count == 0:
  129. string += ds["id"]
  130. else:
  131. string += ",%s" % ds["id"]
  132. count += 1
  133. print "registered_datasets=" + string
  134. def set_absolute_time(self, start_time, end_time=None, timezone=None):
  135. """!Set the absolute time interval with start time and end time
  136. @param start_time: a datetime object specifying the start time of the map
  137. @param end_time: a datetime object specifying the end time of the map
  138. @param timezone: Thee timezone of the map
  139. """
  140. if start_time and not isinstance(start_time, datetime) :
  141. if self.get_layer():
  142. core.fatal(_("Start time must be of type datetime for %s map <%s> with layer: %s") % (self.get_type(), self.get_map_id(), self.get_layer()))
  143. else:
  144. core.fatal(_("Start time must be of type datetime for %s map <%s>") % (self.get_type(), self.get_map_id()))
  145. if end_time and not isinstance(end_time, datetime) :
  146. if self.get_layer():
  147. core.fatal(_("End time must be of type datetime for %s map <%s> with layer: %s") % (self.get_type(), self.get_map_id(), self.get_layer()))
  148. else:
  149. core.fatal(_("End time must be of type datetime for %s map <%s>") % (self.get_type(), self.get_map_id()))
  150. if start_time and end_time:
  151. if start_time > end_time:
  152. if self.get_layer():
  153. core.fatal(_("End time must be greater than start time for %s map <%s> with layer: %s") % (self.get_type(), self.get_map_id(), self.get_layer()))
  154. else:
  155. core.fatal(_("End time must be greater than start time for %s map <%s>") % (self.get_type(), self.get_map_id()))
  156. else:
  157. # Do not create an interval in case start and end time are equal
  158. if start_time == end_time:
  159. end_time = None
  160. self.base.set_ttype("absolute")
  161. self.absolute_time.set_start_time(start_time)
  162. self.absolute_time.set_end_time(end_time)
  163. self.absolute_time.set_timezone(timezone)
  164. def update_absolute_time(self, start_time, end_time=None, timezone=None, dbif = None):
  165. """!Update the absolute time
  166. This method should always be used to set the absolute time. Do not use insert() or update()
  167. to the the time. This update functions assures that the *.timestamp commands are invoked.
  168. @param start_time: a datetime object specifying the start time of the map
  169. @param end_time: a datetime object specifying the end time of the map
  170. @param timezone: Thee timezone of the map
  171. """
  172. connect = False
  173. if dbif == None:
  174. dbif = sql_database_interface()
  175. dbif.connect()
  176. connect = True
  177. self.set_absolute_time(start_time, end_time, timezone)
  178. self.absolute_time.update_all(dbif)
  179. self.base.update(dbif)
  180. if connect == True:
  181. dbif.close()
  182. self.write_absolute_time_to_file()
  183. def write_absolute_time_to_file(self):
  184. """!Start the grass timestamp module to set the time in the file system"""
  185. start_time, end_time, unit = self.get_absolute_time()
  186. start = datetime_to_grass_datetime_string(start_time)
  187. if end_time:
  188. end = datetime_to_grass_datetime_string(end_time)
  189. start += " / %s"%(end)
  190. core.run_command(self.get_timestamp_module_name(), map=self.get_map_id(), date=start)
  191. def set_relative_time(self, start_time, end_time, unit):
  192. """!Set the relative time interval
  193. @param start_time: A double value
  194. @param end_time: A double value
  195. @param unit: The unit of the relative time. Supported units: years, months, days, hours, minutes, seconds
  196. Return True for success and False otherwise
  197. """
  198. if not self.check_relative_time_unit(unit):
  199. if self.get_layer():
  200. core.error(_("Unsupported relative time unit type for %s map <%s> with layer %s: %s") % (self.get_type(), self.get_id(), self.get_layer(), unit))
  201. else:
  202. core.error(_("Unsupported relative time unit type for %s map <%s>: %s") % (self.get_type(), self.get_id(), unit))
  203. return False
  204. if start_time != None and end_time != None:
  205. if int(start_time) > int(end_time):
  206. if self.get_layer():
  207. core.error(_("End time must be greater than start time for %s map <%s> with layer %s") % (self.get_type(), self.get_id(), self.get_layer()))
  208. else:
  209. core.error(_("End time must be greater than start time for %s map <%s>") % (self.get_type(), self.get_id()))
  210. return False
  211. else:
  212. # Do not create an interval in case start and end time are equal
  213. if start_time == end_time:
  214. end_time = None
  215. self.base.set_ttype("relative")
  216. self.relative_time.set_unit(unit)
  217. self.relative_time.set_start_time(int(start_time))
  218. if end_time != None:
  219. self.relative_time.set_end_time(int(end_time))
  220. else:
  221. self.relative_time.set_end_time(None)
  222. return True
  223. def update_relative_time(self, start_time, end_time, unit, dbif = None):
  224. """!Update the relative time interval
  225. This method should always be used to set the absolute time. Do not use insert() or update()
  226. to the the time. This update functions assures that the *.timestamp commands are invoked.
  227. @param start_time: A double value
  228. @param end_time: A double value
  229. @param dbif: The database interface to be used
  230. """
  231. connect = False
  232. if dbif == None:
  233. dbif = sql_database_interface()
  234. dbif.connect()
  235. connect = True
  236. if self.set_relative_time(start_time, end_time, unit):
  237. self.relative_time.update_all(dbif)
  238. self.base.update(dbif)
  239. dbif.connection.commit()
  240. if connect == True:
  241. dbif.close()
  242. self.write_relative_time_to_file()
  243. def write_relative_time_to_file(self):
  244. """!Start the grass timestamp module to set the time in the file system"""
  245. start_time, end_time, unit = self.get_relative_time()
  246. start = "%i %s"%(int(start_time), unit)
  247. if end_time != None:
  248. end = "%i %s"%(int(end_time), unit)
  249. start += " / %s"%(end)
  250. core.run_command(self.get_timestamp_module_name(), map=self.get_map_id(), date=start)
  251. def set_spatial_extent(self, north, south, east, west, top=0, bottom=0):
  252. """!Set the spatial extent of the map
  253. @param north: The northern edge
  254. @param south: The southern edge
  255. @param east: The eastern edge
  256. @param west: The western edge
  257. @param top: The top edge
  258. @param bottom: The bottom edge
  259. """
  260. self.spatial_extent.set_spatial_extent(north, south, east, west, top, bottom)
  261. def check_valid_time(self):
  262. """!Check for correct valid time"""
  263. if self.is_time_absolute():
  264. start, end, tz = self.get_absolute_time()
  265. else:
  266. start, end, unit = self.get_relative_time()
  267. if start != None:
  268. if end != None:
  269. if start >= end:
  270. if self.get_layer():
  271. core.error(_("Map <%s> with layer %s has incorrect time interval, start time is greater than end time") % (self.get_map_id(), self.get_layer()))
  272. else:
  273. core.error(_("Map <%s> has incorrect time interval, start time is greater than end time") % (self.get_map_id()))
  274. return False
  275. else:
  276. core.error(_("Map <%s> has incorrect start time") % (self.get_map_id()))
  277. return False
  278. return True
  279. def delete(self, dbif=None, update=True):
  280. """!Delete a map entry from database if it exists
  281. Remove dependent entries:
  282. * Remove the map entry in each space time dataset in which this map is registered
  283. * Remove the space time dataset register table
  284. @param dbif: The database interface to be used
  285. @param update: Call for each unregister statement the update from registered maps
  286. of the space time dataset. This can slow down the un-registration process significantly.
  287. """
  288. connect = False
  289. if dbif == None:
  290. dbif = sql_database_interface()
  291. dbif.connect()
  292. connect = True
  293. if self.is_in_db(dbif):
  294. # SELECT all needed information from the database
  295. self.select(dbif)
  296. # First we unregister from all dependent space time datasets
  297. self.unregister(dbif, update)
  298. # Remove the strds register table
  299. if self.get_stds_register():
  300. sql = "DROP TABLE " + self.get_stds_register()
  301. #print sql
  302. try:
  303. dbif.cursor.execute(sql)
  304. except:
  305. core.error(_("Unable to remove space time dataset register table <%s>") % (self.get_stds_register()))
  306. core.verbose(_("Delete %s dataset <%s> from temporal database") % (self.get_type(), self.get_id()))
  307. # Delete yourself from the database, trigger functions will take care of dependencies
  308. self.base.delete(dbif)
  309. # Remove the timestamp from the file system
  310. if self.get_type() == "vect":
  311. if self.get_layer():
  312. core.run_command(self.get_timestamp_module_name(), map=self.get_map_id(), layer=self.get_layer(), date="none")
  313. else:
  314. core.run_command(self.get_timestamp_module_name(), map=self.get_map_id(), date="none")
  315. else:
  316. core.run_command(self.get_timestamp_module_name(), map=self.get_map_id(), date="none")
  317. self.reset(None)
  318. dbif.connection.commit()
  319. if connect == True:
  320. dbif.close()
  321. def unregister(self, dbif=None, update=True):
  322. """! Remove the map entry in each space time dataset in which this map is registered
  323. @param dbif: The database interface to be used
  324. @param update: Call for each unregister statement the update from registered maps
  325. of the space time dataset. This can slow down the un-registration process significantly.
  326. """
  327. if self.get_layer():
  328. core.verbose(_("Unregister %s map <%s> with layer %s from space time datasets") % \
  329. (self.get_type(), self.get_map_id(), self.get_layer()))
  330. else:
  331. core.verbose(_("Unregister %s map <%s> from space time datasets") % (self.get_type(), self.get_map_id()))
  332. connect = False
  333. if dbif == None:
  334. dbif = sql_database_interface()
  335. dbif.connect()
  336. connect = True
  337. # Get all datasets in which this map is registered
  338. rows = self.get_registered_datasets(dbif)
  339. # For each stds in which the map is registered
  340. if rows:
  341. count = 0
  342. num_sps = len(rows)
  343. for row in rows:
  344. core.percent(count, num_sps, 1)
  345. count += 1
  346. # Create a space time dataset object to remove the map
  347. # from its register
  348. stds = self.get_new_stds_instance(row["id"])
  349. stds.select(dbif)
  350. stds.unregister_map(self, dbif)
  351. # Take care to update the space time dataset after
  352. # the map has been unregistered
  353. if update == True:
  354. stds.update_from_registered_maps(dbif)
  355. core.percent(1, 1, 1)
  356. dbif.connection.commit()
  357. if connect == True:
  358. dbif.close()
  359. def get_registered_datasets(self, dbif=None):
  360. """!Return all space time dataset ids in which this map is registered as
  361. dictionary like rows with column "id" or None if this map is not registered in any
  362. space time dataset.
  363. @param dbif: The database interface to be used
  364. """
  365. connect = False
  366. if dbif == None:
  367. dbif = sql_database_interface()
  368. dbif.connect()
  369. connect = True
  370. rows = None
  371. try:
  372. if self.get_stds_register() != None:
  373. # Select all stds tables in which this map is registered
  374. sql = "SELECT id FROM " + self.get_stds_register()
  375. dbif.cursor.execute(sql)
  376. rows = dbif.cursor.fetchall()
  377. except:
  378. core.error(_("Unable to select space time dataset register table <%s>") % (self.get_stds_register()))
  379. if connect == True:
  380. dbif.close()
  381. return rows