abstract_map_dataset.py 42 KB

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