abstract_dataset.py 23 KB

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