abstract_space_time_dataset.py 52 KB

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