abstract_space_time_dataset.py 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354
  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. Usage:
  6. @code
  7. import grass.temporal as tgis
  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 temporal_granularity import *
  18. from temporal_relationships import *
  19. ###############################################################################
  20. class abstract_space_time_dataset(abstract_dataset):
  21. """!Abstract space time dataset class
  22. This class represents a space time dataset. Convenient functions
  23. to select, update, insert or delete objects of this type in the SQL
  24. temporal database exists as well as functions to register or unregister
  25. raster maps.
  26. Parts of the temporal logic are implemented in the SQL temporal database,
  27. like the computation of the temporal and spatial extent as well as the
  28. collecting of metadata.
  29. """
  30. def __init__(self, ident):
  31. self.reset(ident)
  32. self.map_counter = 0
  33. def get_new_map_instance(self, ident=None):
  34. """!Return a new instance of a map dataset which is associated with the type of this class
  35. @param ident: The unique identifier of the new object
  36. """
  37. raise IOError("This method must be implemented in the subclasses")
  38. def get_map_register(self):
  39. """!Return the name of the map register table"""
  40. raise IOError("This method must be implemented in the subclasses")
  41. def set_map_register(self, name):
  42. """!Set the name of the map register table
  43. This table stores all map names which are registered in this space time dataset.
  44. @param name: The name of the register table
  45. """
  46. raise IOError("This method must be implemented in the subclasses")
  47. def print_self(self):
  48. """!Print the content of the internal structure to stdout"""
  49. self.base.print_self()
  50. if self.is_time_absolute():
  51. self.absolute_time.print_self()
  52. if self.is_time_relative():
  53. self.relative_time.print_self()
  54. self.spatial_extent.print_self()
  55. self.metadata.print_self()
  56. def print_info(self):
  57. """!Print information about this class in human readable style"""
  58. if self.get_type() == "strds":
  59. # 1 2 3 4 5 6 7
  60. # 0123456789012345678901234567890123456789012345678901234567890123456789012345678
  61. print ""
  62. print " +-------------------- Space Time Raster Dataset -----------------------------+"
  63. if self.get_type() == "str3ds":
  64. # 1 2 3 4 5 6 7
  65. # 0123456789012345678901234567890123456789012345678901234567890123456789012345678
  66. print ""
  67. print " +-------------------- Space Time Raster3d Dataset ---------------------------+"
  68. if self.get_type() == "stvds":
  69. # 1 2 3 4 5 6 7
  70. # 0123456789012345678901234567890123456789012345678901234567890123456789012345678
  71. print ""
  72. print " +-------------------- Space Time Vector Dataset -----------------------------+"
  73. print " | |"
  74. self.base.print_info()
  75. if self.is_time_absolute():
  76. self.absolute_time.print_info()
  77. if self.is_time_relative():
  78. self.relative_time.print_info()
  79. self.spatial_extent.print_info()
  80. self.metadata.print_info()
  81. print " +----------------------------------------------------------------------------+"
  82. def print_shell_info(self):
  83. """!Print information about this class in shell style"""
  84. self.base.print_shell_info()
  85. if self.is_time_absolute():
  86. self.absolute_time.print_shell_info()
  87. if self.is_time_relative():
  88. self.relative_time.print_shell_info()
  89. self.spatial_extent.print_shell_info()
  90. self.metadata.print_shell_info()
  91. def set_initial_values(self, temporal_type, semantic_type, \
  92. title=None, description=None):
  93. """!Set the initial values of the space time dataset
  94. @param temporal_type: The temporal type of this space time dataset (absolute or relative)
  95. @param semantic_type: The semantic type of this dataset
  96. @param title: The title
  97. @param description: The description of this dataset
  98. """
  99. if temporal_type == "absolute":
  100. self.set_time_to_absolute()
  101. elif temporal_type == "relative":
  102. self.set_time_to_relative()
  103. else:
  104. core.fatal(_("Unknown temporal type \"%s\"") % (temporal_type))
  105. self.base.set_semantic_type(semantic_type)
  106. self.metadata.set_title(title)
  107. self.metadata.set_description(description)
  108. def get_semantic_type(self):
  109. """!Return the semantic type of this dataset"""
  110. return self.base.get_semantic_type()
  111. def get_initial_values(self):
  112. """!Return the initial values: temporal_type, semantic_type, title, description"""
  113. temporal_type = self.get_temporal_type()
  114. semantic_type = self.base.get_semantic_type()
  115. title = self.metadata.get_title()
  116. description = self.metadata.get_description()
  117. return temporal_type, semantic_type, title, description
  118. def get_granularity(self):
  119. """!Return the granularity"""
  120. temporal_type = self.get_temporal_type()
  121. if temporal_type == "absolute":
  122. granularity = self.absolute_time.get_granularity()
  123. elif temporal_type == "relative":
  124. granularity = self.relative_time.get_granularity()
  125. return granularity
  126. def set_granularity(self, granularity):
  127. temporal_type = self.get_temporal_type()
  128. if temporal_type == "absolute":
  129. self.set_time_to_absolute()
  130. self.absolute_time.set_granularity(granularity)
  131. elif temporal_type == "relative":
  132. self.set_time_to_relative()
  133. self.relative_time.set_granularity(granularity)
  134. else:
  135. core.fatal(_("Unknown temporal type \"%s\"") % (temporal_type))
  136. def set_relative_time_unit(self, unit):
  137. """!Set the relative time unit which may be of type: years, months, days, hours, minutes or seconds
  138. All maps registered in a (relative time) space time dataset must have the same unit
  139. """
  140. temporal_type = self.get_temporal_type()
  141. if temporal_type == "relative":
  142. if not self.check_relative_time_unit(unit):
  143. core.fatal(_("Unsupported temporal unit: %s") % (unit))
  144. self.relative_time.set_unit(unit)
  145. def get_map_time(self):
  146. """!Return the type of the map time, interval, point, mixed or invalid"""
  147. temporal_type = self.get_temporal_type()
  148. if temporal_type == "absolute":
  149. map_time = self.absolute_time.get_map_time()
  150. elif temporal_type == "relative":
  151. map_time = self.relative_time.get_map_time()
  152. return map_time
  153. def count_temporal_types(self, maps=None, dbif=None):
  154. """!Return the temporal type of the registered maps as dictionary
  155. The map list must be ordered by start time
  156. The temporal type can be:
  157. * point -> only the start time is present
  158. * interval -> start and end time
  159. * invalid -> No valid time point or interval found
  160. @param maps: A sorted (start_time) list of abstract_dataset objects
  161. @param dbif: The database interface to be used
  162. """
  163. if maps == None:
  164. maps = get_registered_maps_as_objects(where=None, order="start_time", dbif=dbif)
  165. time_invalid = 0
  166. time_point = 0
  167. time_interval = 0
  168. tcount = {}
  169. for i in range(len(maps)):
  170. # Check for point and interval data
  171. if maps[i].is_time_absolute():
  172. start, end, tz = maps[i].get_absolute_time()
  173. if maps[i].is_time_relative():
  174. start, end, unit = maps[i].get_relative_time()
  175. if start != None and end != None:
  176. time_interval += 1
  177. elif start != None and end == None:
  178. time_point += 1
  179. else:
  180. time_invalid += 1
  181. tcount["point"] = time_point
  182. tcount["interval"] = time_interval
  183. tcount["invalid"] = time_invalid
  184. return tcount
  185. def count_gaps(self, maps=None, dbif=None):
  186. """!Count the number of gaps between temporal neighbors
  187. @param maps: A sorted (start_time) list of abstract_dataset objects
  188. @param dbif: The database interface to be used
  189. @return The numbers of gaps between temporal neighbors
  190. """
  191. if maps == None:
  192. maps = self.get_registered_maps_as_objects(where=None, order="start_time", dbif=dbif)
  193. gaps = 0
  194. # Check for gaps
  195. for i in range(len(maps)):
  196. if i < len(maps) - 1:
  197. relation = maps[i + 1].temporal_relation(maps[i])
  198. if relation == "after":
  199. gaps += 1
  200. return gaps
  201. def print_temporal_relationships(self, maps=None, dbif=None):
  202. """!Print the temporal relation matrix of all registered maps to stdout
  203. The temporal relation matrix includes the temporal relations between
  204. all registered maps. The relations are strings stored in a list of lists.
  205. @param maps: a ordered by start_time list of map objects
  206. @param dbif: The database interface to be used
  207. """
  208. if maps == None:
  209. maps = self.get_registered_maps_as_objects(where=None, order="start_time", dbif=dbif)
  210. print_temporal_topology_relationships(maps, maps)
  211. def count_temporal_relations(self, maps=None, dbif=None):
  212. """!Count the temporal relations between the registered maps.
  213. The map list must be ordered by start time. Temporal relations are counted
  214. by analysing the sparse upper right side temporal relationships matrix.
  215. @param maps: A sorted (start_time) list of abstract_dataset objects
  216. @param dbif: The database interface to be used
  217. @return A dictionary with counted temporal relationships
  218. """
  219. if maps == None:
  220. maps = self.get_registered_maps_as_objects(where=None, order="start_time", dbif=dbif)
  221. return count_temporal_topology_relationships(maps, maps)
  222. def check_temporal_topology(self, maps=None, dbif=None):
  223. """!Check the temporal topology
  224. Correct topology means, that time intervals are not overlap or
  225. that intervals does not contain other intervals. Equal time intervals or
  226. points of time are not allowed.
  227. The map list must be ordered by start time
  228. Allowed and not allowed temporal relationships for correct topology
  229. after -> allowed
  230. precedes -> allowed
  231. follows -> allowed
  232. precedes -> allowed
  233. equivalent -> not allowed
  234. during -> not allowed
  235. contains -> not allowed
  236. overlaps -> not allowed
  237. overlapped -> not allowed
  238. starts -> not allowed
  239. finishes -> not allowed
  240. started -> not allowed
  241. finished -> not allowed
  242. @param maps: A sorted (start_time) list of abstract_dataset objects
  243. @return True if topology is correct
  244. """
  245. if maps == None:
  246. maps = self.get_registered_maps_as_objects(where=None, order="start_time", dbif=dbif)
  247. relations = count_temporal_topology_relationships(maps, maps)
  248. map_time = self.get_map_time()
  249. if map_time == "interval" or map_time == "mixed":
  250. if relations.has_key("equivalent"):
  251. return False
  252. if relations.has_key("during"):
  253. return False
  254. if relations.has_key("contains"):
  255. return False
  256. if relations.has_key("overlaps"):
  257. return False
  258. if relations.has_key("overlapped"):
  259. return False
  260. if relations.has_key("starts"):
  261. return False
  262. if relations.has_key("finishes"):
  263. return False
  264. if relations.has_key("started"):
  265. return False
  266. if relations.has_key("finished"):
  267. return False
  268. elif map_time == "point":
  269. if relations.has_key("equivalent"):
  270. return False
  271. else:
  272. return False
  273. return True
  274. def sample_by_dataset(self, stds, method=None, spatial=False, dbif=None):
  275. """!Sample this space time dataset with the temporal topology of a second space time dataset
  276. The sample dataset must have "interval" as temporal map type, so all sample maps have valid interval time.
  277. In case spatial is True, the spatial overlap between temporal related maps is performed. Only
  278. temporal related and spatial overlapping maps are returned.
  279. Return all registered maps as ordered (by start_time) object list with
  280. "gap" map objects (id==None). Each list entry is a list of map objects
  281. which are potentially located in temporal relation to the actual granule of the second space time dataset.
  282. Each entry in the object list is a dict. The actual sampler map and its temporal extent (the actual granule) and
  283. the list of samples are stored:
  284. list = self.sample_by_dataset(stds=sampler, method=["during","overlap","contain","equal"])
  285. for entry in list:
  286. granule = entry["granule"]
  287. maplist = entry["samples"]
  288. for map in maplist:
  289. map.select()
  290. map.print_info()
  291. A valid temporal topology (no overlapping or inclusion allowed) is needed to get correct results in case of gaps
  292. in the sample dataset.
  293. Gaps between maps are identified as unregistered maps with id==None.
  294. The map objects are initialized with the id and the temporal extent of the granule (temporal type, start time, end time).
  295. In case more map information are needed, use the select() method for each listed object.
  296. @param stds: The space time dataset to be used for temporal sampling
  297. @param method: This option specifies what sample method should be used. In case the registered maps are of temporal point type,
  298. only the start time is used for sampling. In case of mixed of interval data the user can chose between:
  299. * start: Select maps of which the start time is located in the selection granule
  300. map : s
  301. granule: s-----------------e
  302. map : s--------------------e
  303. granule: s-----------------e
  304. map : s--------e
  305. granule: s-----------------e
  306. * during: Select maps which are temporal during the selection granule
  307. map : s-----------e
  308. granule: s-----------------e
  309. * overlap: Select maps which temporal overlap the selection granule
  310. map : s-----------e
  311. granule: s-----------------e
  312. map : s-----------e
  313. granule: s----------e
  314. * contain: Select maps which temporally contain the selection granule
  315. map : s-----------------e
  316. granule: s-----------e
  317. * equal: Select maps which temporally equal to the selection granule
  318. map : s-----------e
  319. granule: s-----------e
  320. * follows: Select maps which temporally follow the selection granule
  321. map : s-----------e
  322. granule: s-----------e
  323. * precedes: Select maps which temporally precedes the selection granule
  324. map : s-----------e
  325. granule: s-----------e
  326. All these methods can be combined. Method must be of type tuple including the identification strings.
  327. @param spatial: If set True additional the spatial overlapping is used for selection -> spatio-temporal relation.
  328. The returned map objects will have temporal and spatial extents
  329. @param dbif: The database interface to be used
  330. In case nothing found None is returned
  331. """
  332. use_start = False
  333. use_during = False
  334. use_overlap = False
  335. use_contain = False
  336. use_equal = False
  337. use_follows = False
  338. use_precedes = False
  339. # Initialize the methods
  340. if method:
  341. for name in method:
  342. if name == "start":
  343. use_start = True
  344. if name == "during":
  345. use_during = True
  346. if name == "overlap":
  347. use_overlap = True
  348. if name == "contain":
  349. use_contain = True
  350. if name == "equal":
  351. use_equal = True
  352. if name == "follows":
  353. use_follows = True
  354. if name == "precedes":
  355. use_precedes = True
  356. else:
  357. use_during = True
  358. use_overlap = True
  359. use_contain = True
  360. use_equal = True
  361. if self.get_temporal_type() != stds.get_temporal_type():
  362. core.error(_("The space time datasets must be of the same temporal type"))
  363. return None
  364. if stds.get_map_time() != "interval":
  365. core.error(_("The temporal map type of the sample dataset must be interval"))
  366. return None
  367. # In case points of time are available, disable the interval specific methods
  368. if self.get_map_time() == "point":
  369. use_start = True
  370. use_during = False
  371. use_overlap = False
  372. use_contain = False
  373. use_equal = False
  374. use_follows = False
  375. use_precedes = False
  376. dbif, connect = init_dbif(dbif)
  377. obj_list = []
  378. sample_maps = stds.get_registered_maps_as_objects_with_gaps(where=None, dbif=dbif)
  379. for granule in sample_maps:
  380. # Read the spatial extent
  381. if spatial == True:
  382. granule.spatial_extent.select(dbif)
  383. start, end = granule.get_valid_time()
  384. where = create_temporal_relation_sql_where_statement(start, end, use_start, \
  385. use_during, use_overlap, use_contain, use_equal, use_follows, use_precedes)
  386. maps = self.get_registered_maps_as_objects(where, "start_time", dbif)
  387. result = {}
  388. result["granule"] = granule
  389. num_samples = 0
  390. maplist = []
  391. if maps:
  392. for map in maps:
  393. # Read the spatial extent
  394. if spatial == True:
  395. map.spatial_extent.select(dbif)
  396. # Ignore spatial disjoint maps
  397. if not granule.spatial_overlapping(map):
  398. continue
  399. num_samples += 1
  400. maplist.append(copy.copy(map))
  401. # Fill with empty map in case no spatio-temporal relations found
  402. if not maps or num_samples == 0:
  403. map = self.get_new_map_instance(None)
  404. if self.is_time_absolute():
  405. map.set_absolute_time(start, end)
  406. elif self.is_time_relative():
  407. map.set_relative_time(start, end, self.get_relative_time_unit())
  408. maplist.append(copy.copy(map))
  409. result["samples"] = maplist
  410. obj_list.append(copy.copy(result))
  411. if connect == True:
  412. dbif.close()
  413. return obj_list
  414. def get_registered_maps_as_objects_by_granularity(self, gran=None, dbif=None):
  415. """!Return all registered maps as ordered (by start_time) object list with
  416. "gap" map objects (id==None) for temporal topological operations using the
  417. granularity of the space time dataset as increment. Each list entry is a list of map objects
  418. which are potentially located in the actual granule.
  419. A valid temporal topology (no overlapping or inclusion allowed) is needed to get correct results.
  420. The dataset must have "interval" as temporal map type, so all maps have valid interval time.
  421. Gaps between maps are identified as unregistered maps with id==None.
  422. The objects are initialized with the id and the temporal extent (temporal type, start time, end time).
  423. In case more map information are needed, use the select() method for each listed object.
  424. @param gran: The granularity to be used
  425. @param dbif: The database interface to be used
  426. In case nothing found None is returned
  427. """
  428. dbif, connect = init_dbif(dbif)
  429. obj_list = []
  430. if gran == None:
  431. gran = self.get_granularity()
  432. start, end = self.get_valid_time()
  433. while start < end:
  434. if self.is_time_absolute():
  435. next = increment_datetime_by_string(start, gran)
  436. else:
  437. next = start + gran
  438. where = "(start_time <= '%s' and end_time >= '%s')" % (start, next)
  439. rows = self.get_registered_maps("id", where, "start_time", dbif)
  440. if rows:
  441. if len(rows) > 1:
  442. core.warning(_("More than one map found in a granule. Temporal granularity seems to be invalid or the chosen granularity is not a greatest common divider of all intervals and gaps in the dataset."))
  443. maplist = []
  444. for row in rows:
  445. # Take the first map
  446. map = self.get_new_map_instance(rows[0]["id"])
  447. if self.is_time_absolute():
  448. map.set_absolute_time(start, next)
  449. elif self.is_time_relative():
  450. map.set_relative_time(start, next, self.get_relative_time_unit())
  451. maplist.append(copy.copy(map))
  452. obj_list.append(copy.copy(maplist))
  453. start = next
  454. if connect == True:
  455. dbif.close()
  456. return obj_list
  457. def get_registered_maps_as_objects_with_gaps(self, where=None, dbif=None):
  458. """!Return all registered maps as ordered (by start_time) object list with
  459. "gap" map objects (id==None) for temporal topological operations
  460. Gaps between maps are identified as maps with id==None
  461. The objects are initialized with the id and the temporal extent (temporal type, start time, end time).
  462. In case more map information are needed, use the select() method for each listed object.
  463. @param where: The SQL where statement to select a subset of the registered maps without "WHERE"
  464. @param dbif: The database interface to be used
  465. In case nothing found None is returned
  466. """
  467. dbif, connect = init_dbif(dbif)
  468. obj_list = []
  469. maps = self.get_registered_maps_as_objects(where, "start_time", dbif)
  470. if maps and len(maps) > 0:
  471. for i in range(len(maps)):
  472. obj_list.append(maps[i])
  473. # Detect and insert gaps
  474. if i < len(maps) - 1:
  475. relation = maps[i + 1].temporal_relation(maps[i])
  476. if relation == "after":
  477. start1, end1 = maps[i].get_valid_time()
  478. start2, end2 = maps[i + 1].get_valid_time()
  479. end = start2
  480. if end1:
  481. start = end1
  482. else:
  483. start = start1
  484. map = self.get_new_map_instance(None)
  485. if self.is_time_absolute():
  486. map.set_absolute_time(start, end)
  487. elif self.is_time_relative():
  488. map.set_relative_time(start, end, self.get_relative_time_unit())
  489. obj_list.append(copy.copy(map))
  490. if connect == True:
  491. dbif.close()
  492. return obj_list
  493. def get_registered_maps_as_objects(self, where=None, order="start_time", dbif=None):
  494. """!Return all registered maps as ordered object list for temporal topological operations
  495. The objects are initialized with the id and the temporal extent (temporal type, start time, end time).
  496. In case more map information are needed, use the select() method for each listed object.
  497. @param where: The SQL where statement to select a subset of the registered maps without "WHERE"
  498. @param order: The SQL order statement to be used to order the objects in the list without "ORDER BY"
  499. @param dbif: The database interface to be used
  500. In case nothing found None is returned
  501. """
  502. dbif, connect = init_dbif(dbif)
  503. obj_list = []
  504. rows = self.get_registered_maps("id,start_time,end_time", where, order, dbif)
  505. count = 0
  506. if rows:
  507. for row in rows:
  508. core.percent(count, len(rows), 1)
  509. map = self.get_new_map_instance(row["id"])
  510. if self.is_time_absolute():
  511. map.set_absolute_time(row["start_time"], row["end_time"])
  512. elif self.is_time_relative():
  513. map.set_relative_time(row["start_time"], row["end_time"], self.get_relative_time_unit())
  514. obj_list.append(copy.copy(map))
  515. count += 1
  516. core.percent(1, 1, 1)
  517. if connect == True:
  518. dbif.close()
  519. return obj_list
  520. def get_registered_maps(self, columns=None, where = None, order = None, dbif=None):
  521. """!Return sqlite rows of all registered maps.
  522. In case columns are not specified, each row includes all columns specified in the datatype specific view
  523. @param columns: Columns to be selected as SQL compliant string
  524. @param where: The SQL where statement to select a subset of the registered maps without "WHERE"
  525. @param order: The SQL order statement to be used to order the objects in the list without "ORDER BY"
  526. @param dbif: The database interface to be used
  527. In case nothing found None is returned
  528. """
  529. dbif, connect = init_dbif(dbif)
  530. rows = None
  531. if self.get_map_register():
  532. # Use the correct temporal table
  533. if self.get_temporal_type() == "absolute":
  534. map_view = self.get_new_map_instance(None).get_type() + "_view_abs_time"
  535. else:
  536. map_view = self.get_new_map_instance(None).get_type() + "_view_rel_time"
  537. if columns:
  538. sql = "SELECT %s FROM %s WHERE %s.id IN (SELECT id FROM %s)" % (columns, map_view, map_view, self.get_map_register())
  539. else:
  540. sql = "SELECT * FROM %s WHERE %s.id IN (SELECT id FROM %s)" % (map_view, map_view, self.get_map_register())
  541. if where:
  542. sql += " AND (%s)" % (where.split(";")[0])
  543. if order:
  544. sql += " ORDER BY %s" % (order.split(";")[0])
  545. try:
  546. dbif.cursor.execute(sql)
  547. rows = dbif.cursor.fetchall()
  548. except:
  549. if connect == True:
  550. dbif.close()
  551. core.error(_("Unable to get map ids from register table <%s>") % (self.get_map_register()))
  552. raise
  553. if connect == True:
  554. dbif.close()
  555. return rows
  556. def delete(self, dbif=None, execute=True):
  557. """!Delete a space time dataset from the temporal database
  558. This method removes the space time dataset from the temporal database and drops its map register table
  559. @param dbif: The database interface to be used
  560. @param execute: If True the SQL DELETE and DROP table statements will be executed.
  561. If False the prepared SQL statements are returned and must be executed by the caller.
  562. @return The SQL statements if execute == False, else an empty string
  563. """
  564. # First we need to check if maps are registered in this dataset and
  565. # unregister them
  566. core.verbose(_("Delete space time %s dataset <%s> from temporal database") % (self.get_new_map_instance(ident=None).get_type(), self.get_id()))
  567. statement = ""
  568. dbif, connect = init_dbif(dbif)
  569. # SELECT all needed information from the database
  570. self.metadata.select(dbif)
  571. if self.get_map_register():
  572. core.verbose(_("Drop map register table: %s") % (self.get_map_register()))
  573. rows = self.get_registered_maps("id", None, None, dbif)
  574. # Unregister each registered map in the table
  575. if rows:
  576. num_maps = len(rows)
  577. count = 0
  578. for row in rows:
  579. core.percent(count, num_maps, 1)
  580. # Unregister map
  581. map = self.get_new_map_instance(row["id"])
  582. statement += self.unregister_map(map=map, dbif=dbif, execute=False)
  583. count += 1
  584. core.percent(1, 1, 1)
  585. # Safe the DROP table statement
  586. statement += "DROP TABLE " + self.get_map_register() + ";\n"
  587. # Remove the primary key, the foreign keys will be removed by trigger
  588. statement += self.base.get_delete_statement()
  589. if execute == True:
  590. dbif.execute_transaction(statement)
  591. self.reset(None)
  592. if connect == True:
  593. dbif.close()
  594. if execute:
  595. return ""
  596. return statement
  597. def register_map(self, map, dbif=None):
  598. """!Register a map in the space time dataset.
  599. This method takes care of the registration of a map
  600. in a space time dataset.
  601. In case the map is already registered this function will break with a warning
  602. and return False
  603. @param dbif: The database interface to be used
  604. """
  605. dbif, connect = init_dbif(dbif)
  606. if map.is_in_db(dbif) == False:
  607. dbif.close()
  608. core.fatal(_("Only maps with absolute or relative valid time can be registered"))
  609. if map.get_layer():
  610. core.verbose(_("Register %s map <%s> with layer %s in space time %s dataset <%s>") % (map.get_type(), map.get_map_id(), map.get_layer(), map.get_type(), self.get_id()))
  611. else:
  612. core.verbose(_("Register %s map <%s> in space time %s dataset <%s>") % (map.get_type(), map.get_map_id(), map.get_type(), self.get_id()))
  613. # First select all data from the database
  614. map.select(dbif)
  615. if not map.check_valid_time():
  616. if map.get_layer():
  617. core.fatal(_("Map <%s> with layer %s has invalid time") % (map.get_map_id(), map.get_layer()))
  618. else:
  619. core.fatal(_("Map <%s> has invalid time") % (map.get_map_id()))
  620. map_id = map.base.get_id()
  621. map_name = map.base.get_name()
  622. map_mapset = map.base.get_mapset()
  623. map_register_table = map.get_stds_register()
  624. map_rel_time_unit = map.get_relative_time_unit()
  625. map_ttype = map.get_temporal_type()
  626. #print "Map register table", map_register_table
  627. # Get basic info
  628. stds_name = self.base.get_name()
  629. stds_mapset = self.base.get_mapset()
  630. stds_register_table = self.get_map_register()
  631. stds_ttype = self.get_temporal_type()
  632. # The gathered SQL statemets are stroed here
  633. statement = ""
  634. # Check temporal types
  635. if stds_ttype != map_ttype:
  636. if map.get_layer():
  637. core.fatal(_("Temporal type of space time dataset <%s> and map <%s> with layer %s are different") % (self.get_id(), map.get_map_id(), map.get_layer()))
  638. else:
  639. core.fatal(_("Temporal type of space time dataset <%s> and map <%s> are different") % (self.get_id(), map.get_map_id()))
  640. # In case no map has been registered yet, set the relative time unit from the first map
  641. if (self.metadata.get_number_of_maps() == None or self.metadata.get_number_of_maps() == 0) and \
  642. self.map_counter == 0 and self.is_time_relative():
  643. self.set_relative_time_unit(map_rel_time_unit)
  644. statement += self.relative_time.get_update_all_statement_mogrified(dbif)
  645. core.verbose(_("Set temporal unit for space time %s dataset <%s> to %s") % (map.get_type(), self.get_id(), map_rel_time_unit))
  646. stds_rel_time_unit = self.get_relative_time_unit()
  647. # Check the relative time unit
  648. if self.is_time_relative() and (stds_rel_time_unit != map_rel_time_unit):
  649. if map.get_layer():
  650. core.fatal(_("Relative time units of space time dataset <%s> and map <%s> with layer %s are different") % (self.get_id(), map.get_map_id(), map.get_layer()))
  651. else:
  652. core.fatal(_("Relative time units of space time dataset <%s> and map <%s> are different") % (self.get_id(), map.get_map_id()))
  653. #print "STDS register table", stds_register_table
  654. if stds_mapset != map_mapset:
  655. dbif.close()
  656. core.fatal(_("Only maps from the same mapset can be registered"))
  657. # Check if map is already registered
  658. if stds_register_table:
  659. if dbmi.paramstyle == "qmark":
  660. sql = "SELECT id FROM " + stds_register_table + " WHERE id = (?)"
  661. else:
  662. sql = "SELECT id FROM " + stds_register_table + " WHERE id = (%s)"
  663. try:
  664. dbif.cursor.execute(sql, (map_id,))
  665. row = dbif.cursor.fetchone()
  666. except:
  667. row = None
  668. core.warning(_("Error in strds_register_table request"))
  669. raise
  670. if row and row[0] == map_id:
  671. if connect == True:
  672. dbif.close()
  673. if map.get_layer():
  674. core.warning(_("Map <%s> with layer %s is already registered.") % (map.get_map_id(), map.get_layer()))
  675. else:
  676. core.warning(_("Map <%s> is already registered.") % (map.get_map_id()))
  677. return ""
  678. # Create tables
  679. sql_path = get_sql_template_path()
  680. # We need to create the map raster register table precedes we can register the map
  681. if map_register_table == None:
  682. # Create a unique id
  683. uuid_rand = "map_" + str(uuid.uuid4()).replace("-", "")
  684. map_register_table = uuid_rand + "_" + self.get_type() + "_register"
  685. # Read the SQL template
  686. sql = open(os.path.join(sql_path, "map_stds_register_table_template.sql"), 'r').read()
  687. # Create the raster, raster3d and vector tables
  688. sql = sql.replace("GRASS_MAP", map.get_type())
  689. sql = sql.replace("MAP_NAME", map_name + "_" + map_mapset )
  690. sql = sql.replace("TABLE_NAME", uuid_rand )
  691. sql = sql.replace("MAP_ID", map_id)
  692. sql = sql.replace("STDS", self.get_type())
  693. statement += sql
  694. # Set the stds register table name and put it into the DB
  695. map.set_stds_register(map_register_table)
  696. statement += map.metadata.get_update_statement_mogrified(dbif)
  697. if map.get_layer():
  698. core.verbose(_("Created register table <%s> for %s map <%s> with layer %s") % \
  699. (map_register_table, map.get_type(), map.get_map_id(), map.get_layer()))
  700. else:
  701. core.verbose(_("Created register table <%s> for %s map <%s>") % \
  702. (map_register_table, map.get_type(), map.get_map_id()))
  703. # We need to create the table and register it
  704. if stds_register_table == None:
  705. # Create table name
  706. stds_register_table = stds_name + "_" + stds_mapset + "_" + map.get_type() + "_register"
  707. # Read the SQL template
  708. sql = open(os.path.join(sql_path, "stds_map_register_table_template.sql"), 'r').read()
  709. # Create the raster, raster3d and vector tables
  710. sql = sql.replace("GRASS_MAP", map.get_type())
  711. sql = sql.replace("SPACETIME_NAME", stds_name + "_" + stds_mapset )
  712. sql = sql.replace("SPACETIME_ID", self.base.get_id())
  713. sql = sql.replace("STDS", self.get_type())
  714. statement += sql
  715. # Set the map register table name and put it into the DB
  716. self.set_map_register(stds_register_table)
  717. statement += self.metadata.get_update_statement_mogrified(dbif)
  718. core.verbose(_("Created register table <%s> for space time %s dataset <%s>") % \
  719. (stds_register_table, map.get_type(), self.get_id()))
  720. # We need to execute the statement at this time
  721. if statement != "":
  722. dbif.execute_transaction(statement)
  723. statement = ""
  724. # Register the stds in the map stds register table
  725. # Check if the entry is already there
  726. if dbmi.paramstyle == "qmark":
  727. sql = "SELECT id FROM " + map_register_table + " WHERE id = ?"
  728. else:
  729. sql = "SELECT id FROM " + map_register_table + " WHERE id = %s"
  730. try:
  731. dbif.cursor.execute(sql, (self.base.get_id(),))
  732. row = dbif.cursor.fetchone()
  733. except:
  734. row = None
  735. # In case of no entry make a new one
  736. if row == None:
  737. if dbmi.paramstyle == "qmark":
  738. sql = "INSERT INTO " + map_register_table + " (id) " + "VALUES (?);\n"
  739. else:
  740. sql = "INSERT INTO " + map_register_table + " (id) " + "VALUES (%s);\n"
  741. statement += dbif.mogrify_sql_statement((sql, (self.base.get_id(),)))
  742. # Now put the raster name in the stds map register table
  743. if dbmi.paramstyle == "qmark":
  744. sql = "INSERT INTO " + stds_register_table + " (id) " + "VALUES (?);\n"
  745. else:
  746. sql = "INSERT INTO " + stds_register_table + " (id) " + "VALUES (%s);\n"
  747. statement += dbif.mogrify_sql_statement((sql, (map_id,)))
  748. # Now execute the insert transaction
  749. dbif.execute_transaction(statement)
  750. if connect == True:
  751. dbif.close()
  752. # increase the counter
  753. self.map_counter += 1
  754. def unregister_map(self, map, dbif = None, execute=True):
  755. """!Unregister a map from the space time dataset.
  756. This method takes care of the un-registration of a map
  757. from a space time dataset.
  758. @param map: The map object to unregister
  759. @param dbif: The database interface to be used
  760. @param execute: If True the SQL DELETE and DROP table statements will be executed.
  761. If False the prepared SQL statements are returned and must be executed by the caller.
  762. @return The SQL statements if execute == False, else an empty string, None in case of a failure
  763. """
  764. statement = ""
  765. dbif, connect = init_dbif(dbif)
  766. # First select needed data from the database
  767. map.metadata.select(dbif)
  768. map_id = map.get_id()
  769. map_register_table = map.get_stds_register()
  770. stds_register_table = self.get_map_register()
  771. if map.get_layer():
  772. core.verbose(_("Unregister %s map <%s> with layer %s") % (map.get_type(), map.get_map_id(), map.get_layer()))
  773. else:
  774. core.verbose(_("Unregister %s map <%s>") % (map.get_type(), map.get_map_id()))
  775. # Check if the map is registered in the space time raster dataset
  776. if map_register_table != None:
  777. if dbmi.paramstyle == "qmark":
  778. sql = "SELECT id FROM " + map_register_table + " WHERE id = ?"
  779. else:
  780. sql = "SELECT id FROM " + map_register_table + " WHERE id = %s"
  781. try:
  782. dbif.cursor.execute(sql, (self.base.get_id(),))
  783. row = dbif.cursor.fetchone()
  784. except:
  785. row = None
  786. # Break if the map is not registered
  787. if row == None:
  788. if map.get_layer():
  789. core.warning(_("Map <%s> with layer %s is not registered in space time dataset <%s>") %(map.get_map_id(), map.get_layer(), self.base.get_id()))
  790. else:
  791. core.warning(_("Map <%s> is not registered in space time dataset <%s>") %(map.get_map_id(), self.base.get_id()))
  792. if connect == True:
  793. dbif.close()
  794. return ""
  795. # Remove the space time raster dataset from the raster dataset register
  796. if map_register_table != None:
  797. if dbmi.paramstyle == "qmark":
  798. sql = "DELETE FROM " + map_register_table + " WHERE id = ?;\n"
  799. else:
  800. sql = "DELETE FROM " + map_register_table + " WHERE id = %s;\n"
  801. statement += dbif.mogrify_sql_statement((sql, (self.base.get_id(),)))
  802. # Remove the raster map from the space time raster dataset register
  803. if stds_register_table != None:
  804. if dbmi.paramstyle == "qmark":
  805. sql = "DELETE FROM " + stds_register_table + " WHERE id = ?;\n"
  806. else:
  807. sql = "DELETE FROM " + stds_register_table + " WHERE id = %s;\n"
  808. statement += dbif.mogrify_sql_statement((sql, (map_id,)))
  809. if execute == True:
  810. dbif.execute_transaction(statement)
  811. if connect == True:
  812. dbif.close()
  813. # decrease the counter
  814. self.map_counter -= 1
  815. if execute:
  816. return ""
  817. return statement
  818. def update_from_registered_maps(self, dbif = None):
  819. """!This methods updates the spatial and temporal extent as well as
  820. type specific metadata. It should always been called after maps are registered
  821. or unregistered/deleted from the space time dataset.
  822. The update of the temporal extent checks if the end time is set correctly.
  823. In case the registered maps have no valid end time (None) the maximum start time
  824. will be used. If the end time is earlier than the maximum start time, it will
  825. be replaced by the maximum start time.
  826. An other solution to automate this is to use the deactivated trigger
  827. in the SQL files. But this will result in a huge performance issue
  828. in case many maps are registered (>1000).
  829. @param dbif: The database interface to be used
  830. """
  831. core.verbose(_("Update metadata, spatial and temporal extent from all registered maps of <%s>") % (self.get_id()))
  832. # Nothing to do if the register is not present
  833. if not self.get_map_register():
  834. return
  835. dbif, connect = init_dbif(dbif)
  836. map_time = None
  837. use_start_time = False
  838. # Get basic info
  839. stds_name = self.base.get_name()
  840. stds_mapset = self.base.get_mapset()
  841. sql_path = get_sql_template_path()
  842. #We create a transaction
  843. sql_script = ""
  844. # Update the spatial and temporal extent from registered maps
  845. # Read the SQL template
  846. sql = open(os.path.join(sql_path, "update_stds_spatial_temporal_extent_template.sql"), 'r').read()
  847. sql = sql.replace("GRASS_MAP", self.get_new_map_instance(None).get_type())
  848. sql = sql.replace("SPACETIME_NAME", stds_name + "_" + stds_mapset )
  849. sql = sql.replace("SPACETIME_ID", self.base.get_id())
  850. sql = sql.replace("STDS", self.get_type())
  851. sql_script += sql
  852. sql_script += "\n"
  853. # Update type specific metadata
  854. sql = open(os.path.join(sql_path, "update_" + self.get_type() + "_metadata_template.sql"), 'r').read()
  855. sql = sql.replace("GRASS_MAP", self.get_new_map_instance(None).get_type())
  856. sql = sql.replace("SPACETIME_NAME", stds_name + "_" + stds_mapset )
  857. sql = sql.replace("SPACETIME_ID", self.base.get_id())
  858. sql = sql.replace("STDS", self.get_type())
  859. sql_script += sql
  860. sql_script += "\n"
  861. dbif.execute_transaction(sql_script)
  862. # Read and validate the selected end time
  863. self.select()
  864. if self.is_time_absolute():
  865. start_time, end_time, tz = self.get_absolute_time()
  866. else:
  867. start_time, end_time, unit = self.get_relative_time()
  868. # In case no end time is set, use the maximum start time of all registered maps as end time
  869. if end_time == None:
  870. use_start_time = True
  871. else:
  872. # Check if the end time is smaller than the maximum start time
  873. if self.is_time_absolute():
  874. sql = """SELECT max(start_time) FROM GRASS_MAP_absolute_time WHERE GRASS_MAP_absolute_time.id IN
  875. (SELECT id FROM SPACETIME_NAME_GRASS_MAP_register);"""
  876. sql = sql.replace("GRASS_MAP", self.get_new_map_instance(None).get_type())
  877. sql = sql.replace("SPACETIME_NAME", stds_name + "_" + stds_mapset )
  878. else:
  879. sql = """SELECT max(start_time) FROM GRASS_MAP_relative_time WHERE GRASS_MAP_relative_time.id IN
  880. (SELECT id FROM SPACETIME_NAME_GRASS_MAP_register);"""
  881. sql = sql.replace("GRASS_MAP", self.get_new_map_instance(None).get_type())
  882. sql = sql.replace("SPACETIME_NAME", stds_name + "_" + stds_mapset )
  883. dbif.cursor.execute(sql)
  884. row = dbif.cursor.fetchone()
  885. if row != None:
  886. # This seems to be a bug in sqlite3 Python driver
  887. if dbmi.__name__ == "sqlite3":
  888. tstring = row[0]
  889. # Convert the unicode string into the datetime format
  890. if self.is_time_absolute():
  891. if tstring.find(":") > 0:
  892. time_format = "%Y-%m-%d %H:%M:%S"
  893. else:
  894. time_format = "%Y-%m-%d"
  895. max_start_time = datetime.strptime(tstring, time_format)
  896. else:
  897. max_start_time = row[0]
  898. else:
  899. max_start_time = row[0]
  900. if end_time < max_start_time:
  901. use_start_time = True
  902. # Set the maximum start time as end time
  903. if use_start_time:
  904. if self.is_time_absolute():
  905. sql = """UPDATE STDS_absolute_time SET end_time =
  906. (SELECT max(start_time) FROM GRASS_MAP_absolute_time WHERE GRASS_MAP_absolute_time.id IN
  907. (SELECT id FROM SPACETIME_NAME_GRASS_MAP_register)
  908. ) WHERE id = 'SPACETIME_ID';"""
  909. sql = sql.replace("GRASS_MAP", self.get_new_map_instance(None).get_type())
  910. sql = sql.replace("SPACETIME_NAME", stds_name + "_" + stds_mapset )
  911. sql = sql.replace("SPACETIME_ID", self.base.get_id())
  912. sql = sql.replace("STDS", self.get_type())
  913. elif self.is_time_relative():
  914. sql = """UPDATE STDS_relative_time SET end_time =
  915. (SELECT max(start_time) FROM GRASS_MAP_relative_time WHERE GRASS_MAP_relative_time.id IN
  916. (SELECT id FROM SPACETIME_NAME_GRASS_MAP_register)
  917. ) WHERE id = 'SPACETIME_ID';"""
  918. sql = sql.replace("GRASS_MAP", self.get_new_map_instance(None).get_type())
  919. sql = sql.replace("SPACETIME_NAME", stds_name + "_" + stds_mapset )
  920. sql = sql.replace("SPACETIME_ID", self.base.get_id())
  921. sql = sql.replace("STDS", self.get_type())
  922. dbif.execute_transaction(sql)
  923. # Count the temporal map types
  924. maps = self.get_registered_maps_as_objects(dbif=dbif)
  925. tlist = self.count_temporal_types(maps)
  926. if tlist["interval"] > 0 and tlist["point"] == 0 and tlist["invalid"] == 0:
  927. map_time = "interval"
  928. elif tlist["interval"] == 0 and tlist["point"] > 0 and tlist["invalid"] == 0:
  929. map_time = "point"
  930. elif tlist["interval"] > 0 and tlist["point"] > 0 and tlist["invalid"] == 0:
  931. map_time = "mixed"
  932. else:
  933. map_time = "invalid"
  934. # Compute the granularity
  935. if map_time != "invalid":
  936. # Smallest supported temporal resolution
  937. if self.is_time_absolute():
  938. gran = compute_absolute_time_granularity(maps)
  939. elif self.is_time_relative():
  940. gran = compute_relative_time_granularity(maps)
  941. else:
  942. gran = None
  943. # Set the map time type and update the time objects
  944. if self.is_time_absolute():
  945. self.absolute_time.select(dbif)
  946. self.metadata.select(dbif)
  947. if self.metadata.get_number_of_maps() > 0:
  948. self.absolute_time.set_map_time(map_time)
  949. self.absolute_time.set_granularity(gran)
  950. else:
  951. self.absolute_time.set_map_time(None)
  952. self.absolute_time.set_granularity(None)
  953. self.absolute_time.update_all(dbif)
  954. else:
  955. self.relative_time.select(dbif)
  956. self.metadata.select(dbif)
  957. if self.metadata.get_number_of_maps() > 0:
  958. self.relative_time.set_map_time(map_time)
  959. self.relative_time.set_granularity(gran)
  960. else:
  961. self.relative_time.set_map_time(None)
  962. self.relative_time.set_granularity(None)
  963. self.relative_time.update_all(dbif)
  964. if connect == True:
  965. dbif.close()
  966. ###############################################################################
  967. def create_temporal_relation_sql_where_statement(start, end, use_start=True, use_during=False,
  968. use_overlap=False, use_contain=False, use_equal=False,
  969. use_follows=False, use_precedes=False):
  970. """!Create a SQL WHERE statement for temporal relation selection of maps in space time datasets
  971. @param start: The start time
  972. @param end: The end time
  973. @param use_start: Select maps of which the start time is located in the selection granule
  974. map : s
  975. granule: s-----------------e
  976. map : s--------------------e
  977. granule: s-----------------e
  978. map : s--------e
  979. granule: s-----------------e
  980. @param use_during: during: Select maps which are temporal during the selection granule
  981. map : s-----------e
  982. granule: s-----------------e
  983. @param use_overlap: Select maps which temporal overlap the selection granule
  984. map : s-----------e
  985. granule: s-----------------e
  986. map : s-----------e
  987. granule: s----------e
  988. @param use_contain: Select maps which temporally contain the selection granule
  989. map : s-----------------e
  990. granule: s-----------e
  991. @param use_equal: Select maps which temporally equal to the selection granule
  992. map : s-----------e
  993. granule: s-----------e
  994. @param use_follows: Select maps which temporally follow the selection granule
  995. map : s-----------e
  996. granule: s-----------e
  997. @param use_precedes: Select maps which temporally precedes the selection granule
  998. map : s-----------e
  999. granule: s-----------e
  1000. """
  1001. where = "("
  1002. if use_start:
  1003. where += "(start_time >= '%s' and start_time < '%s') " % (start, end)
  1004. if use_during:
  1005. if use_start:
  1006. where += " OR "
  1007. where += "((start_time > '%s' and end_time < '%s') OR " % (start, end)
  1008. where += "(start_time >= '%s' and end_time < '%s') OR " % (start, end)
  1009. where += "(start_time > '%s' and end_time <= '%s'))" % (start, end)
  1010. if use_overlap:
  1011. if use_start or use_during:
  1012. where += " OR "
  1013. where += "((start_time < '%s' and end_time > '%s' and end_time < '%s') OR " % (start, start, end)
  1014. where += "(start_time < '%s' and start_time > '%s' and end_time > '%s'))" % (end, start, end)
  1015. if use_contain:
  1016. if use_start or use_during or use_overlap:
  1017. where += " OR "
  1018. where += "((start_time < '%s' and end_time > '%s') OR " % (start, end)
  1019. where += "(start_time <= '%s' and end_time > '%s') OR " % (start, end)
  1020. where += "(start_time < '%s' and end_time >= '%s'))" % (start, end)
  1021. if use_equal:
  1022. if use_start or use_during or use_overlap or use_contain:
  1023. where += " OR "
  1024. where += "(start_time = '%s' and end_time = '%s')" % (start, end)
  1025. if use_follows:
  1026. if use_start or use_during or use_overlap or use_contain or use_equal:
  1027. where += " OR "
  1028. where += "(start_time = '%s')" % (end)
  1029. if use_precedes:
  1030. if use_start or use_during or use_overlap or use_contain or use_equal or use_follows:
  1031. where += " OR "
  1032. where += "(end_time = '%s')" % (start)
  1033. where += ")"
  1034. # Catch empty where statement
  1035. if where == "()":
  1036. where = None
  1037. return where