abstract_space_time_dataset.py 50 KB

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