abstract_space_time_dataset.py 52 KB

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