abstract_map_dataset.py 18 KB

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