abstract_map_dataset.py 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920
  1. # -*- coding: utf-8 -*-
  2. """!@package grass.temporal
  3. @brief GRASS Python scripting module (temporal GIS functions)
  4. Temporal GIS related functions to be used in temporal GIS Python library package.
  5. Usage:
  6. >>> import grass.temporal as tgis
  7. >>> tmr = TemporalMapRelations()
  8. >>> amd = AbstractMapDataset()
  9. (C) 2008-2011 by the GRASS Development Team
  10. This program is free software under the GNU General Public
  11. License (>=v2). Read the file COPYING that comes with GRASS
  12. for details.
  13. @author Soeren Gebbert
  14. """
  15. from abstract_dataset import *
  16. from datetime_math import *
  17. class TemporalMapRelations(AbstractDataset):
  18. """!This class implements a temporal topology access structure
  19. This object will be set up by temporal topology creation methods.
  20. If correctly initialize the calls next() and prev() let the user walk temporally forward
  21. and backward in time.
  22. The following temporal relations with access methods are supported:
  23. * equal
  24. * follows
  25. * precedes
  26. * overlaps
  27. * overlapped
  28. * during (including starts, finishes)
  29. * contains (including started, finished)
  30. @code:
  31. # We have build the temporal topology and we know the first map
  32. start = first
  33. while start:
  34. # Print all maps this map temporally contains
  35. dlist = start.get_contains()
  36. for map in dlist:
  37. map.print_info()
  38. start = start.next()
  39. @endcode
  40. Usage:
  41. >>> import grass.temporal as tgis
  42. >>> tmr = TemporalMapRelations()
  43. >>> tmr.print_temporal_topology_info()
  44. +-------------------- Temporal Topology -------------------------------------+
  45. >>> tmr.print_temporal_topology_shell_info()
  46. """
  47. def __init__(self):
  48. self.reset_temporal_topology()
  49. def reset_temporal_topology(self):
  50. """!Reset any information about temporal topology"""
  51. self._temporal_topology = {}
  52. self._has_temporal_topology = False
  53. def set_temporal_topology_build_true(self):
  54. """!Same as name"""
  55. self._has_temporal_topology = True
  56. def set_temporal_topology_build_false(self):
  57. """!Same as name"""
  58. self._has_temporal_topology = False
  59. def is_temporal_topology_build(self):
  60. """!Check if the temporal topology was build"""
  61. return self._has_temporal_topology
  62. def set_temporal_next(self, map_):
  63. """!Set the map that is temporally as closest located after this map.
  64. Temporally located means that the start time of the "next" map is
  65. temporally located AFTER the start time of this map, but temporally
  66. near than other maps of the same dataset.
  67. @param map_: This object should be of type AbstractMapDataset or derived classes
  68. """
  69. self._temporal_topology["NEXT"] = map_
  70. def set_temporal_prev(self, map_):
  71. """!Set the map that is temporally as closest located before this map.
  72. Temporally located means that the start time of the "previous" map is
  73. temporally located BEFORE the start time of this map, but temporally
  74. near than other maps of the same dataset.
  75. @param map_: This object should be of type AbstractMapDataset or derived classes
  76. """
  77. self._temporal_topology["PREV"] = map_
  78. def temporal_next(self):
  79. """!Return the map with a start time temporally located after
  80. the start time of this map, but temporal closer than other maps
  81. @return A map object or None
  82. """
  83. if "NEXT" not in self._temporal_topology:
  84. return None
  85. return self._temporal_topology["NEXT"]
  86. def temporal_prev(self):
  87. """!Return the map with a start time temporally located before
  88. the start time of this map, but temporal closer than other maps
  89. @return A map object or None
  90. """
  91. if "PREV" not in self._temporal_topology:
  92. return None
  93. return self._temporal_topology["PREV"]
  94. def append_temporal_equivalent(self, map_):
  95. """!Append a map with equivalent temporal extent as this map
  96. @param map_: This object should be of type AbstractMapDataset or derived classes
  97. """
  98. if "EQUAL" not in self._temporal_topology:
  99. self._temporal_topology["EQUAL"] = []
  100. self._temporal_topology["EQUAL"].append(map_)
  101. def get_temporal_equivalent(self):
  102. """!Return a list of map objects with equivalent temporal extent as this map
  103. @return A list of map objects or None
  104. """
  105. if "EQUAL" not in self._temporal_topology:
  106. return None
  107. return self._temporal_topology["EQUAL"]
  108. def append_temporal_overlaps(self, map_):
  109. """!Append a map that this map temporally overlaps
  110. @param map_: This object should be of type AbstractMapDataset or derived classes
  111. """
  112. if "OVERLAPS" not in self._temporal_topology:
  113. self._temporal_topology["OVERLAPS"] = []
  114. self._temporal_topology["OVERLAPS"].append(map_)
  115. def get_temporal_overlaps(self):
  116. """!Return a list of map objects that this map temporally overlaps
  117. @return A list of map objects or None
  118. """
  119. if "OVERLAPS" not in self._temporal_topology:
  120. return None
  121. return self._temporal_topology["OVERLAPS"]
  122. def append_temporal_overlapped(self, map_):
  123. """!Append a map that this map temporally overlapped
  124. @param map_: This object should be of type AbstractMapDataset or derived classes
  125. """
  126. if "OVERLAPPED" not in self._temporal_topology:
  127. self._temporal_topology["OVERLAPPED"] = []
  128. self._temporal_topology["OVERLAPPED"].append(map_)
  129. def get_temporal_overlapped(self):
  130. """!Return a list of map objects that this map temporally overlapped
  131. @return A list of map objects or None
  132. """
  133. if "OVERLAPPED" not in self._temporal_topology:
  134. return None
  135. return self._temporal_topology["OVERLAPPED"]
  136. def append_temporal_follows(self, map_):
  137. """!Append a map that this map temporally follows
  138. @param map_: This object should be of type AbstractMapDataset or derived classes
  139. """
  140. if "FOLLOWS" not in self._temporal_topology:
  141. self._temporal_topology["FOLLOWS"] = []
  142. self._temporal_topology["FOLLOWS"].append(map_)
  143. def get_temporal_follows(self):
  144. """!Return a list of map objects that this map temporally follows
  145. @return A list of map objects or None
  146. """
  147. if "FOLLOWS" not in self._temporal_topology:
  148. return None
  149. return self._temporal_topology["FOLLOWS"]
  150. def append_temporal_precedes(self, map_):
  151. """!Append a map that this map temporally precedes
  152. @param map_: This object should be of type AbstractMapDataset or derived classes
  153. """
  154. if "PRECEDES" not in self._temporal_topology:
  155. self._temporal_topology["PRECEDES"] = []
  156. self._temporal_topology["PRECEDES"].append(map_)
  157. def get_temporal_precedes(self):
  158. """!Return a list of map objects that this map temporally precedes
  159. @return A list of map objects or None
  160. """
  161. if "PRECEDES" not in self._temporal_topology:
  162. return None
  163. return self._temporal_topology["PRECEDES"]
  164. def append_temporal_during(self, map_):
  165. """!Append a map that this map is temporally located during
  166. This includes temporal relationships starts and finishes
  167. @param map_: This object should be of type AbstractMapDataset or derived classes
  168. """
  169. if "DURING" not in self._temporal_topology:
  170. self._temporal_topology["DURING"] = []
  171. self._temporal_topology["DURING"].append(map_)
  172. def get_temporal_during(self):
  173. """!Return a list of map objects that this map is temporally located during
  174. This includes temporally relationships starts and finishes
  175. @return A list of map objects or None
  176. """
  177. if "DURING" not in self._temporal_topology:
  178. return None
  179. return self._temporal_topology["DURING"]
  180. def append_temporal_contains(self, map_):
  181. """!Append a map that this map temporally contains
  182. This includes temporal relationships started and finished
  183. @param map_: This object should be of type AbstractMapDataset or derived classes
  184. """
  185. if "CONTAINS" not in self._temporal_topology:
  186. self._temporal_topology["CONTAINS"] = []
  187. self._temporal_topology["CONTAINS"].append(map_)
  188. def get_temporal_contains(self):
  189. """!Return a list of map objects that this map temporally contains
  190. This includes temporal relationships started and finished
  191. @return A list of map objects or None
  192. """
  193. if "CONTAINS" not in self._temporal_topology:
  194. return None
  195. return self._temporal_topology["CONTAINS"]
  196. def _generate_map_list_string(self, map_list, line_wrap=True):
  197. count = 0
  198. string = ""
  199. for map_ in map_list:
  200. if line_wrap and count > 0 and count % 3 == 0:
  201. string += "\n | ............................ "
  202. count = 0
  203. if count == 0:
  204. string += map_.get_id()
  205. else:
  206. string += ",%s" % map_.get_id()
  207. count += 1
  208. return string
  209. # Set the properties
  210. temporal_equivalent = property(fget=get_temporal_equivalent,
  211. fset=append_temporal_equivalent)
  212. temporal_follows = property(fget=get_temporal_follows,
  213. fset=append_temporal_follows)
  214. temporal_precedes = property(fget=get_temporal_precedes,
  215. fset=append_temporal_precedes)
  216. temporal_overlaps = property(fget=get_temporal_overlaps,
  217. fset=append_temporal_overlaps)
  218. temporal_overlapped = property(fget=get_temporal_overlapped,
  219. fset=append_temporal_overlapped)
  220. temporal_during = property(fget=get_temporal_during,
  221. fset=append_temporal_during)
  222. temporal_contains = property(fget=get_temporal_contains,
  223. fset=append_temporal_contains)
  224. def print_temporal_topology_info(self):
  225. """!Print information about this class in human readable style"""
  226. _next = self.temporal_next()
  227. _prev = self.temporal_prev()
  228. _equal = self.get_temporal_equivalent()
  229. _follows = self.get_temporal_follows()
  230. _precedes = self.get_temporal_precedes()
  231. _overlaps = self.get_temporal_overlaps()
  232. _overlapped = self.get_temporal_overlapped()
  233. _during = self.get_temporal_during()
  234. _contains = self.get_temporal_contains()
  235. print " +-------------------- Temporal Topology -------------------------------------+"
  236. # 0123456789012345678901234567890
  237. if _next is not None:
  238. print " | Next: ...................... " + str(_next.get_id())
  239. if _prev is not None:
  240. print " | Previous: .................. " + str(_prev.get_id())
  241. if _equal is not None:
  242. print " | Equivalent: ................ " + \
  243. self._generate_map_list_string(_equal)
  244. if _follows is not None:
  245. print " | Follows: ................... " + \
  246. self._generate_map_list_string(_follows)
  247. if _precedes is not None:
  248. print " | Precedes: .................. " + \
  249. self._generate_map_list_string(_precedes)
  250. if _overlaps is not None:
  251. print " | Overlaps: .................. " + \
  252. self._generate_map_list_string(_overlaps)
  253. if _overlapped is not None:
  254. print " | Overlapped: ................ " + \
  255. self._generate_map_list_string(_overlapped)
  256. if _during is not None:
  257. print " | During: .................... " + \
  258. self._generate_map_list_string(_during)
  259. if _contains is not None:
  260. print " | Contains: .................. " + \
  261. self._generate_map_list_string(_contains)
  262. def print_temporal_topology_shell_info(self):
  263. """!Print information about this class in shell style"""
  264. _next = self.temporal_next()
  265. _prev = self.temporal_prev()
  266. _equal = self.get_temporal_equivalent()
  267. _follows = self.get_temporal_follows()
  268. _precedes = self.get_temporal_precedes()
  269. _overlaps = self.get_temporal_overlaps()
  270. _overlapped = self.get_temporal_overlapped()
  271. _during = self.get_temporal_during()
  272. _contains = self.get_temporal_contains()
  273. if _next is not None:
  274. print "next=" + _next.get_id()
  275. if _prev is not None:
  276. print "prev=" + _prev.get_id()
  277. if _equal is not None:
  278. print "equivalent=" + self._generate_map_list_string(_equal, False)
  279. if _follows is not None:
  280. print "follows=" + self._generate_map_list_string(_follows, False)
  281. if _precedes is not None:
  282. print "precedes=" + self._generate_map_list_string(
  283. _precedes, False)
  284. if _overlaps is not None:
  285. print "overlaps=" + self._generate_map_list_string(
  286. _overlaps, False)
  287. if _overlapped is not None:
  288. print "overlapped=" + \
  289. self._generate_map_list_string(_overlapped, False)
  290. if _during is not None:
  291. print "during=" + self._generate_map_list_string(_during, False)
  292. if _contains is not None:
  293. print "contains=" + self._generate_map_list_string(
  294. _contains, False)
  295. ###############################################################################
  296. class AbstractMapDataset(TemporalMapRelations):
  297. """!This is the base class for all maps (raster, vector, raster3d)
  298. providing additional function to set the valid time and the spatial extent.
  299. """
  300. def __init__(self):
  301. TemporalMapRelations.__init__(self)
  302. def get_new_stds_instance(self, ident):
  303. """!Return a new space time dataset instance in which maps
  304. are stored with the type of this class
  305. @param ident: The identifier of the dataset
  306. """
  307. raise ImplementationError(
  308. "This method must be implemented in the subclasses")
  309. def get_stds_register(self):
  310. """!Return the space time dataset register table name in which stds
  311. are listed in which this map is registered"""
  312. raise ImplementationError(
  313. "This method must be implemented in the subclasses")
  314. def set_stds_register(self, name):
  315. """!Set the space time dataset register table name.
  316. This table stores all space time datasets in which this map is registered.
  317. @param ident: The name of the register table
  318. """
  319. raise ImplementationError(
  320. "This method must be implemented in the subclasses")
  321. def check_resolution_with_current_region(self):
  322. """!Check if the raster or voxel resolution is finer than the current resolution
  323. Return "finer" in case the raster/voxel resolution is finer than the current region
  324. Return "coarser" in case the raster/voxel resolution is coarser than the current region
  325. Vector maps are alwyas finer than the current region
  326. """
  327. raise ImplementationError(
  328. "This method must be implemented in the subclasses")
  329. def has_grass_timestamp(self):
  330. """!Check if a grass file bsased time stamp exists for this map.
  331. """
  332. raise ImplementationError(
  333. "This method must be implemented in the subclasses")
  334. def write_timestamp_to_grass(self):
  335. """!Write the timestamp of this map into the map metadata in the grass file system based spatial
  336. database.
  337. """
  338. raise ImplementationError(
  339. "This method must be implemented in the subclasses")
  340. def remove_timestamp_from_grass(self):
  341. """!Remove the timestamp from the grass file system based spatial database
  342. """
  343. raise ImplementationError(
  344. "This method must be implemented in the subclasses")
  345. def map_exists(self):
  346. """!Return True in case the map exists in the grass spatial database
  347. @return True if map exists, False otherwise
  348. """
  349. raise ImplementationError(
  350. "This method must be implemented in the subclasses")
  351. def read_info(self):
  352. """!Read the map info from the grass file system based database and store the content
  353. into a dictionary
  354. """
  355. raise ImplementationError(
  356. "This method must be implemented in the subclasses")
  357. def load(self):
  358. """!Load the content of this object from the grass file system based database"""
  359. raise ImplementationError(
  360. "This method must be implemented in the subclasses")
  361. def _convert_timestamp(self):
  362. """!Convert the valid time into a grass datetime library compatible timestamp string
  363. This methods works for reltaive and absolute time
  364. @return the grass timestamp string
  365. """
  366. start = ""
  367. if self.is_time_absolute():
  368. start_time, end_time, tz = self.get_absolute_time()
  369. start = datetime_to_grass_datetime_string(start_time)
  370. if end_time is not None:
  371. end = datetime_to_grass_datetime_string(end_time)
  372. start += " / %s" % (end)
  373. else:
  374. start_time, end_time, unit = self.get_relative_time()
  375. start = "%i %s" % (int(start_time), unit)
  376. if end_time is not None:
  377. end = "%i %s" % (int(end_time), unit)
  378. start += " / %s" % (end)
  379. return start
  380. def get_map_id(self):
  381. """!Return the map id. The map id is the unique map identifier
  382. in grass and must not be equal to the
  383. primary key identifier (id) of the map in the database.
  384. Since vector maps may have layer information,
  385. the unique id is a combination of name, layer and mapset.
  386. Use get_map_id() every time your need to access the grass map
  387. in the file system but not to identify
  388. map information in the temporal database.
  389. """
  390. return self.base.get_map_id()
  391. def build_id(self, name, mapset, layer=None):
  392. """!Convenient method to build the unique identifier
  393. Existing layer and mapset definitions in the name string will be reused
  394. @param return the id of the vector map as name(:layer)@mapset while layer is optional
  395. """
  396. # Check if the name includes any mapset
  397. if name.find("@") >= 0:
  398. name, mapset = name.split("@")
  399. # Check for layer number in map name
  400. if name.find(":") >= 0:
  401. name, layer = name.split(":")
  402. if layer is not None:
  403. return "%s:%s@%s" % (name, layer, mapset)
  404. else:
  405. return "%s@%s" % (name, mapset)
  406. def get_layer(self):
  407. """!Return the layer of the map or None in case no layer is defined"""
  408. return self.base.get_layer()
  409. def print_info(self):
  410. """!Print information about this class in human readable style"""
  411. if self.get_type() == "raster":
  412. # 1 2 3 4 5 6 7
  413. # 0123456789012345678901234567890123456789012345678901234567890123456789012345678
  414. print ""
  415. print " +-------------------- Raster Dataset ----------------------------------------+"
  416. if self.get_type() == "raster3d":
  417. # 1 2 3 4 5 6 7
  418. # 0123456789012345678901234567890123456789012345678901234567890123456789012345678
  419. print ""
  420. print " +-------------------- Raster3d Dataset --------------------------------------+"
  421. if self.get_type() == "vector":
  422. # 1 2 3 4 5 6 7
  423. # 0123456789012345678901234567890123456789012345678901234567890123456789012345678
  424. print ""
  425. print " +-------------------- Vector Dataset ----------------------------------------+"
  426. print " | |"
  427. self.base.print_info()
  428. if self.is_time_absolute():
  429. self.absolute_time.print_info()
  430. if self.is_time_relative():
  431. self.relative_time.print_info()
  432. self.spatial_extent.print_info()
  433. self.metadata.print_info()
  434. datasets = self.get_registered_datasets()
  435. count = 0
  436. string = ""
  437. if datasets is not None:
  438. for ds in datasets:
  439. if count > 0 and count % 3 == 0:
  440. string += "\n | ............................ "
  441. count = 0
  442. if count == 0:
  443. string += ds["id"]
  444. else:
  445. string += ",%s" % ds["id"]
  446. count += 1
  447. print " | Registered datasets ........ " + string
  448. if self.is_temporal_topology_build():
  449. self.print_temporal_topology_info()
  450. print " +----------------------------------------------------------------------------+"
  451. def print_shell_info(self):
  452. """!Print information about this class in shell style"""
  453. self.base.print_shell_info()
  454. if self.is_time_absolute():
  455. self.absolute_time.print_shell_info()
  456. if self.is_time_relative():
  457. self.relative_time.print_shell_info()
  458. self.spatial_extent.print_shell_info()
  459. self.metadata.print_shell_info()
  460. datasets = self.get_registered_datasets()
  461. count = 0
  462. string = ""
  463. if datasets is not None:
  464. for ds in datasets:
  465. if count == 0:
  466. string += ds["id"]
  467. else:
  468. string += ",%s" % ds["id"]
  469. count += 1
  470. print "registered_datasets=" + string
  471. if self.is_temporal_topology_build():
  472. self.print_temporal_topology_shell_info()
  473. def insert(self, dbif=None, execute=True):
  474. """!Insert temporal dataset entry into database from the internal structure
  475. This functions assures that the timetsamp is written to the
  476. grass file system based database
  477. @param dbif: The database interface to be used
  478. @param execute: If True the SQL statements will be executed.
  479. If False the prepared SQL statements are
  480. returned and must be executed by the caller.
  481. """
  482. self.write_timestamp_to_grass()
  483. return AbstractDataset.insert(self, dbif, execute)
  484. def update(self, dbif=None, execute=True):
  485. """!Update temporal dataset entry of database from the internal structure
  486. excluding None variables
  487. This functions assures that the timetsamp is written to the
  488. grass file system based database
  489. @param dbif: The database interface to be used
  490. @param execute: If True the SQL statements will be executed.
  491. If False the prepared SQL statements are
  492. returned and must be executed by the caller.
  493. """
  494. self.write_timestamp_to_grass()
  495. return AbstractDataset.update(self, dbif, execute)
  496. def update_all(self, dbif=None, execute=True):
  497. """!Update temporal dataset entry of database from the internal structure
  498. and include None varuables.
  499. This functions assures that the timetsamp is written to the
  500. grass file system based database
  501. @param dbif: The database interface to be used
  502. @param execute: If True the SQL statements will be executed.
  503. If False the prepared SQL statements are
  504. returned and must be executed by the caller.
  505. """
  506. self.write_timestamp_to_grass()
  507. return AbstractDataset.update_all(self, dbif, execute)
  508. def set_absolute_time(self, start_time, end_time=None, timezone=None):
  509. """!Set the absolute time interval with start time and end time
  510. @param start_time: a datetime object specifying the start time of the map
  511. @param end_time: a datetime object specifying the end time of the map
  512. @param timezone: Thee timezone of the map
  513. """
  514. if start_time and not isinstance(start_time, datetime):
  515. if self.get_layer() is not None:
  516. core.fatal(_("Start time must be of type datetime for %s map <%s> with layer: %s") % (self.get_type(), self.get_map_id(), self.get_layer()))
  517. else:
  518. core.fatal(_("Start time must be of type datetime for %s map <%s>") % (self.get_type(), self.get_map_id()))
  519. if end_time and not isinstance(end_time, datetime):
  520. if self.get_layer():
  521. core.fatal(_("End time must be of type datetime for %s map <%s> with layer: %s") % (self.get_type(), self.get_map_id(), self.get_layer()))
  522. else:
  523. core.fatal(_("End time must be of type datetime for %s map <%s>") % (self.get_type(), self.get_map_id()))
  524. if start_time is not None and end_time is not None:
  525. if start_time > end_time:
  526. if self.get_layer():
  527. core.fatal(_("End time must be greater than start time for %s map <%s> with layer: %s") % (self.get_type(), self.get_map_id(), self.get_layer()))
  528. else:
  529. core.fatal(_("End time must be greater than start time for %s map <%s>") % (self.get_type(), self.get_map_id()))
  530. else:
  531. # Do not create an interval in case start and end time are equal
  532. if start_time == end_time:
  533. end_time = None
  534. self.base.set_ttype("absolute")
  535. self.absolute_time.set_start_time(start_time)
  536. self.absolute_time.set_end_time(end_time)
  537. self.absolute_time.set_timezone(timezone)
  538. def update_absolute_time(self, start_time, end_time=None, timezone=None, dbif=None):
  539. """!Update the absolute time
  540. This functions assures that the timetsamp is written to the
  541. grass file system based database
  542. @param start_time: a datetime object specifying the start time of the map
  543. @param end_time: a datetime object specifying the end time of the map
  544. @param timezone: Thee timezone of the map
  545. """
  546. dbif, connect = init_dbif(dbif)
  547. self.set_absolute_time(start_time, end_time, timezone)
  548. self.absolute_time.update_all(dbif)
  549. self.base.update(dbif)
  550. if connect:
  551. dbif.close()
  552. self.write_timestamp_to_grass()
  553. def set_relative_time(self, start_time, end_time, unit):
  554. """!Set the relative time interval
  555. @param start_time: A double value
  556. @param end_time: A double value
  557. @param unit: The unit of the relative time. Supported units:
  558. years, months, days, hours, minutes, seconds
  559. Return True for success and False otherwise
  560. """
  561. if not self.check_relative_time_unit(unit):
  562. if self.get_layer() is not None:
  563. core.error(_("Unsupported relative time unit type for %s map <%s> with layer %s: %s") % (self.get_type(), self.get_id(), self.get_layer(), unit))
  564. else:
  565. core.error(_("Unsupported relative time unit type for %s map <%s>: %s") % (self.get_type(), self.get_id(), unit))
  566. return False
  567. if start_time is not None and end_time is not None:
  568. if int(start_time) > int(end_time):
  569. if self.get_layer() is not None:
  570. core.error(_("End time must be greater than start time for %s map <%s> with layer %s") % (self.get_type(), self.get_id(), self.get_layer()))
  571. else:
  572. core.error(_("End time must be greater than start time for %s map <%s>") % (self.get_type(), self.get_id()))
  573. return False
  574. else:
  575. # Do not create an interval in case start and end time are equal
  576. if start_time == end_time:
  577. end_time = None
  578. self.base.set_ttype("relative")
  579. self.relative_time.set_unit(unit)
  580. self.relative_time.set_start_time(int(start_time))
  581. if end_time is not None:
  582. self.relative_time.set_end_time(int(end_time))
  583. else:
  584. self.relative_time.set_end_time(None)
  585. return True
  586. def update_relative_time(self, start_time, end_time, unit, dbif=None):
  587. """!Update the relative time interval
  588. This functions assures that the timetsamp is written to the
  589. grass file system based database
  590. @param start_time: A double value
  591. @param end_time: A double value
  592. @param dbif: The database interface to be used
  593. """
  594. dbif, connect = init_dbif(dbif)
  595. if self.set_relative_time(start_time, end_time, unit):
  596. self.relative_time.update_all(dbif)
  597. self.base.update(dbif)
  598. if connect:
  599. dbif.close()
  600. self.write_timestamp_to_grass()
  601. def set_spatial_extent(self, north, south, east, west, top=0, bottom=0):
  602. """!Set the spatial extent of the map
  603. @param north: The northern edge
  604. @param south: The southern edge
  605. @param east: The eastern edge
  606. @param west: The western edge
  607. @param top: The top edge
  608. @param bottom: The bottom edge
  609. """
  610. self.spatial_extent.set_spatial_extent(
  611. north, south, east, west, top, bottom)
  612. def check_valid_time(self):
  613. """!Check for correct valid time"""
  614. if self.is_time_absolute():
  615. start, end, tz = self.get_absolute_time()
  616. else:
  617. start, end, unit = self.get_relative_time()
  618. if start is not None:
  619. if end is not None:
  620. if start >= end:
  621. if self.get_layer() is not None:
  622. core.error(_("Map <%s> with layer %s has incorrect time interval, start time is greater than end time") % (self.get_map_id(), self.get_layer()))
  623. else:
  624. core.error(_("Map <%s> has incorrect time interval, start time is greater than end time") % (self.get_map_id()))
  625. return False
  626. else:
  627. core.error(_("Map <%s> has incorrect start time") %
  628. (self.get_map_id()))
  629. return False
  630. return True
  631. def delete(self, dbif=None, update=True, execute=True):
  632. """!Delete a map entry from database if it exists
  633. Remove dependent entries:
  634. * Remove the map entry in each space time dataset in which this map is registered
  635. * Remove the space time dataset register table
  636. @param dbif: The database interface to be used
  637. @param update: Call for each unregister statement the update from
  638. registered maps of the space time dataset.
  639. This can slow down the un-registration process significantly.
  640. @param execute: If True the SQL DELETE and DROP table statements will be executed.
  641. If False the prepared SQL statements are
  642. returned and must be executed by the caller.
  643. @return The SQL statements if execute == False, else an empty string,
  644. None in case of a failure
  645. """
  646. dbif, connect = init_dbif(dbif)
  647. statement = ""
  648. if self.is_in_db(dbif):
  649. # SELECT all needed information from the database
  650. self.metadata.select(dbif)
  651. # First we unregister from all dependent space time datasets
  652. statement += self.unregister(
  653. dbif=dbif, update=update, execute=False)
  654. # Remove the strds register table
  655. if self.get_stds_register() is not None:
  656. statement += "DROP TABLE " + self.get_stds_register() + ";\n"
  657. core.verbose(_("Delete %s dataset <%s> from temporal database")
  658. % (self.get_type(), self.get_id()))
  659. # Delete yourself from the database, trigger functions will take care of dependencies
  660. statement += self.base.get_delete_statement()
  661. if execute:
  662. dbif.execute_transaction(statement)
  663. # Remove the timestamp from the file system
  664. self.remove_timestamp_from_grass()
  665. self.reset(None)
  666. if connect:
  667. dbif.close()
  668. if execute:
  669. return ""
  670. return statement
  671. def unregister(self, dbif=None, update=True, execute=True):
  672. """! Remove the map entry in each space time dataset in which this map is registered
  673. @param dbif: The database interface to be used
  674. @param update: Call for each unregister statement the update from registered maps
  675. of the space time dataset. This can slow down the
  676. un-registration process significantly.
  677. @param execute: If True the SQL DELETE and DROP table statements will be executed.
  678. If False the prepared SQL statements are
  679. returned and must be executed by the caller.
  680. @return The SQL statements if execute == False, else an empty string
  681. """
  682. if self.get_layer() is not None:
  683. core.verbose(_("Unregister %s map <%s> with layer %s from space time datasets") %
  684. (self.get_type(), self.get_map_id(), self.get_layer()))
  685. else:
  686. core.verbose(_("Unregister %s map <%s> from space time datasets")
  687. % (self.get_type(), self.get_map_id()))
  688. statement = ""
  689. dbif, connect = init_dbif(dbif)
  690. # Get all datasets in which this map is registered
  691. rows = self.get_registered_datasets(dbif)
  692. # For each stds in which the map is registered
  693. if rows is not None:
  694. count = 0
  695. num_sps = len(rows)
  696. for row in rows:
  697. core.percent(count, num_sps, 1)
  698. count += 1
  699. # Create a space time dataset object to remove the map
  700. # from its register
  701. stds = self.get_new_stds_instance(row["id"])
  702. stds.metadata.select(dbif)
  703. statement += stds.unregister_map(self, dbif, False)
  704. # Take care to update the space time dataset after
  705. # the map has been unregistered
  706. if update == True and execute == True:
  707. stds.update_from_registered_maps(dbif)
  708. core.percent(1, 1, 1)
  709. if execute:
  710. dbif.execute_transaction(statement)
  711. if connect:
  712. dbif.close()
  713. if execute:
  714. return ""
  715. return statement
  716. def get_registered_datasets(self, dbif=None):
  717. """!Return all space time dataset ids in which this map is registered as
  718. dictionary like rows with column "id" or None if this map is not
  719. registered in any space time dataset.
  720. @param dbif: The database interface to be used
  721. """
  722. dbif, connect = init_dbif(dbif)
  723. rows = None
  724. try:
  725. if self.get_stds_register() is not None:
  726. # Select all stds tables in which this map is registered
  727. sql = "SELECT id FROM " + self.get_stds_register()
  728. dbif.cursor.execute(sql)
  729. rows = dbif.cursor.fetchall()
  730. except:
  731. core.error(_("Unable to select space time dataset register table <%s>") % (self.get_stds_register()))
  732. if connect:
  733. dbif.close()
  734. return rows
  735. ###############################################################################
  736. if __name__ == "__main__":
  737. import doctest
  738. doctest.testmod()