abstract_map_dataset.py 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021
  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. def check_resolution_with_current_region(self):
  43. """!Check if the raster or voxel resolution is
  44. finer than the current resolution
  45. - Return "finer" in case the raster/voxel resolution is finer
  46. than the current region
  47. - Return "coarser" in case the raster/voxel resolution is coarser
  48. than the current region
  49. Vector maps have no resolution, since they store the coordinates
  50. directly.
  51. @return "finer" or "coarser"
  52. """
  53. raise ImplementationError(
  54. "This method must be implemented in the subclasses")
  55. @abstractmethod
  56. def has_grass_timestamp(self):
  57. """!Check if a grass file based time stamp exists for this map.
  58. @return True is the grass file based time stamped exists for this
  59. 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"
  129. while layer is 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 the
  271. 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 %(type)s"
  279. " map <%(id)s> with layer: %(l)s") % {
  280. 'type': self.get_type(), 'id': self.get_map_id(),
  281. 'l': self.get_layer()})
  282. return False
  283. else:
  284. core.error(_("Start time must be of type datetime for "
  285. "%(type)s map <%(id)s>") % {
  286. 'type': self.get_type(), 'id': self.get_map_id()})
  287. return False
  288. if end_time and not isinstance(end_time, datetime):
  289. if self.get_layer():
  290. self.msgr.error(_("End time must be of type datetime for %(type)s "
  291. "map <%(id)s> with layer: %(l)s") % {
  292. 'type': self.get_type(), 'id': self.get_map_id(),
  293. 'l': self.get_layer()})
  294. return False
  295. else:
  296. self.msgr.error(_("End time must be of type datetime for "
  297. "%(type)s map <%(id)s>") % {
  298. 'type': self.get_type(), 'id': self.get_map_id()})
  299. return False
  300. if start_time is not None and end_time is not None:
  301. if start_time > end_time:
  302. if self.get_layer():
  303. self.msgr.error(_("End time must be greater than start time for"
  304. " %(type)s map <%(id)s> with layer: %(l)s") % {
  305. 'type': self.get_type(),
  306. 'id': self.get_map_id(),
  307. 'l': self.get_layer()})
  308. return False
  309. else:
  310. self.msgr.error(_("End time must be greater than start time "
  311. "for %(type)s map <%(id)s>") % {
  312. 'type': self.get_type(),
  313. 'id': self.get_map_id()})
  314. return False
  315. else:
  316. # Do not create an interval in case start and end time are
  317. # equal
  318. if start_time == end_time:
  319. end_time = None
  320. self.base.set_ttype("absolute")
  321. self.absolute_time.set_start_time(start_time)
  322. self.absolute_time.set_end_time(end_time)
  323. return True
  324. def update_absolute_time(self, start_time, end_time=None, dbif=None):
  325. """!Update the absolute time
  326. The end time is optional and must be set to None in case of time
  327. instance.
  328. This functions assures that the timestamp is written to the
  329. grass file system based database in addition to the temporal
  330. database entry.
  331. @param start_time a datetime object specifying the start time of
  332. the map
  333. @param end_time a datetime object specifying the end time of the
  334. map, None in case or time instance
  335. @param dbif The database interface to be used
  336. """
  337. if get_enable_mapset_check() is True and self.get_mapset() != get_current_mapset():
  338. self.msgr.fatal(_("Unable to update dataset <%(ds)s> of type %(type)s in the temporal database."
  339. " The mapset of the dataset does not match the current mapset")%\
  340. {"ds":self.get_id(), "type":self.get_type()})
  341. if self.set_absolute_time(start_time, end_time):
  342. dbif, connected = init_dbif(dbif)
  343. self.absolute_time.update_all(dbif)
  344. self.base.update(dbif)
  345. if connected:
  346. dbif.close()
  347. if get_enable_timestamp_write():
  348. self.write_timestamp_to_grass()
  349. def set_relative_time(self, start_time, end_time, unit):
  350. """!Set the relative time interval
  351. The end time is optional and must be set to None in case of time
  352. instance.
  353. This method only modifies this object and does not commit
  354. the modifications to the temporal database.
  355. @param start_time An integer value
  356. @param end_time An integer value, None in case or time instance
  357. @param unit The unit of the relative time. Supported units:
  358. year(s), month(s), day(s), hour(s), minute(s), second(s)
  359. @return True for success and False otherwise
  360. """
  361. if not self.check_relative_time_unit(unit):
  362. if self.get_layer() is not None:
  363. self.msgr.error(_("Unsupported relative time unit type for %(type)s"
  364. " map <%(id)s> with layer %(l)s: %(u)s") % {
  365. 'type': self.get_type(), 'id': self.get_id(),
  366. 'l': self.get_layer(), 'u': unit})
  367. else:
  368. self.msgr.error(_("Unsupported relative time unit type for %(type)s"
  369. " map <%(id)s>: %(u)s") % {
  370. 'type': self.get_type(), 'id': self.get_id(),
  371. 'u': unit})
  372. return False
  373. if start_time is not None and end_time is not None:
  374. if int(start_time) > int(end_time):
  375. if self.get_layer() is not None:
  376. self.msgr.error(_("End time must be greater than start time for"
  377. " %(type)s map <%(id)s> with layer %(l)s") % \
  378. {'type': self.get_type(), 'id': self.get_id(),
  379. 'l': self.get_layer()})
  380. else:
  381. self.msgr.error(_("End time must be greater than start time for"
  382. " %(type)s map <%(id)s>") % {
  383. 'type': self.get_type(), 'id': self.get_id()})
  384. return False
  385. else:
  386. # Do not create an interval in case start and end time are
  387. # equal
  388. if start_time == end_time:
  389. end_time = None
  390. self.base.set_ttype("relative")
  391. self.relative_time.set_unit(unit)
  392. self.relative_time.set_start_time(int(start_time))
  393. if end_time is not None:
  394. self.relative_time.set_end_time(int(end_time))
  395. else:
  396. self.relative_time.set_end_time(None)
  397. return True
  398. def update_relative_time(self, start_time, end_time, unit, dbif=None):
  399. """!Update the relative time interval
  400. The end time is optional and must be set to None in case of time
  401. instance.
  402. This functions assures that the timestamp is written to the
  403. grass file system based database in addition to the temporal
  404. database entry.
  405. @param start_time An integer value
  406. @param end_time An integer value, None in case or time instance
  407. @param unit The relative time unit
  408. @param dbif The database interface to be used
  409. """
  410. if get_enable_mapset_check() is True and self.get_mapset() != get_current_mapset():
  411. self.msgr.fatal(_("Unable to update dataset <%(ds)s> of type %(type)s in the temporal database."
  412. " The mapset of the dataset does not match the current mapset")%\
  413. {"ds":self.get_id(), "type":self.get_type()})
  414. if self.set_relative_time(start_time, end_time, unit):
  415. dbif, connected = init_dbif(dbif)
  416. self.relative_time.update_all(dbif)
  417. self.base.update(dbif)
  418. if connected:
  419. dbif.close()
  420. if get_enable_timestamp_write():
  421. self.write_timestamp_to_grass()
  422. def set_temporal_extent(self, extent):
  423. """!Convenient method to set the temporal extent from a temporal extent object
  424. @param temporal_extent The temporal extent that should be set for this object
  425. @code
  426. >>> import datetime
  427. >>> import grass.temporal as tgis
  428. >>> map = tgis.RasterDataset(None)
  429. >>> temp_ext = tgis.RasterRelativeTime(start_time=1, end_time=2, unit="years")
  430. >>> map.set_temporal_extent(temp_ext)
  431. >>> print map.get_temporal_extent_as_tuple()
  432. (1, 2)
  433. >>> map = tgis.VectorDataset(None)
  434. >>> temp_ext = tgis.VectorAbsoluteTime(start_time=datetime.datetime(2000, 1, 1),
  435. ... end_time=datetime.datetime(2001, 1, 1))
  436. >>> map.set_temporal_extent(temp_ext)
  437. >>> print map.get_temporal_extent_as_tuple()
  438. (datetime.datetime(2000, 1, 1, 0, 0), datetime.datetime(2001, 1, 1, 0, 0))
  439. >>> map1 = tgis.VectorDataset("A@P")
  440. >>> check = map1.set_absolute_time(datetime.datetime(2000,5,5), datetime.datetime(2005,6,6))
  441. >>> print map1.get_temporal_extent_as_tuple()
  442. (datetime.datetime(2000, 5, 5, 0, 0), datetime.datetime(2005, 6, 6, 0, 0))
  443. >>> map2 = tgis.RasterDataset("B@P")
  444. >>> check = map2.set_absolute_time(datetime.datetime(1990,1,1), datetime.datetime(1999,8,1))
  445. >>> print map2.get_temporal_extent_as_tuple()
  446. (datetime.datetime(1990, 1, 1, 0, 0), datetime.datetime(1999, 8, 1, 0, 0))
  447. >>> map2.set_temporal_extent(map1.get_temporal_extent())
  448. >>> print map2.get_temporal_extent_as_tuple()
  449. (datetime.datetime(2000, 5, 5, 0, 0), datetime.datetime(2005, 6, 6, 0, 0))
  450. @endcode
  451. """
  452. if issubclass(type(extent), RelativeTemporalExtent):
  453. start = extent.get_start_time()
  454. end = extent.get_end_time()
  455. unit = extent.get_unit()
  456. self.set_relative_time(start, end, unit)
  457. elif issubclass(type(extent), AbsoluteTemporalExtent):
  458. start = extent.get_start_time()
  459. end = extent.get_end_time()
  460. self.set_absolute_time(start, end)
  461. def temporal_buffer(self, increment, update=False, dbif=None):
  462. """!Create a temporal buffer based on an increment
  463. For absolute time the increment must be a string of type "integer
  464. unit"
  465. Unit can be year, years, month, months, day, days, hour, hours,
  466. minute, minutes, day or days.
  467. @param increment This is the increment, a string in case of absolute
  468. time or an integer in case of relative time
  469. @param update Perform an immediate database update to store the
  470. modified temporal extent, otherwise only this object
  471. will be modified
  472. Usage:
  473. @code
  474. >>> import grass.temporal as tgis
  475. >>> maps = []
  476. >>> for i in range(5):
  477. ... map = tgis.RasterDataset(None)
  478. ... if i%2 == 0:
  479. ... check = map.set_relative_time(i, i + 1, 'years')
  480. ... else:
  481. ... check = map.set_relative_time(i, None, 'years')
  482. ... map.temporal_buffer(3)
  483. ... maps.append(map)
  484. >>> for map in maps:
  485. ... map.temporal_extent.print_info()
  486. +-------------------- Relative time -----------------------------------------+
  487. | Start time:................. -3
  488. | End time:................... 4
  489. | Relative time unit:......... years
  490. +-------------------- Relative time -----------------------------------------+
  491. | Start time:................. -2
  492. | End time:................... 4
  493. | Relative time unit:......... years
  494. +-------------------- Relative time -----------------------------------------+
  495. | Start time:................. -1
  496. | End time:................... 6
  497. | Relative time unit:......... years
  498. +-------------------- Relative time -----------------------------------------+
  499. | Start time:................. 0
  500. | End time:................... 6
  501. | Relative time unit:......... years
  502. +-------------------- Relative time -----------------------------------------+
  503. | Start time:................. 1
  504. | End time:................... 8
  505. | Relative time unit:......... years
  506. >>> maps = []
  507. >>> for i in range(1,5):
  508. ... map = tgis.RasterDataset(None)
  509. ... if i%2 == 0:
  510. ... check = map.set_absolute_time(datetime(2001,i,1), datetime(2001, i + 1, 1))
  511. ... else:
  512. ... check = map.set_absolute_time(datetime(2001,i,1), None)
  513. ... map.temporal_buffer("7 days")
  514. ... maps.append(map)
  515. >>> for map in maps:
  516. ... map.temporal_extent.print_info()
  517. +-------------------- Absolute time -----------------------------------------+
  518. | Start time:................. 2000-12-25 00:00:00
  519. | End time:................... 2001-01-08 00:00:00
  520. +-------------------- Absolute time -----------------------------------------+
  521. | Start time:................. 2001-01-25 00:00:00
  522. | End time:................... 2001-03-08 00:00:00
  523. +-------------------- Absolute time -----------------------------------------+
  524. | Start time:................. 2001-02-22 00:00:00
  525. | End time:................... 2001-03-08 00:00:00
  526. +-------------------- Absolute time -----------------------------------------+
  527. | Start time:................. 2001-03-25 00:00:00
  528. | End time:................... 2001-05-08 00:00:00
  529. @endcode
  530. """
  531. if self.is_time_absolute():
  532. start, end = self.get_absolute_time()
  533. new_start = decrement_datetime_by_string(start, increment)
  534. if end == None:
  535. new_end = increment_datetime_by_string(start, increment)
  536. else:
  537. new_end = increment_datetime_by_string(end, increment)
  538. if update:
  539. self.update_absolute_time(new_start, new_end, dbif=dbif)
  540. else:
  541. self.set_absolute_time(new_start, new_end)
  542. else:
  543. start, end, unit = self.get_relative_time()
  544. new_start = start - increment
  545. if end == None:
  546. new_end = start + increment
  547. else:
  548. new_end = end + increment
  549. if update:
  550. self.update_relative_time(new_start, new_end, unit, dbif=dbif)
  551. else:
  552. self.set_relative_time(new_start, new_end, unit)
  553. def set_spatial_extent_from_values(self, north, south, east, west, top=0, bottom=0):
  554. """!Set the spatial extent of the map from values
  555. This method only modifies this object and does not commit
  556. the modifications to the temporal database.
  557. @param north The northern edge
  558. @param south The southern edge
  559. @param east The eastern edge
  560. @param west The western edge
  561. @param top The top edge
  562. @param bottom The bottom edge
  563. """
  564. self.spatial_extent.set_spatial_extent_from_values(
  565. north, south, east, west, top, bottom)
  566. def set_spatial_extent(self, spatial_extent):
  567. """!Set the spatial extent of the map
  568. This method only modifies this object and does not commit
  569. the modifications to the temporal database.
  570. @param spatial_extent An object of type SpatialExtent or its subclasses
  571. @code
  572. >>> import datetime
  573. >>> import grass.temporal as tgis
  574. >>> map = tgis.RasterDataset(None)
  575. >>> spat_ext = tgis.SpatialExtent(north=10, south=-10, east=20, west=-20, top=5, bottom=-5)
  576. >>> map.set_spatial_extent(spat_ext)
  577. >>> print map.get_spatial_extent_as_tuple()
  578. (10.0, -10.0, 20.0, -20.0, 5.0, -5.0)
  579. @endcode
  580. """
  581. self.spatial_extent.set_spatial_extent(spatial_extent)
  582. def spatial_buffer(self, size, update=False, dbif=None):
  583. """!Buffer the spatial extent by a given size in all
  584. spatial directions.
  585. @param size The buffer size, using the unit of the grass region
  586. @code
  587. >>> import grass.temporal as tgis
  588. >>> map = tgis.RasterDataset(None)
  589. >>> spat_ext = tgis.SpatialExtent(north=10, south=-10, east=20, west=-20, top=5, bottom=-5)
  590. >>> map.set_spatial_extent(spat_ext)
  591. >>> map.spatial_buffer(10)
  592. >>> print map.get_spatial_extent_as_tuple()
  593. (20.0, -20.0, 30.0, -30.0, 15.0, -15.0)
  594. @endcode
  595. """
  596. self.spatial_extent.north += size
  597. self.spatial_extent.south -= size
  598. self.spatial_extent.east += size
  599. self.spatial_extent.west -= size
  600. self.spatial_extent.top += size
  601. self.spatial_extent.bottom -= size
  602. if update:
  603. self.spatial_extent.update(dbif)
  604. def spatial_buffer_2d(self, size, update=False, dbif=None):
  605. """!Buffer the spatial extent by a given size in 2d
  606. spatial directions.
  607. @param size The buffer size, using the unit of the grass region
  608. @code
  609. >>> import grass.temporal as tgis
  610. >>> map = tgis.RasterDataset(None)
  611. >>> spat_ext = tgis.SpatialExtent(north=10, south=-10, east=20, west=-20, top=5, bottom=-5)
  612. >>> map.set_spatial_extent(spat_ext)
  613. >>> map.spatial_buffer_2d(10)
  614. >>> print map.get_spatial_extent_as_tuple()
  615. (20.0, -20.0, 30.0, -30.0, 5.0, -5.0)
  616. @endcode
  617. """
  618. self.spatial_extent.north += size
  619. self.spatial_extent.south -= size
  620. self.spatial_extent.east += size
  621. self.spatial_extent.west -= size
  622. if update:
  623. self.spatial_extent.update(dbif)
  624. def check_for_correct_time(self):
  625. """!Check for correct time"""
  626. if self.is_time_absolute():
  627. start, end= self.get_absolute_time()
  628. else:
  629. start, end, unit = self.get_relative_time()
  630. if start is not None:
  631. if end is not None:
  632. if start >= end:
  633. if self.get_layer() is not None:
  634. self.msgr.error(_("Map <%(id)s> with layer %(layer)s has "
  635. "incorrect time interval, start time is "
  636. "greater than end time") % {
  637. 'id': self.get_map_id(),
  638. 'layer': self.get_layer()})
  639. else:
  640. self.msgr.error(_("Map <%s> has incorrect time interval, "
  641. "start time is greater than end time") % \
  642. (self.get_map_id()))
  643. return False
  644. else:
  645. self.msgr.error(_("Map <%s> has incorrect start time") %
  646. (self.get_map_id()))
  647. return False
  648. return True
  649. def delete(self, dbif=None, update=True, execute=True):
  650. """!Delete a map entry from database if it exists
  651. Remove dependent entries:
  652. * Remove the map entry in each space time dataset in which this map
  653. is registered
  654. * Remove the space time dataset register table
  655. @param dbif The database interface to be used
  656. @param update Call for each unregister statement the update from
  657. registered maps of the space time dataset.
  658. This can slow down the un-registration process
  659. significantly.
  660. @param execute If True the SQL DELETE and DROP table statements will
  661. be executed.
  662. If False the prepared SQL statements are
  663. returned and must be executed by the caller.
  664. @return The SQL statements if execute=False, else an empty string,
  665. None in case of a failure
  666. """
  667. if get_enable_mapset_check() is True and self.get_mapset() != get_current_mapset():
  668. self.msgr.fatal(_("Unable to delete dataset <%(ds)s> of type %(type)s from the temporal database."
  669. " The mapset of the dataset does not match the current mapset")%\
  670. {"ds":self.get_id(), "type":self.get_type()})
  671. dbif, connected = init_dbif(dbif)
  672. statement = ""
  673. if self.is_in_db(dbif):
  674. # SELECT all needed information from the database
  675. self.metadata.select(dbif)
  676. # First we unregister from all dependent space time datasets
  677. statement += self.unregister(
  678. dbif=dbif, update=update, execute=False)
  679. self.msgr.verbose(_("Delete %s dataset <%s> from temporal database")
  680. % (self.get_type(), self.get_id()))
  681. # Delete yourself from the database, trigger functions will
  682. # take care of dependencies
  683. statement += self.base.get_delete_statement()
  684. if execute:
  685. dbif.execute_transaction(statement)
  686. statement = ""
  687. # Remove the timestamp from the file system
  688. self.remove_timestamp_from_grass()
  689. self.reset(None)
  690. if connected:
  691. dbif.close()
  692. return statement
  693. def unregister(self, dbif=None, update=True, execute=True):
  694. """! Remove the map entry in each space time dataset in which this map
  695. is registered
  696. @param dbif The database interface to be used
  697. @param update Call for each unregister statement the update from
  698. registered maps of the space time dataset. This can
  699. slow down the un-registration process significantly.
  700. @param execute If True the SQL DELETE and DROP table statements
  701. will be executed.
  702. If False the prepared SQL statements are
  703. returned and must be executed by the caller.
  704. @return The SQL statements if execute=False, else an empty string
  705. """
  706. if self.get_layer() is not None:
  707. self.msgr.debug(1, "Unregister %(type)s map <%(map)s> with "
  708. "layer %(layer)s from space time datasets" % \
  709. {'type':self.get_type(), 'map':self.get_map_id(),
  710. 'layer':self.get_layer()})
  711. else:
  712. self.msgr.debug(1, "Unregister %(type)s map <%(map)s> "
  713. "from space time datasets"
  714. % {'type':self.get_type(), 'map':self.get_map_id()})
  715. if get_enable_mapset_check() is True and self.get_mapset() != get_current_mapset():
  716. self.msgr.fatal(_("Unable to unregister dataset <%(ds)s> of type %(type)s from the temporal database."
  717. " The mapset of the dataset does not match the current mapset")%\
  718. {"ds":self.get_id(), "type":self.get_type()})
  719. statement = ""
  720. dbif, connected = init_dbif(dbif)
  721. # Get all datasets in which this map is registered
  722. datasets = self.get_registered_stds(dbif)
  723. # For each stds in which the map is registered
  724. if datasets is not None:
  725. for dataset in datasets:
  726. # Create a space time dataset object to remove the map
  727. # from its register
  728. stds = self.get_new_stds_instance(dataset)
  729. stds.metadata.select(dbif)
  730. statement += stds.unregister_map(self, dbif, False)
  731. # Take care to update the space time dataset after
  732. # the map has been unregistered
  733. if update == True and execute == True:
  734. stds.update_from_registered_maps(dbif)
  735. if execute:
  736. dbif.execute_transaction(statement)
  737. statement = ""
  738. if connected:
  739. dbif.close()
  740. return statement
  741. def get_registered_stds(self, dbif=None):
  742. """!Return all space time dataset ids in which this map is registered
  743. as as a list of strings, or None if this map is not
  744. registered in any space time dataset.
  745. @param dbif The database interface to be used
  746. @return A list of ids of all space time datasets in
  747. which this map is registered
  748. """
  749. dbif, connected = init_dbif(dbif)
  750. self.stds_register.select(dbif)
  751. datasets = self.stds_register.get_registered_stds()
  752. if datasets is not None and datasets != "" and datasets.find("@") >= 0:
  753. datasets = datasets.split(",")
  754. else:
  755. datasets = None
  756. if connected:
  757. dbif.close
  758. return datasets
  759. def add_stds_to_register(self, stds_id, dbif=None, execute=True):
  760. """!Add a new space time dataset to the register
  761. @param stds_id The id of the space time dataset to be registered
  762. @param dbif The database interface to be used
  763. @param execute If True the SQL INSERT table statements
  764. will be executed.
  765. If False the prepared SQL statements are
  766. returned and must be executed by the caller.
  767. @return The SQL statements if execute=False, else an empty string
  768. """
  769. dbif, connected = init_dbif(dbif=dbif)
  770. datasets = self.get_registered_stds(dbif=dbif)
  771. if stds_id is None or stds_id == "":
  772. return ""
  773. # Check if no datasets are present
  774. if datasets is None:
  775. datasets = []
  776. # Check if the dataset is already present
  777. if stds_id in datasets:
  778. if connected:
  779. dbif.close
  780. return ""
  781. datasets.append(stds_id)
  782. self.stds_register.set_registered_stds(",".join(datasets))
  783. statement = ""
  784. if execute is True:
  785. self.stds_register.update(dbif=dbif)
  786. else:
  787. statement = self.stds_register.get_update_statement_mogrified(dbif=dbif)
  788. if connected:
  789. dbif.close
  790. return statement
  791. def remove_stds_from_register(self, stds_id, dbif=None, execute=True):
  792. """!Remove a space time dataset from the register
  793. @param stds_id The id of the space time dataset to removed from the registered
  794. @param dbif The database interface to be used
  795. @param execute If True the SQL INSERT table statements
  796. will be executed.
  797. If False the prepared SQL statements are
  798. returned and must be executed by the caller.
  799. @return The SQL statements if execute=False, else an empty string
  800. """
  801. dbif, connected = init_dbif(dbif)
  802. datasets = self.get_registered_stds(dbif=dbif)
  803. # Check if no datasets are present
  804. if datasets is None:
  805. if connected:
  806. dbif.close
  807. return ""
  808. # Check if the dataset is already present
  809. if stds_id not in datasets:
  810. if connected:
  811. dbif.close
  812. return ""
  813. datasets.remove(stds_id)
  814. self.stds_register.set_registered_stds(",".join(datasets))
  815. statement = ""
  816. if execute is True:
  817. self.stds_register.update(dbif=dbif)
  818. else:
  819. statement = self.stds_register.get_update_statement_mogrified(dbif=dbif)
  820. if connected:
  821. dbif.close
  822. return statement
  823. ###############################################################################
  824. if __name__ == "__main__":
  825. import doctest
  826. doctest.testmod()