abstract_space_time_dataset.py 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381
  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. connect = False
  374. if dbif == None:
  375. dbif = sql_database_interface()
  376. dbif.connect()
  377. connect = True
  378. obj_list = []
  379. sample_maps = stds.get_registered_maps_as_objects_with_gaps(where=None, dbif=dbif)
  380. for granule in sample_maps:
  381. # Read the spatial extent
  382. if spatial == True:
  383. granule.spatial_extent.select(dbif)
  384. start, end = granule.get_valid_time()
  385. where = create_temporal_relation_sql_where_statement(start, end, use_start, \
  386. use_during, use_overlap, use_contain, use_equal)
  387. maps = self.get_registered_maps_as_objects(where, "start_time", dbif)
  388. result = {}
  389. result["granule"] = granule
  390. num_samples = 0
  391. maplist = []
  392. if maps:
  393. for map in maps:
  394. # Read the spatial extent
  395. if spatial == True:
  396. map.spatial_extent.select(dbif)
  397. # Ignore spatial disjoint maps
  398. if not granule.spatial_overlapping(map):
  399. continue
  400. num_samples += 1
  401. maplist.append(copy.copy(map))
  402. # Fill with empty map in case no spatio-temporal relations found
  403. if not maps or num_samples == 0:
  404. map = self.get_new_map_instance(None)
  405. if self.is_time_absolute():
  406. map.set_absolute_time(start, end)
  407. elif self.is_time_relative():
  408. map.set_relative_time(start, end, self.get_relative_time_unit())
  409. maplist.append(copy.copy(map))
  410. result["samples"] = maplist
  411. obj_list.append(copy.copy(result))
  412. if connect == True:
  413. dbif.close()
  414. return obj_list
  415. def get_registered_maps_as_objects_by_granularity(self, gran=None, dbif=None):
  416. """Return all registered maps as ordered (by start_time) object list with
  417. "gap" map objects (id==None) for temporal topological operations using the
  418. granularity of the space time dataset as increment. Each list entry is a list of map objects
  419. which are potentially located in the actual granule.
  420. A valid temporal topology (no overlapping or inclusion allowed) is needed to get correct results.
  421. The dataset must have "interval" as temporal map type, so all maps have valid interval time.
  422. Gaps between maps are identified as unregistered maps with id==None.
  423. The objects are initialized with the id and the temporal extent (temporal type, start time, end time).
  424. In case more map information are needed, use the select() method for each listed object.
  425. @param gran: The granularity to be used
  426. @param dbif: The database interface to be used
  427. In case nothing found None is returned
  428. """
  429. connect = False
  430. if dbif == None:
  431. dbif = sql_database_interface()
  432. dbif.connect()
  433. connect = True
  434. obj_list = []
  435. if gran == None:
  436. gran = self.get_granularity()
  437. start, end = self.get_valid_time()
  438. while start < end:
  439. if self.is_time_absolute():
  440. next = increment_datetime_by_string(start, gran)
  441. else:
  442. next = start + gran
  443. where = "(start_time <= '%s' and end_time >= '%s')" % (start, next)
  444. rows = self.get_registered_maps("id", where, "start_time", dbif)
  445. if rows:
  446. if len(rows) > 1:
  447. 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."))
  448. maplist = []
  449. for row in rows:
  450. # Take the first map
  451. map = self.get_new_map_instance(rows[0]["id"])
  452. if self.is_time_absolute():
  453. map.set_absolute_time(start, next)
  454. elif self.is_time_relative():
  455. map.set_relative_time(start, next, self.get_relative_time_unit())
  456. maplist.append(copy.copy(map))
  457. obj_list.append(copy.copy(maplist))
  458. start = next
  459. if connect == True:
  460. dbif.close()
  461. return obj_list
  462. def get_registered_maps_as_objects_with_gaps(self, where=None, dbif=None):
  463. """Return all registered maps as ordered (by start_time) object list with
  464. "gap" map objects (id==None) for temporal topological operations
  465. Gaps between maps are identified as maps with id==None
  466. The objects are initialized with the id and the temporal extent (temporal type, start time, end time).
  467. In case more map information are needed, use the select() method for each listed object.
  468. @param where: The SQL where statement to select a subset of the registered maps without "WHERE"
  469. @param dbif: The database interface to be used
  470. In case nothing found None is returned
  471. """
  472. connect = False
  473. if dbif == None:
  474. dbif = sql_database_interface()
  475. dbif.connect()
  476. connect = True
  477. obj_list = []
  478. maps = self.get_registered_maps_as_objects(where, "start_time", dbif)
  479. if maps and len(maps) > 0:
  480. for i in range(len(maps)):
  481. obj_list.append(maps[i])
  482. # Detect and insert gaps
  483. if i < len(maps) - 1:
  484. relation = maps[i + 1].temporal_relation(maps[i])
  485. if relation == "after":
  486. start1, end1 = maps[i].get_valid_time()
  487. start2, end2 = maps[i + 1].get_valid_time()
  488. end = start2
  489. if end1:
  490. start = end1
  491. else:
  492. start = start1
  493. map = self.get_new_map_instance(None)
  494. if self.is_time_absolute():
  495. map.set_absolute_time(start, end)
  496. elif self.is_time_relative():
  497. map.set_relative_time(start, end, self.get_relative_time_unit())
  498. obj_list.append(copy.copy(map))
  499. if connect == True:
  500. dbif.close()
  501. return obj_list
  502. def get_registered_maps_as_objects(self, where=None, order="start_time", dbif=None):
  503. """Return all registered maps as ordered object list for temporal topological operations
  504. The objects are initialized with the id and the temporal extent (temporal type, start time, end time).
  505. In case more map information are needed, use the select() method for each listed object.
  506. @param where: The SQL where statement to select a subset of the registered maps without "WHERE"
  507. @param order: The SQL order statement to be used to order the objects in the list without "ORDER BY"
  508. @param dbif: The database interface to be used
  509. In case nothing found None is returned
  510. """
  511. connect = False
  512. if dbif == None:
  513. dbif = sql_database_interface()
  514. dbif.connect()
  515. connect = True
  516. obj_list = []
  517. rows = self.get_registered_maps("id,start_time,end_time", where, order, dbif)
  518. count = 0
  519. if rows:
  520. for row in rows:
  521. core.percent(count, len(rows), 1)
  522. map = self.get_new_map_instance(row["id"])
  523. if self.is_time_absolute():
  524. map.set_absolute_time(row["start_time"], row["end_time"])
  525. elif self.is_time_relative():
  526. map.set_relative_time(row["start_time"], row["end_time"], self.get_relative_time_unit())
  527. obj_list.append(copy.copy(map))
  528. count += 1
  529. core.percent(1, 1, 1)
  530. if connect == True:
  531. dbif.close()
  532. return obj_list
  533. def get_registered_maps(self, columns=None, where = None, order = None, dbif=None):
  534. """Return sqlite rows of all registered maps.
  535. In case columns are not specified, each row includes all columns specified in the datatype specific view
  536. @param columns: Columns to be selected as SQL compliant string
  537. @param where: The SQL where statement to select a subset of the registered maps without "WHERE"
  538. @param order: The SQL order statement to be used to order the objects in the list without "ORDER BY"
  539. @param dbif: The database interface to be used
  540. In case nothing found None is returned
  541. """
  542. connect = False
  543. if dbif == None:
  544. dbif = sql_database_interface()
  545. dbif.connect()
  546. connect = True
  547. rows = None
  548. if self.get_map_register():
  549. # Use the correct temporal table
  550. if self.get_temporal_type() == "absolute":
  551. map_view = self.get_new_map_instance(None).get_type() + "_view_abs_time"
  552. else:
  553. map_view = self.get_new_map_instance(None).get_type() + "_view_rel_time"
  554. if columns:
  555. sql = "SELECT %s FROM %s WHERE %s.id IN (SELECT id FROM %s)" % (columns, map_view, map_view, self.get_map_register())
  556. else:
  557. sql = "SELECT * FROM %s WHERE %s.id IN (SELECT id FROM %s)" % (map_view, map_view, self.get_map_register())
  558. if where:
  559. sql += " AND %s" % (where)
  560. if order:
  561. sql += " ORDER BY %s" % (order)
  562. try:
  563. dbif.cursor.execute(sql)
  564. rows = dbif.cursor.fetchall()
  565. except:
  566. if connect == True:
  567. dbif.close()
  568. core.error(_("Unable to get map ids from register table <%s>") % (self.get_map_register()))
  569. raise
  570. if connect == True:
  571. dbif.close()
  572. return rows
  573. def delete(self, dbif=None):
  574. """Delete a space time dataset from the temporal database
  575. This method removes the space time dataset from the temporal database and drops its map register table
  576. @param dbif: The database interface to be used
  577. """
  578. # First we need to check if maps are registered in this dataset and
  579. # unregister them
  580. core.verbose(_("Delete space time %s dataset <%s> from temporal database") % (self.get_new_map_instance(ident=None).get_type(), self.get_id()))
  581. connect = False
  582. if dbif == None:
  583. dbif = sql_database_interface()
  584. dbif.connect()
  585. connect = True
  586. # SELECT all needed information from the database
  587. self.select(dbif)
  588. core.verbose(_("Drop map register table: %s") % (self.get_map_register()))
  589. if self.get_map_register():
  590. rows = self.get_registered_maps("id", None, None, dbif)
  591. # Unregister each registered map in the table
  592. if rows:
  593. num_maps = len(rows)
  594. count = 0
  595. for row in rows:
  596. core.percent(count, num_maps, 1)
  597. # Unregister map
  598. map = self.get_new_map_instance(row["id"])
  599. self.unregister_map(map, dbif)
  600. count += 1
  601. core.percent(1, 1, 1)
  602. try:
  603. # Drop the map register table
  604. sql = "DROP TABLE " + self.get_map_register()
  605. dbif.cursor.execute(sql)
  606. dbif.connection.commit()
  607. except:
  608. if connect == True:
  609. dbif.close()
  610. core.error(_("Unable to drop table <%s>") % (self.get_map_register()))
  611. raise
  612. # Remove the primary key, the foreign keys will be removed by trigger
  613. self.base.delete(dbif)
  614. self.reset(None)
  615. if connect == True:
  616. dbif.close()
  617. def register_map(self, map, dbif=None):
  618. """ Register a map in the space time dataset.
  619. This method takes care of the registration of a map
  620. in a space time dataset.
  621. In case the map is already registered this function will break with a warning
  622. and return False
  623. @param dbif: The database interface to be used
  624. """
  625. connect = False
  626. if dbif == None:
  627. dbif = sql_database_interface()
  628. dbif.connect()
  629. connect = True
  630. if map.is_in_db(dbif) == False:
  631. dbif.close()
  632. core.fatal(_("Only maps with absolute or relative valid time can be registered"))
  633. if map.get_layer():
  634. 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()))
  635. else:
  636. 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()))
  637. # First select all data from the database
  638. map.select(dbif)
  639. if not map.check_valid_time():
  640. if map.get_layer():
  641. core.fatal(_("Map <%s> with layer %s has invalid time") % map.get_map_id(), map.get_layer())
  642. else:
  643. core.fatal(_("Map <%s> has invalid time") % map.get_map_id())
  644. map_id = map.base.get_id()
  645. map_name = map.base.get_name()
  646. map_mapset = map.base.get_mapset()
  647. map_register_table = map.get_stds_register()
  648. map_rel_time_unit = map.get_relative_time_unit()
  649. map_ttype = map.get_temporal_type()
  650. #print "Map register table", map_register_table
  651. # Get basic info
  652. stds_name = self.base.get_name()
  653. stds_mapset = self.base.get_mapset()
  654. stds_register_table = self.get_map_register()
  655. stds_ttype = self.get_temporal_type()
  656. # Check temporal types
  657. if stds_ttype != map_ttype:
  658. if map.get_layer():
  659. 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()))
  660. else:
  661. core.fatal(_("Temporal type of space time dataset <%s> and map <%s> are different") % (self.get_id(), map.get_map_id()))
  662. # In case no map has been registered yet, set the relative time unit from the first map
  663. if (self.metadata.get_number_of_maps() == None or self.metadata.get_number_of_maps() == 0) and \
  664. self.map_counter == 0 and self.is_time_relative():
  665. self.set_relative_time_unit(map_rel_time_unit)
  666. self.relative_time.update()
  667. core.verbose(_("Set temporal unit for space time %s dataset <%s> to %s") % (map.get_type(), self.get_id(), map_rel_time_unit))
  668. stds_rel_time_unit = self.get_relative_time_unit()
  669. # Check the relative time unit
  670. if self.is_time_relative() and (stds_rel_time_unit != map_rel_time_unit):
  671. if map.get_layer():
  672. 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()))
  673. else:
  674. core.fatal(_("Relative time units of space time dataset <%s> and map <%s> are different") % (self.get_id(), map.get_map_id()))
  675. #print "STDS register table", stds_register_table
  676. if stds_mapset != map_mapset:
  677. dbif.close()
  678. core.fatal(_("Only maps from the same mapset can be registered"))
  679. # Check if map is already registered
  680. if stds_register_table:
  681. if dbmi.paramstyle == "qmark":
  682. sql = "SELECT id FROM " + stds_register_table + " WHERE id = (?)"
  683. else:
  684. sql = "SELECT id FROM " + stds_register_table + " WHERE id = (%s)"
  685. dbif.cursor.execute(sql, (map_id,))
  686. row = dbif.cursor.fetchone()
  687. # In case of no entry make a new one
  688. if row and row[0] == map_id:
  689. if connect == True:
  690. dbif.close()
  691. if map.get_layer():
  692. core.warning(_("Map <%s> with layer %s is already registered.") % (map.get_map_id(), map.get_layer()))
  693. else:
  694. core.warning(_("Map <%s> is already registered.") % (map.get_map_id()))
  695. return False
  696. # Create tables
  697. sql_path = get_sql_template_path()
  698. # We need to create the map raster register table before we can register the map
  699. if map_register_table == None:
  700. # Create a unique id
  701. uuid_rand = "map_" + str(uuid.uuid4()).replace("-", "")
  702. map_register_table = uuid_rand + "_" + self.get_type() + "_register"
  703. # Read the SQL template
  704. sql = open(os.path.join(sql_path, "map_stds_register_table_template.sql"), 'r').read()
  705. # Create the raster, raster3d and vector tables
  706. sql = sql.replace("GRASS_MAP", map.get_type())
  707. sql = sql.replace("MAP_NAME", map_name + "_" + map_mapset )
  708. sql = sql.replace("TABLE_NAME", uuid_rand )
  709. sql = sql.replace("MAP_ID", map_id)
  710. sql = sql.replace("STDS", self.get_type())
  711. try:
  712. if dbmi.__name__ == "sqlite3":
  713. dbif.cursor.executescript(sql)
  714. else:
  715. dbif.cursor.execute(sql)
  716. except:
  717. if connect == True:
  718. dbif.close()
  719. if map.get_layer():
  720. core.error(_("Unable to create the space time %s dataset register table for map <%s> with layer %s") % \
  721. (map.get_type(), map.get_map_id(), map.get_layer()))
  722. else:
  723. core.error(_("Unable to create the space time %s dataset register table for <%s>") % \
  724. (map.get_type(), map.get_map_id()))
  725. raise
  726. # Set the stds register table name and put it into the DB
  727. map.set_stds_register(map_register_table)
  728. map.metadata.update(dbif)
  729. if map.get_layer():
  730. core.verbose(_("Created register table <%s> for %s map <%s> with layer %s") % \
  731. (map_register_table, map.get_type(), map.get_map_id(), map.get_layer()))
  732. else:
  733. core.verbose(_("Created register table <%s> for %s map <%s>") % \
  734. (map_register_table, map.get_type(), map.get_map_id()))
  735. # We need to create the table and register it
  736. if stds_register_table == None:
  737. # Create table name
  738. stds_register_table = stds_name + "_" + stds_mapset + "_" + map.get_type() + "_register"
  739. # Read the SQL template
  740. sql = open(os.path.join(sql_path, "stds_map_register_table_template.sql"), 'r').read()
  741. # Create the raster, raster3d and vector tables
  742. sql = sql.replace("GRASS_MAP", map.get_type())
  743. sql = sql.replace("SPACETIME_NAME", stds_name + "_" + stds_mapset )
  744. sql = sql.replace("SPACETIME_ID", self.base.get_id())
  745. sql = sql.replace("STDS", self.get_type())
  746. sql_script = ""
  747. sql_script += "BEGIN TRANSACTION;\n"
  748. sql_script += sql
  749. sql_script += "\n"
  750. sql_script += "END TRANSACTION;"
  751. try:
  752. if dbmi.__name__ == "sqlite3":
  753. dbif.cursor.executescript(sql_script)
  754. else:
  755. dbif.cursor.execute(sql_script)
  756. dbif.connection.commit()
  757. except:
  758. if connect == True:
  759. dbif.close()
  760. if map.get_layer():
  761. core.error(_("Unable to create the space time %s dataset register table for map <%s> with layer %s") % \
  762. (map.get_type(), map.get_map_id(), map.get_layer()))
  763. else:
  764. core.error(_("Unable to create the space time %s dataset register table for <%s>") % \
  765. (map.get_type(), map.get_map_id()))
  766. raise
  767. # Set the map register table name and put it into the DB
  768. self.set_map_register(stds_register_table)
  769. self.metadata.update(dbif)
  770. core.verbose(_("Created register table <%s> for space time %s dataset <%s>") % \
  771. (stds_register_table, map.get_type(), self.get_id()))
  772. # Register the stds in the map stds register table
  773. # Check if the entry is already there
  774. if dbmi.paramstyle == "qmark":
  775. sql = "SELECT id FROM " + map_register_table + " WHERE id = ?"
  776. else:
  777. sql = "SELECT id FROM " + map_register_table + " WHERE id = %s"
  778. dbif.cursor.execute(sql, (self.base.get_id(),))
  779. row = dbif.cursor.fetchone()
  780. # In case of no entry make a new one
  781. if row == None:
  782. if dbmi.paramstyle == "qmark":
  783. sql = "INSERT INTO " + map_register_table + " (id) " + "VALUES (?)"
  784. else:
  785. sql = "INSERT INTO " + map_register_table + " (id) " + "VALUES (%s)"
  786. #print sql
  787. dbif.cursor.execute(sql, (self.base.get_id(),))
  788. # Now put the raster name in the stds map register table
  789. if dbmi.paramstyle == "qmark":
  790. sql = "INSERT INTO " + stds_register_table + " (id) " + "VALUES (?)"
  791. else:
  792. sql = "INSERT INTO " + stds_register_table + " (id) " + "VALUES (%s)"
  793. #print sql
  794. dbif.cursor.execute(sql, (map_id,))
  795. if connect == True:
  796. dbif.close()
  797. # increase the counter
  798. self.map_counter += 1
  799. return True
  800. def unregister_map(self, map, dbif = None):
  801. """Unregister a map from the space time dataset.
  802. This method takes care of the un-registration of a map
  803. from a space time dataset.
  804. @param map: The map object to unregister
  805. @param dbif: The database interface to be used
  806. """
  807. connect = False
  808. if dbif == None:
  809. dbif = sql_database_interface()
  810. dbif.connect()
  811. connect = True
  812. if map.is_in_db(dbif) == False:
  813. dbif.close()
  814. if map.get_layer():
  815. core.fatal(_("Unable to find map <%s> with layer %s in temporal database") % (map.get_map_id(), map.get_layer()))
  816. else:
  817. core.fatal(_("Unable to find map <%s> in temporal database") % (map.get_map_id()))
  818. if map.get_layer():
  819. core.verbose(_("Unregister %s map <%s> with layer %s") % (map.get_type(), map.get_map_id(), map.get_layer()))
  820. else:
  821. core.verbose(_("Unregister %s map <%s>") % (map.get_type(), map.get_map_id()))
  822. # First select all data from the database
  823. map.select(dbif)
  824. map_id = map.get_id()
  825. map_register_table = map.get_stds_register()
  826. stds_register_table = self.get_map_register()
  827. # Check if the map is registered in the space time raster dataset
  828. if dbmi.paramstyle == "qmark":
  829. sql = "SELECT id FROM " + map_register_table + " WHERE id = ?"
  830. else:
  831. sql = "SELECT id FROM " + map_register_table + " WHERE id = %s"
  832. dbif.cursor.execute(sql, (self.base.get_id(),))
  833. row = dbif.cursor.fetchone()
  834. # Break if the map is not registered
  835. if row == None:
  836. if map.get_layer():
  837. 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()))
  838. else:
  839. core.warning(_("Map <%s> is not registered in space time dataset <%s>") %(map.get_map_id(), self.base.get_id()))
  840. if connect == True:
  841. dbif.close()
  842. return False
  843. # Remove the space time raster dataset from the raster dataset register
  844. if map_register_table != None:
  845. if dbmi.paramstyle == "qmark":
  846. sql = "DELETE FROM " + map_register_table + " WHERE id = ?"
  847. else:
  848. sql = "DELETE FROM " + map_register_table + " WHERE id = %s"
  849. dbif.cursor.execute(sql, (self.base.get_id(),))
  850. # Remove the raster map from the space time raster dataset register
  851. if stds_register_table != None:
  852. if dbmi.paramstyle == "qmark":
  853. sql = "DELETE FROM " + stds_register_table + " WHERE id = ?"
  854. else:
  855. sql = "DELETE FROM " + stds_register_table + " WHERE id = %s"
  856. dbif.cursor.execute(sql, (map_id,))
  857. if connect == True:
  858. dbif.close()
  859. # decrease the counter
  860. self.map_counter -= 1
  861. def update_from_registered_maps(self, dbif = None):
  862. """This methods updates the spatial and temporal extent as well as
  863. type specific metadata. It should always been called after maps are registered
  864. or unregistered/deleted from the space time dataset.
  865. The update of the temporal extent checks if the end time is set correctly.
  866. In case the registered maps have no valid end time (None) the maximum start time
  867. will be used. If the end time is earlier than the maximum start time, it will
  868. be replaced by the maximum start time.
  869. An other solution to automate this is to use the deactivated trigger
  870. in the SQL files. But this will result in a huge performance issue
  871. in case many maps are registered (>1000).
  872. @param dbif: The database interface to be used
  873. """
  874. core.verbose(_("Update metadata, spatial and temporal extent from all registered maps of <%s>") % (self.get_id()))
  875. # Nothing to do if the register is not present
  876. if not self.get_map_register():
  877. return
  878. connect = False
  879. if dbif == None:
  880. dbif = sql_database_interface()
  881. dbif.connect()
  882. connect = True
  883. map_time = None
  884. use_start_time = False
  885. # Get basic info
  886. stds_name = self.base.get_name()
  887. stds_mapset = self.base.get_mapset()
  888. sql_path = get_sql_template_path()
  889. #We create a transaction
  890. sql_script = ""
  891. sql_script += "BEGIN TRANSACTION;\n"
  892. # Update the spatial and temporal extent from registered maps
  893. # Read the SQL template
  894. sql = open(os.path.join(sql_path, "update_stds_spatial_temporal_extent_template.sql"), 'r').read()
  895. sql = sql.replace("GRASS_MAP", self.get_new_map_instance(None).get_type())
  896. sql = sql.replace("SPACETIME_NAME", stds_name + "_" + stds_mapset )
  897. sql = sql.replace("SPACETIME_ID", self.base.get_id())
  898. sql = sql.replace("STDS", self.get_type())
  899. sql_script += sql
  900. sql_script += "\n"
  901. # Update type specific metadata
  902. sql = open(os.path.join(sql_path, "update_" + self.get_type() + "_metadata_template.sql"), 'r').read()
  903. sql = sql.replace("GRASS_MAP", self.get_new_map_instance(None).get_type())
  904. sql = sql.replace("SPACETIME_NAME", stds_name + "_" + stds_mapset )
  905. sql = sql.replace("SPACETIME_ID", self.base.get_id())
  906. sql = sql.replace("STDS", self.get_type())
  907. sql_script += sql
  908. sql_script += "\n"
  909. sql_script += "END TRANSACTION;"
  910. if dbmi.__name__ == "sqlite3":
  911. dbif.cursor.executescript(sql_script)
  912. else:
  913. dbif.cursor.execute(sql_script)
  914. # Read and validate the selected end time
  915. self.select()
  916. if self.is_time_absolute():
  917. start_time, end_time, tz = self.get_absolute_time()
  918. else:
  919. start_time, end_time, unit = self.get_relative_time()
  920. # In case no end time is set, use the maximum start time of all registered maps as end time
  921. if end_time == None:
  922. use_start_time = True
  923. else:
  924. # Check if the end time is smaller than the maximum start time
  925. if self.is_time_absolute():
  926. sql = """SELECT max(start_time) FROM GRASS_MAP_absolute_time WHERE GRASS_MAP_absolute_time.id IN
  927. (SELECT id FROM SPACETIME_NAME_GRASS_MAP_register);"""
  928. sql = sql.replace("GRASS_MAP", self.get_new_map_instance(None).get_type())
  929. sql = sql.replace("SPACETIME_NAME", stds_name + "_" + stds_mapset )
  930. else:
  931. sql = """SELECT max(start_time) FROM GRASS_MAP_relative_time WHERE GRASS_MAP_relative_time.id IN
  932. (SELECT id FROM SPACETIME_NAME_GRASS_MAP_register);"""
  933. sql = sql.replace("GRASS_MAP", self.get_new_map_instance(None).get_type())
  934. sql = sql.replace("SPACETIME_NAME", stds_name + "_" + stds_mapset )
  935. dbif.cursor.execute(sql)
  936. row = dbif.cursor.fetchone()
  937. if row != None:
  938. # This seems to be a bug in sqlite3 Python driver
  939. if dbmi.__name__ == "sqlite3":
  940. tstring = row[0]
  941. # Convert the unicode string into the datetime format
  942. if self.is_time_absolute():
  943. if tstring.find(":") > 0:
  944. time_format = "%Y-%m-%d %H:%M:%S"
  945. else:
  946. time_format = "%Y-%m-%d"
  947. max_start_time = datetime.strptime(tstring, time_format)
  948. else:
  949. max_start_time = row[0]
  950. else:
  951. max_start_time = row[0]
  952. if end_time < max_start_time:
  953. use_start_time = True
  954. # Set the maximum start time as end time
  955. if use_start_time:
  956. if self.is_time_absolute():
  957. sql = """UPDATE STDS_absolute_time SET end_time =
  958. (SELECT max(start_time) FROM GRASS_MAP_absolute_time WHERE GRASS_MAP_absolute_time.id IN
  959. (SELECT id FROM SPACETIME_NAME_GRASS_MAP_register)
  960. ) WHERE id = 'SPACETIME_ID';"""
  961. sql = sql.replace("GRASS_MAP", self.get_new_map_instance(None).get_type())
  962. sql = sql.replace("SPACETIME_NAME", stds_name + "_" + stds_mapset )
  963. sql = sql.replace("SPACETIME_ID", self.base.get_id())
  964. sql = sql.replace("STDS", self.get_type())
  965. elif self.is_time_relative():
  966. sql = """UPDATE STDS_relative_time SET end_time =
  967. (SELECT max(start_time) FROM GRASS_MAP_relative_time WHERE GRASS_MAP_relative_time.id IN
  968. (SELECT id FROM SPACETIME_NAME_GRASS_MAP_register)
  969. ) WHERE id = 'SPACETIME_ID';"""
  970. sql = sql.replace("GRASS_MAP", self.get_new_map_instance(None).get_type())
  971. sql = sql.replace("SPACETIME_NAME", stds_name + "_" + stds_mapset )
  972. sql = sql.replace("SPACETIME_ID", self.base.get_id())
  973. sql = sql.replace("STDS", self.get_type())
  974. if dbmi.__name__ == "sqlite3":
  975. dbif.cursor.executescript(sql)
  976. else:
  977. dbif.cursor.execute(sql)
  978. # Count the temporal map types
  979. maps = self.get_registered_maps_as_objects(dbif=dbif)
  980. tlist = self.count_temporal_types(maps)
  981. if tlist["interval"] > 0 and tlist["point"] == 0 and tlist["invalid"] == 0:
  982. map_time = "interval"
  983. elif tlist["interval"] == 0 and tlist["point"] > 0 and tlist["invalid"] == 0:
  984. map_time = "point"
  985. elif tlist["interval"] > 0 and tlist["point"] > 0 and tlist["invalid"] == 0:
  986. map_time = "mixed"
  987. else:
  988. map_time = "invalid"
  989. # Compute the granularity
  990. if map_time != "invalid":
  991. # Smallest supported temporal resolution
  992. if self.is_time_absolute():
  993. gran = compute_absolute_time_granularity(maps)
  994. elif self.is_time_relative():
  995. gran = compute_relative_time_granularity(maps)
  996. else:
  997. gran = None
  998. # Set the map time type and update the time objects
  999. if self.is_time_absolute():
  1000. self.absolute_time.select(dbif)
  1001. self.metadata.select(dbif)
  1002. if self.metadata.get_number_of_maps() > 0:
  1003. self.absolute_time.set_map_time(map_time)
  1004. self.absolute_time.set_granularity(gran)
  1005. else:
  1006. self.absolute_time.set_map_time(None)
  1007. self.absolute_time.set_granularity(None)
  1008. self.absolute_time.update_all(dbif)
  1009. else:
  1010. self.relative_time.select(dbif)
  1011. self.metadata.select(dbif)
  1012. if self.metadata.get_number_of_maps() > 0:
  1013. self.relative_time.set_map_time(map_time)
  1014. self.relative_time.set_granularity(gran)
  1015. else:
  1016. self.relative_time.set_map_time(None)
  1017. self.relative_time.set_granularity(None)
  1018. self.relative_time.update_all(dbif)
  1019. if connect == True:
  1020. dbif.close()
  1021. ###############################################################################
  1022. def create_temporal_relation_sql_where_statement(start, end, use_start=True, use_during=False,
  1023. use_overlap=False, use_contain=False, use_equal=False):
  1024. """ Create a SQL WHERE statement for temporal relation selection of maps in space time datasets
  1025. @param start: The start time
  1026. @param end: The end time
  1027. @param use_start: Select maps of which the start time is located in the selection granule
  1028. map : s
  1029. granule: s-----------------e
  1030. map : s--------------------e
  1031. granule: s-----------------e
  1032. map : s--------e
  1033. granule: s-----------------e
  1034. @param use_during: during: Select maps which are temporal during the selection granule
  1035. map : s-----------e
  1036. granule: s-----------------e
  1037. @param use_overlap: Select maps which temporal overlap the selection granule
  1038. map : s-----------e
  1039. granule: s-----------------e
  1040. map : s-----------e
  1041. granule: s----------e
  1042. @param use_contain: Select maps which temporally contain the selection granule
  1043. map : s-----------------e
  1044. granule: s-----------e
  1045. @param use_equal: Select maps which temporally equal to the selection granule
  1046. map : s-----------e
  1047. granule: s-----------e
  1048. """
  1049. where = "("
  1050. if use_start:
  1051. where += "(start_time >= '%s' and start_time < '%s') " % (start, end)
  1052. if use_during:
  1053. if use_start:
  1054. where += " OR "
  1055. where += "((start_time > '%s' and end_time < '%s') OR " % (start, end)
  1056. where += "(start_time >= '%s' and end_time < '%s') OR " % (start, end)
  1057. where += "(start_time > '%s' and end_time <= '%s'))" % (start, end)
  1058. if use_overlap:
  1059. if use_start or use_during:
  1060. where += " OR "
  1061. where += "((start_time < '%s' and end_time > '%s' and end_time < '%s') OR " % (start, start, end)
  1062. where += "(start_time < '%s' and start_time > '%s' and end_time > '%s'))" % (end, start, end)
  1063. if use_contain:
  1064. if use_start or use_during or use_overlap:
  1065. where += " OR "
  1066. where += "((start_time < '%s' and end_time > '%s') OR " % (start, end)
  1067. where += "(start_time <= '%s' and end_time > '%s') OR " % (start, end)
  1068. where += "(start_time < '%s' and end_time >= '%s'))" % (start, end)
  1069. if use_equal:
  1070. if use_start or use_during or use_overlap or use_contain:
  1071. where += " OR "
  1072. where += "(start_time = '%s' and end_time = '%s')" % (start, end)
  1073. where += ")"
  1074. # Catch empty where statement
  1075. if where == "()":
  1076. where = None
  1077. return where