abstract_map_dataset.py 35 KB

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