abstract_dataset.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636
  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. >>> ad = AbstractDataset()
  9. >>> ad.reset(ident="soil@PERMANENT")
  10. Traceback (most recent call last):
  11. File "/usr/lib/python2.7/doctest.py", line 1289, in __run
  12. compileflags, 1) in test.globs
  13. File "<doctest __main__[2]>", line 1, in <module>
  14. ad.reset(ident="soil@PERMANENT")
  15. File "AbstractDataset.py", line 53, in reset
  16. raise ImplementationError("This method must be implemented in the subclasses")
  17. ImplementationError: 'This method must be implemented in the subclasses'
  18. @endcode
  19. (C) 2011-2012 by the GRASS Development Team
  20. This program is free software under the GNU General Public
  21. License (>=v2). Read the file COPYING that comes with GRASS
  22. for details.
  23. @author Soeren Gebbert
  24. """
  25. import uuid
  26. import copy
  27. from temporal_extent import *
  28. from spatial_extent import *
  29. from metadata import *
  30. from temporal_topology_dataset_connector import *
  31. from spatial_topology_dataset_connector import *
  32. class ImplementationError(Exception):
  33. """!Exception raised for the calling of methods that should be implemented in
  34. sub classes.
  35. """
  36. def __init__(self, msg):
  37. self.msg = msg
  38. def __str__(self):
  39. return repr(self.msg)
  40. ###############################################################################
  41. class AbstractDataset(SpatialTopologyDatasetConnector, TemporalTopologyDatasetConnector):
  42. """!This is the base class for all datasets
  43. (raster, vector, raster3d, strds, stvds, str3ds)"""
  44. def __init__(self):
  45. SpatialTopologyDatasetConnector.__init__(self)
  46. TemporalTopologyDatasetConnector.__init__(self)
  47. def reset_topology(self):
  48. """!Reset any information about temporal topology"""
  49. self.reset_spatial_topology()
  50. self.reset_temporal_topology()
  51. def get_number_of_relations(self):
  52. """! Return a dictionary in which the keys are the relation names and the value
  53. are the number of relations.
  54. The following relations are available:
  55. Spatial relations
  56. - equivalent
  57. - overlap
  58. - in
  59. - contain
  60. - meet
  61. - cover
  62. - covered
  63. Temporal relations
  64. - equal
  65. - follows
  66. - precedes
  67. - overlaps
  68. - overlapped
  69. - during (including starts, finishes)
  70. - contains (including started, finished)
  71. - starts
  72. - started
  73. - finishes
  74. - finished
  75. To access topological information the spatial, temporal or booth topologies must be build first
  76. using the SpatioTemporalTopologyBuilder.
  77. @return the dictionary with relations as keys and number as values or None in case the topology wasn't build
  78. """
  79. if self.is_temporal_topology_build() and not self.is_spatial_topology_build():
  80. return self.get_number_of_temporal_relations()
  81. elif self.is_spatial_topology_build() and not self.is_temporal_topology_build():
  82. self.get_number_of_spatial_relations()
  83. else:
  84. return self.get_number_of_temporal_relations() + \
  85. self.get_number_of_spatial_relations()
  86. return None
  87. def set_topology_build_true(self):
  88. """!Use this method when the spatio-temporal topology was build"""
  89. self.set_spatial_topology_build_true()
  90. self.set_temporal_topology_build_true()
  91. def set_topology_build_false(self):
  92. """!Use this method when the spatio-temporal topology was not build"""
  93. self.set_spatial_topology_build_false()
  94. self.set_temporal_topology_build_false()
  95. def is_topology_build(self):
  96. """!Check if the spatial and temporal topology was build
  97. @return A dictionary with "spatial" and "temporal" as keys that have boolen values
  98. """
  99. d = {}
  100. d["spatial"] = self.is_spatial_topology_build()
  101. d["temporal"] = self.is_temporal_topology_build()
  102. return d
  103. def print_topology_info(self):
  104. if self.is_temporal_topology_build():
  105. self.print_temporal_topology_info()
  106. if self.is_spatial_topology_build():
  107. self.print_spatial_topology_info()
  108. def print_topology_shell_info(self):
  109. if self.is_temporal_topology_build():
  110. self.print_temporal_topology_shell_info()
  111. if self.is_spatial_topology_build():
  112. self.print_spatial_topology_shell_info()
  113. def reset(self, ident):
  114. """!Reset the internal structure and set the identifier
  115. @param ident The identifier of the dataset that "name@mapset" or in case of vector maps "name:layer@mapset"
  116. """
  117. raise ImplementationError("This method must be implemented in the subclasses")
  118. def get_type(self):
  119. """!Return the type of this class as string
  120. The type can be "vect", "rast", "rast3d", "stvds", "strds" or "str3ds"
  121. @return "vect", "rast", "rast3d", "stvds", "strds" or "str3ds"
  122. """
  123. raise ImplementationError("This method must be implemented in the subclasses")
  124. def get_new_instance(self, ident):
  125. """!Return a new instance with the type of this class
  126. @param ident The identifier of the new dataset instance
  127. @return A new instance with the type of this object
  128. """
  129. raise ImplementationError("This method must be implemented in the subclasses")
  130. def spatial_overlapping(self, dataset):
  131. """!Return True if the spatial extents overlap
  132. @param dataset The abstract dataset to check spatial overlapping
  133. @return True if self and the provided dataset spatial overlap
  134. """
  135. raise ImplementationError("This method must be implemented in the subclasses")
  136. def spatial_intersection(self, dataset):
  137. """!Return the spatial intersection as spatial_extent
  138. object or None in case no intersection was found.
  139. @param dataset The abstract dataset to intersect with
  140. @return The intersection spatial extent
  141. """
  142. raise ImplementationError("This method must be implemented in the subclasses")
  143. def spatial_union(self, dataset):
  144. """!Return the spatial union as spatial_extent
  145. object or None in case the extents does not overlap or meet.
  146. @param dataset The abstract dataset to create a union with
  147. @return The union spatial extent
  148. """
  149. raise ImplementationError("This method must be implemented in the subclasses")
  150. def spatial_disjoint_union(self, dataset):
  151. """!Return the spatial union as spatial_extent object.
  152. @param dataset The abstract dataset to create a union with
  153. @return The union spatial extent
  154. """
  155. raise ImplementationError("This method must be implemented in the subclasses")
  156. def spatial_relation(self, dataset):
  157. """!Return the spatial relationship between self and dataset
  158. @param dataset The abstract dataset to compute the spatial relation with self
  159. @return The spatial relationship as string
  160. """
  161. raise ImplementationError("This method must be implemented in the subclasses")
  162. def print_info(self):
  163. """!Print information about this class in human readable style"""
  164. raise ImplementationError("This method must be implemented in the subclasses")
  165. def print_shell_info(self):
  166. """!Print information about this class in shell style"""
  167. raise ImplementationError("This method must be implemented in the subclasses")
  168. def print_self(self):
  169. """!Print the content of the internal structure to stdout"""
  170. raise ImplementationError("This method must be implemented in the subclasses")
  171. def set_id(self, ident):
  172. self.base.set_id(ident)
  173. self.temporal_extent.set_id(ident)
  174. self.spatial_extent.set_id(ident)
  175. self.metadata.set_id(ident)
  176. def get_id(self):
  177. """!Return the unique identifier of the dataset
  178. @return The id of the dataset "name(:layer)@mapset" as string
  179. """
  180. return self.base.get_id()
  181. def get_name(self):
  182. """!Return the name
  183. @return The name of the dataset as string
  184. """
  185. return self.base.get_name()
  186. def get_mapset(self):
  187. """!Return the mapset
  188. @return The mapset in which the dataset was created as string
  189. """
  190. return self.base.get_mapset()
  191. def get_temporal_extent_as_tuple(self):
  192. """!Returns a tuple of the valid start and end time
  193. Start and end time can be either of type datetime or of type integer,
  194. depending on the temporal type.
  195. @return A tuple of (start_time, end_time)
  196. """
  197. start = self.temporal_extent.get_start_time()
  198. end = self.temporal_extent.get_end_time()
  199. return (start, end)
  200. def get_absolute_time(self):
  201. """!Returns the start time, the end
  202. time and the timezone of the map as tuple
  203. @attention: The timezone is currently not used.
  204. The start time is of type datetime.
  205. The end time is of type datetime in case of interval time,
  206. or None on case of a time instance.
  207. @return A tuple of (start_time, end_time, timezone)
  208. """
  209. start = self.absolute_time.get_start_time()
  210. end = self.absolute_time.get_end_time()
  211. tz = self.absolute_time.get_timezone()
  212. return (start, end, tz)
  213. def get_relative_time(self):
  214. """!Returns the start time, the end
  215. time and the temporal unit of the dataset as tuple
  216. The start time is of type integer.
  217. The end time is of type integer in case of interval time,
  218. or None on case of a time instance.
  219. @return A tuple of (start_time, end_time, unit)
  220. """
  221. start = self.relative_time.get_start_time()
  222. end = self.relative_time.get_end_time()
  223. unit = self.relative_time.get_unit()
  224. return (start, end, unit)
  225. def get_relative_time_unit(self):
  226. """!Returns the relative time unit
  227. @return The relative time unit as string, None if not present
  228. """
  229. return self.relative_time.get_unit()
  230. def check_relative_time_unit(self, unit):
  231. """!Check if unit is of type year(s), month(s), day(s), hour(s),
  232. minute(s) or second(s)
  233. @param unit The unit string
  234. @return True if success, False otherwise
  235. """
  236. # Check unit
  237. units = ["year", "years", "month", "months", "day", "days", "hour",
  238. "hours", "minute", "minutes", "second", "seconds"]
  239. if unit not in units:
  240. return False
  241. return True
  242. def get_temporal_type(self):
  243. """!Return the temporal type of this dataset
  244. The temporal type can be absolute or relative
  245. @return The temporal type of the dataset as string
  246. """
  247. return self.base.get_ttype()
  248. def get_spatial_extent_as_tuple(self):
  249. """!Return the spatial extent as tuple
  250. Top and bottom are set to 0 in case of a two dimensional spatial extent.
  251. @return A the spatial extent as tuple (north, south, east, west, top, bottom)
  252. """
  253. return self.spatial_extent.get_spatial_extent_as_tuple()
  254. def select(self, dbif=None):
  255. """!Select temporal dataset entry from database and fill
  256. the internal structure
  257. The content of every dataset is stored in the temporal database.
  258. This method must be used to fill this object with the content
  259. from the temporal database.
  260. @param dbif The database interface to be used
  261. """
  262. dbif, connected = init_dbif(dbif)
  263. self.base.select(dbif)
  264. self.temporal_extent.select(dbif)
  265. self.spatial_extent.select(dbif)
  266. self.metadata.select(dbif)
  267. if connected:
  268. dbif.close()
  269. def is_in_db(self, dbif=None):
  270. """!Check if the dataset is registered in the database
  271. @param dbif The database interface to be used
  272. @return True if the dataset is registered in the database
  273. """
  274. return self.base.is_in_db(dbif)
  275. def delete(self):
  276. """!Delete dataset from database if it exists"""
  277. raise ImplementationError("This method must be implemented in the subclasses")
  278. def insert(self, dbif=None, execute=True):
  279. """!Insert dataset into database
  280. @param dbif The database interface to be used
  281. @param execute If True the SQL statements will be executed.
  282. If False the prepared SQL statements are returned
  283. and must be executed by the caller.
  284. @return The SQL insert statement in case execute=False, or an empty string otherwise
  285. """
  286. dbif, connected = init_dbif(dbif)
  287. # Build the INSERT SQL statement
  288. statement = self.base.get_insert_statement_mogrified(dbif)
  289. statement += self.temporal_extent.get_insert_statement_mogrified(dbif)
  290. statement += self.spatial_extent.get_insert_statement_mogrified(dbif)
  291. statement += self.metadata.get_insert_statement_mogrified(dbif)
  292. if execute:
  293. dbif.execute_transaction(statement)
  294. if connected:
  295. dbif.close()
  296. return ""
  297. if connected:
  298. dbif.close()
  299. return statement
  300. def update(self, dbif=None, execute=True, ident=None):
  301. """!Update the dataset entry in the database from the internal structure
  302. excluding None variables
  303. @param dbif The database interface to be used
  304. @param execute If True the SQL statements will be executed.
  305. If False the prepared SQL statements are returned
  306. and must be executed by the caller.
  307. @param ident The identifier to be updated, useful for renaming
  308. @return The SQL update statement in case execute=False, or an empty string otherwise
  309. """
  310. dbif, connected = init_dbif(dbif)
  311. # Build the UPDATE SQL statement
  312. statement = self.base.get_update_statement_mogrified(dbif, ident)
  313. statement += self.temporal_extent.get_update_statement_mogrified(dbif,
  314. ident)
  315. statement += self.spatial_extent.get_update_statement_mogrified(dbif,
  316. ident)
  317. statement += self.metadata.get_update_statement_mogrified(dbif, ident)
  318. if execute:
  319. dbif.execute_transaction(statement)
  320. if connected:
  321. dbif.close()
  322. return ""
  323. if connected:
  324. dbif.close()
  325. return statement
  326. def update_all(self, dbif=None, execute=True, ident=None):
  327. """!Update the dataset entry in the database from the internal structure
  328. and include None variables.
  329. @param dbif The database interface to be used
  330. @param execute If True the SQL statements will be executed.
  331. If False the prepared SQL statements are returned
  332. and must be executed by the caller.
  333. @param ident The identifier to be updated, useful for renaming
  334. @return The SQL update statement in case execute=False, or an empty string otherwise
  335. """
  336. dbif, connected = init_dbif(dbif)
  337. # Build the UPDATE SQL statement
  338. statement = self.base.get_update_all_statement_mogrified(dbif, ident)
  339. statement += self.temporal_extent.get_update_all_statement_mogrified(dbif,
  340. ident)
  341. statement += self.spatial_extent.get_update_all_statement_mogrified(
  342. dbif, ident)
  343. statement += self.metadata.get_update_all_statement_mogrified(dbif, ident)
  344. if execute:
  345. dbif.execute_transaction(statement)
  346. if connected:
  347. dbif.close()
  348. return ""
  349. if connected:
  350. dbif.close()
  351. return statement
  352. def set_time_to_absolute(self):
  353. """!Set the temporal type to absolute"""
  354. self.base.set_ttype("absolute")
  355. def set_time_to_relative(self):
  356. """!Set the temporal type to relative"""
  357. self.base.set_ttype("relative")
  358. def is_time_absolute(self):
  359. """!Return True in case the temporal type is absolute
  360. @return True if temporal type is absolute, False otherwise
  361. """
  362. if "temporal_type" in self.base.D:
  363. return self.base.get_ttype() == "absolute"
  364. else:
  365. return None
  366. def is_time_relative(self):
  367. """!Return True in case the temporal type is relative
  368. @return True if temporal type is relative, False otherwise
  369. """
  370. if "temporal_type" in self.base.D:
  371. return self.base.get_ttype() == "relative"
  372. else:
  373. return None
  374. def _get_temporal_extent(self):
  375. """!Return the temporal extent of the correct internal type
  376. """
  377. if self.is_time_absolute():
  378. return self.absolute_time
  379. if self.is_time_relative():
  380. return self.relative_time
  381. return None
  382. temporal_extent = property(fget=_get_temporal_extent)
  383. def temporal_relation(self, dataset):
  384. """!Return the temporal relation of self and the provided dataset
  385. @return The temporal relation as string
  386. """
  387. return self.temporal_extent.temporal_relation(dataset.temporal_extent)
  388. def temporal_intersection(self, dataset):
  389. """!Intersect self with the provided dataset and
  390. return a new temporal extent with the new start and end time
  391. @param dataset The abstract dataset to temporal intersect with
  392. @return The new temporal extent with start and end time,
  393. or None in case of no intersection
  394. """
  395. return self.temporal_extent.intersect(dataset.temporal_extent)
  396. def temporal_union(self, dataset):
  397. """!Creates a union with the provided dataset and
  398. return a new temporal extent with the new start and end time.
  399. @param dataset The abstract dataset to create temporal union with
  400. @return The new temporal extent with start and end time,
  401. or None in case of no intersection
  402. """
  403. return self.temporal_extent.union(dataset.temporal_extent)
  404. def temporal_disjoint_union(self, dataset):
  405. """!Creates a union with the provided dataset and
  406. return a new temporal extent with the new start and end time.
  407. @param dataset The abstract dataset to create temporal union with
  408. @return The new temporal extent with start and end time,
  409. or None in case of no intersection
  410. """
  411. return self.temporal_extent.disjoint_union(dataset.temporal_extent)
  412. ###############################################################################
  413. class AbstractDatasetComparisonKeyStartTime(object):
  414. """!This comparison key can be used to sort lists of abstract datasets
  415. by start time
  416. Example:
  417. # Return all maps in a space time raster dataset as map objects
  418. map_list = strds.get_registered_maps_as_objects()
  419. # Sort the maps in the list by start time
  420. sorted_map_list = sorted(
  421. map_list, key=AbstractDatasetComparisonKeyStartTime)
  422. """
  423. def __init__(self, obj, *args):
  424. self.obj = obj
  425. def __lt__(self, other):
  426. startA, endA = self.obj.get_temporal_extent_as_tuple()
  427. startB, endB = other.obj.get_temporal_extent_as_tuple()
  428. return startA < startB
  429. def __gt__(self, other):
  430. startA, endA = self.obj.get_temporal_extent_as_tuple()
  431. startB, endB = other.obj.get_temporal_extent_as_tuple()
  432. return startA > startB
  433. def __eq__(self, other):
  434. startA, endA = self.obj.get_temporal_extent_as_tuple()
  435. startB, endB = other.obj.get_temporal_extent_as_tuple()
  436. return startA == startB
  437. def __le__(self, other):
  438. startA, endA = self.obj.get_temporal_extent_as_tuple()
  439. startB, endB = other.obj.get_temporal_extent_as_tuple()
  440. return startA <= startB
  441. def __ge__(self, other):
  442. startA, endA = self.obj.get_temporal_extent_as_tuple()
  443. startB, endB = other.obj.get_temporal_extent_as_tuple()
  444. return startA >= startB
  445. def __ne__(self, other):
  446. startA, endA = self.obj.get_temporal_extent_as_tuple()
  447. startB, endB = other.obj.get_temporal_extent_as_tuple()
  448. return startA != startB
  449. ###############################################################################
  450. class AbstractDatasetComparisonKeyEndTime(object):
  451. """!This comparison key can be used to sort lists of abstract datasets
  452. by end time
  453. Example:
  454. # Return all maps in a space time raster dataset as map objects
  455. map_list = strds.get_registered_maps_as_objects()
  456. # Sort the maps in the list by end time
  457. sorted_map_list = sorted(
  458. map_list, key=AbstractDatasetComparisonKeyEndTime)
  459. """
  460. def __init__(self, obj, *args):
  461. self.obj = obj
  462. def __lt__(self, other):
  463. startA, endA = self.obj.get_temporal_extent_as_tuple()
  464. startB, endB = other.obj.get_temporal_extent_as_tuple()
  465. return endA < endB
  466. def __gt__(self, other):
  467. startA, endA = self.obj.get_temporal_extent_as_tuple()
  468. startB, endB = other.obj.get_temporal_extent_as_tuple()
  469. return endA > endB
  470. def __eq__(self, other):
  471. startA, endA = self.obj.get_temporal_extent_as_tuple()
  472. startB, endB = other.obj.get_temporal_extent_as_tuple()
  473. return endA == endB
  474. def __le__(self, other):
  475. startA, endA = self.obj.get_temporal_extent_as_tuple()
  476. startB, endB = other.obj.get_temporal_extent_as_tuple()
  477. return endA <= endB
  478. def __ge__(self, other):
  479. startA, endA = self.obj.get_temporal_extent_as_tuple()
  480. startB, endB = other.obj.get_temporal_extent_as_tuple()
  481. return endA >= endB
  482. def __ne__(self, other):
  483. startA, endA = self.obj.get_temporal_extent_as_tuple()
  484. startB, endB = other.obj.get_temporal_extent_as_tuple()
  485. return endA != endB
  486. ###############################################################################
  487. if __name__ == "__main__":
  488. import doctest
  489. doctest.testmod()