abstract_map_dataset.py 42 KB

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