spatio_temporal_relationships.py 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995
  1. """!@package grass.temporal
  2. @brief GRASS Python scripting module (temporal GIS functions)
  3. Temporal GIS related functions to be used in temporal GIS Python library package.
  4. Usage:
  5. @code
  6. import grass.temporal as tgis
  7. tgis.print_temporal_relations(maps)
  8. ...
  9. @endcode
  10. (C) 2008-2011 by the GRASS Development Team
  11. This program is free software under the GNU General Public
  12. License (>=v2). Read the file COPYING that comes with GRASS
  13. for details.
  14. @author Soeren Gebbert
  15. """
  16. from abstract_dataset import *
  17. from datetime_math import *
  18. import grass.lib.vector as vector
  19. import grass.lib.gis as gis
  20. from ctypes import *
  21. ###############################################################################
  22. class SpatioTemporalTopologyBuilder(object):
  23. """!This class is designed to build the spatio-temporal topology
  24. of spatio-temporally related abstract dataset objects.
  25. The abstract dataset objects must be provided as a single list, or in two lists.
  26. Example:
  27. @code
  28. # We have a space time raster dataset and build a map list
  29. # from all registered maps ordered by start time
  30. maps = strds.get_registered_maps_as_objects()
  31. # Now lets build the temporal topology of the maps in the list
  32. tb = SpatioTemporalTopologyBuilder()
  33. tb.build(maps)
  34. dbif, connected = init_dbif(None)
  35. for map in tb:
  36. map.select(dbif)
  37. map.print_info()
  38. # Same can be done with the existing map list
  39. # But be aware that this is might not be temporally ordered
  40. for map in maps:
  41. map.select(dbf)
  42. map.print_info()
  43. # Using the next and previous methods, we can iterate over the
  44. # topological related maps in this way
  45. first = tb.get_first()
  46. while first:
  47. first.print_topology_info()
  48. first = first.next()
  49. # Dictionary like accessed
  50. map = tb["name@mapset"]
  51. >>> # Example with two lists of maps
  52. >>> import grass.temporal as tgis
  53. >>> import datetime
  54. >>> # Create two list of maps with equal time stamps
  55. >>> mapsA = []
  56. >>> mapsB = []
  57. >>> for i in range(4):
  58. ... idA = "a%i@B"%(i)
  59. ... mapA = tgis.RasterDataset(idA)
  60. ... idB = "b%i@B"%(i)
  61. ... mapB = tgis.RasterDataset(idB)
  62. ... check = mapA.set_relative_time(i, i + 1, "months")
  63. ... check = mapB.set_relative_time(i, i + 1, "months")
  64. ... mapsA.append(mapA)
  65. ... mapsB.append(mapB)
  66. >>> # Build the topology between the two map lists
  67. >>> tb = SpatioTemporalTopologyBuilder()
  68. >>> tb.build(mapsA, mapsB, None)
  69. >>> # Check relations of mapsA
  70. >>> for map in mapsA:
  71. ... if map.get_equal():
  72. ... relations = map.get_equal()
  73. ... print "Map %s has equal relation to map %s"%(map.get_name(),
  74. ... relations[0].get_name())
  75. Map a0 has equal relation to map b0
  76. Map a1 has equal relation to map b1
  77. Map a2 has equal relation to map b2
  78. Map a3 has equal relation to map b3
  79. >>> # Check relations of mapsB
  80. >>> for map in mapsB:
  81. ... if map.get_equal():
  82. ... relations = map.get_equal()
  83. ... print "Map %s has equal relation to map %s"%(map.get_name(),
  84. ... relations[0].get_name())
  85. Map b0 has equal relation to map a0
  86. Map b1 has equal relation to map a1
  87. Map b2 has equal relation to map a2
  88. Map b3 has equal relation to map a3
  89. >>> mapsA = []
  90. >>> mapsB = []
  91. >>> for i in range(4):
  92. ... idA = "a%i@B"%(i)
  93. ... mapA = tgis.RasterDataset(idA)
  94. ... idB = "b%i@B"%(i)
  95. ... mapB = tgis.RasterDataset(idB)
  96. ... check = mapA.set_relative_time(i, i + 1, "months")
  97. ... check = mapB.set_relative_time(i + 1, i + 2, "months")
  98. ... mapsA.append(mapA)
  99. ... mapsB.append(mapB)
  100. >>> # Build the topology between the two map lists
  101. >>> tb = SpatioTemporalTopologyBuilder()
  102. >>> tb.build(mapsA, mapsB, None)
  103. >>> # Check relations of mapsA
  104. >>> for map in mapsA:
  105. ... print(map.get_temporal_extent_as_tuple())
  106. ... m = map.get_temporal_relations()
  107. ... for key in m.keys():
  108. ... if key not in ["NEXT", "PREV"]:
  109. ... print(key, m[key][0].get_temporal_extent_as_tuple())
  110. (0, 1)
  111. ('PRECEDES', (1, 2))
  112. (1, 2)
  113. ('PRECEDES', (2, 3))
  114. ('EQUAL', (1, 2))
  115. (2, 3)
  116. ('FOLLOWS', (1, 2))
  117. ('PRECEDES', (3, 4))
  118. ('EQUAL', (2, 3))
  119. (3, 4)
  120. ('FOLLOWS', (2, 3))
  121. ('EQUAL', (3, 4))
  122. ('PRECEDES', (4, 5))
  123. >>> mapsA = []
  124. >>> mapsB = []
  125. >>> for i in range(4):
  126. ... idA = "a%i@B"%(i)
  127. ... mapA = tgis.RasterDataset(idA)
  128. ... idB = "b%i@B"%(i)
  129. ... mapB = tgis.RasterDataset(idB)
  130. ... start = datetime.datetime(2000 + i, 1, 1)
  131. ... end = datetime.datetime(2000 + i + 1, 1, 1)
  132. ... check = mapA.set_absolute_time(start, end)
  133. ... start = datetime.datetime(2000 + i + 1, 1, 1)
  134. ... end = datetime.datetime(2000 + i + 2, 1, 1)
  135. ... check = mapB.set_absolute_time(start, end)
  136. ... mapsA.append(mapA)
  137. ... mapsB.append(mapB)
  138. >>> # Build the topology between the two map lists
  139. >>> tb = SpatioTemporalTopologyBuilder()
  140. >>> tb.build(mapsA, mapsB, None)
  141. >>> # Check relations of mapsA
  142. >>> for map in mapsA:
  143. ... print(map.get_temporal_extent_as_tuple())
  144. ... m = map.get_temporal_relations()
  145. ... for key in m.keys():
  146. ... if key not in ["NEXT", "PREV"]:
  147. ... print(key, m[key][0].get_temporal_extent_as_tuple())
  148. (datetime.datetime(2000, 1, 1, 0, 0), datetime.datetime(2001, 1, 1, 0, 0))
  149. ('PRECEDES', (datetime.datetime(2001, 1, 1, 0, 0), datetime.datetime(2002, 1, 1, 0, 0)))
  150. (datetime.datetime(2001, 1, 1, 0, 0), datetime.datetime(2002, 1, 1, 0, 0))
  151. ('PRECEDES', (datetime.datetime(2002, 1, 1, 0, 0), datetime.datetime(2003, 1, 1, 0, 0)))
  152. ('EQUAL', (datetime.datetime(2001, 1, 1, 0, 0), datetime.datetime(2002, 1, 1, 0, 0)))
  153. (datetime.datetime(2002, 1, 1, 0, 0), datetime.datetime(2003, 1, 1, 0, 0))
  154. ('FOLLOWS', (datetime.datetime(2001, 1, 1, 0, 0), datetime.datetime(2002, 1, 1, 0, 0)))
  155. ('PRECEDES', (datetime.datetime(2003, 1, 1, 0, 0), datetime.datetime(2004, 1, 1, 0, 0)))
  156. ('EQUAL', (datetime.datetime(2002, 1, 1, 0, 0), datetime.datetime(2003, 1, 1, 0, 0)))
  157. (datetime.datetime(2003, 1, 1, 0, 0), datetime.datetime(2004, 1, 1, 0, 0))
  158. ('FOLLOWS', (datetime.datetime(2002, 1, 1, 0, 0), datetime.datetime(2003, 1, 1, 0, 0)))
  159. ('EQUAL', (datetime.datetime(2003, 1, 1, 0, 0), datetime.datetime(2004, 1, 1, 0, 0)))
  160. ('PRECEDES', (datetime.datetime(2004, 1, 1, 0, 0), datetime.datetime(2005, 1, 1, 0, 0)))
  161. >>> mapsA = []
  162. >>> mapsB = []
  163. >>> for i in range(4):
  164. ... idA = "a%i@B"%(i)
  165. ... mapA = tgis.RasterDataset(idA)
  166. ... idB = "b%i@B"%(i)
  167. ... mapB = tgis.RasterDataset(idB)
  168. ... start = datetime.datetime(2000 + i, 1, 1)
  169. ... end = datetime.datetime(2000 + i + 1, 1, 1)
  170. ... check = mapA.set_absolute_time(start, end)
  171. ... start = datetime.datetime(2000 + i, 1, 1)
  172. ... end = datetime.datetime(2000 + i + 3, 1, 1)
  173. ... check = mapB.set_absolute_time(start, end)
  174. ... mapsA.append(mapA)
  175. ... mapsB.append(mapB)
  176. >>> # Build the topology between the two map lists
  177. >>> tb = SpatioTemporalTopologyBuilder()
  178. >>> tb.build(mapsA, mapsB, None)
  179. >>> # Check relations of mapsA
  180. >>> for map in mapsA:
  181. ... print(map.get_temporal_extent_as_tuple())
  182. ... m = map.get_temporal_relations()
  183. ... for key in m.keys():
  184. ... if key not in ["NEXT", "PREV"]:
  185. ... print(key, m[key][0].get_temporal_extent_as_tuple())
  186. (datetime.datetime(2000, 1, 1, 0, 0), datetime.datetime(2001, 1, 1, 0, 0))
  187. ('DURING', (datetime.datetime(2000, 1, 1, 0, 0), datetime.datetime(2003, 1, 1, 0, 0)))
  188. ('STARTS', (datetime.datetime(2000, 1, 1, 0, 0), datetime.datetime(2003, 1, 1, 0, 0)))
  189. ('PRECEDES', (datetime.datetime(2001, 1, 1, 0, 0), datetime.datetime(2004, 1, 1, 0, 0)))
  190. (datetime.datetime(2001, 1, 1, 0, 0), datetime.datetime(2002, 1, 1, 0, 0))
  191. ('DURING', (datetime.datetime(2000, 1, 1, 0, 0), datetime.datetime(2003, 1, 1, 0, 0)))
  192. ('STARTS', (datetime.datetime(2001, 1, 1, 0, 0), datetime.datetime(2004, 1, 1, 0, 0)))
  193. ('PRECEDES', (datetime.datetime(2002, 1, 1, 0, 0), datetime.datetime(2005, 1, 1, 0, 0)))
  194. (datetime.datetime(2002, 1, 1, 0, 0), datetime.datetime(2003, 1, 1, 0, 0))
  195. ('PRECEDES', (datetime.datetime(2003, 1, 1, 0, 0), datetime.datetime(2006, 1, 1, 0, 0)))
  196. ('FINISHES', (datetime.datetime(2000, 1, 1, 0, 0), datetime.datetime(2003, 1, 1, 0, 0)))
  197. ('DURING', (datetime.datetime(2000, 1, 1, 0, 0), datetime.datetime(2003, 1, 1, 0, 0)))
  198. ('STARTS', (datetime.datetime(2002, 1, 1, 0, 0), datetime.datetime(2005, 1, 1, 0, 0)))
  199. (datetime.datetime(2003, 1, 1, 0, 0), datetime.datetime(2004, 1, 1, 0, 0))
  200. ('FOLLOWS', (datetime.datetime(2000, 1, 1, 0, 0), datetime.datetime(2003, 1, 1, 0, 0)))
  201. ('DURING', (datetime.datetime(2001, 1, 1, 0, 0), datetime.datetime(2004, 1, 1, 0, 0)))
  202. ('FINISHES', (datetime.datetime(2001, 1, 1, 0, 0), datetime.datetime(2004, 1, 1, 0, 0)))
  203. ('STARTS', (datetime.datetime(2003, 1, 1, 0, 0), datetime.datetime(2006, 1, 1, 0, 0)))
  204. >>> mapsA = []
  205. >>> mapsB = []
  206. >>> for i in range(4):
  207. ... idA = "a%i@B"%(i)
  208. ... mapA = tgis.RasterDataset(idA)
  209. ... idB = "b%i@B"%(i)
  210. ... mapB = tgis.RasterDataset(idB)
  211. ... start = datetime.datetime(2000 + i, 1, 1)
  212. ... end = datetime.datetime(2000 + i + 2, 1, 1)
  213. ... check = mapA.set_absolute_time(start, end)
  214. ... start = datetime.datetime(2000 + i, 1, 1)
  215. ... end = datetime.datetime(2000 + i + 3, 1, 1)
  216. ... check = mapB.set_absolute_time(start, end)
  217. ... mapsA.append(mapA)
  218. ... mapsB.append(mapB)
  219. >>> # Build the topology between the two map lists
  220. >>> tb = SpatioTemporalTopologyBuilder()
  221. >>> tb.build(mapsA, mapsB, None)
  222. >>> # Check relations of mapsA
  223. >>> for map in mapsA:
  224. ... print(map.get_temporal_extent_as_tuple())
  225. ... m = map.get_temporal_relations()
  226. ... for key in m.keys():
  227. ... if key not in ["NEXT", "PREV"]:
  228. ... print(key, m[key][0].get_temporal_extent_as_tuple())
  229. (datetime.datetime(2000, 1, 1, 0, 0), datetime.datetime(2002, 1, 1, 0, 0))
  230. ('OVERLAPS', (datetime.datetime(2001, 1, 1, 0, 0), datetime.datetime(2004, 1, 1, 0, 0)))
  231. ('DURING', (datetime.datetime(2000, 1, 1, 0, 0), datetime.datetime(2003, 1, 1, 0, 0)))
  232. ('STARTS', (datetime.datetime(2000, 1, 1, 0, 0), datetime.datetime(2003, 1, 1, 0, 0)))
  233. ('PRECEDES', (datetime.datetime(2002, 1, 1, 0, 0), datetime.datetime(2005, 1, 1, 0, 0)))
  234. (datetime.datetime(2001, 1, 1, 0, 0), datetime.datetime(2003, 1, 1, 0, 0))
  235. ('OVERLAPS', (datetime.datetime(2002, 1, 1, 0, 0), datetime.datetime(2005, 1, 1, 0, 0)))
  236. ('PRECEDES', (datetime.datetime(2003, 1, 1, 0, 0), datetime.datetime(2006, 1, 1, 0, 0)))
  237. ('FINISHES', (datetime.datetime(2000, 1, 1, 0, 0), datetime.datetime(2003, 1, 1, 0, 0)))
  238. ('DURING', (datetime.datetime(2000, 1, 1, 0, 0), datetime.datetime(2003, 1, 1, 0, 0)))
  239. ('STARTS', (datetime.datetime(2001, 1, 1, 0, 0), datetime.datetime(2004, 1, 1, 0, 0)))
  240. (datetime.datetime(2002, 1, 1, 0, 0), datetime.datetime(2004, 1, 1, 0, 0))
  241. ('OVERLAPS', (datetime.datetime(2003, 1, 1, 0, 0), datetime.datetime(2006, 1, 1, 0, 0)))
  242. ('OVERLAPPED', (datetime.datetime(2000, 1, 1, 0, 0), datetime.datetime(2003, 1, 1, 0, 0)))
  243. ('FINISHES', (datetime.datetime(2001, 1, 1, 0, 0), datetime.datetime(2004, 1, 1, 0, 0)))
  244. ('DURING', (datetime.datetime(2001, 1, 1, 0, 0), datetime.datetime(2004, 1, 1, 0, 0)))
  245. ('STARTS', (datetime.datetime(2002, 1, 1, 0, 0), datetime.datetime(2005, 1, 1, 0, 0)))
  246. (datetime.datetime(2003, 1, 1, 0, 0), datetime.datetime(2005, 1, 1, 0, 0))
  247. ('OVERLAPPED', (datetime.datetime(2001, 1, 1, 0, 0), datetime.datetime(2004, 1, 1, 0, 0)))
  248. ('DURING', (datetime.datetime(2002, 1, 1, 0, 0), datetime.datetime(2005, 1, 1, 0, 0)))
  249. ('FINISHES', (datetime.datetime(2002, 1, 1, 0, 0), datetime.datetime(2005, 1, 1, 0, 0)))
  250. ('STARTS', (datetime.datetime(2003, 1, 1, 0, 0), datetime.datetime(2006, 1, 1, 0, 0)))
  251. ('FOLLOWS', (datetime.datetime(2000, 1, 1, 0, 0), datetime.datetime(2003, 1, 1, 0, 0)))
  252. @endcode
  253. """
  254. def __init__(self):
  255. self._reset()
  256. # 0001-01-01 00:00:00
  257. self._timeref = datetime(1,1,1)
  258. def _reset(self):
  259. self._store = {}
  260. self._first = None
  261. self._iteratable = False
  262. def _set_first(self, first):
  263. self._first = first
  264. self._insert(first)
  265. def _detect_first(self):
  266. if len(self) > 0:
  267. prev_ = self._store.values()[0]
  268. while prev_ is not None:
  269. self._first = prev_
  270. prev_ = prev_.prev()
  271. def _insert(self, t):
  272. self._store[t.get_id()] = t
  273. def get_first(self):
  274. """!Return the first map with the earliest start time
  275. @return The map with the earliest start time
  276. """
  277. return self._first
  278. def _build_internal_iteratable(self, maps, spatial):
  279. """!Build an iteratable temporal topology structure for all maps in
  280. the list and store the maps internally
  281. Basically the "next" and "prev" relations will be set in the
  282. temporal topology structure of each map
  283. The maps will be added to the object, so they can be
  284. accessed using the iterator of this class
  285. @param maps A sorted (by start_time)list of abstract_dataset
  286. objects with initiated temporal extent
  287. """
  288. self._build_iteratable(maps, spatial)
  289. for _map in maps:
  290. self._insert(_map)
  291. # Detect the first map
  292. self._detect_first()
  293. def _build_iteratable(self, maps, spatial):
  294. """!Build an iteratable temporal topology structure for
  295. all maps in the list
  296. Basically the "next" and "prev" relations will be set in
  297. the temporal topology structure of each map.
  298. @param maps A sorted (by start_time)list of abstract_dataset
  299. objects with initiated temporal extent
  300. """
  301. # for i in xrange(len(maps)):
  302. # offset = i + 1
  303. # for j in xrange(offset, len(maps)):
  304. # # Get the temporal relationship
  305. # relation = maps[j].temporal_relation(maps[i])
  306. #
  307. # # Build the next reference
  308. # if relation != "equal" and relation != "started":
  309. # maps[i].set_next(maps[j])
  310. # break
  311. # First we need to order the map list chronologically
  312. sorted_maps = sorted(
  313. maps, key=AbstractDatasetComparisonKeyStartTime)
  314. for i in xrange(len(sorted_maps) - 1):
  315. sorted_maps[i].set_next(sorted_maps[i + 1])
  316. for map_ in sorted_maps:
  317. next_ = map_.next()
  318. if next_:
  319. next_.set_prev(map_)
  320. map_.set_temporal_topology_build_true()
  321. if spatial is not None:
  322. map_.set_spatial_topology_build_true()
  323. def _map_to_rect(self, tree, map_, spatial=None):
  324. """!Use the spatio-temporal extent of a map to create and
  325. return a RTree rectange
  326. @param spatial This indicates if the spatial topology is created as well:
  327. spatial can be None (no spatial topology), "2D" using west, east,
  328. #south, north or "3D" using west, east, south, north, bottom, top
  329. """
  330. rect = vector.RTreeAllocRect(tree)
  331. start, end = map_.get_temporal_extent_as_tuple()
  332. if not end:
  333. end = start
  334. if map_.is_time_absolute():
  335. start = time_delta_to_relative_time(start - self._timeref)
  336. end = time_delta_to_relative_time(end - self._timeref)
  337. if spatial is None:
  338. vector.RTreeSetRect1D(rect, tree, float(start), float(end))
  339. elif spatial == "2D":
  340. north, south, east, west, top, bottom = map_.get_spatial_extent_as_tuple()
  341. vector.RTreeSetRect3D(rect, tree, west, east, south, north,
  342. float(start), float(end))
  343. elif spatial == "3D":
  344. north, south, east, west, top, bottom = map_.get_spatial_extent_as_tuple()
  345. vector.RTreeSetRect4D(rect, tree, west, east, south, north,
  346. bottom, top, float(start), float(end))
  347. return rect
  348. def _build_rtree(self, maps, spatial=None):
  349. """!Build and return the 1-4 dimensional R*-Tree
  350. @param spatial This indicates if the spatial topology is created as well:
  351. spatial can be None (no spatial topology), "2D" using west, east,
  352. south, north or "3D" using west, east, south, north, bottom, top
  353. """
  354. dim = 1
  355. if spatial == "2D":
  356. dim = 3
  357. if spatial == "3D":
  358. dim = 4
  359. tree = vector.RTreeCreateTree(-1, 0, dim)
  360. for i in xrange(len(maps)):
  361. rect = self._map_to_rect(tree, maps[i], spatial)
  362. vector.RTreeInsertRect(rect, i + 1, tree)
  363. return tree
  364. def build(self, mapsA, mapsB=None, spatial=None):
  365. """!Build the spatio-temporal topology structure between
  366. one or two unordered lists of abstract dataset objects
  367. This method builds the temporal or spatio-temporal topology from mapsA to
  368. mapsB and vice verse. The spatio-temporal topology structure of each map
  369. will be reseted and rebuild for mapsA and mapsB.
  370. After building the temporal or spatio-temporal topology the modified
  371. map objects of mapsA can be accessed
  372. in the same way as a dictionary using there id.
  373. The implemented iterator assures
  374. the chronological iteration over the mapsA.
  375. @param mapsA A list of abstract_dataset
  376. objects with initiated spatio-temporal extent
  377. @param mapsB An optional list of abstract_dataset
  378. objects with initiated spatio-temporal extent
  379. @param spatial This indicates if the spatial topology is created as well:
  380. spatial can be None (no spatial topology), "2D" using west, east,
  381. south, north or "3D" using west, east, south, north, bottom, top
  382. """
  383. identical = False
  384. if mapsA == mapsB:
  385. identical = True
  386. if mapsB == None:
  387. mapsB = mapsA
  388. idetnical = True
  389. for map_ in mapsA:
  390. map_.reset_topology()
  391. if not identical:
  392. for map_ in mapsB:
  393. map_.reset_topology()
  394. tree = self. _build_rtree(mapsA, spatial)
  395. for j in xrange(len(mapsB)):
  396. list_ = gis.ilist()
  397. rect = self._map_to_rect(tree, mapsB[j], spatial)
  398. vector.RTreeSearch2(tree, rect, byref(list_))
  399. vector.RTreeFreeRect(rect)
  400. for k in xrange(list_.n_values):
  401. i = list_.value[k] - 1
  402. # Get the temporal relationship
  403. relation = mapsB[j].temporal_relation(mapsA[i])
  404. A = mapsA[i]
  405. B = mapsB[j]
  406. set_temoral_relationship(A, B, relation)
  407. if spatial is not None:
  408. relation = mapsB[j].spatial_relation(mapsA[i])
  409. set_spatial_relationship(A, B, relation)
  410. self._build_internal_iteratable(mapsA, spatial)
  411. if not identical and mapsB != None:
  412. self._build_iteratable(mapsB, spatial)
  413. vector.RTreeDestroyTree(tree)
  414. def __iter__(self):
  415. start_ = self._first
  416. while start_ is not None:
  417. yield start_
  418. start_ = start_.next()
  419. def __getitem__(self, index):
  420. return self._store[index.get_id()]
  421. def __len__(self):
  422. return len(self._store)
  423. def __contains__(self, _map):
  424. return _map in self._store.values()
  425. ###############################################################################
  426. def set_temoral_relationship(A, B, relation):
  427. if relation == "equal":
  428. if B != A:
  429. if not B.get_equal() or \
  430. (B.get_equal() and \
  431. A not in B.get_equal()):
  432. B.append_equal(A)
  433. if not A.get_equal() or \
  434. (A.get_equal() and \
  435. B not in A.get_equal()):
  436. A.append_equal(B)
  437. elif relation == "follows":
  438. if not B.get_follows() or \
  439. (B.get_follows() and \
  440. A not in B.get_follows()):
  441. B.append_follows(A)
  442. if not A.get_precedes() or \
  443. (A.get_precedes() and
  444. B not in A.get_precedes()):
  445. A.append_precedes(B)
  446. elif relation == "precedes":
  447. if not B.get_precedes() or \
  448. (B.get_precedes() and \
  449. A not in B.get_precedes()):
  450. B.append_precedes(A)
  451. if not A.get_follows() or \
  452. (A.get_follows() and \
  453. B not in A.get_follows()):
  454. A.append_follows(B)
  455. elif relation == "during" or relation == "starts" or \
  456. relation == "finishes":
  457. if not B.get_during() or \
  458. (B.get_during() and \
  459. A not in B.get_during()):
  460. B.append_during(A)
  461. if not A.get_contains() or \
  462. (A.get_contains() and \
  463. B not in A.get_contains()):
  464. A.append_contains(B)
  465. if relation == "starts":
  466. if not B.get_starts() or \
  467. (B.get_starts() and \
  468. A not in B.get_starts()):
  469. B.append_starts(A)
  470. if not A.get_started() or \
  471. (A.get_started() and \
  472. B not in A.get_started()):
  473. A.append_started(B)
  474. if relation == "finishes":
  475. if not B.get_finishes() or \
  476. (B.get_finishes() and \
  477. A not in B.get_finishes()):
  478. B.append_finishes(A)
  479. if not A.get_finished() or \
  480. (A.get_finished() and \
  481. B not in A.get_finished()):
  482. A.append_finished(B)
  483. elif relation == "contains" or relation == "started" or \
  484. relation == "finished":
  485. if not B.get_contains() or \
  486. (B.get_contains() and \
  487. A not in B.get_contains()):
  488. B.append_contains(A)
  489. if not A.get_during() or \
  490. (A.get_during() and \
  491. B not in A.get_during()):
  492. A.append_during(B)
  493. if relation == "started":
  494. if not B.get_started() or \
  495. (B.get_started() and \
  496. A not in B.get_started()):
  497. B.append_started(A)
  498. if not A.get_starts() or \
  499. (A.get_starts() and \
  500. B not in A.get_starts()):
  501. A.append_starts(B)
  502. if relation == "finished":
  503. if not B.get_finished() or \
  504. (B.get_finished() and \
  505. A not in B.get_finished()):
  506. B.append_finished(A)
  507. if not A.get_finishes() or \
  508. (A.get_finishes() and \
  509. B not in A.get_finishes()):
  510. A.append_finishes(B)
  511. elif relation == "overlaps":
  512. if not B.get_overlaps() or \
  513. (B.get_overlaps() and \
  514. A not in B.get_overlaps()):
  515. B.append_overlaps(A)
  516. if not A.get_overlapped() or \
  517. (A.get_overlapped() and \
  518. B not in A.get_overlapped()):
  519. A.append_overlapped(B)
  520. elif relation == "overlapped":
  521. if not B.get_overlapped() or \
  522. (B.get_overlapped() and \
  523. A not in B.get_overlapped()):
  524. B.append_overlapped(A)
  525. if not A.get_overlaps() or \
  526. (A.get_overlaps() and \
  527. B not in A.get_overlaps()):
  528. A.append_overlaps(B)
  529. ###############################################################################
  530. def set_spatial_relationship(A, B, relation):
  531. if relation == "equivalent":
  532. if B != A:
  533. if not B.get_equivalent() or \
  534. (B.get_equivalent() and \
  535. A not in B.get_equivalent()):
  536. B.append_equivalent(A)
  537. if not A.get_equivalent() or \
  538. (A.get_equivalent() and \
  539. B not in A.get_equivalent()):
  540. A.append_equivalent(B)
  541. elif relation == "overlap":
  542. if not B.get_overlap() or \
  543. (B.get_overlap() and \
  544. A not in B.get_overlap()):
  545. B.append_overlap(A)
  546. if not A.get_overlap() or \
  547. (A.get_overlap() and
  548. B not in A.get_overlap()):
  549. A.append_overlap(B)
  550. elif relation == "meet":
  551. if not B.get_meet() or \
  552. (B.get_meet() and \
  553. A not in B.get_meet()):
  554. B.append_meet(A)
  555. if not A.get_meet() or \
  556. (A.get_meet() and
  557. B not in A.get_meet()):
  558. A.append_meet(B)
  559. elif relation == "contain":
  560. if not B.get_contain() or \
  561. (B.get_contain() and \
  562. A not in B.get_contain()):
  563. B.append_contain(A)
  564. if not A.get_in() or \
  565. (A.get_in() and \
  566. B not in A.get_in()):
  567. A.append_in(B)
  568. elif relation == "in":
  569. if not B.get_in() or \
  570. (B.get_in() and \
  571. A not in B.get_in()):
  572. B.append_in(A)
  573. if not A.get_contain() or \
  574. (A.get_contain() and \
  575. B not in A.get_contain()):
  576. A.append_contain(B)
  577. elif relation == "cover":
  578. if not B.get_cover() or \
  579. (B.get_cover() and \
  580. A not in B.get_cover()):
  581. B.append_cover(A)
  582. if not A.get_covered() or \
  583. (A.get_covered() and \
  584. B not in A.get_covered()):
  585. A.append_covered(B)
  586. elif relation == "covered":
  587. if not B.get_covered() or \
  588. (B.get_covered() and \
  589. A not in B.get_covered()):
  590. B.append_covered(A)
  591. if not A.get_cover() or \
  592. (A.get_cover() and \
  593. B not in A.get_cover()):
  594. A.append_cover(B)
  595. ###############################################################################
  596. def print_temporal_topology_relationships(maps1, maps2=None, dbif=None):
  597. """!Print the temporal relationships of the
  598. map lists maps1 and maps2 to stdout.
  599. @param maps1 A list of abstract_dataset
  600. objects with initiated temporal extent
  601. @param maps2 An optional list of abstract_dataset
  602. objects with initiated temporal extent
  603. @param dbif The database interface to be used
  604. """
  605. tb = SpatioTemporalTopologyBuilder()
  606. tb.build(maps1, maps2)
  607. dbif, connected = init_dbif(dbif)
  608. for _map in tb:
  609. _map.select(dbif)
  610. _map.print_info()
  611. if connected:
  612. dbif.close()
  613. return
  614. ###############################################################################
  615. def print_spatio_temporal_topology_relationships(maps1, maps2=None, spatial="2D", dbif=None):
  616. """!Print the temporal relationships of the
  617. map lists maps1 and maps2 to stdout.
  618. @param maps1 A list of abstract_dataset
  619. objects with initiated temporal extent
  620. @param maps2 An optional list of abstract_dataset
  621. objects with initiated temporal extent
  622. @param spatial The dimension of the spatial extent to be used: "2D" using west, east,
  623. south, north or "3D" using west, east, south, north, bottom, top
  624. @param dbif The database interface to be used
  625. """
  626. tb = SpatioTemporalTopologyBuilder()
  627. tb.build(maps1, maps2, spatial)
  628. dbif, connected = init_dbif(dbif)
  629. for _map in tb:
  630. _map.select(dbif)
  631. _map.print_info()
  632. if connected:
  633. dbif.close()
  634. return
  635. ###############################################################################
  636. def count_temporal_topology_relationships(maps1, maps2=None, dbif=None):
  637. """!Count the temporal relations of a single list of maps or between two lists of maps
  638. @param maps1 A list of abstract_dataset
  639. objects with initiated temporal extent
  640. @param maps2 A list of abstract_dataset
  641. objects with initiated temporal extent
  642. @param dbif The database interface to be used
  643. @return A dictionary with counted temporal relationships
  644. """
  645. tb = SpatioTemporalTopologyBuilder()
  646. tb.build(maps1, maps2)
  647. dbif, connected = init_dbif(dbif)
  648. relations = None
  649. for _map in tb:
  650. if relations != None:
  651. r = _map.get_number_of_relations()
  652. for k in r.keys():
  653. relations[k] += r[k]
  654. else:
  655. relations = _map.get_number_of_relations()
  656. if connected:
  657. dbif.close()
  658. return relations
  659. ###############################################################################
  660. def create_temporal_relation_sql_where_statement(
  661. start, end, use_start=True, use_during=False,
  662. use_overlap=False, use_contain=False, use_equal=False,
  663. use_follows=False, use_precedes=False):
  664. """!Create a SQL WHERE statement for temporal relation selection of maps in space time datasets
  665. @param start The start time
  666. @param end The end time
  667. @param use_start Select maps of which the start time is located in the selection granule
  668. @verbatim
  669. map : s
  670. granule: s-----------------e
  671. map : s--------------------e
  672. granule: s-----------------e
  673. map : s--------e
  674. granule: s-----------------e
  675. @endverbatim
  676. @param use_during Select maps which are temporal during the selection granule
  677. @verbatim
  678. map : s-----------e
  679. granule: s-----------------e
  680. @endverbatim
  681. @param use_overlap Select maps which temporal overlap the selection granule
  682. @verbatim
  683. map : s-----------e
  684. granule: s-----------------e
  685. map : s-----------e
  686. granule: s----------e
  687. @endverbatim
  688. @param use_contain Select maps which temporally contain the selection granule
  689. @verbatim
  690. map : s-----------------e
  691. granule: s-----------e
  692. @endverbatim
  693. @param use_equal Select maps which temporally equal to the selection granule
  694. @verbatim
  695. map : s-----------e
  696. granule: s-----------e
  697. @endverbatim
  698. @param use_follows Select maps which temporally follow the selection granule
  699. @verbatim
  700. map : s-----------e
  701. granule: s-----------e
  702. @endverbatim
  703. @param use_precedes Select maps which temporally precedes the selection granule
  704. @verbatim
  705. map : s-----------e
  706. granule: s-----------e
  707. @endverbatim
  708. Usage:
  709. @code
  710. >>> # Relative time
  711. >>> start = 1
  712. >>> end = 2
  713. >>> create_temporal_relation_sql_where_statement(start, end,
  714. ... use_start=False)
  715. >>> create_temporal_relation_sql_where_statement(start, end)
  716. '((start_time >= 1 and start_time < 2) )'
  717. >>> create_temporal_relation_sql_where_statement(start, end,
  718. ... use_start=True)
  719. '((start_time >= 1 and start_time < 2) )'
  720. >>> create_temporal_relation_sql_where_statement(start, end,
  721. ... use_start=False, use_during=True)
  722. '(((start_time > 1 and end_time < 2) OR (start_time >= 1 and end_time < 2) OR (start_time > 1 and end_time <= 2)))'
  723. >>> create_temporal_relation_sql_where_statement(start, end,
  724. ... use_start=False, use_overlap=True)
  725. '(((start_time < 1 and end_time > 1 and end_time < 2) OR (start_time < 2 and start_time > 1 and end_time > 2)))'
  726. >>> create_temporal_relation_sql_where_statement(start, end,
  727. ... use_start=False, use_contain=True)
  728. '(((start_time < 1 and end_time > 2) OR (start_time <= 1 and end_time > 2) OR (start_time < 1 and end_time >= 2)))'
  729. >>> create_temporal_relation_sql_where_statement(start, end,
  730. ... use_start=False, use_equal=True)
  731. '((start_time = 1 and end_time = 2))'
  732. >>> create_temporal_relation_sql_where_statement(start, end,
  733. ... use_start=False, use_follows=True)
  734. '((start_time = 2))'
  735. >>> create_temporal_relation_sql_where_statement(start, end,
  736. ... use_start=False, use_precedes=True)
  737. '((end_time = 1))'
  738. >>> create_temporal_relation_sql_where_statement(start, end,
  739. ... use_start=True, use_during=True, use_overlap=True, use_contain=True,
  740. ... use_equal=True, use_follows=True, use_precedes=True)
  741. '((start_time >= 1 and start_time < 2) OR ((start_time > 1 and end_time < 2) OR (start_time >= 1 and end_time < 2) OR (start_time > 1 and end_time <= 2)) OR ((start_time < 1 and end_time > 1 and end_time < 2) OR (start_time < 2 and start_time > 1 and end_time > 2)) OR ((start_time < 1 and end_time > 2) OR (start_time <= 1 and end_time > 2) OR (start_time < 1 and end_time >= 2)) OR (start_time = 1 and end_time = 2) OR (start_time = 2) OR (end_time = 1))'
  742. >>> # Absolute time
  743. >>> start = datetime(2001, 1, 1, 12, 30)
  744. >>> end = datetime(2001, 3, 31, 14, 30)
  745. >>> create_temporal_relation_sql_where_statement(start, end,
  746. ... use_start=False)
  747. >>> create_temporal_relation_sql_where_statement(start, end)
  748. "((start_time >= '2001-01-01 12:30:00' and start_time < '2001-03-31 14:30:00') )"
  749. >>> create_temporal_relation_sql_where_statement(start, end,
  750. ... use_start=True)
  751. "((start_time >= '2001-01-01 12:30:00' and start_time < '2001-03-31 14:30:00') )"
  752. >>> create_temporal_relation_sql_where_statement(start, end,
  753. ... use_start=False, use_during=True)
  754. "(((start_time > '2001-01-01 12:30:00' and end_time < '2001-03-31 14:30:00') OR (start_time >= '2001-01-01 12:30:00' and end_time < '2001-03-31 14:30:00') OR (start_time > '2001-01-01 12:30:00' and end_time <= '2001-03-31 14:30:00')))"
  755. >>> create_temporal_relation_sql_where_statement(start, end,
  756. ... use_start=False, use_overlap=True)
  757. "(((start_time < '2001-01-01 12:30:00' and end_time > '2001-01-01 12:30:00' and end_time < '2001-03-31 14:30:00') OR (start_time < '2001-03-31 14:30:00' and start_time > '2001-01-01 12:30:00' and end_time > '2001-03-31 14:30:00')))"
  758. >>> create_temporal_relation_sql_where_statement(start, end,
  759. ... use_start=False, use_contain=True)
  760. "(((start_time < '2001-01-01 12:30:00' and end_time > '2001-03-31 14:30:00') OR (start_time <= '2001-01-01 12:30:00' and end_time > '2001-03-31 14:30:00') OR (start_time < '2001-01-01 12:30:00' and end_time >= '2001-03-31 14:30:00')))"
  761. >>> create_temporal_relation_sql_where_statement(start, end,
  762. ... use_start=False, use_equal=True)
  763. "((start_time = '2001-01-01 12:30:00' and end_time = '2001-03-31 14:30:00'))"
  764. >>> create_temporal_relation_sql_where_statement(start, end,
  765. ... use_start=False, use_follows=True)
  766. "((start_time = '2001-03-31 14:30:00'))"
  767. >>> create_temporal_relation_sql_where_statement(start, end,
  768. ... use_start=False, use_precedes=True)
  769. "((end_time = '2001-01-01 12:30:00'))"
  770. >>> create_temporal_relation_sql_where_statement(start, end,
  771. ... use_start=True, use_during=True, use_overlap=True, use_contain=True,
  772. ... use_equal=True, use_follows=True, use_precedes=True)
  773. "((start_time >= '2001-01-01 12:30:00' and start_time < '2001-03-31 14:30:00') OR ((start_time > '2001-01-01 12:30:00' and end_time < '2001-03-31 14:30:00') OR (start_time >= '2001-01-01 12:30:00' and end_time < '2001-03-31 14:30:00') OR (start_time > '2001-01-01 12:30:00' and end_time <= '2001-03-31 14:30:00')) OR ((start_time < '2001-01-01 12:30:00' and end_time > '2001-01-01 12:30:00' and end_time < '2001-03-31 14:30:00') OR (start_time < '2001-03-31 14:30:00' and start_time > '2001-01-01 12:30:00' and end_time > '2001-03-31 14:30:00')) OR ((start_time < '2001-01-01 12:30:00' and end_time > '2001-03-31 14:30:00') OR (start_time <= '2001-01-01 12:30:00' and end_time > '2001-03-31 14:30:00') OR (start_time < '2001-01-01 12:30:00' and end_time >= '2001-03-31 14:30:00')) OR (start_time = '2001-01-01 12:30:00' and end_time = '2001-03-31 14:30:00') OR (start_time = '2001-03-31 14:30:00') OR (end_time = '2001-01-01 12:30:00'))"
  774. @endcode
  775. """
  776. where = "("
  777. if use_start:
  778. if isinstance(start, datetime):
  779. where += "(start_time >= '%s' and start_time < '%s') " % (start, end)
  780. else:
  781. where += "(start_time >= %i and start_time < %i) " % (start, end)
  782. if use_during:
  783. if use_start:
  784. where += " OR "
  785. if isinstance(start, datetime):
  786. where += "((start_time > '%s' and end_time < '%s') OR " % (start, end)
  787. where += "(start_time >= '%s' and end_time < '%s') OR " % (start, end)
  788. where += "(start_time > '%s' and end_time <= '%s'))" % (start, end)
  789. else:
  790. where += "((start_time > %i and end_time < %i) OR " % (start, end)
  791. where += "(start_time >= %i and end_time < %i) OR " % (start, end)
  792. where += "(start_time > %i and end_time <= %i))" % (start, end)
  793. if use_overlap:
  794. if use_start or use_during:
  795. where += " OR "
  796. if isinstance(start, datetime):
  797. where += "((start_time < '%s' and end_time > '%s' and end_time < '%s') OR " % (start, start, end)
  798. where += "(start_time < '%s' and start_time > '%s' and end_time > '%s'))" % (end, start, end)
  799. else:
  800. where += "((start_time < %i and end_time > %i and end_time < %i) OR " % (start, start, end)
  801. where += "(start_time < %i and start_time > %i and end_time > %i))" % (end, start, end)
  802. if use_contain:
  803. if use_start or use_during or use_overlap:
  804. where += " OR "
  805. if isinstance(start, datetime):
  806. where += "((start_time < '%s' and end_time > '%s') OR " % (start, end)
  807. where += "(start_time <= '%s' and end_time > '%s') OR " % (start, end)
  808. where += "(start_time < '%s' and end_time >= '%s'))" % (start, end)
  809. else:
  810. where += "((start_time < %i and end_time > %i) OR " % (start, end)
  811. where += "(start_time <= %i and end_time > %i) OR " % (start, end)
  812. where += "(start_time < %i and end_time >= %i))" % (start, end)
  813. if use_equal:
  814. if use_start or use_during or use_overlap or use_contain:
  815. where += " OR "
  816. if isinstance(start, datetime):
  817. where += "(start_time = '%s' and end_time = '%s')" % (start, end)
  818. else:
  819. where += "(start_time = %i and end_time = %i)" % (start, end)
  820. if use_follows:
  821. if use_start or use_during or use_overlap or use_contain or use_equal:
  822. where += " OR "
  823. if isinstance(start, datetime):
  824. where += "(start_time = '%s')" % (end)
  825. else:
  826. where += "(start_time = %i)" % (end)
  827. if use_precedes:
  828. if use_start or use_during or use_overlap or use_contain or use_equal \
  829. or use_follows:
  830. where += " OR "
  831. if isinstance(start, datetime):
  832. where += "(end_time = '%s')" % (start)
  833. else:
  834. where += "(end_time = %i)" % (start)
  835. where += ")"
  836. # Catch empty where statement
  837. if where == "()":
  838. where = None
  839. return where
  840. ###############################################################################
  841. if __name__ == "__main__":
  842. import doctest
  843. doctest.testmod()