abstract_space_time_dataset.py 71 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765
  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. (C) 2011-2012 by the GRASS Development Team
  6. This program is free software under the GNU General Public
  7. License (>=v2). Read the file COPYING that comes with GRASS
  8. for details.
  9. @author Soeren Gebbert
  10. """
  11. from abstract_dataset import *
  12. from temporal_granularity import *
  13. from temporal_relationships import *
  14. ###############################################################################
  15. class AbstractSpaceTimeDataset(AbstractDataset):
  16. """!Abstract space time dataset class
  17. This class represents a space time dataset. Convenient functions
  18. to select, update, insert or delete objects of this type in the SQL
  19. temporal database exists as well as functions to register or unregister
  20. raster maps.
  21. Parts of the temporal logic are implemented in the SQL temporal database,
  22. like the computation of the temporal and spatial extent as well as the
  23. collecting of metadata.
  24. """
  25. def __init__(self, ident):
  26. AbstractDataset.__init__(self)
  27. self.reset(ident)
  28. self.map_counter = 0
  29. def get_new_map_instance(self, ident=None):
  30. """!Return a new instance of a map dataset which is associated
  31. with the type of this class
  32. @param ident: The unique identifier of the new object
  33. """
  34. raise ImplementationError(
  35. "This method must be implemented in the subclasses")
  36. def create_map_register_name(self):
  37. """!Create the name of the map register table of this space time dataset
  38. The name, mapset and the map type are used to create the table name.
  39. ATTENTION: It must be assured that the base object has selected its
  40. content from the database.
  41. """
  42. return self.base.get_name() + "_" + \
  43. self.base.get_mapset() + "_" + \
  44. self.get_new_map_instance(None).get_type() + "_register"
  45. def get_map_register(self):
  46. """!Return the name of the map register table"""
  47. raise ImplementationError(
  48. "This method must be implemented in the subclasses")
  49. def set_map_register(self, name):
  50. """!Set the name of the map register table
  51. This table stores all map names which are registered
  52. in this space time dataset.
  53. @param name: The name of the register table
  54. """
  55. raise ImplementationError(
  56. "This method must be implemented in the subclasses")
  57. def print_self(self):
  58. """!Print the content of the internal structure to stdout"""
  59. self.base.print_self()
  60. if self.is_time_absolute():
  61. self.absolute_time.print_self()
  62. if self.is_time_relative():
  63. self.relative_time.print_self()
  64. self.spatial_extent.print_self()
  65. self.metadata.print_self()
  66. def print_info(self):
  67. """!Print information about this class in human readable style"""
  68. if self.get_type() == "strds":
  69. # 1 2 3 4 5 6 7
  70. # 0123456789012345678901234567890123456789012345678901234567890123456789012345678
  71. print " +-------------------- Space Time Raster Dataset -----------------------------+"
  72. if self.get_type() == "str3ds":
  73. # 1 2 3 4 5 6 7
  74. # 0123456789012345678901234567890123456789012345678901234567890123456789012345678
  75. print " +-------------------- Space Time 3D Raster Dataset --------------------------+"
  76. if self.get_type() == "stvds":
  77. # 1 2 3 4 5 6 7
  78. # 0123456789012345678901234567890123456789012345678901234567890123456789012345678
  79. print " +-------------------- Space Time Vector Dataset -----------------------------+"
  80. print " | |"
  81. self.base.print_info()
  82. if self.is_time_absolute():
  83. self.absolute_time.print_info()
  84. if self.is_time_relative():
  85. self.relative_time.print_info()
  86. self.spatial_extent.print_info()
  87. self.metadata.print_info()
  88. print " +----------------------------------------------------------------------------+"
  89. def print_shell_info(self):
  90. """!Print information about this class in shell style"""
  91. self.base.print_shell_info()
  92. if self.is_time_absolute():
  93. self.absolute_time.print_shell_info()
  94. if self.is_time_relative():
  95. self.relative_time.print_shell_info()
  96. self.spatial_extent.print_shell_info()
  97. self.metadata.print_shell_info()
  98. def set_initial_values(self, temporal_type, semantic_type,
  99. title=None, description=None):
  100. """!Set the initial values of the space time dataset
  101. @param temporal_type: The temporal type of this space
  102. time dataset (absolute or relative)
  103. @param semantic_type: The semantic type of this dataset
  104. @param title: The title
  105. @param description: The description of this dataset
  106. """
  107. if temporal_type == "absolute":
  108. self.set_time_to_absolute()
  109. elif temporal_type == "relative":
  110. self.set_time_to_relative()
  111. else:
  112. core.fatal(_("Unknown temporal type \"%s\"") % (temporal_type))
  113. self.base.set_semantic_type(semantic_type)
  114. self.metadata.set_title(title)
  115. self.metadata.set_description(description)
  116. def get_semantic_type(self):
  117. """!Return the semantic type of this dataset"""
  118. return self.base.get_semantic_type()
  119. def get_initial_values(self):
  120. """!Return the initial values: temporal_type,
  121. semantic_type, title, description"""
  122. temporal_type = self.get_temporal_type()
  123. semantic_type = self.base.get_semantic_type()
  124. title = self.metadata.get_title()
  125. description = self.metadata.get_description()
  126. return temporal_type, semantic_type, title, description
  127. def get_granularity(self):
  128. """!Return the granularity
  129. Granularity can be of absolute time or relative time.
  130. In case of absolute time a string containing an integer
  131. value and the time unit (years, months, days, hours, minuts, seconds).
  132. In case of relative time an integer value is expected.
  133. """
  134. temporal_type = self.get_temporal_type()
  135. if temporal_type == "absolute":
  136. granularity = self.absolute_time.get_granularity()
  137. elif temporal_type == "relative":
  138. granularity = self.relative_time.get_granularity()
  139. return granularity
  140. def set_granularity(self, granularity):
  141. """!Set the granularity
  142. Granularity can be of absolute time or relative time.
  143. In case of absolute time a string containing an integer
  144. value and the time unit (years, months, days, hours, minuts, seconds).
  145. In case of relative time an integer value is expected.
  146. """
  147. temporal_type = self.get_temporal_type()
  148. if temporal_type == "absolute":
  149. self.set_time_to_absolute()
  150. self.absolute_time.set_granularity(granularity)
  151. elif temporal_type == "relative":
  152. self.set_time_to_relative()
  153. self.relative_time.set_granularity(granularity)
  154. else:
  155. core.fatal(_("Unknown temporal type \"%s\"") % (temporal_type))
  156. def set_relative_time_unit(self, unit):
  157. """!Set the relative time unit which may be of type:
  158. years, months, days, hours, minutes or seconds
  159. All maps registered in a (relative time)
  160. space time dataset must have the same unit
  161. """
  162. temporal_type = self.get_temporal_type()
  163. if temporal_type == "relative":
  164. if not self.check_relative_time_unit(unit):
  165. core.fatal(_("Unsupported temporal unit: %s") % (unit))
  166. self.relative_time.set_unit(unit)
  167. def get_map_time(self):
  168. """!Return the type of the map time, interval, point, mixed or invalid"""
  169. temporal_type = self.get_temporal_type()
  170. if temporal_type == "absolute":
  171. map_time = self.absolute_time.get_map_time()
  172. elif temporal_type == "relative":
  173. map_time = self.relative_time.get_map_time()
  174. return map_time
  175. def count_temporal_types(self, maps=None, dbif=None):
  176. """!Return the temporal type of the registered maps as dictionary
  177. The map list must be ordered by start time
  178. The temporal type can be:
  179. - point -> only the start time is present
  180. - interval -> start and end time
  181. - invalid -> No valid time point or interval found
  182. @param maps: A sorted (start_time) list of AbstractDataset objects
  183. @param dbif: The database interface to be used
  184. """
  185. if maps is None:
  186. maps = get_registered_maps_as_objects(
  187. where=None, order="start_time", dbif=dbif)
  188. time_invalid = 0
  189. time_point = 0
  190. time_interval = 0
  191. tcount = {}
  192. for i in range(len(maps)):
  193. # Check for point and interval data
  194. if maps[i].is_time_absolute():
  195. start, end, tz = maps[i].get_absolute_time()
  196. if maps[i].is_time_relative():
  197. start, end, unit = maps[i].get_relative_time()
  198. if start is not None and end is not None:
  199. time_interval += 1
  200. elif start is not None and end is None:
  201. time_point += 1
  202. else:
  203. time_invalid += 1
  204. tcount["point"] = time_point
  205. tcount["interval"] = time_interval
  206. tcount["invalid"] = time_invalid
  207. return tcount
  208. def count_gaps(self, maps=None, dbif=None):
  209. """!Count the number of gaps between temporal neighbors
  210. @param maps: A sorted (start_time) list of AbstractDataset objects
  211. @param dbif: The database interface to be used
  212. @return The numbers of gaps between temporal neighbors
  213. """
  214. if maps is None:
  215. maps = self.get_registered_maps_as_objects(
  216. where=None, order="start_time", dbif=dbif)
  217. gaps = 0
  218. # Check for gaps
  219. for i in range(len(maps)):
  220. if i < len(maps) - 1:
  221. relation = maps[i + 1].temporal_relation(maps[i])
  222. if relation == "after":
  223. gaps += 1
  224. return gaps
  225. def print_temporal_relationships(self, maps=None, dbif=None):
  226. """!Print the temporal relation matrix of all registered maps to stdout
  227. The temporal relation matrix includes the temporal relations between
  228. all registered maps. The relations are strings stored in a list of lists.
  229. @param maps: a ordered by start_time list of map objects
  230. @param dbif: The database interface to be used
  231. """
  232. if maps is None:
  233. maps = self.get_registered_maps_as_objects(
  234. where=None, order="start_time", dbif=dbif)
  235. print_temporal_topology_relationships(maps, maps)
  236. def count_temporal_relations(self, maps=None, dbif=None):
  237. """!Count the temporal relations between the registered maps.
  238. The map list must be ordered by start time.
  239. Temporal relations are counted by analysing the sparse
  240. upper right side temporal relationships matrix.
  241. @param maps: A sorted (start_time) list of AbstractDataset objects
  242. @param dbif: The database interface to be used
  243. @return A dictionary with counted temporal relationships
  244. """
  245. if maps is None:
  246. maps = self.get_registered_maps_as_objects(
  247. where=None, order="start_time", dbif=dbif)
  248. return count_temporal_topology_relationships(maps, maps)
  249. def check_temporal_topology(self, maps=None, dbif=None):
  250. """!Check the temporal topology
  251. Correct topology means, that time intervals are not overlap or
  252. that intervals does not contain other intervals.
  253. Equal time intervals are not allowed.
  254. The map list must be ordered by start time
  255. Allowed and not allowed temporal relationships for correct topology:
  256. @verbatim
  257. - after -> allowed
  258. - precedes -> allowed
  259. - follows -> allowed
  260. - precedes -> allowed
  261. - equivalent -> not allowed
  262. - during -> not allowed
  263. - contains -> not allowed
  264. - overlaps -> not allowed
  265. - overlapped -> not allowed
  266. - starts -> not allowed
  267. - finishes -> not allowed
  268. - started -> not allowed
  269. - finished -> not allowed
  270. @endverbatim
  271. @param maps: A sorted (start_time) list of AbstractDataset objects
  272. @param dbif: The database interface to be used
  273. @return True if topology is correct
  274. """
  275. if maps is None:
  276. maps = self.get_registered_maps_as_objects(
  277. where=None, order="start_time", dbif=dbif)
  278. relations = count_temporal_topology_relationships(maps, maps)
  279. map_time = self.get_map_time()
  280. if map_time == "interval" or map_time == "mixed":
  281. if "equivalent" in relations:
  282. return False
  283. if "during" in relations:
  284. return False
  285. if "contains" in relations:
  286. return False
  287. if "overlaps" in relations:
  288. return False
  289. if "overlapped" in relations:
  290. return False
  291. if "starts" in relations:
  292. return False
  293. if "finishes" in relations:
  294. return False
  295. if "started" in relations:
  296. return False
  297. if "finished" in relations:
  298. return False
  299. elif map_time == "point":
  300. if "equivalent" in relations:
  301. return False
  302. else:
  303. return False
  304. return True
  305. def sample_by_dataset(self, stds, method=None, spatial=False, dbif=None):
  306. """!Sample this space time dataset with the temporal topology
  307. of a second space time dataset
  308. The sample dataset must have "interval" as temporal map type,
  309. so all sample maps have valid interval time.
  310. In case spatial is True, the spatial overlap between
  311. temporal related maps is performed. Only
  312. temporal related and spatial overlapping maps are returned.
  313. Return all registered maps as ordered (by start_time) object list with
  314. "gap" map objects (id==None). Each list entry is a list of map objects
  315. which are potentially located in temporal relation to the actual
  316. granule of the second space time dataset.
  317. Each entry in the object list is a dict. The actual sampler
  318. map and its temporal extent (the actual granule) and
  319. the list of samples are stored:
  320. @code
  321. list = self.sample_by_dataset(stds=sampler, method=[
  322. "during","overlap","contain","equal"])
  323. for entry in list:
  324. granule = entry["granule"]
  325. maplist = entry["samples"]
  326. for map in maplist:
  327. map.select()
  328. map.print_info()
  329. @endcode
  330. A valid temporal topology (no overlapping or inclusion allowed)
  331. is needed to get correct results in case of gaps in the sample dataset.
  332. Gaps between maps are identified as unregistered maps with id==None.
  333. The map objects are initialized with the id and the temporal
  334. extent of the granule (temporal type, start time, end time).
  335. In case more map information are needed, use the select()
  336. method for each listed object.
  337. @param stds: The space time dataset to be used for temporal sampling
  338. @param method: This option specifies what sample method should be used.
  339. In case the registered maps are of temporal point type,
  340. only the start time is used for sampling. In case of mixed
  341. of interval data the user can chose between:
  342. - start: Select maps of which the start time is
  343. located in the selection granule
  344. @verbatim
  345. map : s
  346. granule: s-----------------e
  347. map : s--------------------e
  348. granule: s-----------------e
  349. map : s--------e
  350. granule: s-----------------e
  351. @endverbatim
  352. - during: Select maps which are temporal
  353. during the selection granule
  354. @verbatim
  355. map : s-----------e
  356. granule: s-----------------e
  357. @endverbatim
  358. - overlap: Select maps which temporal overlap
  359. the selection granule
  360. @verbatim
  361. map : s-----------e
  362. granule: s-----------------e
  363. map : s-----------e
  364. granule: s----------e
  365. @endverbatim
  366. - contain: Select maps which temporally contain
  367. the selection granule
  368. @verbatim
  369. map : s-----------------e
  370. granule: s-----------e
  371. @endverbatim
  372. - equal: Select maps which temporally equal
  373. to the selection granule
  374. @verbatim
  375. map : s-----------e
  376. granule: s-----------e
  377. @endverbatim
  378. - follows: Select maps which temporally follow
  379. the selection granule
  380. @verbatim
  381. map : s-----------e
  382. granule: s-----------e
  383. @endverbatim
  384. - precedes: Select maps which temporally precedes
  385. the selection granule
  386. @verbatim
  387. map : s-----------e
  388. granule: s-----------e
  389. @endverbatim
  390. All these methods can be combined. Method must be of
  391. type tuple including the identification strings.
  392. @param spatial: If set True additional the spatial overlapping
  393. is used for selection -> spatio-temporal relation.
  394. The returned map objects will have temporal and
  395. spatial extents
  396. @param dbif: The database interface to be used
  397. In case nothing found None is returned
  398. """
  399. use_start = False
  400. use_during = False
  401. use_overlap = False
  402. use_contain = False
  403. use_equal = False
  404. use_follows = False
  405. use_precedes = False
  406. # Initialize the methods
  407. if method is not None:
  408. for name in method:
  409. if name == "start":
  410. use_start = True
  411. if name == "during":
  412. use_during = True
  413. if name == "overlap":
  414. use_overlap = True
  415. if name == "contain":
  416. use_contain = True
  417. if name == "equal":
  418. use_equal = True
  419. if name == "follows":
  420. use_follows = True
  421. if name == "precedes":
  422. use_precedes = True
  423. else:
  424. use_during = True
  425. use_overlap = True
  426. use_contain = True
  427. use_equal = True
  428. if self.get_temporal_type() != stds.get_temporal_type():
  429. core.error(_("The space time datasets must be of "
  430. "the same temporal type"))
  431. return None
  432. if stds.get_map_time() != "interval":
  433. core.error(_("The temporal map type of the sample "
  434. "dataset must be interval"))
  435. return None
  436. # In case points of time are available, disable the interval specific methods
  437. if self.get_map_time() == "point":
  438. use_start = True
  439. use_during = False
  440. use_overlap = False
  441. use_contain = False
  442. use_equal = False
  443. use_follows = False
  444. use_precedes = False
  445. dbif, connect = init_dbif(dbif)
  446. obj_list = []
  447. sample_maps = stds.get_registered_maps_as_objects_with_gaps(
  448. where=None, dbif=dbif)
  449. for granule in sample_maps:
  450. # Read the spatial extent
  451. if spatial:
  452. granule.spatial_extent.select(dbif)
  453. start, end = granule.get_valid_time()
  454. where = create_temporal_relation_sql_where_statement(
  455. start, end, use_start,
  456. use_during, use_overlap, use_contain, use_equal, use_follows, use_precedes)
  457. maps = self.get_registered_maps_as_objects(
  458. where, "start_time", dbif)
  459. result = {}
  460. result["granule"] = granule
  461. num_samples = 0
  462. maplist = []
  463. if maps is not None:
  464. for map in maps:
  465. # Read the spatial extent
  466. if spatial:
  467. map.spatial_extent.select(dbif)
  468. # Ignore spatial disjoint maps
  469. if not granule.spatial_overlapping(map):
  470. continue
  471. num_samples += 1
  472. maplist.append(copy.copy(map))
  473. # Fill with empty map in case no spatio-temporal relations found
  474. if maps is None or num_samples == 0:
  475. map = self.get_new_map_instance(None)
  476. if self.is_time_absolute():
  477. map.set_absolute_time(start, end)
  478. elif self.is_time_relative():
  479. map.set_relative_time(start, end,
  480. self.get_relative_time_unit())
  481. maplist.append(copy.copy(map))
  482. result["samples"] = maplist
  483. obj_list.append(copy.copy(result))
  484. if connect:
  485. dbif.close()
  486. return obj_list
  487. def get_registered_maps_as_objects_by_granularity(self, gran=None, dbif=None):
  488. """!Return all registered maps as ordered (by start_time) object list with
  489. "gap" map objects (id==None) for temporal topological operations using
  490. the granularity of the space time dataset as increment.
  491. Each list entry is a list of map objects
  492. which are potentially located in the actual granule.
  493. A valid temporal topology (no overlapping or inclusion allowed)
  494. is needed to get correct results.
  495. Gaps between maps are identified as unregistered maps with id==None.
  496. The objects are initialized with the id and the temporal
  497. extent (temporal type, start time, end time).
  498. In case more map information are needed, use the select()
  499. method for each listed object.
  500. @param gran: The granularity to be used
  501. @param dbif: The database interface to be used
  502. @return ordered object list, in case nothing found None is returned
  503. """
  504. dbif, connect = init_dbif(dbif)
  505. obj_list = []
  506. if gran is None:
  507. gran = self.get_granularity()
  508. start, end = self.get_valid_time()
  509. while start < end:
  510. if self.is_time_absolute():
  511. next = increment_datetime_by_string(start, gran)
  512. else:
  513. next = start + gran
  514. where = "(start_time <= '%s' and end_time >= '%s')" % (start, next)
  515. rows = self.get_registered_maps("id", where, "start_time", dbif)
  516. found_gap = False
  517. if rows is not None and len(rows) != 0:
  518. if len(rows) > 1:
  519. core.warning(_("More than one map found in a granule. "
  520. "Temporal granularity seems to be invalid or"
  521. " the chosen granularity is not a greatest "
  522. "common divider of all intervals and gaps "
  523. "in the dataset."))
  524. maplist = []
  525. for row in rows:
  526. # Take the first map
  527. map = self.get_new_map_instance(rows[0]["id"])
  528. if self.is_time_absolute():
  529. map.set_absolute_time(start, next)
  530. elif self.is_time_relative():
  531. map.set_relative_time(start, next,
  532. self.get_relative_time_unit())
  533. maplist.append(copy.copy(map))
  534. obj_list.append(copy.copy(maplist))
  535. else:
  536. # Searching for time instances
  537. where = "(start_time = '%s')" % (start)
  538. rows = self.get_registered_maps("id", where, "start_time", dbif)
  539. if rows is not None and len(rows) != 0:
  540. if len(rows) > 1:
  541. core.warning(_("More than one map found in a granule. "
  542. "Temporal granularity seems to be invalid or"
  543. " the chosen granularity is not a greatest "
  544. "common divider of all time instances "
  545. "in the dataset."))
  546. maplist = []
  547. for row in rows:
  548. # Take the first map
  549. map = self.get_new_map_instance(rows[0]["id"])
  550. if self.is_time_absolute():
  551. map.set_absolute_time(start, None)
  552. elif self.is_time_relative():
  553. map.set_relative_time(start, None,
  554. self.get_relative_time_unit())
  555. maplist.append(copy.copy(map))
  556. obj_list.append(copy.copy(maplist))
  557. found_gap = True
  558. # Gap handling
  559. if found_gap:
  560. # Found a gap
  561. map = self.get_new_map_instance(None)
  562. if self.is_time_absolute():
  563. map.set_absolute_time(start, next)
  564. elif self.is_time_relative():
  565. map.set_relative_time(start, next,
  566. self.get_relative_time_unit())
  567. maplist = []
  568. maplist.append(copy.copy(map))
  569. obj_list.append(copy.copy(maplist))
  570. start = next
  571. if connect:
  572. dbif.close()
  573. if obj_list:
  574. return obj_list
  575. return None
  576. def get_registered_maps_as_objects_with_gaps(self, where=None, dbif=None):
  577. """!Return all registered maps as ordered (by start_time) object list with
  578. "gap" map objects (id==None) for temporal topological operations
  579. Gaps between maps are identified as maps with id==None
  580. The objects are initialized with the id and the
  581. temporal extent (temporal type, start time, end time).
  582. In case more map information are needed, use the select()
  583. method for each listed object.
  584. @param where: The SQL where statement to select a
  585. subset of the registered maps without "WHERE"
  586. @param dbif: The database interface to be used
  587. @return ordered object list, in case nothing found None is returned
  588. """
  589. dbif, connect = init_dbif(dbif)
  590. obj_list = []
  591. maps = self.get_registered_maps_as_objects(where, "start_time", dbif)
  592. if maps is not None and len(maps) > 0:
  593. for i in range(len(maps)):
  594. obj_list.append(maps[i])
  595. # Detect and insert gaps
  596. if i < len(maps) - 1:
  597. relation = maps[i + 1].temporal_relation(maps[i])
  598. if relation == "after":
  599. start1, end1 = maps[i].get_valid_time()
  600. start2, end2 = maps[i + 1].get_valid_time()
  601. end = start2
  602. if end1 is not None:
  603. start = end1
  604. else:
  605. start = start1
  606. map = self.get_new_map_instance(None)
  607. if self.is_time_absolute():
  608. map.set_absolute_time(start, end)
  609. elif self.is_time_relative():
  610. map.set_relative_time(start, end,
  611. self.get_relative_time_unit())
  612. obj_list.append(copy.copy(map))
  613. if connect:
  614. dbif.close()
  615. return obj_list
  616. def get_registered_maps_as_objects(self, where=None, order="start_time",
  617. dbif=None):
  618. """!Return all registered maps as ordered object list for
  619. temporal topological operations
  620. The objects are initialized with the id and the temporal extent
  621. (temporal type, start time, end time).
  622. In case more map information are needed, use the select()
  623. method for each listed object.
  624. @param where: The SQL where statement to select a subset of
  625. the registered maps without "WHERE"
  626. @param order: The SQL order statement to be used to order the
  627. objects in the list without "ORDER BY"
  628. @param dbif: The database interface to be used
  629. @return The ordered map object list,
  630. In case nothing found None is returned
  631. """
  632. dbif, connect = init_dbif(dbif)
  633. obj_list = []
  634. rows = self.get_registered_maps(
  635. "id,start_time,end_time", where, order, dbif)
  636. count = 0
  637. if rows is not None:
  638. for row in rows:
  639. core.percent(count, len(rows), 1)
  640. map = self.get_new_map_instance(row["id"])
  641. if self.is_time_absolute():
  642. map.set_absolute_time(row["start_time"], row["end_time"])
  643. elif self.is_time_relative():
  644. map.set_relative_time(row["start_time"], row["end_time"],
  645. self.get_relative_time_unit())
  646. obj_list.append(copy.copy(map))
  647. count += 1
  648. core.percent(1, 1, 1)
  649. if connect:
  650. dbif.close()
  651. return obj_list
  652. def get_registered_maps(self, columns=None, where=None, order=None, dbif=None):
  653. """!Return SQL rows of all registered maps.
  654. In case columns are not specified, each row includes all columns
  655. specified in the datatype specific view.
  656. @param columns: Columns to be selected as SQL compliant string
  657. @param where: The SQL where statement to select a subset
  658. of the registered maps without "WHERE"
  659. @param order: The SQL order statement to be used to order the
  660. objects in the list without "ORDER BY"
  661. @param dbif: The database interface to be used
  662. @return SQL rows of all registered maps,
  663. In case nothing found None is returned
  664. """
  665. dbif, connect = init_dbif(dbif)
  666. rows = None
  667. if self.get_map_register() is not None:
  668. # Use the correct temporal table
  669. if self.get_temporal_type() == "absolute":
  670. map_view = self.get_new_map_instance(
  671. None).get_type() + "_view_abs_time"
  672. else:
  673. map_view = self.get_new_map_instance(
  674. None).get_type() + "_view_rel_time"
  675. if columns is not None and columns != "":
  676. sql = "SELECT %s FROM %s WHERE %s.id IN (SELECT id FROM %s)" %\
  677. (columns, map_view, map_view, self.get_map_register())
  678. else:
  679. sql = "SELECT * FROM %s WHERE %s.id IN (SELECT id FROM %s)" % \
  680. (map_view, map_view, self.get_map_register())
  681. if where is not None and where != "":
  682. sql += " AND (%s)" % (where.split(";")[0])
  683. if order is not None and order != "":
  684. sql += " ORDER BY %s" % (order.split(";")[0])
  685. try:
  686. dbif.cursor.execute(sql)
  687. rows = dbif.cursor.fetchall()
  688. except:
  689. if connect:
  690. dbif.close()
  691. core.error(_("Unable to get map ids from register table <%s>")
  692. % (self.get_map_register()))
  693. raise
  694. if connect:
  695. dbif.close()
  696. return rows
  697. def rename(self, ident, dbif=None):
  698. """!Rename the space time dataset
  699. This method renames the space time dataset, the map register table
  700. and updates the entries in registered maps stds register.
  701. @param ident: The new identifier name@mapset
  702. @param dbif: The database interface to be used
  703. """
  704. dbif, connect = init_dbif(dbif)
  705. # SELECT all needed information from the database
  706. self.select(dbif)
  707. # We need to select the registered maps here
  708. maps = self.get_registered_maps_as_objects(None, "start_time", dbif)
  709. # Safe old identifier
  710. old_ident = self.get_id()
  711. # We need to rename the old table
  712. old_map_register_table = self.get_map_register()
  713. # Set new identifier
  714. self.set_id(ident)
  715. # Create map register table name from new identifier
  716. new_map_register_table = self.create_map_register_name()
  717. # Set new map register table name
  718. self.set_map_register(new_map_register_table)
  719. # Get the update statement, we update the table entry of the old identifier
  720. statement = self.update(dbif, execute=False, ident=old_ident)
  721. # We need to rename the raster register table
  722. statement += "ALTER TABLE %s RENAME TO \'%s\';\n"%\
  723. (old_map_register_table, new_map_register_table)
  724. # We need to rename the space time dataset in the maps register table
  725. if maps:
  726. for map in maps:
  727. map.select()
  728. statement += "UPDATE %s SET id = \'%s\' WHERE id = \'%s\';\n"%\
  729. (map.get_stds_register(), ident, old_ident)
  730. # Execute the accumulated statements
  731. dbif.execute_transaction(statement)
  732. if connect:
  733. dbif.close()
  734. def delete(self, dbif=None, execute=True):
  735. """!Delete a space time dataset from the temporal database
  736. This method removes the space time dataset from the temporal
  737. database and drops its map register table
  738. @param dbif: The database interface to be used
  739. @param execute: If True the SQL DELETE and DROP table
  740. statements will be executed.
  741. If False the prepared SQL statements are returned
  742. and must be executed by the caller.
  743. @return The SQL statements if execute == False, else an empty string
  744. """
  745. # First we need to check if maps are registered in this dataset and
  746. # unregister them
  747. core.verbose(_("Delete space time %s dataset <%s> from temporal "
  748. "database") % \
  749. (self.get_new_map_instance(ident=None).get_type(),
  750. self.get_id()))
  751. statement = ""
  752. dbif, connect = init_dbif(dbif)
  753. # SELECT all needed information from the database
  754. self.metadata.select(dbif)
  755. if self.get_map_register() is not None:
  756. core.verbose(_("Drop map register table: %s") % (
  757. self.get_map_register()))
  758. rows = self.get_registered_maps("id", None, None, dbif)
  759. # Unregister each registered map in the table
  760. if rows is not None:
  761. num_maps = len(rows)
  762. count = 0
  763. for row in rows:
  764. core.percent(count, num_maps, 1)
  765. # Unregister map
  766. map = self.get_new_map_instance(row["id"])
  767. statement += self.unregister_map(
  768. map=map, dbif=dbif, execute=False)
  769. count += 1
  770. core.percent(1, 1, 1)
  771. # Safe the DROP table statement
  772. statement += "DROP TABLE " + self.get_map_register() + ";\n"
  773. # Remove the primary key, the foreign keys will be removed by trigger
  774. statement += self.base.get_delete_statement()
  775. if execute:
  776. dbif.execute_transaction(statement)
  777. self.reset(None)
  778. if connect:
  779. dbif.close()
  780. if execute:
  781. return ""
  782. return statement
  783. def register_map(self, map, dbif=None):
  784. """!Register a map in the space time dataset.
  785. This method takes care of the registration of a map
  786. in a space time dataset.
  787. In case the map is already registered this function
  788. will break with a warning and return False.
  789. @param map: The AbstractMapDataset object that should be registered
  790. @param dbif: The database interface to be used
  791. """
  792. dbif, connect = init_dbif(dbif)
  793. if map.is_in_db(dbif) == False:
  794. dbif.close()
  795. core.fatal(_("Only maps with absolute or relative valid time can "
  796. "be registered"))
  797. if map.get_layer():
  798. core.verbose(_("Register %s map <%s> with layer %s in space "
  799. "time %s dataset <%s>") % (map.get_type(),
  800. map.get_map_id(),
  801. map.get_layer(),
  802. map.get_type(),
  803. self.get_id()))
  804. else:
  805. core.verbose(_("Register %s map <%s> in space time %s "
  806. "dataset <%s>") % (map.get_type(), map.get_map_id(),
  807. map.get_type(), self.get_id()))
  808. # First select all data from the database
  809. map.select(dbif)
  810. if not map.check_valid_time():
  811. if map.get_layer():
  812. core.fatal(_("Map <%s> with layer %s has invalid time")
  813. % (map.get_map_id(), map.get_layer()))
  814. else:
  815. core.fatal(_("Map <%s> has invalid time") % (map.get_map_id()))
  816. map_id = map.base.get_id()
  817. map_name = map.base.get_name()
  818. map_mapset = map.base.get_mapset()
  819. map_register_table = map.get_stds_register()
  820. map_rel_time_unit = map.get_relative_time_unit()
  821. map_ttype = map.get_temporal_type()
  822. #print "Map register table", map_register_table
  823. # Get basic info
  824. stds_name = self.base.get_name()
  825. stds_mapset = self.base.get_mapset()
  826. stds_register_table = self.get_map_register()
  827. stds_ttype = self.get_temporal_type()
  828. # The gathered SQL statemets are stroed here
  829. statement = ""
  830. # Check temporal types
  831. if stds_ttype != map_ttype:
  832. if map.get_layer():
  833. core.fatal(_("Temporal type of space time dataset <%s> and "
  834. "map <%s> with layer %s are different") % \
  835. (self.get_id(), map.get_map_id(), map.get_layer()))
  836. else:
  837. core.fatal(_("Temporal type of space time dataset <%s> and "
  838. "map <%s> are different") % \
  839. (self.get_id(), map.get_map_id()))
  840. # In case no map has been registered yet, set the
  841. # relative time unit from the first map
  842. if (self.metadata.get_number_of_maps() is None or \
  843. self.metadata.get_number_of_maps() == 0) and \
  844. self.map_counter == 0 and self.is_time_relative():
  845. self.set_relative_time_unit(map_rel_time_unit)
  846. statement += self.relative_time.get_update_all_statement_mogrified(
  847. dbif)
  848. core.verbose(_("Set temporal unit for space time %s dataset "
  849. "<%s> to %s") % (map.get_type(), self.get_id(),
  850. map_rel_time_unit))
  851. stds_rel_time_unit = self.get_relative_time_unit()
  852. # Check the relative time unit
  853. if self.is_time_relative() and (stds_rel_time_unit != map_rel_time_unit):
  854. if map.get_layer():
  855. core.fatal(_("Relative time units of space time dataset "
  856. "<%s> and map <%s> with layer %s are different") %\
  857. (self.get_id(), map.get_map_id(), map.get_layer()))
  858. else:
  859. core.fatal(_("Relative time units of space time dataset "
  860. "<%s> and map <%s> are different") % \
  861. (self.get_id(), map.get_map_id()))
  862. #print "STDS register table", stds_register_table
  863. if stds_mapset != map_mapset:
  864. dbif.close()
  865. core.fatal(_("Only maps from the same mapset can be registered"))
  866. # Check if map is already registered
  867. if stds_register_table is not None:
  868. if dbif.dbmi.paramstyle == "qmark":
  869. sql = "SELECT id FROM " + \
  870. stds_register_table + " WHERE id = (?)"
  871. else:
  872. sql = "SELECT id FROM " + \
  873. stds_register_table + " WHERE id = (%s)"
  874. try:
  875. dbif.cursor.execute(sql, (map_id,))
  876. row = dbif.cursor.fetchone()
  877. except:
  878. row = None
  879. core.warning(_("Error in strds_register_table request"))
  880. raise
  881. if row is not None and row[0] == map_id:
  882. if connect == True:
  883. dbif.close()
  884. if map.get_layer() is not None:
  885. core.warning(_("Map <%s> with layer %s is already "
  886. "registered.") % (map.get_map_id(),
  887. map.get_layer()))
  888. else:
  889. core.warning(_("Map <%s> is already registered.")
  890. % (map.get_map_id()))
  891. return ""
  892. # Create tables
  893. sql_path = get_sql_template_path()
  894. # We need to create the map raster register table precedes we can register the map
  895. if map_register_table is None:
  896. # Create a unique id
  897. uuid_rand = "map_" + str(uuid.uuid4()).replace("-", "")
  898. map_register_table = uuid_rand + "_" + \
  899. self.get_type() + "_register"
  900. # Read the SQL template
  901. sql = open(os.path.join(sql_path,
  902. "map_stds_register_table_template.sql"),
  903. 'r').read()
  904. # Create the raster, raster3d and vector tables
  905. sql = sql.replace("GRASS_MAP", map.get_type())
  906. sql = sql.replace("MAP_NAME", map_name + "_" + map_mapset)
  907. sql = sql.replace("TABLE_NAME", uuid_rand)
  908. sql = sql.replace("MAP_ID", map_id)
  909. sql = sql.replace("STDS", self.get_type())
  910. statement += sql
  911. # Set the stds register table name and put it into the DB
  912. map.set_stds_register(map_register_table)
  913. statement += map.metadata.get_update_statement_mogrified(dbif)
  914. if map.get_layer():
  915. core.verbose(_("Created register table <%s> for "
  916. "%s map <%s> with layer %s") %
  917. (map_register_table, map.get_type(),
  918. map.get_map_id(), map.get_layer()))
  919. else:
  920. core.verbose(_("Created register table <%s> for %s map <%s>") %
  921. (map_register_table, map.get_type(),
  922. map.get_map_id()))
  923. # We need to create the table and register it
  924. if stds_register_table is None:
  925. # Create table name
  926. stds_register_table = self.create_map_register_name()
  927. # Read the SQL template
  928. sql = open(os.path.join(sql_path,
  929. "stds_map_register_table_template.sql"),
  930. 'r').read()
  931. # Create the raster, raster3d and vector tables
  932. sql = sql.replace("GRASS_MAP", map.get_type())
  933. sql = sql.replace("SPACETIME_NAME", stds_name + "_" + stds_mapset)
  934. sql = sql.replace("SPACETIME_ID", self.base.get_id())
  935. sql = sql.replace("STDS", self.get_type())
  936. statement += sql
  937. # Set the map register table name and put it into the DB
  938. self.set_map_register(stds_register_table)
  939. statement += self.metadata.get_update_statement_mogrified(dbif)
  940. core.verbose(_("Created register table <%s> for space "
  941. "time %s dataset <%s>") %
  942. (stds_register_table, map.get_type(), self.get_id()))
  943. # We need to execute the statement at this time
  944. if statement != "":
  945. dbif.execute_transaction(statement)
  946. statement = ""
  947. # Register the stds in the map stds register table
  948. # Check if the entry is already there
  949. if dbif.dbmi.paramstyle == "qmark":
  950. sql = "SELECT id FROM " + map_register_table + " WHERE id = ?"
  951. else:
  952. sql = "SELECT id FROM " + map_register_table + " WHERE id = %s"
  953. try:
  954. dbif.cursor.execute(sql, (self.base.get_id(),))
  955. row = dbif.cursor.fetchone()
  956. except:
  957. row = None
  958. # In case of no entry make a new one
  959. if row is None:
  960. if dbif.dbmi.paramstyle == "qmark":
  961. sql = "INSERT INTO " + map_register_table + \
  962. " (id) " + "VALUES (?);\n"
  963. else:
  964. sql = "INSERT INTO " + map_register_table + \
  965. " (id) " + "VALUES (%s);\n"
  966. statement += dbif.mogrify_sql_statement(
  967. (sql, (self.base.get_id(),)))
  968. # Now put the raster name in the stds map register table
  969. if dbif.dbmi.paramstyle == "qmark":
  970. sql = "INSERT INTO " + stds_register_table + \
  971. " (id) " + "VALUES (?);\n"
  972. else:
  973. sql = "INSERT INTO " + stds_register_table + \
  974. " (id) " + "VALUES (%s);\n"
  975. statement += dbif.mogrify_sql_statement((sql, (map_id,)))
  976. # Now execute the insert transaction
  977. dbif.execute_transaction(statement)
  978. if connect:
  979. dbif.close()
  980. # increase the counter
  981. self.map_counter += 1
  982. def unregister_map(self, map, dbif=None, execute=True):
  983. """!Unregister a map from the space time dataset.
  984. This method takes care of the un-registration of a map
  985. from a space time dataset.
  986. @param map: The map object to unregister
  987. @param dbif: The database interface to be used
  988. @param execute: If True the SQL DELETE and DROP table
  989. statements will be executed.
  990. If False the prepared SQL statements are
  991. returned and must be executed by the caller.
  992. @return The SQL statements if execute == False, else an empty
  993. string, None in case of a failure
  994. """
  995. statement = ""
  996. dbif, connect = init_dbif(dbif)
  997. # First select needed data from the database
  998. map.metadata.select(dbif)
  999. map_id = map.get_id()
  1000. map_register_table = map.get_stds_register()
  1001. stds_register_table = self.get_map_register()
  1002. if map.get_layer() is not None:
  1003. core.verbose(_("Unregister %s map <%s> with layer %s") % \
  1004. (map.get_type(), map.get_map_id(), map.get_layer()))
  1005. else:
  1006. core.verbose(_("Unregister %s map <%s>") % (
  1007. map.get_type(), map.get_map_id()))
  1008. # Check if the map is registered in the space time raster dataset
  1009. if map_register_table is not None:
  1010. if dbif.dbmi.paramstyle == "qmark":
  1011. sql = "SELECT id FROM " + map_register_table + " WHERE id = ?"
  1012. else:
  1013. sql = "SELECT id FROM " + map_register_table + " WHERE id = %s"
  1014. try:
  1015. dbif.cursor.execute(sql, (self.base.get_id(),))
  1016. row = dbif.cursor.fetchone()
  1017. except:
  1018. row = None
  1019. # Break if the map is not registered
  1020. if row is None:
  1021. if map.get_layer() is not None:
  1022. core.warning(_("Map <%s> with layer %s is not registered "
  1023. "in space time dataset <%s>") % \
  1024. (map.get_map_id(), map.get_layer(),
  1025. self.base.get_id()))
  1026. else:
  1027. core.warning(_("Map <%s> is not registered in space "
  1028. "time dataset <%s>") % (map.get_map_id(),
  1029. self.base.get_id()))
  1030. if connect == True:
  1031. dbif.close()
  1032. return ""
  1033. # Remove the space time raster dataset from the raster dataset register
  1034. if map_register_table is not None:
  1035. if dbif.dbmi.paramstyle == "qmark":
  1036. sql = "DELETE FROM " + map_register_table + " WHERE id = ?;\n"
  1037. else:
  1038. sql = "DELETE FROM " + map_register_table + " WHERE id = %s;\n"
  1039. statement += dbif.mogrify_sql_statement(
  1040. (sql, (self.base.get_id(),)))
  1041. # Remove the raster map from the space time raster dataset register
  1042. if stds_register_table is not None:
  1043. if dbif.dbmi.paramstyle == "qmark":
  1044. sql = "DELETE FROM " + stds_register_table + " WHERE id = ?;\n"
  1045. else:
  1046. sql = "DELETE FROM " + \
  1047. stds_register_table + " WHERE id = %s;\n"
  1048. statement += dbif.mogrify_sql_statement((sql, (map_id,)))
  1049. if execute:
  1050. dbif.execute_transaction(statement)
  1051. if connect:
  1052. dbif.close()
  1053. # decrease the counter
  1054. self.map_counter -= 1
  1055. if execute:
  1056. return ""
  1057. return statement
  1058. def update_from_registered_maps(self, dbif=None):
  1059. """!This methods updates the spatial and temporal extent as well as
  1060. type specific metadata. It should always been called after maps are registered
  1061. or unregistered/deleted from the space time dataset.
  1062. The update of the temporal extent checks if the end time is set correctly.
  1063. In case the registered maps have no valid end time (None) the maximum start time
  1064. will be used. If the end time is earlier than the maximum start time, it will
  1065. be replaced by the maximum start time.
  1066. An other solution to automate this is to use the deactivated trigger
  1067. in the SQL files. But this will result in a huge performance issue
  1068. in case many maps are registered (>1000).
  1069. @param dbif: The database interface to be used
  1070. """
  1071. core.verbose(_("Update metadata, spatial and temporal extent from "
  1072. "all registered maps of <%s>") % (self.get_id()))
  1073. # Nothing to do if the register is not present
  1074. if not self.get_map_register():
  1075. return
  1076. dbif, connect = init_dbif(dbif)
  1077. map_time = None
  1078. use_start_time = False
  1079. # Get basic info
  1080. stds_name = self.base.get_name()
  1081. stds_mapset = self.base.get_mapset()
  1082. sql_path = get_sql_template_path()
  1083. #We create a transaction
  1084. sql_script = ""
  1085. # Update the spatial and temporal extent from registered maps
  1086. # Read the SQL template
  1087. sql = open(os.path.join(sql_path,
  1088. "update_stds_spatial_temporal_extent_template.sql"),
  1089. 'r').read()
  1090. sql = sql.replace(
  1091. "GRASS_MAP", self.get_new_map_instance(None).get_type())
  1092. sql = sql.replace("SPACETIME_NAME", stds_name + "_" + stds_mapset)
  1093. sql = sql.replace("SPACETIME_ID", self.base.get_id())
  1094. sql = sql.replace("STDS", self.get_type())
  1095. sql_script += sql
  1096. sql_script += "\n"
  1097. # Update type specific metadata
  1098. sql = open(os.path.join(sql_path, "update_" +
  1099. self.get_type() + "_metadata_template.sql"), 'r').read()
  1100. sql = sql.replace(
  1101. "GRASS_MAP", self.get_new_map_instance(None).get_type())
  1102. sql = sql.replace("SPACETIME_NAME", stds_name + "_" + stds_mapset)
  1103. sql = sql.replace("SPACETIME_ID", self.base.get_id())
  1104. sql = sql.replace("STDS", self.get_type())
  1105. sql_script += sql
  1106. sql_script += "\n"
  1107. dbif.execute_transaction(sql_script)
  1108. # Read and validate the selected end time
  1109. self.select()
  1110. if self.is_time_absolute():
  1111. start_time, end_time, tz = self.get_absolute_time()
  1112. else:
  1113. start_time, end_time, unit = self.get_relative_time()
  1114. # In case no end time is set, use the maximum start time of
  1115. # all registered maps as end time
  1116. if end_time is None:
  1117. use_start_time = True
  1118. else:
  1119. # Check if the end time is smaller than the maximum start time
  1120. if self.is_time_absolute():
  1121. sql = """SELECT max(start_time) FROM GRASS_MAP_absolute_time
  1122. WHERE GRASS_MAP_absolute_time.id IN
  1123. (SELECT id FROM SPACETIME_NAME_GRASS_MAP_register);"""
  1124. sql = sql.replace("GRASS_MAP", self.get_new_map_instance(
  1125. None).get_type())
  1126. sql = sql.replace("SPACETIME_NAME",
  1127. stds_name + "_" + stds_mapset)
  1128. else:
  1129. sql = """SELECT max(start_time) FROM GRASS_MAP_relative_time
  1130. WHERE GRASS_MAP_relative_time.id IN
  1131. (SELECT id FROM SPACETIME_NAME_GRASS_MAP_register);"""
  1132. sql = sql.replace("GRASS_MAP", self.get_new_map_instance(
  1133. None).get_type())
  1134. sql = sql.replace("SPACETIME_NAME",
  1135. stds_name + "_" + stds_mapset)
  1136. dbif.cursor.execute(sql)
  1137. row = dbif.cursor.fetchone()
  1138. if row is not None:
  1139. # This seems to be a bug in sqlite3 Python driver
  1140. if dbif.dbmi.__name__ == "sqlite3":
  1141. tstring = row[0]
  1142. # Convert the unicode string into the datetime format
  1143. if self.is_time_absolute():
  1144. if tstring.find(":") > 0:
  1145. time_format = "%Y-%m-%d %H:%M:%S"
  1146. else:
  1147. time_format = "%Y-%m-%d"
  1148. max_start_time = datetime.strptime(
  1149. tstring, time_format)
  1150. else:
  1151. max_start_time = row[0]
  1152. else:
  1153. max_start_time = row[0]
  1154. if end_time < max_start_time:
  1155. use_start_time = True
  1156. # Set the maximum start time as end time
  1157. if use_start_time:
  1158. if self.is_time_absolute():
  1159. sql = """UPDATE STDS_absolute_time SET end_time =
  1160. (SELECT max(start_time) FROM GRASS_MAP_absolute_time WHERE
  1161. GRASS_MAP_absolute_time.id IN
  1162. (SELECT id FROM SPACETIME_NAME_GRASS_MAP_register)
  1163. ) WHERE id = 'SPACETIME_ID';"""
  1164. sql = sql.replace("GRASS_MAP", self.get_new_map_instance(
  1165. None).get_type())
  1166. sql = sql.replace("SPACETIME_NAME",
  1167. stds_name + "_" + stds_mapset)
  1168. sql = sql.replace("SPACETIME_ID", self.base.get_id())
  1169. sql = sql.replace("STDS", self.get_type())
  1170. elif self.is_time_relative():
  1171. sql = """UPDATE STDS_relative_time SET end_time =
  1172. (SELECT max(start_time) FROM GRASS_MAP_relative_time WHERE
  1173. GRASS_MAP_relative_time.id IN
  1174. (SELECT id FROM SPACETIME_NAME_GRASS_MAP_register)
  1175. ) WHERE id = 'SPACETIME_ID';"""
  1176. sql = sql.replace("GRASS_MAP", self.get_new_map_instance(
  1177. None).get_type())
  1178. sql = sql.replace("SPACETIME_NAME",
  1179. stds_name + "_" + stds_mapset)
  1180. sql = sql.replace("SPACETIME_ID", self.base.get_id())
  1181. sql = sql.replace("STDS", self.get_type())
  1182. dbif.execute_transaction(sql)
  1183. # Count the temporal map types
  1184. maps = self.get_registered_maps_as_objects(dbif=dbif)
  1185. tlist = self.count_temporal_types(maps)
  1186. if tlist["interval"] > 0 and tlist["point"] == 0 and \
  1187. tlist["invalid"] == 0:
  1188. map_time = "interval"
  1189. elif tlist["interval"] == 0 and tlist["point"] > 0 and \
  1190. tlist["invalid"] == 0:
  1191. map_time = "point"
  1192. elif tlist["interval"] > 0 and tlist["point"] > 0 and \
  1193. tlist["invalid"] == 0:
  1194. map_time = "mixed"
  1195. else:
  1196. map_time = "invalid"
  1197. # Compute the granularity
  1198. if map_time != "invalid":
  1199. # Smallest supported temporal resolution
  1200. if self.is_time_absolute():
  1201. gran = compute_absolute_time_granularity(maps)
  1202. elif self.is_time_relative():
  1203. gran = compute_relative_time_granularity(maps)
  1204. else:
  1205. gran = None
  1206. # Set the map time type and update the time objects
  1207. if self.is_time_absolute():
  1208. self.absolute_time.select(dbif)
  1209. self.metadata.select(dbif)
  1210. if self.metadata.get_number_of_maps() > 0:
  1211. self.absolute_time.set_map_time(map_time)
  1212. self.absolute_time.set_granularity(gran)
  1213. else:
  1214. self.absolute_time.set_map_time(None)
  1215. self.absolute_time.set_granularity(None)
  1216. self.absolute_time.update_all(dbif)
  1217. else:
  1218. self.relative_time.select(dbif)
  1219. self.metadata.select(dbif)
  1220. if self.metadata.get_number_of_maps() > 0:
  1221. self.relative_time.set_map_time(map_time)
  1222. self.relative_time.set_granularity(gran)
  1223. else:
  1224. self.relative_time.set_map_time(None)
  1225. self.relative_time.set_granularity(None)
  1226. self.relative_time.update_all(dbif)
  1227. if connect:
  1228. dbif.close()
  1229. ###############################################################################
  1230. def create_temporal_relation_sql_where_statement(
  1231. start, end, use_start=True, use_during=False,
  1232. use_overlap=False, use_contain=False, use_equal=False,
  1233. use_follows=False, use_precedes=False):
  1234. """!Create a SQL WHERE statement for temporal relation selection of maps in space time datasets
  1235. @param start: The start time
  1236. @param end: The end time
  1237. @param use_start: Select maps of which the start time is located in the selection granule
  1238. @verbatim
  1239. map : s
  1240. granule: s-----------------e
  1241. map : s--------------------e
  1242. granule: s-----------------e
  1243. map : s--------e
  1244. granule: s-----------------e
  1245. @endverbatim
  1246. @param use_during: during: Select maps which are temporal during the selection granule
  1247. @verbatim
  1248. map : s-----------e
  1249. granule: s-----------------e
  1250. @endverbatim
  1251. @param use_overlap: Select maps which temporal overlap the selection granule
  1252. @verbatim
  1253. map : s-----------e
  1254. granule: s-----------------e
  1255. map : s-----------e
  1256. granule: s----------e
  1257. @endverbatim
  1258. @param use_contain: Select maps which temporally contain the selection granule
  1259. @verbatim
  1260. map : s-----------------e
  1261. granule: s-----------e
  1262. @endverbatim
  1263. @param use_equal: Select maps which temporally equal to the selection granule
  1264. @verbatim
  1265. map : s-----------e
  1266. granule: s-----------e
  1267. @endverbatim
  1268. @param use_follows: Select maps which temporally follow the selection granule
  1269. @verbatim
  1270. map : s-----------e
  1271. granule: s-----------e
  1272. @endverbatim
  1273. @param use_precedes: Select maps which temporally precedes the selection granule
  1274. @verbatim
  1275. map : s-----------e
  1276. granule: s-----------e
  1277. @endverbatim
  1278. Usage:
  1279. @code
  1280. >>> # Relative time
  1281. >>> start = 1
  1282. >>> end = 2
  1283. >>> create_temporal_relation_sql_where_statement(start, end,
  1284. ... use_start=False)
  1285. >>> create_temporal_relation_sql_where_statement(start, end)
  1286. '((start_time >= 1 and start_time < 2) )'
  1287. >>> create_temporal_relation_sql_where_statement(start, end,
  1288. ... use_start=True)
  1289. '((start_time >= 1 and start_time < 2) )'
  1290. >>> create_temporal_relation_sql_where_statement(start, end,
  1291. ... use_start=False, use_during=True)
  1292. '(((start_time > 1 and end_time < 2) OR (start_time >= 1 and end_time < 2) OR (start_time > 1 and end_time <= 2)))'
  1293. >>> create_temporal_relation_sql_where_statement(start, end,
  1294. ... use_start=False, use_overlap=True)
  1295. '(((start_time < 1 and end_time > 1 and end_time < 2) OR (start_time < 2 and start_time > 1 and end_time > 2)))'
  1296. >>> create_temporal_relation_sql_where_statement(start, end,
  1297. ... use_start=False, use_contain=True)
  1298. '(((start_time < 1 and end_time > 2) OR (start_time <= 1 and end_time > 2) OR (start_time < 1 and end_time >= 2)))'
  1299. >>> create_temporal_relation_sql_where_statement(start, end,
  1300. ... use_start=False, use_equal=True)
  1301. '((start_time = 1 and end_time = 2))'
  1302. >>> create_temporal_relation_sql_where_statement(start, end,
  1303. ... use_start=False, use_follows=True)
  1304. '((start_time = 2))'
  1305. >>> create_temporal_relation_sql_where_statement(start, end,
  1306. ... use_start=False, use_precedes=True)
  1307. '((end_time = 1))'
  1308. >>> create_temporal_relation_sql_where_statement(start, end,
  1309. ... use_start=True, use_during=True, use_overlap=True, use_contain=True,
  1310. ... use_equal=True, use_follows=True, use_precedes=True)
  1311. '((start_time >= 1 and start_time < 2) OR ((start_time > 1 and end_time < 2) OR (start_time >= 1 and end_time < 2) OR (start_time > 1 and end_time <= 2)) OR ((start_time < 1 and end_time > 1 and end_time < 2) OR (start_time < 2 and start_time > 1 and end_time > 2)) OR ((start_time < 1 and end_time > 2) OR (start_time <= 1 and end_time > 2) OR (start_time < 1 and end_time >= 2)) OR (start_time = 1 and end_time = 2) OR (start_time = 2) OR (end_time = 1))'
  1312. >>> # Absolute time
  1313. >>> start = datetime(2001, 1, 1, 12, 30)
  1314. >>> end = datetime(2001, 3, 31, 14, 30)
  1315. >>> create_temporal_relation_sql_where_statement(start, end,
  1316. ... use_start=False)
  1317. >>> create_temporal_relation_sql_where_statement(start, end)
  1318. "((start_time >= '2001-01-01 12:30:00' and start_time < '2001-03-31 14:30:00') )"
  1319. >>> create_temporal_relation_sql_where_statement(start, end,
  1320. ... use_start=True)
  1321. "((start_time >= '2001-01-01 12:30:00' and start_time < '2001-03-31 14:30:00') )"
  1322. >>> create_temporal_relation_sql_where_statement(start, end,
  1323. ... use_start=False, use_during=True)
  1324. "(((start_time > '2001-01-01 12:30:00' and end_time < '2001-03-31 14:30:00') OR (start_time >= '2001-01-01 12:30:00' and end_time < '2001-03-31 14:30:00') OR (start_time > '2001-01-01 12:30:00' and end_time <= '2001-03-31 14:30:00')))"
  1325. >>> create_temporal_relation_sql_where_statement(start, end,
  1326. ... use_start=False, use_overlap=True)
  1327. "(((start_time < '2001-01-01 12:30:00' and end_time > '2001-01-01 12:30:00' and end_time < '2001-03-31 14:30:00') OR (start_time < '2001-03-31 14:30:00' and start_time > '2001-01-01 12:30:00' and end_time > '2001-03-31 14:30:00')))"
  1328. >>> create_temporal_relation_sql_where_statement(start, end,
  1329. ... use_start=False, use_contain=True)
  1330. "(((start_time < '2001-01-01 12:30:00' and end_time > '2001-03-31 14:30:00') OR (start_time <= '2001-01-01 12:30:00' and end_time > '2001-03-31 14:30:00') OR (start_time < '2001-01-01 12:30:00' and end_time >= '2001-03-31 14:30:00')))"
  1331. >>> create_temporal_relation_sql_where_statement(start, end,
  1332. ... use_start=False, use_equal=True)
  1333. "((start_time = '2001-01-01 12:30:00' and end_time = '2001-03-31 14:30:00'))"
  1334. >>> create_temporal_relation_sql_where_statement(start, end,
  1335. ... use_start=False, use_follows=True)
  1336. "((start_time = '2001-03-31 14:30:00'))"
  1337. >>> create_temporal_relation_sql_where_statement(start, end,
  1338. ... use_start=False, use_precedes=True)
  1339. "((end_time = '2001-01-01 12:30:00'))"
  1340. >>> create_temporal_relation_sql_where_statement(start, end,
  1341. ... use_start=True, use_during=True, use_overlap=True, use_contain=True,
  1342. ... use_equal=True, use_follows=True, use_precedes=True)
  1343. "((start_time >= '2001-01-01 12:30:00' and start_time < '2001-03-31 14:30:00') OR ((start_time > '2001-01-01 12:30:00' and end_time < '2001-03-31 14:30:00') OR (start_time >= '2001-01-01 12:30:00' and end_time < '2001-03-31 14:30:00') OR (start_time > '2001-01-01 12:30:00' and end_time <= '2001-03-31 14:30:00')) OR ((start_time < '2001-01-01 12:30:00' and end_time > '2001-01-01 12:30:00' and end_time < '2001-03-31 14:30:00') OR (start_time < '2001-03-31 14:30:00' and start_time > '2001-01-01 12:30:00' and end_time > '2001-03-31 14:30:00')) OR ((start_time < '2001-01-01 12:30:00' and end_time > '2001-03-31 14:30:00') OR (start_time <= '2001-01-01 12:30:00' and end_time > '2001-03-31 14:30:00') OR (start_time < '2001-01-01 12:30:00' and end_time >= '2001-03-31 14:30:00')) OR (start_time = '2001-01-01 12:30:00' and end_time = '2001-03-31 14:30:00') OR (start_time = '2001-03-31 14:30:00') OR (end_time = '2001-01-01 12:30:00'))"
  1344. @endcode
  1345. """
  1346. where = "("
  1347. if use_start:
  1348. if isinstance(start, datetime):
  1349. where += "(start_time >= '%s' and start_time < '%s') " % (start, end)
  1350. else:
  1351. where += "(start_time >= %i and start_time < %i) " % (start, end)
  1352. if use_during:
  1353. if use_start:
  1354. where += " OR "
  1355. if isinstance(start, datetime):
  1356. where += "((start_time > '%s' and end_time < '%s') OR " % (start, end)
  1357. where += "(start_time >= '%s' and end_time < '%s') OR " % (start, end)
  1358. where += "(start_time > '%s' and end_time <= '%s'))" % (start, end)
  1359. else:
  1360. where += "((start_time > %i and end_time < %i) OR " % (start, end)
  1361. where += "(start_time >= %i and end_time < %i) OR " % (start, end)
  1362. where += "(start_time > %i and end_time <= %i))" % (start, end)
  1363. if use_overlap:
  1364. if use_start or use_during:
  1365. where += " OR "
  1366. if isinstance(start, datetime):
  1367. where += "((start_time < '%s' and end_time > '%s' and end_time < '%s') OR " % (start, start, end)
  1368. where += "(start_time < '%s' and start_time > '%s' and end_time > '%s'))" % (end, start, end)
  1369. else:
  1370. where += "((start_time < %i and end_time > %i and end_time < %i) OR " % (start, start, end)
  1371. where += "(start_time < %i and start_time > %i and end_time > %i))" % (end, start, end)
  1372. if use_contain:
  1373. if use_start or use_during or use_overlap:
  1374. where += " OR "
  1375. if isinstance(start, datetime):
  1376. where += "((start_time < '%s' and end_time > '%s') OR " % (start, end)
  1377. where += "(start_time <= '%s' and end_time > '%s') OR " % (start, end)
  1378. where += "(start_time < '%s' and end_time >= '%s'))" % (start, end)
  1379. else:
  1380. where += "((start_time < %i and end_time > %i) OR " % (start, end)
  1381. where += "(start_time <= %i and end_time > %i) OR " % (start, end)
  1382. where += "(start_time < %i and end_time >= %i))" % (start, end)
  1383. if use_equal:
  1384. if use_start or use_during or use_overlap or use_contain:
  1385. where += " OR "
  1386. if isinstance(start, datetime):
  1387. where += "(start_time = '%s' and end_time = '%s')" % (start, end)
  1388. else:
  1389. where += "(start_time = %i and end_time = %i)" % (start, end)
  1390. if use_follows:
  1391. if use_start or use_during or use_overlap or use_contain or use_equal:
  1392. where += " OR "
  1393. if isinstance(start, datetime):
  1394. where += "(start_time = '%s')" % (end)
  1395. else:
  1396. where += "(start_time = %i)" % (end)
  1397. if use_precedes:
  1398. if use_start or use_during or use_overlap or use_contain or use_equal \
  1399. or use_follows:
  1400. where += " OR "
  1401. if isinstance(start, datetime):
  1402. where += "(end_time = '%s')" % (start)
  1403. else:
  1404. where += "(end_time = %i)" % (start)
  1405. where += ")"
  1406. # Catch empty where statement
  1407. if where == "()":
  1408. where = None
  1409. return where
  1410. ###############################################################################
  1411. if __name__ == "__main__":
  1412. import doctest
  1413. doctest.testmod()