abstract_map_dataset.py 15 KB

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