abstract_dataset.py 22 KB

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