abstract_map_dataset.py 38 KB

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