abstract_dataset.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648
  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. (C) 2011-2012 by the GRASS Development Team
  6. This program is free software under the GNU General Public
  7. License (>=v2). Read the file COPYING that comes with GRASS
  8. for details.
  9. @author Soeren Gebbert
  10. """
  11. import uuid
  12. import copy
  13. from abc import ABCMeta, abstractmethod
  14. from temporal_extent import *
  15. from spatial_extent import *
  16. from metadata import *
  17. from temporal_topology_dataset_connector import *
  18. from spatial_topology_dataset_connector import *
  19. class ImplementationError(Exception):
  20. """!Exception raised for the calling of methods that should be implemented in
  21. sub classes.
  22. """
  23. def __init__(self, msg):
  24. self.msg = msg
  25. def __str__(self):
  26. return repr(self.msg)
  27. ###############################################################################
  28. class AbstractDataset(SpatialTopologyDatasetConnector, TemporalTopologyDatasetConnector):
  29. """!This is the base class for all datasets
  30. (raster, vector, raster3d, strds, stvds, str3ds)"""
  31. __metaclass__ = ABCMeta
  32. def __init__(self):
  33. SpatialTopologyDatasetConnector.__init__(self)
  34. TemporalTopologyDatasetConnector.__init__(self)
  35. self.msgr = get_tgis_message_interface()
  36. def reset_topology(self):
  37. """!Reset any information about temporal topology"""
  38. self.reset_spatial_topology()
  39. self.reset_temporal_topology()
  40. def get_number_of_relations(self):
  41. """! Return a dictionary in which the keys are the relation names and the value
  42. are the number of relations.
  43. The following relations are available:
  44. Spatial relations
  45. - equivalent
  46. - overlap
  47. - in
  48. - contain
  49. - meet
  50. - cover
  51. - covered
  52. Temporal relations
  53. - equal
  54. - follows
  55. - precedes
  56. - overlaps
  57. - overlapped
  58. - during (including starts, finishes)
  59. - contains (including started, finished)
  60. - starts
  61. - started
  62. - finishes
  63. - finished
  64. To access topological information the spatial, temporal or booth topologies must be build first
  65. using the SpatioTemporalTopologyBuilder.
  66. @return the dictionary with relations as keys and number as values or None in case the topology wasn't build
  67. """
  68. if self.is_temporal_topology_build() and not self.is_spatial_topology_build():
  69. return self.get_number_of_temporal_relations()
  70. elif self.is_spatial_topology_build() and not self.is_temporal_topology_build():
  71. self.get_number_of_spatial_relations()
  72. else:
  73. return self.get_number_of_temporal_relations() + \
  74. self.get_number_of_spatial_relations()
  75. return None
  76. def set_topology_build_true(self):
  77. """!Use this method when the spatio-temporal topology was build"""
  78. self.set_spatial_topology_build_true()
  79. self.set_temporal_topology_build_true()
  80. def set_topology_build_false(self):
  81. """!Use this method when the spatio-temporal topology was not build"""
  82. self.set_spatial_topology_build_false()
  83. self.set_temporal_topology_build_false()
  84. def is_topology_build(self):
  85. """!Check if the spatial and temporal topology was build
  86. @return A dictionary with "spatial" and "temporal" as keys that have boolen values
  87. """
  88. d = {}
  89. d["spatial"] = self.is_spatial_topology_build()
  90. d["temporal"] = self.is_temporal_topology_build()
  91. return d
  92. def print_topology_info(self):
  93. if self.is_temporal_topology_build():
  94. self.print_temporal_topology_info()
  95. if self.is_spatial_topology_build():
  96. self.print_spatial_topology_info()
  97. def print_topology_shell_info(self):
  98. if self.is_temporal_topology_build():
  99. self.print_temporal_topology_shell_info()
  100. if self.is_spatial_topology_build():
  101. self.print_spatial_topology_shell_info()
  102. @abstractmethod
  103. def reset(self, ident):
  104. """!Reset the internal structure and set the identifier
  105. This method creates the dataset specific internal objects
  106. that store the base information, the spatial and temporal extent
  107. and the metadata. It must be implemented in the dataset
  108. specific subclasses. This is the code for the
  109. vector dataset:
  110. self.base = VectorBase(ident=ident)
  111. self.absolute_time = VectorAbsoluteTime(ident=ident)
  112. self.relative_time = VectorRelativeTime(ident=ident)
  113. self.spatial_extent = VectorSpatialExtent(ident=ident)
  114. self.metadata = VectorMetadata(ident=ident)
  115. @param ident The identifier of the dataset that "name@mapset" or in case of vector maps "name:layer@mapset"
  116. """
  117. @abstractmethod
  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. @abstractmethod
  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. @abstractmethod
  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. @abstractmethod
  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. @abstractmethod
  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. @abstractmethod
  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. @abstractmethod
  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. @abstractmethod
  162. def print_info(self):
  163. """!Print information about this class in human readable style"""
  164. @abstractmethod
  165. def print_shell_info(self):
  166. """!Print information about this class in shell style"""
  167. @abstractmethod
  168. def print_self(self):
  169. """!Print the content of the internal structure to stdout"""
  170. def set_id(self, ident):
  171. """!Set the identifier of the dataset"""
  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 get_spatial_extent(self):
  255. """!Return the spatial extent
  256. """
  257. return self.spatial_extent
  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. @abstractmethod
  280. def delete(self):
  281. """!Delete dataset from database if it exists"""
  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. if self.get_mapset() != get_current_mapset():
  291. core.fatal(_("Unable to insert dataset <%(ds)s> of type %(type)s in the temporal database."
  292. " The mapset of the dataset does not match the current mapset")%\
  293. {"ds":self.get_id(), "type":self.get_type()})
  294. dbif, connected = init_dbif(dbif)
  295. # Build the INSERT SQL statement
  296. statement = self.base.get_insert_statement_mogrified(dbif)
  297. statement += self.temporal_extent.get_insert_statement_mogrified(dbif)
  298. statement += self.spatial_extent.get_insert_statement_mogrified(dbif)
  299. statement += self.metadata.get_insert_statement_mogrified(dbif)
  300. if execute:
  301. dbif.execute_transaction(statement)
  302. if connected:
  303. dbif.close()
  304. return ""
  305. if connected:
  306. dbif.close()
  307. return statement
  308. def update(self, dbif=None, execute=True, ident=None):
  309. """!Update the dataset entry in the database from the internal structure
  310. excluding None variables
  311. @param dbif The database interface to be used
  312. @param execute If True the SQL statements will be executed.
  313. If False the prepared SQL statements are returned
  314. and must be executed by the caller.
  315. @param ident The identifier to be updated, useful for renaming
  316. @return The SQL update statement in case execute=False, or an empty string otherwise
  317. """
  318. if self.get_mapset() != get_current_mapset():
  319. core.fatal(_("Unable to update dataset <%(ds)s> of type %(type)s in the temporal database."
  320. " The mapset of the dataset does not match the current mapset")%\
  321. {"ds":self.get_id(), "type":self.get_type()})
  322. dbif, connected = init_dbif(dbif)
  323. # Build the UPDATE SQL statement
  324. statement = self.base.get_update_statement_mogrified(dbif, ident)
  325. statement += self.temporal_extent.get_update_statement_mogrified(dbif,
  326. ident)
  327. statement += self.spatial_extent.get_update_statement_mogrified(dbif,
  328. ident)
  329. statement += self.metadata.get_update_statement_mogrified(dbif, ident)
  330. if execute:
  331. dbif.execute_transaction(statement)
  332. if connected:
  333. dbif.close()
  334. return ""
  335. if connected:
  336. dbif.close()
  337. return statement
  338. def update_all(self, dbif=None, execute=True, ident=None):
  339. """!Update the dataset entry in the database from the internal structure
  340. and include None variables.
  341. @param dbif The database interface to be used
  342. @param execute If True the SQL statements will be executed.
  343. If False the prepared SQL statements are returned
  344. and must be executed by the caller.
  345. @param ident The identifier to be updated, useful for renaming
  346. @return The SQL update statement in case execute=False, or an empty string otherwise
  347. """
  348. if self.get_mapset() != get_current_mapset():
  349. core.fatal(_("Unable to update dataset <%(ds)s> of type %(type)s in the temporal database."
  350. " The mapset of the dataset does not match the current mapset")%\
  351. {"ds":self.get_id(), "type":self.get_type()})
  352. dbif, connected = init_dbif(dbif)
  353. # Build the UPDATE SQL statement
  354. statement = self.base.get_update_all_statement_mogrified(dbif, ident)
  355. statement += self.temporal_extent.get_update_all_statement_mogrified(dbif,
  356. ident)
  357. statement += self.spatial_extent.get_update_all_statement_mogrified(
  358. dbif, ident)
  359. statement += self.metadata.get_update_all_statement_mogrified(dbif, ident)
  360. if execute:
  361. dbif.execute_transaction(statement)
  362. if connected:
  363. dbif.close()
  364. return ""
  365. if connected:
  366. dbif.close()
  367. return statement
  368. def is_time_absolute(self):
  369. """!Return True in case the temporal type is absolute
  370. @return True if temporal type is absolute, False otherwise
  371. """
  372. if "temporal_type" in self.base.D:
  373. return self.base.get_ttype() == "absolute"
  374. else:
  375. return None
  376. def is_time_relative(self):
  377. """!Return True in case the temporal type is relative
  378. @return True if temporal type is relative, False otherwise
  379. """
  380. if "temporal_type" in self.base.D:
  381. return self.base.get_ttype() == "relative"
  382. else:
  383. return None
  384. def get_temporal_extent(self):
  385. """!Return the temporal extent of the correct internal type
  386. """
  387. if self.is_time_absolute():
  388. return self.absolute_time
  389. if self.is_time_relative():
  390. return self.relative_time
  391. return None
  392. temporal_extent = property(fget=get_temporal_extent)
  393. def temporal_relation(self, dataset):
  394. """!Return the temporal relation of self and the provided dataset
  395. @return The temporal relation as string
  396. """
  397. return self.temporal_extent.temporal_relation(dataset.temporal_extent)
  398. def temporal_intersection(self, dataset):
  399. """!Intersect self with the provided dataset and
  400. return a new temporal extent with the new start and end time
  401. @param dataset The abstract dataset to temporal intersect with
  402. @return The new temporal extent with start and end time,
  403. or None in case of no intersection
  404. """
  405. return self.temporal_extent.intersect(dataset.temporal_extent)
  406. def temporal_union(self, dataset):
  407. """!Creates a union with the provided dataset and
  408. return a new temporal extent with the new start and end time.
  409. @param dataset The abstract dataset to create temporal union with
  410. @return The new temporal extent with start and end time,
  411. or None in case of no intersection
  412. """
  413. return self.temporal_extent.union(dataset.temporal_extent)
  414. def temporal_disjoint_union(self, dataset):
  415. """!Creates a union with the provided dataset and
  416. return a new temporal extent with the new start and end time.
  417. @param dataset The abstract dataset to create temporal union with
  418. @return The new temporal extent with start and end time
  419. """
  420. return self.temporal_extent.disjoint_union(dataset.temporal_extent)
  421. ###############################################################################
  422. class AbstractDatasetComparisonKeyStartTime(object):
  423. """!This comparison key can be used to sort lists of abstract datasets
  424. by start time
  425. Example:
  426. # Return all maps in a space time raster dataset as map objects
  427. map_list = strds.get_registered_maps_as_objects()
  428. # Sort the maps in the list by start time
  429. sorted_map_list = sorted(
  430. map_list, key=AbstractDatasetComparisonKeyStartTime)
  431. """
  432. def __init__(self, obj, *args):
  433. self.obj = obj
  434. def __lt__(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 __gt__(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 __eq__(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. def __le__(self, other):
  447. startA, endA = self.obj.get_temporal_extent_as_tuple()
  448. startB, endB = other.obj.get_temporal_extent_as_tuple()
  449. return startA <= startB
  450. def __ge__(self, other):
  451. startA, endA = self.obj.get_temporal_extent_as_tuple()
  452. startB, endB = other.obj.get_temporal_extent_as_tuple()
  453. return startA >= startB
  454. def __ne__(self, other):
  455. startA, endA = self.obj.get_temporal_extent_as_tuple()
  456. startB, endB = other.obj.get_temporal_extent_as_tuple()
  457. return startA != startB
  458. ###############################################################################
  459. class AbstractDatasetComparisonKeyEndTime(object):
  460. """!This comparison key can be used to sort lists of abstract datasets
  461. by end time
  462. Example:
  463. # Return all maps in a space time raster dataset as map objects
  464. map_list = strds.get_registered_maps_as_objects()
  465. # Sort the maps in the list by end time
  466. sorted_map_list = sorted(
  467. map_list, key=AbstractDatasetComparisonKeyEndTime)
  468. """
  469. def __init__(self, obj, *args):
  470. self.obj = obj
  471. def __lt__(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 __gt__(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 __eq__(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. def __le__(self, other):
  484. startA, endA = self.obj.get_temporal_extent_as_tuple()
  485. startB, endB = other.obj.get_temporal_extent_as_tuple()
  486. return endA <= endB
  487. def __ge__(self, other):
  488. startA, endA = self.obj.get_temporal_extent_as_tuple()
  489. startB, endB = other.obj.get_temporal_extent_as_tuple()
  490. return endA >= endB
  491. def __ne__(self, other):
  492. startA, endA = self.obj.get_temporal_extent_as_tuple()
  493. startB, endB = other.obj.get_temporal_extent_as_tuple()
  494. return endA != endB
  495. ###############################################################################
  496. if __name__ == "__main__":
  497. import doctest
  498. doctest.testmod()