abstract_dataset.py 23 KB

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