abstract_dataset.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616
  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 SpatialTopologyBuilder, TemporalTopologyBuilder or 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_relation(self, dataset):
  137. """!Return the spatial relationship between self and dataset
  138. @param dataset The abstract dataset to compute the spatial relation with self
  139. @return The spatial relationship as string
  140. """
  141. raise ImplementationError("This method must be implemented in the subclasses")
  142. def print_info(self):
  143. """!Print information about this class in human readable style"""
  144. raise ImplementationError("This method must be implemented in the subclasses")
  145. def print_shell_info(self):
  146. """!Print information about this class in shell style"""
  147. raise ImplementationError("This method must be implemented in the subclasses")
  148. def print_self(self):
  149. """!Print the content of the internal structure to stdout"""
  150. raise ImplementationError("This method must be implemented in the subclasses")
  151. def set_id(self, ident):
  152. self.base.set_id(ident)
  153. if self.is_time_absolute():
  154. self.absolute_time.set_id(ident)
  155. if self.is_time_relative():
  156. self.relative_time.set_id(ident)
  157. self.spatial_extent.set_id(ident)
  158. self.metadata.set_id(ident)
  159. def get_id(self):
  160. """!Return the unique identifier of the dataset
  161. @return The id of the dataset "name(:layer)@mapset" as string
  162. """
  163. return self.base.get_id()
  164. def get_name(self):
  165. """!Return the name
  166. @return The name of the dataset as string
  167. """
  168. return self.base.get_name()
  169. def get_mapset(self):
  170. """!Return the mapset
  171. @return The mapset in which the dataset was created as string
  172. """
  173. return self.base.get_mapset()
  174. def get_valid_time(self):
  175. """!Returns a tuple of the valid start and end time
  176. Start and end time can be either of type datetime or of type integer,
  177. depending on the temporal type.
  178. @return A tuple of (start_time, end_time)
  179. """
  180. start = None
  181. end = None
  182. if self.is_time_absolute():
  183. start = self.absolute_time.get_start_time()
  184. end = self.absolute_time.get_end_time()
  185. if self.is_time_relative():
  186. start = self.relative_time.get_start_time()
  187. end = self.relative_time.get_end_time()
  188. return (start, end)
  189. def get_absolute_time(self):
  190. """!Returns the start time, the end
  191. time and the timezone of the map as tuple
  192. @attention: The timezone is currently not used.
  193. The start time is of type datetime.
  194. The end time is of type datetime in case of interval time,
  195. or None on case of a time instance.
  196. @return A tuple of (start_time, end_time, timezone)
  197. """
  198. start = self.absolute_time.get_start_time()
  199. end = self.absolute_time.get_end_time()
  200. tz = self.absolute_time.get_timezone()
  201. return (start, end, tz)
  202. def get_relative_time(self):
  203. """!Returns the start time, the end
  204. time and the temporal unit of the dataset as tuple
  205. The start time is of type integer.
  206. The end time is of type integer in case of interval time,
  207. or None on case of a time instance.
  208. @return A tuple of (start_time, end_time, unit)
  209. """
  210. start = self.relative_time.get_start_time()
  211. end = self.relative_time.get_end_time()
  212. unit = self.relative_time.get_unit()
  213. return (start, end, unit)
  214. def get_relative_time_unit(self):
  215. """!Returns the relative time unit
  216. @return The relative time unit as string, None if not present
  217. """
  218. return self.relative_time.get_unit()
  219. def check_relative_time_unit(self, unit):
  220. """!Check if unit is of type year(s), month(s), day(s), hour(s),
  221. minute(s) or second(s)
  222. @param unit The unit string
  223. @return True if success, False otherwise
  224. """
  225. # Check unit
  226. units = ["year", "years", "month", "months", "day", "days", "hour",
  227. "hours", "minute", "minutes", "second", "seconds"]
  228. if unit not in units:
  229. return False
  230. return True
  231. def get_temporal_type(self):
  232. """!Return the temporal type of this dataset
  233. The temporal type can be absolute or relative
  234. @return The temporal type of the dataset as string
  235. """
  236. return self.base.get_ttype()
  237. def get_spatial_extent(self):
  238. """!Return the spatial extent as tuple
  239. Top and bottom are set to 0 in case of a two dimensional spatial extent.
  240. @return A the spatial extent as tuple (north, south, east, west, top, bottom)
  241. """
  242. return self.spatial_extent.get_spatial_extent()
  243. def select(self, dbif=None):
  244. """!Select temporal dataset entry from database and fill
  245. the internal structure
  246. The content of every dataset is stored in the temporal database.
  247. This method must be used to fill this object with the content
  248. from the temporal database.
  249. @param dbif The database interface to be used
  250. """
  251. dbif, connected = init_dbif(dbif)
  252. self.base.select(dbif)
  253. if self.is_time_absolute():
  254. self.absolute_time.select(dbif)
  255. if self.is_time_relative():
  256. self.relative_time.select(dbif)
  257. self.spatial_extent.select(dbif)
  258. self.metadata.select(dbif)
  259. if connected:
  260. dbif.close()
  261. def is_in_db(self, dbif=None):
  262. """!Check if the dataset is registered in the database
  263. @param dbif The database interface to be used
  264. @return True if the dataset is registered in the database
  265. """
  266. return self.base.is_in_db(dbif)
  267. def delete(self):
  268. """!Delete dataset from database if it exists"""
  269. raise ImplementationError("This method must be implemented in the subclasses")
  270. def insert(self, dbif=None, execute=True):
  271. """!Insert dataset into database
  272. @param dbif The database interface to be used
  273. @param execute If True the SQL statements will be executed.
  274. If False the prepared SQL statements are returned
  275. and must be executed by the caller.
  276. @return The SQL insert statement in case execute=False, or an empty string otherwise
  277. """
  278. dbif, connected = init_dbif(dbif)
  279. # Build the INSERT SQL statement
  280. statement = self.base.get_insert_statement_mogrified(dbif)
  281. if self.is_time_absolute():
  282. statement += self.absolute_time.get_insert_statement_mogrified(
  283. dbif)
  284. if self.is_time_relative():
  285. statement += self.relative_time.get_insert_statement_mogrified(
  286. dbif)
  287. statement += self.spatial_extent.get_insert_statement_mogrified(dbif)
  288. statement += self.metadata.get_insert_statement_mogrified(dbif)
  289. if execute:
  290. dbif.execute_transaction(statement)
  291. if connected:
  292. dbif.close()
  293. return ""
  294. if connected:
  295. dbif.close()
  296. return statement
  297. def update(self, dbif=None, execute=True, ident=None):
  298. """!Update the dataset entry in the database from the internal structure
  299. excluding None variables
  300. @param dbif The database interface to be used
  301. @param execute If True the SQL statements will be executed.
  302. If False the prepared SQL statements are returned
  303. and must be executed by the caller.
  304. @param ident The identifier to be updated, useful for renaming
  305. @return The SQL update statement in case execute=False, or an empty string otherwise
  306. """
  307. dbif, connected = init_dbif(dbif)
  308. # Build the UPDATE SQL statement
  309. statement = self.base.get_update_statement_mogrified(dbif, ident)
  310. if self.is_time_absolute():
  311. statement += self.absolute_time.get_update_statement_mogrified(
  312. dbif, ident)
  313. if self.is_time_relative():
  314. statement += self.relative_time.get_update_statement_mogrified(
  315. dbif, ident)
  316. statement += self.spatial_extent.get_update_statement_mogrified(dbif,
  317. ident)
  318. statement += self.metadata.get_update_statement_mogrified(dbif, ident)
  319. if execute:
  320. dbif.execute_transaction(statement)
  321. if connected:
  322. dbif.close()
  323. return ""
  324. if connected:
  325. dbif.close()
  326. return statement
  327. def update_all(self, dbif=None, execute=True, ident=None):
  328. """!Update the dataset entry in the database from the internal structure
  329. and include None variables.
  330. @param dbif The database interface to be used
  331. @param execute If True the SQL statements will be executed.
  332. If False the prepared SQL statements are returned
  333. and must be executed by the caller.
  334. @param ident The identifier to be updated, useful for renaming
  335. @return The SQL update statement in case execute=False, or an empty string otherwise
  336. """
  337. dbif, connected = init_dbif(dbif)
  338. # Build the UPDATE SQL statement
  339. statement = self.base.get_update_all_statement_mogrified(dbif, ident)
  340. if self.is_time_absolute():
  341. statement += self.absolute_time.get_update_all_statement_mogrified(
  342. dbif, ident)
  343. if self.is_time_relative():
  344. statement += self.relative_time.get_update_all_statement_mogrified(
  345. dbif, ident)
  346. statement += self.spatial_extent.get_update_all_statement_mogrified(
  347. dbif, ident)
  348. statement += self.metadata.get_update_all_statement_mogrified(dbif, ident)
  349. if execute:
  350. dbif.execute_transaction(statement)
  351. if connected:
  352. dbif.close()
  353. return ""
  354. if connected:
  355. dbif.close()
  356. return statement
  357. def set_time_to_absolute(self):
  358. """!Set the temporal type to absolute"""
  359. self.base.set_ttype("absolute")
  360. def set_time_to_relative(self):
  361. """!Set the temporal type to relative"""
  362. self.base.set_ttype("relative")
  363. def is_time_absolute(self):
  364. """!Return True in case the temporal type is absolute
  365. @return True if temporal type is absolute, False otherwise
  366. """
  367. if "temporal_type" in self.base.D:
  368. return self.base.get_ttype() == "absolute"
  369. else:
  370. return None
  371. def is_time_relative(self):
  372. """!Return True in case the temporal type is relative
  373. @return True if temporal type is relative, False otherwise
  374. """
  375. if "temporal_type" in self.base.D:
  376. return self.base.get_ttype() == "relative"
  377. else:
  378. return None
  379. def temporal_relation(self, dataset):
  380. """!Return the temporal relation of self and the provided dataset
  381. @return The temporal relation as string
  382. """
  383. if self.is_time_absolute() and dataset.is_time_absolute():
  384. return self.absolute_time.temporal_relation(dataset.absolute_time)
  385. if self.is_time_relative() and dataset.is_time_relative():
  386. return self.relative_time.temporal_relation(dataset.relative_time)
  387. return None
  388. def temporal_intersection(self, dataset):
  389. """!Intersect self with the provided datasetand
  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. if self.is_time_absolute() and dataset.is_time_absolute():
  396. return self.absolute_time.intersect(dataset.absolute_time)
  397. if self.is_time_relative() and dataset.is_time_relative():
  398. return self.relative_time.intersect(dataset.relative_time)
  399. return None
  400. ###############################################################################
  401. class AbstractDatasetComparisonKeyStartTime(object):
  402. """!This comparison key can be used to sort lists of abstract datasets
  403. by start time
  404. Example:
  405. # Return all maps in a space time raster dataset as map objects
  406. map_list = strds.get_registered_maps_as_objects()
  407. # Sort the maps in the list by start time
  408. sorted_map_list = sorted(
  409. map_list, key=AbstractDatasetComparisonKeyStartTime)
  410. """
  411. def __init__(self, obj, *args):
  412. self.obj = obj
  413. def __lt__(self, other):
  414. startA, endA = self.obj.get_valid_time()
  415. startB, endB = other.obj.get_valid_time()
  416. return startA < startB
  417. def __gt__(self, other):
  418. startA, endA = self.obj.get_valid_time()
  419. startB, endB = other.obj.get_valid_time()
  420. return startA > startB
  421. def __eq__(self, other):
  422. startA, endA = self.obj.get_valid_time()
  423. startB, endB = other.obj.get_valid_time()
  424. return startA == startB
  425. def __le__(self, other):
  426. startA, endA = self.obj.get_valid_time()
  427. startB, endB = other.obj.get_valid_time()
  428. return startA <= startB
  429. def __ge__(self, other):
  430. startA, endA = self.obj.get_valid_time()
  431. startB, endB = other.obj.get_valid_time()
  432. return startA >= startB
  433. def __ne__(self, other):
  434. startA, endA = self.obj.get_valid_time()
  435. startB, endB = other.obj.get_valid_time()
  436. return startA != startB
  437. ###############################################################################
  438. class AbstractDatasetComparisonKeyEndTime(object):
  439. """!This comparison key can be used to sort lists of abstract datasets
  440. by end time
  441. Example:
  442. # Return all maps in a space time raster dataset as map objects
  443. map_list = strds.get_registered_maps_as_objects()
  444. # Sort the maps in the list by end time
  445. sorted_map_list = sorted(
  446. map_list, key=AbstractDatasetComparisonKeyEndTime)
  447. """
  448. def __init__(self, obj, *args):
  449. self.obj = obj
  450. def __lt__(self, other):
  451. startA, endA = self.obj.get_valid_time()
  452. startB, endB = other.obj.get_valid_time()
  453. return endA < endB
  454. def __gt__(self, other):
  455. startA, endA = self.obj.get_valid_time()
  456. startB, endB = other.obj.get_valid_time()
  457. return endA > endB
  458. def __eq__(self, other):
  459. startA, endA = self.obj.get_valid_time()
  460. startB, endB = other.obj.get_valid_time()
  461. return endA == endB
  462. def __le__(self, other):
  463. startA, endA = self.obj.get_valid_time()
  464. startB, endB = other.obj.get_valid_time()
  465. return endA <= endB
  466. def __ge__(self, other):
  467. startA, endA = self.obj.get_valid_time()
  468. startB, endB = other.obj.get_valid_time()
  469. return endA >= endB
  470. def __ne__(self, other):
  471. startA, endA = self.obj.get_valid_time()
  472. startB, endB = other.obj.get_valid_time()
  473. return endA != endB
  474. ###############################################################################
  475. if __name__ == "__main__":
  476. import doctest
  477. doctest.testmod()