abstract_map_dataset.py 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963
  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. (C) 2011-2013 by the GRASS Development Team
  6. This program is free software under the GNU General Public
  7. License (>=v2). Read the file COPYING that comes with GRASS
  8. for details.
  9. @author Soeren Gebbert
  10. """
  11. from abstract_dataset import *
  12. from datetime_math import *
  13. class AbstractMapDataset(AbstractDataset):
  14. """!This is the base class for all maps (raster, vector, raster3d).
  15. The temporal extent, the spatial extent and the metadata of maps
  16. are stored in the temporal database. Maps can be registered in the
  17. temporal database, updated and deleted.
  18. This class provides all functionalities that are needed to manage maps
  19. in the temporal database. That are:
  20. - insert() to register the map and therefore its spatio-temporal extent
  21. and metadata in the temporal database
  22. - update() to update the map spatio-temporal extent and metadata in the
  23. temporal database
  24. - unregister() to unregister the map from each space time dataset in
  25. which this map is registered
  26. - delete() to remove the map from the temporal database
  27. - Methods to set relative and absolute time stamps
  28. - Abstract methods that must be implemented in the map specific
  29. subclasses
  30. """
  31. __metaclass__ = ABCMeta
  32. def __init__(self):
  33. AbstractDataset.__init__(self)
  34. self.ciface = get_tgis_c_library_interface()
  35. @abstractmethod
  36. def get_new_stds_instance(self, ident):
  37. """!Return a new space time dataset instance that store maps with the
  38. type of this map object (rast, rast3d or vect)
  39. @param ident The identifier of the space time dataset
  40. @return The new space time dataset instance
  41. """
  42. @abstractmethod
  43. def get_stds_register(self):
  44. """!Return the space time dataset register table name
  45. Maps can be registered in several different space time datasets.
  46. This method returns the name of the register table in the
  47. temporal database.
  48. @return The name of the stds register table
  49. """
  50. @abstractmethod
  51. def set_stds_register(self, name):
  52. """!Set the space time dataset register table name.
  53. This table stores all space time datasets in
  54. which this map is registered.
  55. @param name The name of the register table
  56. """
  57. def check_resolution_with_current_region(self):
  58. """!Check if the raster or voxel resolution is
  59. finer than the current resolution
  60. - Return "finer" in case the raster/voxel resolution is finer
  61. than the current region
  62. - Return "coarser" in case the raster/voxel resolution is coarser
  63. than the current region
  64. Vector maps have no resolution, since they store the coordinates
  65. directly.
  66. @return "finer" or "coarser"
  67. """
  68. raise ImplementationError(
  69. "This method must be implemented in the subclasses")
  70. @abstractmethod
  71. def has_grass_timestamp(self):
  72. """!Check if a grass file based time stamp exists for this map.
  73. @return True is the grass file based time stamped exists for this
  74. map
  75. """
  76. @abstractmethod
  77. def write_timestamp_to_grass(self):
  78. """!Write the timestamp of this map into the map metadata
  79. in the grass file system based spatial database.
  80. """
  81. @abstractmethod
  82. def read_timestamp_from_grass(self):
  83. """!Read the timestamp of this map from the map metadata
  84. in the grass file system based spatial database and
  85. set the internal time stamp that should be insert/updated
  86. in the temporal database.
  87. """
  88. @abstractmethod
  89. def remove_timestamp_from_grass(self):
  90. """!Remove the timestamp from the grass file
  91. system based spatial database
  92. """
  93. @abstractmethod
  94. def map_exists(self):
  95. """!Return True in case the map exists in the grass spatial database
  96. @return True if map exists, False otherwise
  97. """
  98. @abstractmethod
  99. def load(self):
  100. """!Load the content of this object from the grass
  101. file system based database"""
  102. def _convert_timestamp(self):
  103. """!Convert the valid time into a grass datetime library
  104. compatible timestamp string
  105. This methods works for relative and absolute time
  106. @return the grass timestamp string
  107. """
  108. start = ""
  109. if self.is_time_absolute():
  110. start_time, end_time, tz = self.get_absolute_time()
  111. start = datetime_to_grass_datetime_string(start_time)
  112. if end_time is not None:
  113. end = datetime_to_grass_datetime_string(end_time)
  114. start += " / %s" % (end)
  115. else:
  116. start_time, end_time, unit = self.get_relative_time()
  117. start = "%i %s" % (int(start_time), unit)
  118. if end_time is not None:
  119. end = "%i %s" % (int(end_time), unit)
  120. start += " / %s" % (end)
  121. return start
  122. def get_map_id(self):
  123. """!Return the map id. The map id is the unique identifier
  124. in grass and must not be equal to the
  125. primary key identifier (id) of the map in the database.
  126. Since vector maps may have layer information,
  127. the unique id is a combination of name, layer and mapset.
  128. Use get_map_id() every time your need to access the grass map
  129. in the file system but not to identify
  130. map information in the temporal database.
  131. @return The map id "name@mapset"
  132. """
  133. return self.base.get_map_id()
  134. @staticmethod
  135. def build_id(name, mapset, layer=None):
  136. """!Convenient method to build the unique identifier
  137. Existing layer and mapset definitions in the name
  138. string will be reused
  139. @param name The name of the map
  140. @param mapset The mapset in which the map is located
  141. @param layer The layer of the vector map, use None in case no
  142. layer exists
  143. @return the id of the map as "name(:layer)@mapset"
  144. while layer is optional
  145. """
  146. # Check if the name includes any mapset
  147. if name.find("@") >= 0:
  148. name, mapset = name.split("@")
  149. # Check for layer number in map name
  150. if name.find(":") >= 0:
  151. name, layer = name.split(":")
  152. if layer is not None:
  153. return "%s:%s@%s" % (name, layer, mapset)
  154. else:
  155. return "%s@%s" % (name, mapset)
  156. def get_layer(self):
  157. """!Return the layer of the map
  158. @return the layer of the map or None in case no layer is defined
  159. """
  160. return self.base.get_layer()
  161. def print_self(self):
  162. """!Print the content of the internal structure to stdout"""
  163. self.base.print_self()
  164. self.temporal_extent.print_self()
  165. self.spatial_extent.print_self()
  166. self.metadata.print_self()
  167. def print_info(self):
  168. """!Print information about this object in human readable style"""
  169. if self.get_type() == "raster":
  170. # 1 2 3 4 5 6 7
  171. # 0123456789012345678901234567890123456789012345678901234567890123456789012345678
  172. print " +-------------------- Raster Dataset ----------------------------------------+"
  173. if self.get_type() == "raster3d":
  174. # 1 2 3 4 5 6 7
  175. # 0123456789012345678901234567890123456789012345678901234567890123456789012345678
  176. print " +-------------------- 3D Raster Dataset -------------------------------------+"
  177. if self.get_type() == "vector":
  178. # 1 2 3 4 5 6 7
  179. # 0123456789012345678901234567890123456789012345678901234567890123456789012345678
  180. print " +-------------------- Vector Dataset ----------------------------------------+"
  181. print " | |"
  182. self.base.print_info()
  183. self.temporal_extent.print_info()
  184. if self.is_topology_build():
  185. self.print_topology_info()
  186. self.spatial_extent.print_info()
  187. self.metadata.print_info()
  188. datasets = self.get_registered_datasets()
  189. count = 0
  190. string = ""
  191. if datasets is not None:
  192. for ds in datasets:
  193. if count > 0 and count % 3 == 0:
  194. string += "\n | ............................ "
  195. count = 0
  196. if count == 0:
  197. string += ds["id"]
  198. else:
  199. string += ",%s" % ds["id"]
  200. count += 1
  201. print " | Registered datasets ........ " + string
  202. print " +----------------------------------------------------------------------------+"
  203. def print_shell_info(self):
  204. """!Print information about this object in shell style"""
  205. self.base.print_shell_info()
  206. self.temporal_extent.print_shell_info()
  207. self.spatial_extent.print_shell_info()
  208. self.metadata.print_shell_info()
  209. datasets = self.get_registered_datasets()
  210. count = 0
  211. string = ""
  212. if datasets is not None:
  213. for ds in datasets:
  214. if count == 0:
  215. string += ds["id"]
  216. else:
  217. string += ",%s" % ds["id"]
  218. count += 1
  219. print "registered_datasets=" + string
  220. if self.is_topology_build():
  221. self.print_topology_shell_info()
  222. def insert(self, dbif=None, execute=True):
  223. """!Insert the map content into the database from the internal
  224. structure
  225. This functions assures that the timestamp is written to the
  226. grass file system based database in addition to the temporal
  227. database entry.
  228. @param dbif The database interface to be used
  229. @param execute If True the SQL statements will be executed.
  230. If False the prepared SQL statements are
  231. returned and must be executed by the caller.
  232. @return The SQL insert statement in case execute=False, or an
  233. empty string otherwise
  234. """
  235. self.write_timestamp_to_grass()
  236. return AbstractDataset.insert(self, dbif, execute)
  237. def update(self, dbif=None, execute=True):
  238. """!Update the map content in the database from the internal structure
  239. excluding None variables
  240. This functions assures that the timestamp is written to the
  241. grass file system based database in addition to the temporal
  242. database entry.
  243. @param dbif The database interface to be used
  244. @param execute If True the SQL statements will be executed.
  245. If False the prepared SQL statements are
  246. returned and must be executed by the caller.
  247. @return The SQL insert statement in case execute=False, or an
  248. empty string otherwise
  249. """
  250. self.write_timestamp_to_grass()
  251. return AbstractDataset.update(self, dbif, execute)
  252. def update_all(self, dbif=None, execute=True):
  253. """!Update the map content in the database from the internal structure
  254. including None variables
  255. This functions assures that the timestamp is written to the
  256. grass file system based database in addition to the temporal
  257. database entry.
  258. @param dbif The database interface to be used
  259. @param execute If True the SQL statements will be executed.
  260. If False the prepared SQL statements are
  261. returned and must be executed by the caller.
  262. @return The SQL insert statement in case execute=False, or an
  263. empty string otherwise
  264. """
  265. self.write_timestamp_to_grass()
  266. return AbstractDataset.update_all(self, dbif, execute)
  267. def set_time_to_absolute(self):
  268. """!Set the temporal type to absolute"""
  269. self.base.set_ttype("absolute")
  270. def set_time_to_relative(self):
  271. """!Set the temporal type to relative"""
  272. self.base.set_ttype("relative")
  273. def set_absolute_time(self, start_time, end_time=None, timezone=None):
  274. """!Set the absolute time with start time and end time
  275. The end time is optional and must be set to None in case of time
  276. instance.
  277. This method only modifies this object and does not commit
  278. the modifications to the temporal database.
  279. @param start_time a datetime object specifying the start time of the
  280. map
  281. @param end_time a datetime object specifying the end time of the
  282. map, None in case or time instance
  283. @param timezone Thee timezone of the map (not used)
  284. @return True for success and False otherwise
  285. """
  286. if start_time and not isinstance(start_time, datetime):
  287. if self.get_layer() is not None:
  288. self.msgr.error(_("Start time must be of type datetime for %(type)s"
  289. " map <%(id)s> with layer: %(l)s") % {
  290. 'type': self.get_type(), 'id': self.get_map_id(),
  291. 'l': self.get_layer()})
  292. return False
  293. else:
  294. core.error(_("Start time must be of type datetime for "
  295. "%(type)s map <%(id)s>") % {
  296. 'type': self.get_type(), 'id': self.get_map_id()})
  297. return False
  298. if end_time and not isinstance(end_time, datetime):
  299. if self.get_layer():
  300. self.msgr.error(_("End time must be of type datetime for %(type)s "
  301. "map <%(id)s> with layer: %(l)s") % {
  302. 'type': self.get_type(), 'id': self.get_map_id(),
  303. 'l': self.get_layer()})
  304. return False
  305. else:
  306. self.msgr.error(_("End time must be of type datetime for "
  307. "%(type)s map <%(id)s>") % {
  308. 'type': self.get_type(), 'id': self.get_map_id()})
  309. return False
  310. if start_time is not None and end_time is not None:
  311. if start_time > end_time:
  312. if self.get_layer():
  313. self.msgr.error(_("End time must be greater than start time for"
  314. " %(type)s map <%(id)s> with layer: %(l)s") % {
  315. 'type': self.get_type(),
  316. 'id': self.get_map_id(),
  317. 'l': self.get_layer()})
  318. return False
  319. else:
  320. self.msgr.error(_("End time must be greater than start time "
  321. "for %(type)s map <%(id)s>") % {
  322. 'type': self.get_type(),
  323. 'id': self.get_map_id()})
  324. return False
  325. else:
  326. # Do not create an interval in case start and end time are
  327. # equal
  328. if start_time == end_time:
  329. end_time = None
  330. self.base.set_ttype("absolute")
  331. self.absolute_time.set_start_time(start_time)
  332. self.absolute_time.set_end_time(end_time)
  333. self.absolute_time.set_timezone(timezone)
  334. return True
  335. def update_absolute_time(self, start_time, end_time=None,
  336. timezone=None, dbif=None):
  337. """!Update the absolute time
  338. The end time is optional and must be set to None in case of time
  339. instance.
  340. This functions assures that the timestamp is written to the
  341. grass file system based database in addition to the temporal
  342. database entry.
  343. @param start_time a datetime object specifying the start time of
  344. the map
  345. @param end_time a datetime object specifying the end time of the
  346. map, None in case or time instance
  347. @param timezone Thee timezone of the map (not used)
  348. @param dbif The database interface to be used
  349. """
  350. if self.get_mapset() != get_current_mapset():
  351. self.msgr.fatal(_("Unable to update dataset <%(ds)s> of type %(type)s in the temporal database."
  352. " The mapset of the dataset does not match the current mapset")%\
  353. {"ds":self.get_id(), "type":self.get_type()})
  354. if self.set_absolute_time(start_time, end_time, timezone):
  355. dbif, connected = init_dbif(dbif)
  356. self.absolute_time.update_all(dbif)
  357. self.base.update(dbif)
  358. if connected:
  359. dbif.close()
  360. self.write_timestamp_to_grass()
  361. def set_relative_time(self, start_time, end_time, unit):
  362. """!Set the relative time interval
  363. The end time is optional and must be set to None in case of time
  364. instance.
  365. This method only modifies this object and does not commit
  366. the modifications to the temporal database.
  367. @param start_time An integer value
  368. @param end_time An integer value, None in case or time instance
  369. @param unit The unit of the relative time. Supported units:
  370. year(s), month(s), day(s), hour(s), minute(s), second(s)
  371. @return True for success and False otherwise
  372. """
  373. if not self.check_relative_time_unit(unit):
  374. if self.get_layer() is not None:
  375. self.msgr.error(_("Unsupported relative time unit type for %(type)s"
  376. " map <%(id)s> with layer %(l)s: %(u)s") % {
  377. 'type': self.get_type(), 'id': self.get_id(),
  378. 'l': self.get_layer(), 'u': unit})
  379. else:
  380. self.msgr.error(_("Unsupported relative time unit type for %(type)s"
  381. " map <%(id)s>: %(u)s") % {
  382. 'type': self.get_type(), 'id': self.get_id(),
  383. 'u': unit})
  384. return False
  385. if start_time is not None and end_time is not None:
  386. if int(start_time) > int(end_time):
  387. if self.get_layer() is not None:
  388. self.msgr.error(_("End time must be greater than start time for"
  389. " %(type)s map <%(id)s> with layer %(l)s") % \
  390. {'type': self.get_type(), 'id': self.get_id(),
  391. 'l': self.get_layer()})
  392. else:
  393. self.msgr.error(_("End time must be greater than start time for"
  394. " %(type)s map <%(id)s>") % {
  395. 'type': self.get_type(), 'id': self.get_id()})
  396. return False
  397. else:
  398. # Do not create an interval in case start and end time are
  399. # equal
  400. if start_time == end_time:
  401. end_time = None
  402. self.base.set_ttype("relative")
  403. self.relative_time.set_unit(unit)
  404. self.relative_time.set_start_time(int(start_time))
  405. if end_time is not None:
  406. self.relative_time.set_end_time(int(end_time))
  407. else:
  408. self.relative_time.set_end_time(None)
  409. return True
  410. def update_relative_time(self, start_time, end_time, unit, dbif=None):
  411. """!Update the relative time interval
  412. The end time is optional and must be set to None in case of time
  413. instance.
  414. This functions assures that the timestamp is written to the
  415. grass file system based database in addition to the temporal
  416. database entry.
  417. @param start_time An integer value
  418. @param end_time An integer value, None in case or time instance
  419. @param unit The relative time unit
  420. @param dbif The database interface to be used
  421. """
  422. if self.get_mapset() != get_current_mapset():
  423. self.msgr.fatal(_("Unable to update dataset <%(ds)s> of type %(type)s in the temporal database."
  424. " The mapset of the dataset does not match the current mapset")%\
  425. {"ds":self.get_id(), "type":self.get_type()})
  426. if self.set_relative_time(start_time, end_time, unit):
  427. dbif, connected = init_dbif(dbif)
  428. self.relative_time.update_all(dbif)
  429. self.base.update(dbif)
  430. if connected:
  431. dbif.close()
  432. self.write_timestamp_to_grass()
  433. def set_temporal_extent(self, extent):
  434. """!Convenient method to set the temporal extent from a temporal extent object
  435. @param temporal_extent The temporal extent that should be set for this object
  436. @code
  437. >>> import datetime
  438. >>> import grass.temporal as tgis
  439. >>> map = tgis.RasterDataset(None)
  440. >>> temp_ext = tgis.RasterRelativeTime(start_time=1, end_time=2, unit="years")
  441. >>> map.set_temporal_extent(temp_ext)
  442. >>> print map.get_temporal_extent_as_tuple()
  443. (1, 2)
  444. >>> map = tgis.VectorDataset(None)
  445. >>> temp_ext = tgis.VectorAbsoluteTime(start_time=datetime.datetime(2000, 1, 1),
  446. ... end_time=datetime.datetime(2001, 1, 1))
  447. >>> map.set_temporal_extent(temp_ext)
  448. >>> print map.get_temporal_extent_as_tuple()
  449. (datetime.datetime(2000, 1, 1, 0, 0), datetime.datetime(2001, 1, 1, 0, 0))
  450. >>> map1 = tgis.VectorDataset("A@P")
  451. >>> check = map1.set_absolute_time(datetime.datetime(2000,5,5), datetime.datetime(2005,6,6), None)
  452. >>> print map1.get_temporal_extent_as_tuple()
  453. (datetime.datetime(2000, 5, 5, 0, 0), datetime.datetime(2005, 6, 6, 0, 0))
  454. >>> map2 = tgis.RasterDataset("B@P")
  455. >>> check = map2.set_absolute_time(datetime.datetime(1990,1,1), datetime.datetime(1999,8,1), None)
  456. >>> print map2.get_temporal_extent_as_tuple()
  457. (datetime.datetime(1990, 1, 1, 0, 0), datetime.datetime(1999, 8, 1, 0, 0))
  458. >>> map2.set_temporal_extent(map1.get_temporal_extent())
  459. >>> print map2.get_temporal_extent_as_tuple()
  460. (datetime.datetime(2000, 5, 5, 0, 0), datetime.datetime(2005, 6, 6, 0, 0))
  461. @endcode
  462. """
  463. if issubclass(type(extent), RelativeTemporalExtent):
  464. start = extent.get_start_time()
  465. end = extent.get_end_time()
  466. unit = extent.get_unit()
  467. self.set_relative_time(start, end, unit)
  468. elif issubclass(type(extent), AbsoluteTemporalExtent):
  469. start = extent.get_start_time()
  470. end = extent.get_end_time()
  471. tz = extent.get_timezone()
  472. self.set_absolute_time(start, end, tz)
  473. def temporal_buffer(self, increment, update=False, dbif=None):
  474. """!Create a temporal buffer based on an increment
  475. For absolute time the increment must be a string of type "integer
  476. unit"
  477. Unit can be year, years, month, months, day, days, hour, hours,
  478. minute, minutes, day or days.
  479. @param increment This is the increment, a string in case of absolute
  480. time or an integer in case of relative time
  481. @param update Perform an immediate database update to store the
  482. modified temporal extent, otherwise only this object
  483. will be modified
  484. Usage:
  485. @code
  486. >>> import grass.temporal as tgis
  487. >>> maps = []
  488. >>> for i in range(5):
  489. ... map = tgis.RasterDataset(None)
  490. ... if i%2 == 0:
  491. ... check = map.set_relative_time(i, i + 1, 'years')
  492. ... else:
  493. ... check = map.set_relative_time(i, None, 'years')
  494. ... map.temporal_buffer(3)
  495. ... maps.append(map)
  496. >>> for map in maps:
  497. ... map.temporal_extent.print_info()
  498. +-------------------- Relative time -----------------------------------------+
  499. | Start time:................. -3
  500. | End time:................... 4
  501. | Relative time unit:......... years
  502. +-------------------- Relative time -----------------------------------------+
  503. | Start time:................. -2
  504. | End time:................... 4
  505. | Relative time unit:......... years
  506. +-------------------- Relative time -----------------------------------------+
  507. | Start time:................. -1
  508. | End time:................... 6
  509. | Relative time unit:......... years
  510. +-------------------- Relative time -----------------------------------------+
  511. | Start time:................. 0
  512. | End time:................... 6
  513. | Relative time unit:......... years
  514. +-------------------- Relative time -----------------------------------------+
  515. | Start time:................. 1
  516. | End time:................... 8
  517. | Relative time unit:......... years
  518. >>> maps = []
  519. >>> for i in range(1,5):
  520. ... map = tgis.RasterDataset(None)
  521. ... if i%2 == 0:
  522. ... check = map.set_absolute_time(datetime(2001,i,1), datetime(2001, i + 1, 1))
  523. ... else:
  524. ... check = map.set_absolute_time(datetime(2001,i,1), None)
  525. ... map.temporal_buffer("7 days")
  526. ... maps.append(map)
  527. >>> for map in maps:
  528. ... map.temporal_extent.print_info()
  529. +-------------------- Absolute time -----------------------------------------+
  530. | Start time:................. 2000-12-25 00:00:00
  531. | End time:................... 2001-01-08 00:00:00
  532. +-------------------- Absolute time -----------------------------------------+
  533. | Start time:................. 2001-01-25 00:00:00
  534. | End time:................... 2001-03-08 00:00:00
  535. +-------------------- Absolute time -----------------------------------------+
  536. | Start time:................. 2001-02-22 00:00:00
  537. | End time:................... 2001-03-08 00:00:00
  538. +-------------------- Absolute time -----------------------------------------+
  539. | Start time:................. 2001-03-25 00:00:00
  540. | End time:................... 2001-05-08 00:00:00
  541. @endcode
  542. """
  543. if self.is_time_absolute():
  544. start, end, tz = self.get_absolute_time()
  545. new_start = decrement_datetime_by_string(start, increment)
  546. if end == None:
  547. new_end = increment_datetime_by_string(start, increment)
  548. else:
  549. new_end = increment_datetime_by_string(end, increment)
  550. if update:
  551. self.update_absolute_time(new_start, new_end, tz, dbif=dbif)
  552. else:
  553. self.set_absolute_time(new_start, new_end, tz)
  554. else:
  555. start, end, unit = self.get_relative_time()
  556. new_start = start - increment
  557. if end == None:
  558. new_end = start + increment
  559. else:
  560. new_end = end + increment
  561. if update:
  562. self.update_relative_time(new_start, new_end, unit, dbif=dbif)
  563. else:
  564. self.set_relative_time(new_start, new_end, unit)
  565. def set_spatial_extent_from_values(self, north, south, east, west, top=0, bottom=0):
  566. """!Set the spatial extent of the map from values
  567. This method only modifies this object and does not commit
  568. the modifications to the temporal database.
  569. @param north The northern edge
  570. @param south The southern edge
  571. @param east The eastern edge
  572. @param west The western edge
  573. @param top The top edge
  574. @param bottom The bottom edge
  575. """
  576. self.spatial_extent.set_spatial_extent_from_values(
  577. north, south, east, west, top, bottom)
  578. def set_spatial_extent(self, spatial_extent):
  579. """!Set the spatial extent of the map
  580. This method only modifies this object and does not commit
  581. the modifications to the temporal database.
  582. @param spatial_extent An object of type SpatialExtent or its subclasses
  583. @code
  584. >>> import datetime
  585. >>> import grass.temporal as tgis
  586. >>> map = tgis.RasterDataset(None)
  587. >>> spat_ext = tgis.SpatialExtent(north=10, south=-10, east=20, west=-20, top=5, bottom=-5)
  588. >>> map.set_spatial_extent(spat_ext)
  589. >>> print map.get_spatial_extent_as_tuple()
  590. (10.0, -10.0, 20.0, -20.0, 5.0, -5.0)
  591. @endcode
  592. """
  593. self.spatial_extent.set_spatial_extent(spatial_extent)
  594. def spatial_buffer(self, size, update=False, dbif=None):
  595. """!Buffer the spatial extent by a given size in all
  596. spatial directions.
  597. @param size The buffer size, using the unit of the grass region
  598. @code
  599. >>> import grass.temporal as tgis
  600. >>> map = tgis.RasterDataset(None)
  601. >>> spat_ext = tgis.SpatialExtent(north=10, south=-10, east=20, west=-20, top=5, bottom=-5)
  602. >>> map.set_spatial_extent(spat_ext)
  603. >>> map.spatial_buffer(10)
  604. >>> print map.get_spatial_extent_as_tuple()
  605. (20.0, -20.0, 30.0, -30.0, 15.0, -15.0)
  606. @endcode
  607. """
  608. self.spatial_extent.north += size
  609. self.spatial_extent.south -= size
  610. self.spatial_extent.east += size
  611. self.spatial_extent.west -= size
  612. self.spatial_extent.top += size
  613. self.spatial_extent.bottom -= size
  614. if update:
  615. self.spatial_extent.update(dbif)
  616. def spatial_buffer_2d(self, size, update=False, dbif=None):
  617. """!Buffer the spatial extent by a given size in 2d
  618. spatial directions.
  619. @param size The buffer size, using the unit of the grass region
  620. @code
  621. >>> import grass.temporal as tgis
  622. >>> map = tgis.RasterDataset(None)
  623. >>> spat_ext = tgis.SpatialExtent(north=10, south=-10, east=20, west=-20, top=5, bottom=-5)
  624. >>> map.set_spatial_extent(spat_ext)
  625. >>> map.spatial_buffer_2d(10)
  626. >>> print map.get_spatial_extent_as_tuple()
  627. (20.0, -20.0, 30.0, -30.0, 5.0, -5.0)
  628. @endcode
  629. """
  630. self.spatial_extent.north += size
  631. self.spatial_extent.south -= size
  632. self.spatial_extent.east += size
  633. self.spatial_extent.west -= size
  634. if update:
  635. self.spatial_extent.update(dbif)
  636. def check_for_correct_time(self):
  637. """!Check for correct time"""
  638. if self.is_time_absolute():
  639. start, end, tz = self.get_absolute_time()
  640. else:
  641. start, end, unit = self.get_relative_time()
  642. if start is not None:
  643. if end is not None:
  644. if start >= end:
  645. if self.get_layer() is not None:
  646. self.msgr.error(_("Map <%(id)s> with layer %(layer)s has "
  647. "incorrect time interval, start time is "
  648. "greater than end time") % {
  649. 'id': self.get_map_id(),
  650. 'layer': self.get_layer()})
  651. else:
  652. self.msgr.error(_("Map <%s> has incorrect time interval, "
  653. "start time is greater than end time") % \
  654. (self.get_map_id()))
  655. return False
  656. else:
  657. self.msgr.error(_("Map <%s> has incorrect start time") %
  658. (self.get_map_id()))
  659. return False
  660. return True
  661. def delete(self, dbif=None, update=True, execute=True):
  662. """!Delete a map entry from database if it exists
  663. Remove dependent entries:
  664. * Remove the map entry in each space time dataset in which this map
  665. is registered
  666. * Remove the space time dataset register table
  667. @param dbif The database interface to be used
  668. @param update Call for each unregister statement the update from
  669. registered maps of the space time dataset.
  670. This can slow down the un-registration process
  671. significantly.
  672. @param execute If True the SQL DELETE and DROP table statements will
  673. be executed.
  674. If False the prepared SQL statements are
  675. returned and must be executed by the caller.
  676. @return The SQL statements if execute=False, else an empty string,
  677. None in case of a failure
  678. """
  679. if self.get_mapset() != get_current_mapset():
  680. self.msgr.fatal(_("Unable to delete dataset <%(ds)s> of type %(type)s from the temporal database."
  681. " The mapset of the dataset does not match the current mapset")%\
  682. {"ds":self.get_id(), "type":self.get_type()})
  683. dbif, connected = init_dbif(dbif)
  684. statement = ""
  685. if self.is_in_db(dbif):
  686. # SELECT all needed information from the database
  687. self.metadata.select(dbif)
  688. # First we unregister from all dependent space time datasets
  689. statement += self.unregister(
  690. dbif=dbif, update=update, execute=False)
  691. # Remove the strds register table
  692. if self.get_stds_register() is not None:
  693. statement += "DROP TABLE IF EXISTS " + self.get_stds_register() + ";\n"
  694. self.msgr.verbose(_("Delete %s dataset <%s> from temporal database")
  695. % (self.get_type(), self.get_id()))
  696. # Delete yourself from the database, trigger functions will
  697. # take care of dependencies
  698. statement += self.base.get_delete_statement()
  699. if execute:
  700. dbif.execute_transaction(statement)
  701. # Remove the timestamp from the file system
  702. self.remove_timestamp_from_grass()
  703. self.reset(None)
  704. if connected:
  705. dbif.close()
  706. if execute:
  707. return ""
  708. return statement
  709. def unregister(self, dbif=None, update=True, execute=True):
  710. """! Remove the map entry in each space time dataset in which this map
  711. is registered
  712. @param dbif The database interface to be used
  713. @param update Call for each unregister statement the update from
  714. registered maps of the space time dataset. This can
  715. slow down the un-registration process significantly.
  716. @param execute If True the SQL DELETE and DROP table statements
  717. will be executed.
  718. If False the prepared SQL statements are
  719. returned and must be executed by the caller.
  720. @return The SQL statements if execute=False, else an empty string
  721. """
  722. if self.get_layer() is not None:
  723. self.msgr.debug(1, _("Unregister %(type)s map <%(map)s> with "
  724. "layer %(layer)s from space time datasets" % \
  725. {'type':self.get_type(), 'map':self.get_map_id(),
  726. 'layer':self.get_layer()}))
  727. else:
  728. self.msgr.debug(1, _("Unregister %(type)s map <%(map)s> "
  729. "from space time datasets"
  730. % {'type':self.get_type(), 'map':self.get_map_id()}))
  731. if self.get_mapset() != get_current_mapset():
  732. self.msgr.fatal(_("Unable to unregister dataset <%(ds)s> of type %(type)s from the temporal database."
  733. " The mapset of the dataset does not match the current mapset")%\
  734. {"ds":self.get_id(), "type":self.get_type()})
  735. statement = ""
  736. dbif, connected = init_dbif(dbif)
  737. # Get all datasets in which this map is registered
  738. rows = self.get_registered_datasets(dbif)
  739. # For each stds in which the map is registered
  740. if rows is not None:
  741. for row in rows:
  742. # Create a space time dataset object to remove the map
  743. # from its register
  744. stds = self.get_new_stds_instance(row["id"])
  745. stds.metadata.select(dbif)
  746. statement += stds.unregister_map(self, dbif, False)
  747. # Take care to update the space time dataset after
  748. # the map has been unregistered
  749. if update == True and execute == True:
  750. stds.update_from_registered_maps(dbif)
  751. if execute:
  752. dbif.execute_transaction(statement)
  753. if connected:
  754. dbif.close()
  755. if execute:
  756. return ""
  757. return statement
  758. def get_registered_datasets(self, dbif=None):
  759. """!Return all space time dataset ids in which this map is registered
  760. as dictionary like rows with column "id" or None if this map is not
  761. registered in any space time dataset.
  762. @param dbif The database interface to be used
  763. @return The SQL rows with the ids of all space time datasets in
  764. which this map is registered
  765. """
  766. dbif, connected = init_dbif(dbif)
  767. rows = None
  768. try:
  769. if self.get_stds_register() is not None:
  770. # Select all stds tables in which this map is registered
  771. sql = "SELECT id FROM " + self.get_stds_register()
  772. dbif.cursor.execute(sql)
  773. rows = dbif.cursor.fetchall()
  774. except:
  775. self.msgr.error(_("Unable to select space time dataset register table "
  776. "<%s>") % (self.get_stds_register()))
  777. if connected:
  778. dbif.close()
  779. return rows
  780. ###############################################################################
  781. if __name__ == "__main__":
  782. import doctest
  783. doctest.testmod()