spatio_temporal_relationships.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761
  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. # Using the next and previous methods, we can iterate over the
  39. # topological related maps in this way
  40. _first = tb.get_first()
  41. while _first:
  42. _first.print_topology_info()
  43. _first = _first.next()
  44. # Dictionary like accessed
  45. _map = tb["name@mapset"]
  46. @endcode
  47. """
  48. def __init__(self):
  49. self._reset()
  50. # 0001-01-01 00:00:00
  51. self._timeref = datetime(1,1,1)
  52. def _reset(self):
  53. self._store = {}
  54. self._first = None
  55. self._iteratable = False
  56. def _set_first(self, first):
  57. self._first = first
  58. self._insert(first)
  59. def _detect_first(self):
  60. if len(self) > 0:
  61. prev_ = self._store.values()[0]
  62. while prev_ is not None:
  63. self._first = prev_
  64. prev_ = prev_.prev()
  65. def _insert(self, t):
  66. self._store[t.get_id()] = t
  67. def get_first(self):
  68. """!Return the first map with the earliest start time
  69. @return The map with the earliest start time
  70. """
  71. return self._first
  72. def _build_internal_iteratable(self, maps):
  73. """!Build an iteratable temporal topology structure for all maps in
  74. the list and store the maps internally
  75. Basically the "next" and "prev" relations will be set in the
  76. temporal topology structure of each map
  77. The maps will be added to the object, so they can be
  78. accessed using the iterator of this class
  79. @param maps A sorted (by start_time)list of abstract_dataset
  80. objects with initiated temporal extent
  81. """
  82. self._build_iteratable(maps)
  83. for _map in maps:
  84. self._insert(_map)
  85. # Detect the first map
  86. self._detect_first()
  87. def _build_iteratable(self, maps):
  88. """!Build an iteratable temporal topology structure for
  89. all maps in the list
  90. Basically the "next" and "prev" relations will be set in
  91. the temporal topology structure of each map.
  92. @param maps A sorted (by start_time)list of abstract_dataset
  93. objects with initiated temporal extent
  94. """
  95. # for i in xrange(len(maps)):
  96. # offset = i + 1
  97. # for j in xrange(offset, len(maps)):
  98. # # Get the temporal relationship
  99. # relation = maps[j].temporal_relation(maps[i])
  100. #
  101. # # Build the next reference
  102. # if relation != "equal" and relation != "started":
  103. # maps[i].set_next(maps[j])
  104. # break
  105. # First we need to order the map list chronologically
  106. sorted_maps = sorted(
  107. maps, key=AbstractDatasetComparisonKeyStartTime)
  108. for i in xrange(len(sorted_maps) - 1):
  109. sorted_maps[i].set_next(sorted_maps[i + 1])
  110. for map_ in sorted_maps:
  111. next_ = map_.next()
  112. if next_:
  113. next_.set_prev(map_)
  114. map_.set_temporal_topology_build_true()
  115. def _map_to_rect(self, tree, map_, spatial=None):
  116. """Use the temporal extent of a map to create and return a RTree rectange
  117. @param spatial This indicates if the spatial topology is created as well:
  118. spatial can be None (no spatial topology), "2D" using west, east,
  119. #south, north or "3D" using west, east, south, north, bottom, top
  120. """
  121. rect = vector.RTreeAllocRect(tree)
  122. start, end = map_.get_valid_time()
  123. if not end:
  124. end = start
  125. if map_.is_time_absolute():
  126. start = time_delta_to_relative_time(start - self._timeref)
  127. end = time_delta_to_relative_time(end - self._timeref)
  128. if spatial is None:
  129. vector.RTreeSetRect1D(rect, tree, float(start), float(end))
  130. elif spatial == "2D":
  131. north, south, east, west, top, bottom = map_.get_spatial_extent()
  132. vector.RTreeSetRect3D(rect, tree, west, east, south, north,
  133. float(start), float(end))
  134. elif spatial == "3D":
  135. north, south, east, west, top, bottom = map_.get_spatial_extent()
  136. vector.RTreeSetRect4D(rect, tree, west, east, south, north,
  137. bottom, top, float(start), float(end))
  138. return rect
  139. def _build_rtree(self, maps, spatial=None):
  140. """Build and return the 1-4 dimensional R*-Tree
  141. @param spatial This indicates if the spatial topology is created as well:
  142. spatial can be None (no spatial topology), "2D" using west, east,
  143. south, north or "3D" using west, east, south, north, bottom, top
  144. """
  145. dim = 1
  146. if spatial == "2D":
  147. dim = 3
  148. if spatial == "3D":
  149. dim = 4
  150. tree = vector.RTreeCreateTree(-1, 0, dim)
  151. for i in xrange(len(maps)):
  152. rect = self._map_to_rect(tree, maps[i], spatial)
  153. vector.RTreeInsertRect(rect, i + 1, tree)
  154. return tree
  155. def build(self, mapsA, mapsB=None, spatial=None):
  156. """!Build the spatio-temporal topology structure between
  157. one or two unordered lists of abstract dataset objects
  158. This method builds the temporal or spatio-temporal topology from mapsA to
  159. mapsB and vice verse. The spatio-temporal topology structure of each map
  160. will be reseted and rebuild for mapsA and mapsB.
  161. After building the temporal or spatio-temporal topology the modified
  162. map objects of mapsA can be accessed
  163. in the same way as a dictionary using there id.
  164. The implemented iterator assures
  165. the chronological iteration over the mapsA.
  166. @param mapsA A list of abstract_dataset
  167. objects with initiated temporal extent
  168. @param mapsB An optional list of abstract_dataset
  169. objects with initiated temporal extent
  170. @param spatial This indicates if the spatial topology is created as well:
  171. spatial can be None (no spatial topology), "2D" using west, east,
  172. south, north or "3D" using west, east, south, north, bottom, top
  173. """
  174. if spatial is not None:
  175. dbif, connected = init_dbif(None)
  176. identical = False
  177. if mapsA == mapsB:
  178. identical = True
  179. if mapsB == None:
  180. mapsB = mapsA
  181. idetnical = True
  182. for map_ in mapsA:
  183. map_.reset_topology()
  184. # Spatial extent from the database
  185. if spatial is not None:
  186. map_.select(dbif)
  187. if not identical:
  188. for map_ in mapsB:
  189. map_.reset_topology()
  190. # Spatial extent from the database
  191. if spatial is not None:
  192. map_.select(dbif)
  193. tree = self. _build_rtree(mapsA, spatial)
  194. for j in xrange(len(mapsB)):
  195. list_ = gis.ilist()
  196. rect = self._map_to_rect(tree, mapsB[j], spatial)
  197. num = vector.RTreeSearch2(tree, rect, byref(list_))
  198. vector.RTreeFreeRect(rect)
  199. for k in xrange(list_.n_values):
  200. i = list_.value[k] - 1
  201. # Get the temporal relationship
  202. relation = mapsB[j].temporal_relation(mapsA[i])
  203. A = mapsA[i]
  204. B = mapsB[j]
  205. set_temoral_relationship(A, B, relation)
  206. if spatial is not None:
  207. relation = mapsB[j].spatial_relation(mapsA[i])
  208. set_spatial_relationship(A, B, relation)
  209. self._build_internal_iteratable(mapsA)
  210. if not identical and mapsB != None:
  211. self._build_iteratable(mapsB)
  212. vector.RTreeDestroyTree(tree)
  213. if spatial is not None:
  214. if connected:
  215. dbif.close()
  216. def __iter__(self):
  217. start_ = self._first
  218. while start_ is not None:
  219. yield start_
  220. start_ = start_.next()
  221. def __getitem__(self, index):
  222. return self._store[index.get_id()]
  223. def __len__(self):
  224. return len(self._store)
  225. def __contains__(self, _map):
  226. return _map in self._store.values()
  227. ###############################################################################
  228. def set_temoral_relationship(A, B, relation):
  229. if relation == "equal":
  230. if B != A:
  231. if not B.get_equal() or \
  232. (B.get_equal() and \
  233. A not in B.get_equal()):
  234. B.append_equal(A)
  235. if not A.get_equal() or \
  236. (A.get_equal() and \
  237. B not in A.get_equal()):
  238. A.append_equal(B)
  239. elif relation == "follows":
  240. if not B.get_follows() or \
  241. (B.get_follows() and \
  242. A not in B.get_follows()):
  243. B.append_follows(A)
  244. if not A.get_precedes() or \
  245. (A.get_precedes() and
  246. B not in A.get_precedes()):
  247. A.append_precedes(B)
  248. elif relation == "precedes":
  249. if not B.get_precedes() or \
  250. (B.get_precedes() and \
  251. A not in B.get_precedes()):
  252. B.append_precedes(A)
  253. if not A.get_follows() or \
  254. (A.get_follows() and \
  255. B not in A.get_follows()):
  256. A.append_follows(B)
  257. elif relation == "during" or relation == "starts" or \
  258. relation == "finishes":
  259. if not B.get_during() or \
  260. (B.get_during() and \
  261. A not in B.get_during()):
  262. B.append_during(A)
  263. if not A.get_contains() or \
  264. (A.get_contains() and \
  265. B not in A.get_contains()):
  266. A.append_contains(B)
  267. if relation == "starts":
  268. if not B.get_starts() or \
  269. (B.get_starts() and \
  270. A not in B.get_starts()):
  271. B.append_starts(A)
  272. if not A.get_started() or \
  273. (A.get_started() and \
  274. B not in A.get_started()):
  275. A.append_started(B)
  276. if relation == "finishes":
  277. if not B.get_finishes() or \
  278. (B.get_finishes() and \
  279. A not in B.get_finishes()):
  280. B.append_finishes(A)
  281. if not A.get_finished() or \
  282. (A.get_finished() and \
  283. B not in A.get_finished()):
  284. A.append_finished(B)
  285. elif relation == "contains" or relation == "started" or \
  286. relation == "finished":
  287. if not B.get_contains() or \
  288. (B.get_contains() and \
  289. A not in B.get_contains()):
  290. B.append_contains(A)
  291. if not A.get_during() or \
  292. (A.get_during() and \
  293. B not in A.get_during()):
  294. A.append_during(B)
  295. if relation == "started":
  296. if not B.get_started() or \
  297. (B.get_started() and \
  298. A not in B.get_started()):
  299. B.append_started(A)
  300. if not A.get_starts() or \
  301. (A.get_starts() and \
  302. B not in A.get_starts()):
  303. A.append_starts(B)
  304. if relation == "finished":
  305. if not B.get_finished() or \
  306. (B.get_finished() and \
  307. A not in B.get_finished()):
  308. B.append_finished(A)
  309. if not A.get_finishes() or \
  310. (A.get_finishes() and \
  311. B not in A.get_finishes()):
  312. A.append_finishes(B)
  313. elif relation == "overlaps":
  314. if not B.get_overlaps() or \
  315. (B.get_overlaps() and \
  316. A not in B.get_overlaps()):
  317. B.append_overlaps(A)
  318. if not A.get_overlapped() or \
  319. (A.get_overlapped() and \
  320. B not in A.get_overlapped()):
  321. A.append_overlapped(B)
  322. elif relation == "overlapped":
  323. if not B.get_overlapped() or \
  324. (B.get_overlapped() and \
  325. A not in B.get_overlapped()):
  326. B.append_overlapped(A)
  327. if not A.get_overlaps() or \
  328. (A.get_overlaps() and \
  329. B not in A.get_overlaps()):
  330. A.append_overlaps(B)
  331. ###############################################################################
  332. def set_spatial_relationship(A, B, relation):
  333. if relation == "equivalent":
  334. if B != A:
  335. if not B.get_equivalent() or \
  336. (B.get_equivalent() and \
  337. A not in B.get_equivalent()):
  338. B.append_equivalent(A)
  339. if not A.get_equivalent() or \
  340. (A.get_equivalent() and \
  341. B not in A.get_equivalent()):
  342. A.append_equivalent(B)
  343. elif relation == "overlap":
  344. if not B.get_overlap() or \
  345. (B.get_overlap() and \
  346. A not in B.get_overlap()):
  347. B.append_overlap(A)
  348. if not A.get_overlap() or \
  349. (A.get_overlap() and
  350. B not in A.get_overlap()):
  351. A.append_overlap(B)
  352. elif relation == "meet":
  353. if not B.get_meet() or \
  354. (B.get_meet() and \
  355. A not in B.get_meet()):
  356. B.append_meet(A)
  357. if not A.get_meet() or \
  358. (A.get_meet() and
  359. B not in A.get_meet()):
  360. A.append_meet(B)
  361. elif relation == "contain":
  362. if not B.get_contain() or \
  363. (B.get_contain() and \
  364. A not in B.get_contain()):
  365. B.append_contain(A)
  366. if not A.get_in() or \
  367. (A.get_in() and \
  368. B not in A.get_in()):
  369. A.append_in(B)
  370. elif relation == "in":
  371. if not B.get_in() or \
  372. (B.get_in() and \
  373. A not in B.get_in()):
  374. B.append_in(A)
  375. if not A.get_contain() or \
  376. (A.get_contain() and \
  377. B not in A.get_contain()):
  378. A.append_contain(B)
  379. elif relation == "cover":
  380. if not B.get_cover() or \
  381. (B.get_cover() and \
  382. A not in B.get_cover()):
  383. B.append_cover(A)
  384. if not A.get_covered() or \
  385. (A.get_covered() and \
  386. B not in A.get_covered()):
  387. A.append_covered(B)
  388. elif relation == "covered":
  389. if not B.get_covered() or \
  390. (B.get_covered() and \
  391. A not in B.get_covered()):
  392. B.append_covered(A)
  393. if not A.get_cover() or \
  394. (A.get_cover() and \
  395. B not in A.get_cover()):
  396. A.append_cover(B)
  397. ###############################################################################
  398. def print_temporal_topology_relationships(maps1, maps2=None, dbif=None):
  399. """!Print the temporal relationships of the
  400. map lists maps1 and maps2 to stdout.
  401. @param maps1 A list of abstract_dataset
  402. objects with initiated temporal extent
  403. @param maps2 An optional list of abstract_dataset
  404. objects with initiated temporal extent
  405. @param dbif The database interface to be used
  406. """
  407. tb = SpatioTemporalTopologyBuilder()
  408. tb.build(maps1, maps2)
  409. dbif, connected = init_dbif(dbif)
  410. for _map in tb:
  411. _map.select(dbif)
  412. _map.print_info()
  413. if connected:
  414. dbif.close()
  415. return
  416. ###############################################################################
  417. def count_temporal_topology_relationships(maps1, maps2=None, dbif=None):
  418. """!Count the temporal relations of a single list of maps or between two lists of maps
  419. @param maps1 A list of abstract_dataset
  420. objects with initiated temporal extent
  421. @param maps2 A list of abstract_dataset
  422. objects with initiated temporal extent
  423. @param dbif The database interface to be used
  424. @return A dictionary with counted temporal relationships
  425. """
  426. tb = SpatioTemporalTopologyBuilder()
  427. tb.build(maps1, maps2)
  428. dbif, connected = init_dbif(dbif)
  429. relations = None
  430. for _map in tb:
  431. if relations != None:
  432. r = _map.get_number_of_relations()
  433. for k in r.keys():
  434. relations[k] += r[k]
  435. else:
  436. relations = _map.get_number_of_relations()
  437. if connected:
  438. dbif.close()
  439. return relations
  440. ###############################################################################
  441. def create_temporal_relation_sql_where_statement(
  442. start, end, use_start=True, use_during=False,
  443. use_overlap=False, use_contain=False, use_equal=False,
  444. use_follows=False, use_precedes=False):
  445. """!Create a SQL WHERE statement for temporal relation selection of maps in space time datasets
  446. @param start The start time
  447. @param end The end time
  448. @param use_start Select maps of which the start time is located in the selection granule
  449. @verbatim
  450. map : s
  451. granule: s-----------------e
  452. map : s--------------------e
  453. granule: s-----------------e
  454. map : s--------e
  455. granule: s-----------------e
  456. @endverbatim
  457. @param use_during Select maps which are temporal during the selection granule
  458. @verbatim
  459. map : s-----------e
  460. granule: s-----------------e
  461. @endverbatim
  462. @param use_overlap Select maps which temporal overlap the selection granule
  463. @verbatim
  464. map : s-----------e
  465. granule: s-----------------e
  466. map : s-----------e
  467. granule: s----------e
  468. @endverbatim
  469. @param use_contain Select maps which temporally contain the selection granule
  470. @verbatim
  471. map : s-----------------e
  472. granule: s-----------e
  473. @endverbatim
  474. @param use_equal Select maps which temporally equal to the selection granule
  475. @verbatim
  476. map : s-----------e
  477. granule: s-----------e
  478. @endverbatim
  479. @param use_follows Select maps which temporally follow the selection granule
  480. @verbatim
  481. map : s-----------e
  482. granule: s-----------e
  483. @endverbatim
  484. @param use_precedes Select maps which temporally precedes the selection granule
  485. @verbatim
  486. map : s-----------e
  487. granule: s-----------e
  488. @endverbatim
  489. Usage:
  490. @code
  491. >>> # Relative time
  492. >>> start = 1
  493. >>> end = 2
  494. >>> create_temporal_relation_sql_where_statement(start, end,
  495. ... use_start=False)
  496. >>> create_temporal_relation_sql_where_statement(start, end)
  497. '((start_time >= 1 and start_time < 2) )'
  498. >>> create_temporal_relation_sql_where_statement(start, end,
  499. ... use_start=True)
  500. '((start_time >= 1 and start_time < 2) )'
  501. >>> create_temporal_relation_sql_where_statement(start, end,
  502. ... use_start=False, use_during=True)
  503. '(((start_time > 1 and end_time < 2) OR (start_time >= 1 and end_time < 2) OR (start_time > 1 and end_time <= 2)))'
  504. >>> create_temporal_relation_sql_where_statement(start, end,
  505. ... use_start=False, use_overlap=True)
  506. '(((start_time < 1 and end_time > 1 and end_time < 2) OR (start_time < 2 and start_time > 1 and end_time > 2)))'
  507. >>> create_temporal_relation_sql_where_statement(start, end,
  508. ... use_start=False, use_contain=True)
  509. '(((start_time < 1 and end_time > 2) OR (start_time <= 1 and end_time > 2) OR (start_time < 1 and end_time >= 2)))'
  510. >>> create_temporal_relation_sql_where_statement(start, end,
  511. ... use_start=False, use_equal=True)
  512. '((start_time = 1 and end_time = 2))'
  513. >>> create_temporal_relation_sql_where_statement(start, end,
  514. ... use_start=False, use_follows=True)
  515. '((start_time = 2))'
  516. >>> create_temporal_relation_sql_where_statement(start, end,
  517. ... use_start=False, use_precedes=True)
  518. '((end_time = 1))'
  519. >>> create_temporal_relation_sql_where_statement(start, end,
  520. ... use_start=True, use_during=True, use_overlap=True, use_contain=True,
  521. ... use_equal=True, use_follows=True, use_precedes=True)
  522. '((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))'
  523. >>> # Absolute time
  524. >>> start = datetime(2001, 1, 1, 12, 30)
  525. >>> end = datetime(2001, 3, 31, 14, 30)
  526. >>> create_temporal_relation_sql_where_statement(start, end,
  527. ... use_start=False)
  528. >>> create_temporal_relation_sql_where_statement(start, end)
  529. "((start_time >= '2001-01-01 12:30:00' and start_time < '2001-03-31 14:30:00') )"
  530. >>> create_temporal_relation_sql_where_statement(start, end,
  531. ... use_start=True)
  532. "((start_time >= '2001-01-01 12:30:00' and start_time < '2001-03-31 14:30:00') )"
  533. >>> create_temporal_relation_sql_where_statement(start, end,
  534. ... use_start=False, use_during=True)
  535. "(((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')))"
  536. >>> create_temporal_relation_sql_where_statement(start, end,
  537. ... use_start=False, use_overlap=True)
  538. "(((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')))"
  539. >>> create_temporal_relation_sql_where_statement(start, end,
  540. ... use_start=False, use_contain=True)
  541. "(((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')))"
  542. >>> create_temporal_relation_sql_where_statement(start, end,
  543. ... use_start=False, use_equal=True)
  544. "((start_time = '2001-01-01 12:30:00' and end_time = '2001-03-31 14:30:00'))"
  545. >>> create_temporal_relation_sql_where_statement(start, end,
  546. ... use_start=False, use_follows=True)
  547. "((start_time = '2001-03-31 14:30:00'))"
  548. >>> create_temporal_relation_sql_where_statement(start, end,
  549. ... use_start=False, use_precedes=True)
  550. "((end_time = '2001-01-01 12:30:00'))"
  551. >>> create_temporal_relation_sql_where_statement(start, end,
  552. ... use_start=True, use_during=True, use_overlap=True, use_contain=True,
  553. ... use_equal=True, use_follows=True, use_precedes=True)
  554. "((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'))"
  555. @endcode
  556. """
  557. where = "("
  558. if use_start:
  559. if isinstance(start, datetime):
  560. where += "(start_time >= '%s' and start_time < '%s') " % (start, end)
  561. else:
  562. where += "(start_time >= %i and start_time < %i) " % (start, end)
  563. if use_during:
  564. if use_start:
  565. where += " OR "
  566. if isinstance(start, datetime):
  567. where += "((start_time > '%s' and end_time < '%s') OR " % (start, end)
  568. where += "(start_time >= '%s' and end_time < '%s') OR " % (start, end)
  569. where += "(start_time > '%s' and end_time <= '%s'))" % (start, end)
  570. else:
  571. where += "((start_time > %i and end_time < %i) OR " % (start, end)
  572. where += "(start_time >= %i and end_time < %i) OR " % (start, end)
  573. where += "(start_time > %i and end_time <= %i))" % (start, end)
  574. if use_overlap:
  575. if use_start or use_during:
  576. where += " OR "
  577. if isinstance(start, datetime):
  578. where += "((start_time < '%s' and end_time > '%s' and end_time < '%s') OR " % (start, start, end)
  579. where += "(start_time < '%s' and start_time > '%s' and end_time > '%s'))" % (end, start, end)
  580. else:
  581. where += "((start_time < %i and end_time > %i and end_time < %i) OR " % (start, start, end)
  582. where += "(start_time < %i and start_time > %i and end_time > %i))" % (end, start, end)
  583. if use_contain:
  584. if use_start or use_during or use_overlap:
  585. where += " OR "
  586. if isinstance(start, datetime):
  587. where += "((start_time < '%s' and end_time > '%s') OR " % (start, end)
  588. where += "(start_time <= '%s' and end_time > '%s') OR " % (start, end)
  589. where += "(start_time < '%s' and end_time >= '%s'))" % (start, end)
  590. else:
  591. where += "((start_time < %i and end_time > %i) OR " % (start, end)
  592. where += "(start_time <= %i and end_time > %i) OR " % (start, end)
  593. where += "(start_time < %i and end_time >= %i))" % (start, end)
  594. if use_equal:
  595. if use_start or use_during or use_overlap or use_contain:
  596. where += " OR "
  597. if isinstance(start, datetime):
  598. where += "(start_time = '%s' and end_time = '%s')" % (start, end)
  599. else:
  600. where += "(start_time = %i and end_time = %i)" % (start, end)
  601. if use_follows:
  602. if use_start or use_during or use_overlap or use_contain or use_equal:
  603. where += " OR "
  604. if isinstance(start, datetime):
  605. where += "(start_time = '%s')" % (end)
  606. else:
  607. where += "(start_time = %i)" % (end)
  608. if use_precedes:
  609. if use_start or use_during or use_overlap or use_contain or use_equal \
  610. or use_follows:
  611. where += " OR "
  612. if isinstance(start, datetime):
  613. where += "(end_time = '%s')" % (start)
  614. else:
  615. where += "(end_time = %i)" % (start)
  616. where += ")"
  617. # Catch empty where statement
  618. if where == "()":
  619. where = None
  620. return where
  621. ###############################################################################
  622. if __name__ == "__main__":
  623. import doctest
  624. doctest.testmod()