abstract_space_time_dataset.py 72 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791
  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. Space time datasets with interval time, time instances and mixed time
  496. are supported.
  497. Gaps between maps are identified as unregistered maps with id==None.
  498. The objects are initialized with the id and the temporal
  499. extent (temporal type, start time, end time).
  500. In case more map information are needed, use the select()
  501. method for each listed object.
  502. @param gran: The granularity to be used, if None the granularity of
  503. the space time dataset is used.
  504. @param dbif: The database interface to be used
  505. @return ordered object list, in case nothing found None is returned
  506. """
  507. dbif, connect = init_dbif(dbif)
  508. obj_list = []
  509. if gran is None:
  510. gran = self.get_granularity()
  511. start, end = self.get_valid_time()
  512. # Time instances and mixed time
  513. is_irregular = False
  514. # We need to adjust the end time in case the the dataset ha no
  515. # interval time, so we can catch time instances at the end
  516. if self.get_map_time() != "interval":
  517. is_irregular = True
  518. if self.is_time_absolute():
  519. end = increment_datetime_by_string(end, gran)
  520. else:
  521. end = end + gran
  522. while start < end:
  523. if self.is_time_absolute():
  524. next = increment_datetime_by_string(start, gran)
  525. else:
  526. next = start + gran
  527. where = "(start_time <= '%s' and end_time >= '%s')" % (start, next)
  528. rows = self.get_registered_maps("id", where, "start_time", dbif)
  529. found_gap = False
  530. if rows is not None and len(rows) != 0:
  531. if len(rows) > 1:
  532. core.warning(_("More than one map found in a granule. "
  533. "Temporal granularity seems to be invalid or"
  534. " the chosen granularity is not a greatest "
  535. "common divider of all intervals and gaps "
  536. "in the dataset."))
  537. maplist = []
  538. for row in rows:
  539. # Take the first map
  540. map = self.get_new_map_instance(rows[0]["id"])
  541. if self.is_time_absolute():
  542. map.set_absolute_time(start, next)
  543. elif self.is_time_relative():
  544. map.set_relative_time(start, next,
  545. self.get_relative_time_unit())
  546. maplist.append(copy.copy(map))
  547. obj_list.append(copy.copy(maplist))
  548. else:
  549. # We truely found a gap and maybe a time instance
  550. found_gap = True
  551. # Searching for time instances with start time in the current
  552. # granule
  553. where = "(start_time = '%s')" % (start)
  554. rows = self.get_registered_maps("id", where, "start_time", dbif)
  555. if rows is not None and len(rows) != 0:
  556. if len(rows) > 1:
  557. core.warning(_("More than one map found in a granule. "
  558. "Temporal granularity seems to be invalid or"
  559. " the chosen granularity is not a greatest "
  560. "common divider of all time instances "
  561. "in the dataset."))
  562. maplist = []
  563. for row in rows:
  564. # Take the first map
  565. map = self.get_new_map_instance(rows[0]["id"])
  566. if self.is_time_absolute():
  567. map.set_absolute_time(start, None)
  568. elif self.is_time_relative():
  569. map.set_relative_time(start, None,
  570. self.get_relative_time_unit())
  571. maplist.append(copy.copy(map))
  572. obj_list.append(copy.copy(maplist))
  573. # In case of irregular time (point, mixed) the last granule
  574. # does not belong to the dataset and will be ignored
  575. if is_irregular:
  576. if next == end:
  577. found_gap = False
  578. # Gap handling
  579. if found_gap:
  580. # Append a map object with None as id to indicate a gap
  581. map = self.get_new_map_instance(None)
  582. if self.is_time_absolute():
  583. map.set_absolute_time(start, next)
  584. elif self.is_time_relative():
  585. map.set_relative_time(start, next,
  586. self.get_relative_time_unit())
  587. maplist = []
  588. maplist.append(copy.copy(map))
  589. obj_list.append(copy.copy(maplist))
  590. start = next
  591. if connect:
  592. dbif.close()
  593. if obj_list:
  594. return obj_list
  595. return None
  596. def get_registered_maps_as_objects_with_gaps(self, where=None, dbif=None):
  597. """!Return all registered maps as ordered (by start_time) object list with
  598. "gap" map objects (id==None) for temporal topological operations
  599. Gaps between maps are identified as maps with id==None
  600. The objects are initialized with the id and the
  601. temporal extent (temporal type, start time, end time).
  602. In case more map information are needed, use the select()
  603. method for each listed object.
  604. @param where: The SQL where statement to select a
  605. subset of the registered maps without "WHERE"
  606. @param dbif: The database interface to be used
  607. @return ordered object list, in case nothing found None is returned
  608. """
  609. dbif, connect = init_dbif(dbif)
  610. obj_list = []
  611. maps = self.get_registered_maps_as_objects(where, "start_time", dbif)
  612. if maps is not None and len(maps) > 0:
  613. for i in range(len(maps)):
  614. obj_list.append(maps[i])
  615. # Detect and insert gaps
  616. if i < len(maps) - 1:
  617. relation = maps[i + 1].temporal_relation(maps[i])
  618. if relation == "after":
  619. start1, end1 = maps[i].get_valid_time()
  620. start2, end2 = maps[i + 1].get_valid_time()
  621. end = start2
  622. if end1 is not None:
  623. start = end1
  624. else:
  625. start = start1
  626. map = self.get_new_map_instance(None)
  627. if self.is_time_absolute():
  628. map.set_absolute_time(start, end)
  629. elif self.is_time_relative():
  630. map.set_relative_time(start, end,
  631. self.get_relative_time_unit())
  632. obj_list.append(copy.copy(map))
  633. if connect:
  634. dbif.close()
  635. return obj_list
  636. def get_registered_maps_as_objects(self, where=None, order="start_time",
  637. dbif=None):
  638. """!Return all registered maps as ordered object list for
  639. temporal topological operations
  640. The objects are initialized with the id and the temporal extent
  641. (temporal type, start time, end time).
  642. In case more map information are needed, use the select()
  643. method for each listed object.
  644. @param where: The SQL where statement to select a subset of
  645. the registered maps without "WHERE"
  646. @param order: The SQL order statement to be used to order the
  647. objects in the list without "ORDER BY"
  648. @param dbif: The database interface to be used
  649. @return The ordered map object list,
  650. In case nothing found None is returned
  651. """
  652. dbif, connect = init_dbif(dbif)
  653. obj_list = []
  654. rows = self.get_registered_maps(
  655. "id,start_time,end_time", where, order, dbif)
  656. count = 0
  657. if rows is not None:
  658. for row in rows:
  659. core.percent(count, len(rows), 1)
  660. map = self.get_new_map_instance(row["id"])
  661. if self.is_time_absolute():
  662. map.set_absolute_time(row["start_time"], row["end_time"])
  663. elif self.is_time_relative():
  664. map.set_relative_time(row["start_time"], row["end_time"],
  665. self.get_relative_time_unit())
  666. obj_list.append(copy.copy(map))
  667. count += 1
  668. core.percent(1, 1, 1)
  669. if connect:
  670. dbif.close()
  671. return obj_list
  672. def get_registered_maps(self, columns=None, where=None, order=None, dbif=None):
  673. """!Return SQL rows of all registered maps.
  674. In case columns are not specified, each row includes all columns
  675. specified in the datatype specific view.
  676. @param columns: Columns to be selected as SQL compliant string
  677. @param where: The SQL where statement to select a subset
  678. of the registered maps without "WHERE"
  679. @param order: The SQL order statement to be used to order the
  680. objects in the list without "ORDER BY"
  681. @param dbif: The database interface to be used
  682. @return SQL rows of all registered maps,
  683. In case nothing found None is returned
  684. """
  685. dbif, connect = init_dbif(dbif)
  686. rows = None
  687. if self.get_map_register() is not None:
  688. # Use the correct temporal table
  689. if self.get_temporal_type() == "absolute":
  690. map_view = self.get_new_map_instance(
  691. None).get_type() + "_view_abs_time"
  692. else:
  693. map_view = self.get_new_map_instance(
  694. None).get_type() + "_view_rel_time"
  695. if columns is not None and columns != "":
  696. sql = "SELECT %s FROM %s WHERE %s.id IN (SELECT id FROM %s)" %\
  697. (columns, map_view, map_view, self.get_map_register())
  698. else:
  699. sql = "SELECT * FROM %s WHERE %s.id IN (SELECT id FROM %s)" % \
  700. (map_view, map_view, self.get_map_register())
  701. if where is not None and where != "":
  702. sql += " AND (%s)" % (where.split(";")[0])
  703. if order is not None and order != "":
  704. sql += " ORDER BY %s" % (order.split(";")[0])
  705. try:
  706. dbif.cursor.execute(sql)
  707. rows = dbif.cursor.fetchall()
  708. except:
  709. if connect:
  710. dbif.close()
  711. core.error(_("Unable to get map ids from register table <%s>")
  712. % (self.get_map_register()))
  713. raise
  714. if connect:
  715. dbif.close()
  716. return rows
  717. def rename(self, ident, dbif=None):
  718. """!Rename the space time dataset
  719. This method renames the space time dataset, the map register table
  720. and updates the entries in registered maps stds register.
  721. @param ident: The new identifier name@mapset
  722. @param dbif: The database interface to be used
  723. """
  724. dbif, connect = init_dbif(dbif)
  725. # SELECT all needed information from the database
  726. self.select(dbif)
  727. # We need to select the registered maps here
  728. maps = self.get_registered_maps_as_objects(None, "start_time", dbif)
  729. # Safe old identifier
  730. old_ident = self.get_id()
  731. # We need to rename the old table
  732. old_map_register_table = self.get_map_register()
  733. # Set new identifier
  734. self.set_id(ident)
  735. # Create map register table name from new identifier
  736. new_map_register_table = self.create_map_register_name()
  737. # Set new map register table name
  738. self.set_map_register(new_map_register_table)
  739. # Get the update statement, we update the table entry of the old identifier
  740. statement = self.update(dbif, execute=False, ident=old_ident)
  741. # We need to rename the raster register table
  742. statement += "ALTER TABLE %s RENAME TO \'%s\';\n"%\
  743. (old_map_register_table, new_map_register_table)
  744. # We need to rename the space time dataset in the maps register table
  745. if maps:
  746. for map in maps:
  747. map.select()
  748. statement += "UPDATE %s SET id = \'%s\' WHERE id = \'%s\';\n"%\
  749. (map.get_stds_register(), ident, old_ident)
  750. # Execute the accumulated statements
  751. dbif.execute_transaction(statement)
  752. if connect:
  753. dbif.close()
  754. def delete(self, dbif=None, execute=True):
  755. """!Delete a space time dataset from the temporal database
  756. This method removes the space time dataset from the temporal
  757. database and drops its map register table
  758. @param dbif: The database interface to be used
  759. @param execute: If True the SQL DELETE and DROP table
  760. statements will be executed.
  761. If False the prepared SQL statements are returned
  762. and must be executed by the caller.
  763. @return The SQL statements if execute == False, else an empty string
  764. """
  765. # First we need to check if maps are registered in this dataset and
  766. # unregister them
  767. core.verbose(_("Delete space time %s dataset <%s> from temporal "
  768. "database") % \
  769. (self.get_new_map_instance(ident=None).get_type(),
  770. self.get_id()))
  771. statement = ""
  772. dbif, connect = init_dbif(dbif)
  773. # SELECT all needed information from the database
  774. self.metadata.select(dbif)
  775. if self.get_map_register() is not None:
  776. core.verbose(_("Drop map register table: %s") % (
  777. self.get_map_register()))
  778. rows = self.get_registered_maps("id", None, None, dbif)
  779. # Unregister each registered map in the table
  780. if rows is not None:
  781. num_maps = len(rows)
  782. count = 0
  783. for row in rows:
  784. core.percent(count, num_maps, 1)
  785. # Unregister map
  786. map = self.get_new_map_instance(row["id"])
  787. statement += self.unregister_map(
  788. map=map, dbif=dbif, execute=False)
  789. count += 1
  790. core.percent(1, 1, 1)
  791. # Safe the DROP table statement
  792. statement += "DROP TABLE " + self.get_map_register() + ";\n"
  793. # Remove the primary key, the foreign keys will be removed by trigger
  794. statement += self.base.get_delete_statement()
  795. if execute:
  796. dbif.execute_transaction(statement)
  797. self.reset(None)
  798. if connect:
  799. dbif.close()
  800. if execute:
  801. return ""
  802. return statement
  803. def register_map(self, map, dbif=None):
  804. """!Register a map in the space time dataset.
  805. This method takes care of the registration of a map
  806. in a space time dataset.
  807. In case the map is already registered this function
  808. will break with a warning and return False.
  809. @param map: The AbstractMapDataset object that should be registered
  810. @param dbif: The database interface to be used
  811. """
  812. dbif, connect = init_dbif(dbif)
  813. if map.is_in_db(dbif) == False:
  814. dbif.close()
  815. core.fatal(_("Only maps with absolute or relative valid time can "
  816. "be registered"))
  817. if map.get_layer():
  818. core.verbose(_("Register %s map <%s> with layer %s in space "
  819. "time %s dataset <%s>") % (map.get_type(),
  820. map.get_map_id(),
  821. map.get_layer(),
  822. map.get_type(),
  823. self.get_id()))
  824. else:
  825. core.verbose(_("Register %s map <%s> in space time %s "
  826. "dataset <%s>") % (map.get_type(), map.get_map_id(),
  827. map.get_type(), self.get_id()))
  828. # First select all data from the database
  829. map.select(dbif)
  830. if not map.check_valid_time():
  831. if map.get_layer():
  832. core.fatal(_("Map <%s> with layer %s has invalid time")
  833. % (map.get_map_id(), map.get_layer()))
  834. else:
  835. core.fatal(_("Map <%s> has invalid time") % (map.get_map_id()))
  836. map_id = map.base.get_id()
  837. map_name = map.base.get_name()
  838. map_mapset = map.base.get_mapset()
  839. map_register_table = map.get_stds_register()
  840. map_rel_time_unit = map.get_relative_time_unit()
  841. map_ttype = map.get_temporal_type()
  842. #print "Map register table", map_register_table
  843. # Get basic info
  844. stds_name = self.base.get_name()
  845. stds_mapset = self.base.get_mapset()
  846. stds_register_table = self.get_map_register()
  847. stds_ttype = self.get_temporal_type()
  848. # The gathered SQL statemets are stroed here
  849. statement = ""
  850. # Check temporal types
  851. if stds_ttype != map_ttype:
  852. if map.get_layer():
  853. core.fatal(_("Temporal type of space time dataset <%s> and "
  854. "map <%s> with layer %s are different") % \
  855. (self.get_id(), map.get_map_id(), map.get_layer()))
  856. else:
  857. core.fatal(_("Temporal type of space time dataset <%s> and "
  858. "map <%s> are different") % \
  859. (self.get_id(), map.get_map_id()))
  860. # In case no map has been registered yet, set the
  861. # relative time unit from the first map
  862. if (self.metadata.get_number_of_maps() is None or \
  863. self.metadata.get_number_of_maps() == 0) and \
  864. self.map_counter == 0 and self.is_time_relative():
  865. self.set_relative_time_unit(map_rel_time_unit)
  866. statement += self.relative_time.get_update_all_statement_mogrified(
  867. dbif)
  868. core.verbose(_("Set temporal unit for space time %s dataset "
  869. "<%s> to %s") % (map.get_type(), self.get_id(),
  870. map_rel_time_unit))
  871. stds_rel_time_unit = self.get_relative_time_unit()
  872. # Check the relative time unit
  873. if self.is_time_relative() and (stds_rel_time_unit != map_rel_time_unit):
  874. if map.get_layer():
  875. core.fatal(_("Relative time units of space time dataset "
  876. "<%s> and map <%s> with layer %s are different") %\
  877. (self.get_id(), map.get_map_id(), map.get_layer()))
  878. else:
  879. core.fatal(_("Relative time units of space time dataset "
  880. "<%s> and map <%s> are different") % \
  881. (self.get_id(), map.get_map_id()))
  882. #print "STDS register table", stds_register_table
  883. if stds_mapset != map_mapset:
  884. dbif.close()
  885. core.fatal(_("Only maps from the same mapset can be registered"))
  886. # Check if map is already registered
  887. if stds_register_table is not None:
  888. if dbif.dbmi.paramstyle == "qmark":
  889. sql = "SELECT id FROM " + \
  890. stds_register_table + " WHERE id = (?)"
  891. else:
  892. sql = "SELECT id FROM " + \
  893. stds_register_table + " WHERE id = (%s)"
  894. try:
  895. dbif.cursor.execute(sql, (map_id,))
  896. row = dbif.cursor.fetchone()
  897. except:
  898. row = None
  899. core.warning(_("Error in strds_register_table request"))
  900. raise
  901. if row is not None and row[0] == map_id:
  902. if connect == True:
  903. dbif.close()
  904. if map.get_layer() is not None:
  905. core.warning(_("Map <%s> with layer %s is already "
  906. "registered.") % (map.get_map_id(),
  907. map.get_layer()))
  908. else:
  909. core.warning(_("Map <%s> is already registered.")
  910. % (map.get_map_id()))
  911. return ""
  912. # Create tables
  913. sql_path = get_sql_template_path()
  914. # We need to create the map raster register table precedes we can register the map
  915. if map_register_table is None:
  916. # Create a unique id
  917. uuid_rand = "map_" + str(uuid.uuid4()).replace("-", "")
  918. map_register_table = uuid_rand + "_" + \
  919. self.get_type() + "_register"
  920. # Read the SQL template
  921. sql = open(os.path.join(sql_path,
  922. "map_stds_register_table_template.sql"),
  923. 'r').read()
  924. # Create the raster, raster3d and vector tables
  925. sql = sql.replace("GRASS_MAP", map.get_type())
  926. sql = sql.replace("MAP_NAME", map_name + "_" + map_mapset)
  927. sql = sql.replace("TABLE_NAME", uuid_rand)
  928. sql = sql.replace("MAP_ID", map_id)
  929. sql = sql.replace("STDS", self.get_type())
  930. statement += sql
  931. # Set the stds register table name and put it into the DB
  932. map.set_stds_register(map_register_table)
  933. statement += map.metadata.get_update_statement_mogrified(dbif)
  934. if map.get_layer():
  935. core.verbose(_("Created register table <%s> for "
  936. "%s map <%s> with layer %s") %
  937. (map_register_table, map.get_type(),
  938. map.get_map_id(), map.get_layer()))
  939. else:
  940. core.verbose(_("Created register table <%s> for %s map <%s>") %
  941. (map_register_table, map.get_type(),
  942. map.get_map_id()))
  943. # We need to create the table and register it
  944. if stds_register_table is None:
  945. # Create table name
  946. stds_register_table = self.create_map_register_name()
  947. # Read the SQL template
  948. sql = open(os.path.join(sql_path,
  949. "stds_map_register_table_template.sql"),
  950. 'r').read()
  951. # Create the raster, raster3d and vector tables
  952. sql = sql.replace("GRASS_MAP", map.get_type())
  953. sql = sql.replace("SPACETIME_NAME", stds_name + "_" + stds_mapset)
  954. sql = sql.replace("SPACETIME_ID", self.base.get_id())
  955. sql = sql.replace("STDS", self.get_type())
  956. statement += sql
  957. # Set the map register table name and put it into the DB
  958. self.set_map_register(stds_register_table)
  959. statement += self.metadata.get_update_statement_mogrified(dbif)
  960. core.verbose(_("Created register table <%s> for space "
  961. "time %s dataset <%s>") %
  962. (stds_register_table, map.get_type(), self.get_id()))
  963. # We need to execute the statement at this time
  964. if statement != "":
  965. dbif.execute_transaction(statement)
  966. statement = ""
  967. # Register the stds in the map stds register table
  968. # Check if the entry is already there
  969. if dbif.dbmi.paramstyle == "qmark":
  970. sql = "SELECT id FROM " + map_register_table + " WHERE id = ?"
  971. else:
  972. sql = "SELECT id FROM " + map_register_table + " WHERE id = %s"
  973. try:
  974. dbif.cursor.execute(sql, (self.base.get_id(),))
  975. row = dbif.cursor.fetchone()
  976. except:
  977. row = None
  978. # In case of no entry make a new one
  979. if row is None:
  980. if dbif.dbmi.paramstyle == "qmark":
  981. sql = "INSERT INTO " + map_register_table + \
  982. " (id) " + "VALUES (?);\n"
  983. else:
  984. sql = "INSERT INTO " + map_register_table + \
  985. " (id) " + "VALUES (%s);\n"
  986. statement += dbif.mogrify_sql_statement(
  987. (sql, (self.base.get_id(),)))
  988. # Now put the raster name in the stds map register table
  989. if dbif.dbmi.paramstyle == "qmark":
  990. sql = "INSERT INTO " + stds_register_table + \
  991. " (id) " + "VALUES (?);\n"
  992. else:
  993. sql = "INSERT INTO " + stds_register_table + \
  994. " (id) " + "VALUES (%s);\n"
  995. statement += dbif.mogrify_sql_statement((sql, (map_id,)))
  996. # Now execute the insert transaction
  997. dbif.execute_transaction(statement)
  998. if connect:
  999. dbif.close()
  1000. # increase the counter
  1001. self.map_counter += 1
  1002. def unregister_map(self, map, dbif=None, execute=True):
  1003. """!Unregister a map from the space time dataset.
  1004. This method takes care of the un-registration of a map
  1005. from a space time dataset.
  1006. @param map: The map object to unregister
  1007. @param dbif: The database interface to be used
  1008. @param execute: If True the SQL DELETE and DROP table
  1009. statements will be executed.
  1010. If False the prepared SQL statements are
  1011. returned and must be executed by the caller.
  1012. @return The SQL statements if execute == False, else an empty
  1013. string, None in case of a failure
  1014. """
  1015. statement = ""
  1016. dbif, connect = init_dbif(dbif)
  1017. # First select needed data from the database
  1018. map.metadata.select(dbif)
  1019. map_id = map.get_id()
  1020. map_register_table = map.get_stds_register()
  1021. stds_register_table = self.get_map_register()
  1022. if map.get_layer() is not None:
  1023. core.verbose(_("Unregister %s map <%s> with layer %s") % \
  1024. (map.get_type(), map.get_map_id(), map.get_layer()))
  1025. else:
  1026. core.verbose(_("Unregister %s map <%s>") % (
  1027. map.get_type(), map.get_map_id()))
  1028. # Check if the map is registered in the space time raster dataset
  1029. if map_register_table is not None:
  1030. if dbif.dbmi.paramstyle == "qmark":
  1031. sql = "SELECT id FROM " + map_register_table + " WHERE id = ?"
  1032. else:
  1033. sql = "SELECT id FROM " + map_register_table + " WHERE id = %s"
  1034. try:
  1035. dbif.cursor.execute(sql, (self.base.get_id(),))
  1036. row = dbif.cursor.fetchone()
  1037. except:
  1038. row = None
  1039. # Break if the map is not registered
  1040. if row is None:
  1041. if map.get_layer() is not None:
  1042. core.warning(_("Map <%s> with layer %s is not registered "
  1043. "in space time dataset <%s>") % \
  1044. (map.get_map_id(), map.get_layer(),
  1045. self.base.get_id()))
  1046. else:
  1047. core.warning(_("Map <%s> is not registered in space "
  1048. "time dataset <%s>") % (map.get_map_id(),
  1049. self.base.get_id()))
  1050. if connect == True:
  1051. dbif.close()
  1052. return ""
  1053. # Remove the space time raster dataset from the raster dataset register
  1054. if map_register_table is not None:
  1055. if dbif.dbmi.paramstyle == "qmark":
  1056. sql = "DELETE FROM " + map_register_table + " WHERE id = ?;\n"
  1057. else:
  1058. sql = "DELETE FROM " + map_register_table + " WHERE id = %s;\n"
  1059. statement += dbif.mogrify_sql_statement(
  1060. (sql, (self.base.get_id(),)))
  1061. # Remove the raster map from the space time raster dataset register
  1062. if stds_register_table is not None:
  1063. if dbif.dbmi.paramstyle == "qmark":
  1064. sql = "DELETE FROM " + stds_register_table + " WHERE id = ?;\n"
  1065. else:
  1066. sql = "DELETE FROM " + \
  1067. stds_register_table + " WHERE id = %s;\n"
  1068. statement += dbif.mogrify_sql_statement((sql, (map_id,)))
  1069. if execute:
  1070. dbif.execute_transaction(statement)
  1071. if connect:
  1072. dbif.close()
  1073. # decrease the counter
  1074. self.map_counter -= 1
  1075. if execute:
  1076. return ""
  1077. return statement
  1078. def update_from_registered_maps(self, dbif=None):
  1079. """!This methods updates the spatial and temporal extent as well as
  1080. type specific metadata. It should always been called after maps are registered
  1081. or unregistered/deleted from the space time dataset.
  1082. The update of the temporal extent checks if the end time is set correctly.
  1083. In case the registered maps have no valid end time (None) the maximum start time
  1084. will be used. If the end time is earlier than the maximum start time, it will
  1085. be replaced by the maximum start time.
  1086. An other solution to automate this is to use the deactivated trigger
  1087. in the SQL files. But this will result in a huge performance issue
  1088. in case many maps are registered (>1000).
  1089. @param dbif: The database interface to be used
  1090. """
  1091. core.verbose(_("Update metadata, spatial and temporal extent from "
  1092. "all registered maps of <%s>") % (self.get_id()))
  1093. # Nothing to do if the register is not present
  1094. if not self.get_map_register():
  1095. return
  1096. dbif, connect = init_dbif(dbif)
  1097. map_time = None
  1098. use_start_time = False
  1099. # Get basic info
  1100. stds_name = self.base.get_name()
  1101. stds_mapset = self.base.get_mapset()
  1102. sql_path = get_sql_template_path()
  1103. #We create a transaction
  1104. sql_script = ""
  1105. # Update the spatial and temporal extent from registered maps
  1106. # Read the SQL template
  1107. sql = open(os.path.join(sql_path,
  1108. "update_stds_spatial_temporal_extent_template.sql"),
  1109. 'r').read()
  1110. sql = sql.replace(
  1111. "GRASS_MAP", self.get_new_map_instance(None).get_type())
  1112. sql = sql.replace("SPACETIME_NAME", stds_name + "_" + stds_mapset)
  1113. sql = sql.replace("SPACETIME_ID", self.base.get_id())
  1114. sql = sql.replace("STDS", self.get_type())
  1115. sql_script += sql
  1116. sql_script += "\n"
  1117. # Update type specific metadata
  1118. sql = open(os.path.join(sql_path, "update_" +
  1119. self.get_type() + "_metadata_template.sql"), 'r').read()
  1120. sql = sql.replace(
  1121. "GRASS_MAP", self.get_new_map_instance(None).get_type())
  1122. sql = sql.replace("SPACETIME_NAME", stds_name + "_" + stds_mapset)
  1123. sql = sql.replace("SPACETIME_ID", self.base.get_id())
  1124. sql = sql.replace("STDS", self.get_type())
  1125. sql_script += sql
  1126. sql_script += "\n"
  1127. dbif.execute_transaction(sql_script)
  1128. # Read and validate the selected end time
  1129. self.select()
  1130. if self.is_time_absolute():
  1131. start_time, end_time, tz = self.get_absolute_time()
  1132. else:
  1133. start_time, end_time, unit = self.get_relative_time()
  1134. # In case no end time is set, use the maximum start time of
  1135. # all registered maps as end time
  1136. if end_time is None:
  1137. use_start_time = True
  1138. else:
  1139. # Check if the end time is smaller than the maximum start time
  1140. if self.is_time_absolute():
  1141. sql = """SELECT max(start_time) FROM GRASS_MAP_absolute_time
  1142. WHERE GRASS_MAP_absolute_time.id IN
  1143. (SELECT id FROM SPACETIME_NAME_GRASS_MAP_register);"""
  1144. sql = sql.replace("GRASS_MAP", self.get_new_map_instance(
  1145. None).get_type())
  1146. sql = sql.replace("SPACETIME_NAME",
  1147. stds_name + "_" + stds_mapset)
  1148. else:
  1149. sql = """SELECT max(start_time) FROM GRASS_MAP_relative_time
  1150. WHERE GRASS_MAP_relative_time.id IN
  1151. (SELECT id FROM SPACETIME_NAME_GRASS_MAP_register);"""
  1152. sql = sql.replace("GRASS_MAP", self.get_new_map_instance(
  1153. None).get_type())
  1154. sql = sql.replace("SPACETIME_NAME",
  1155. stds_name + "_" + stds_mapset)
  1156. dbif.cursor.execute(sql)
  1157. row = dbif.cursor.fetchone()
  1158. if row is not None:
  1159. # This seems to be a bug in sqlite3 Python driver
  1160. if dbif.dbmi.__name__ == "sqlite3":
  1161. tstring = row[0]
  1162. # Convert the unicode string into the datetime format
  1163. if self.is_time_absolute():
  1164. if tstring.find(":") > 0:
  1165. time_format = "%Y-%m-%d %H:%M:%S"
  1166. else:
  1167. time_format = "%Y-%m-%d"
  1168. max_start_time = datetime.strptime(
  1169. tstring, time_format)
  1170. else:
  1171. max_start_time = row[0]
  1172. else:
  1173. max_start_time = row[0]
  1174. if end_time < max_start_time:
  1175. use_start_time = True
  1176. # Set the maximum start time as end time
  1177. if use_start_time:
  1178. if self.is_time_absolute():
  1179. sql = """UPDATE STDS_absolute_time SET end_time =
  1180. (SELECT max(start_time) FROM GRASS_MAP_absolute_time WHERE
  1181. GRASS_MAP_absolute_time.id IN
  1182. (SELECT id FROM SPACETIME_NAME_GRASS_MAP_register)
  1183. ) WHERE id = 'SPACETIME_ID';"""
  1184. sql = sql.replace("GRASS_MAP", self.get_new_map_instance(
  1185. None).get_type())
  1186. sql = sql.replace("SPACETIME_NAME",
  1187. stds_name + "_" + stds_mapset)
  1188. sql = sql.replace("SPACETIME_ID", self.base.get_id())
  1189. sql = sql.replace("STDS", self.get_type())
  1190. elif self.is_time_relative():
  1191. sql = """UPDATE STDS_relative_time SET end_time =
  1192. (SELECT max(start_time) FROM GRASS_MAP_relative_time WHERE
  1193. GRASS_MAP_relative_time.id IN
  1194. (SELECT id FROM SPACETIME_NAME_GRASS_MAP_register)
  1195. ) WHERE id = 'SPACETIME_ID';"""
  1196. sql = sql.replace("GRASS_MAP", self.get_new_map_instance(
  1197. None).get_type())
  1198. sql = sql.replace("SPACETIME_NAME",
  1199. stds_name + "_" + stds_mapset)
  1200. sql = sql.replace("SPACETIME_ID", self.base.get_id())
  1201. sql = sql.replace("STDS", self.get_type())
  1202. dbif.execute_transaction(sql)
  1203. # Count the temporal map types
  1204. maps = self.get_registered_maps_as_objects(dbif=dbif)
  1205. tlist = self.count_temporal_types(maps)
  1206. if tlist["interval"] > 0 and tlist["point"] == 0 and \
  1207. tlist["invalid"] == 0:
  1208. map_time = "interval"
  1209. elif tlist["interval"] == 0 and tlist["point"] > 0 and \
  1210. tlist["invalid"] == 0:
  1211. map_time = "point"
  1212. elif tlist["interval"] > 0 and tlist["point"] > 0 and \
  1213. tlist["invalid"] == 0:
  1214. map_time = "mixed"
  1215. else:
  1216. map_time = "invalid"
  1217. # Compute the granularity
  1218. if map_time != "invalid":
  1219. # Smallest supported temporal resolution
  1220. if self.is_time_absolute():
  1221. gran = compute_absolute_time_granularity(maps)
  1222. elif self.is_time_relative():
  1223. gran = compute_relative_time_granularity(maps)
  1224. else:
  1225. gran = None
  1226. # Set the map time type and update the time objects
  1227. if self.is_time_absolute():
  1228. self.absolute_time.select(dbif)
  1229. self.metadata.select(dbif)
  1230. if self.metadata.get_number_of_maps() > 0:
  1231. self.absolute_time.set_map_time(map_time)
  1232. self.absolute_time.set_granularity(gran)
  1233. else:
  1234. self.absolute_time.set_map_time(None)
  1235. self.absolute_time.set_granularity(None)
  1236. self.absolute_time.update_all(dbif)
  1237. else:
  1238. self.relative_time.select(dbif)
  1239. self.metadata.select(dbif)
  1240. if self.metadata.get_number_of_maps() > 0:
  1241. self.relative_time.set_map_time(map_time)
  1242. self.relative_time.set_granularity(gran)
  1243. else:
  1244. self.relative_time.set_map_time(None)
  1245. self.relative_time.set_granularity(None)
  1246. self.relative_time.update_all(dbif)
  1247. if connect:
  1248. dbif.close()
  1249. ###############################################################################
  1250. def create_temporal_relation_sql_where_statement(
  1251. start, end, use_start=True, use_during=False,
  1252. use_overlap=False, use_contain=False, use_equal=False,
  1253. use_follows=False, use_precedes=False):
  1254. """!Create a SQL WHERE statement for temporal relation selection of maps in space time datasets
  1255. @param start: The start time
  1256. @param end: The end time
  1257. @param use_start: Select maps of which the start time is located in the selection granule
  1258. @verbatim
  1259. map : s
  1260. granule: s-----------------e
  1261. map : s--------------------e
  1262. granule: s-----------------e
  1263. map : s--------e
  1264. granule: s-----------------e
  1265. @endverbatim
  1266. @param use_during: during: Select maps which are temporal during the selection granule
  1267. @verbatim
  1268. map : s-----------e
  1269. granule: s-----------------e
  1270. @endverbatim
  1271. @param use_overlap: Select maps which temporal overlap the selection granule
  1272. @verbatim
  1273. map : s-----------e
  1274. granule: s-----------------e
  1275. map : s-----------e
  1276. granule: s----------e
  1277. @endverbatim
  1278. @param use_contain: Select maps which temporally contain the selection granule
  1279. @verbatim
  1280. map : s-----------------e
  1281. granule: s-----------e
  1282. @endverbatim
  1283. @param use_equal: Select maps which temporally equal to the selection granule
  1284. @verbatim
  1285. map : s-----------e
  1286. granule: s-----------e
  1287. @endverbatim
  1288. @param use_follows: Select maps which temporally follow the selection granule
  1289. @verbatim
  1290. map : s-----------e
  1291. granule: s-----------e
  1292. @endverbatim
  1293. @param use_precedes: Select maps which temporally precedes the selection granule
  1294. @verbatim
  1295. map : s-----------e
  1296. granule: s-----------e
  1297. @endverbatim
  1298. Usage:
  1299. @code
  1300. >>> # Relative time
  1301. >>> start = 1
  1302. >>> end = 2
  1303. >>> create_temporal_relation_sql_where_statement(start, end,
  1304. ... use_start=False)
  1305. >>> create_temporal_relation_sql_where_statement(start, end)
  1306. '((start_time >= 1 and start_time < 2) )'
  1307. >>> create_temporal_relation_sql_where_statement(start, end,
  1308. ... use_start=True)
  1309. '((start_time >= 1 and start_time < 2) )'
  1310. >>> create_temporal_relation_sql_where_statement(start, end,
  1311. ... use_start=False, use_during=True)
  1312. '(((start_time > 1 and end_time < 2) OR (start_time >= 1 and end_time < 2) OR (start_time > 1 and end_time <= 2)))'
  1313. >>> create_temporal_relation_sql_where_statement(start, end,
  1314. ... use_start=False, use_overlap=True)
  1315. '(((start_time < 1 and end_time > 1 and end_time < 2) OR (start_time < 2 and start_time > 1 and end_time > 2)))'
  1316. >>> create_temporal_relation_sql_where_statement(start, end,
  1317. ... use_start=False, use_contain=True)
  1318. '(((start_time < 1 and end_time > 2) OR (start_time <= 1 and end_time > 2) OR (start_time < 1 and end_time >= 2)))'
  1319. >>> create_temporal_relation_sql_where_statement(start, end,
  1320. ... use_start=False, use_equal=True)
  1321. '((start_time = 1 and end_time = 2))'
  1322. >>> create_temporal_relation_sql_where_statement(start, end,
  1323. ... use_start=False, use_follows=True)
  1324. '((start_time = 2))'
  1325. >>> create_temporal_relation_sql_where_statement(start, end,
  1326. ... use_start=False, use_precedes=True)
  1327. '((end_time = 1))'
  1328. >>> create_temporal_relation_sql_where_statement(start, end,
  1329. ... use_start=True, use_during=True, use_overlap=True, use_contain=True,
  1330. ... use_equal=True, use_follows=True, use_precedes=True)
  1331. '((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))'
  1332. >>> # Absolute time
  1333. >>> start = datetime(2001, 1, 1, 12, 30)
  1334. >>> end = datetime(2001, 3, 31, 14, 30)
  1335. >>> create_temporal_relation_sql_where_statement(start, end,
  1336. ... use_start=False)
  1337. >>> create_temporal_relation_sql_where_statement(start, end)
  1338. "((start_time >= '2001-01-01 12:30:00' and start_time < '2001-03-31 14:30:00') )"
  1339. >>> create_temporal_relation_sql_where_statement(start, end,
  1340. ... use_start=True)
  1341. "((start_time >= '2001-01-01 12:30:00' and start_time < '2001-03-31 14:30:00') )"
  1342. >>> create_temporal_relation_sql_where_statement(start, end,
  1343. ... use_start=False, use_during=True)
  1344. "(((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')))"
  1345. >>> create_temporal_relation_sql_where_statement(start, end,
  1346. ... use_start=False, use_overlap=True)
  1347. "(((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')))"
  1348. >>> create_temporal_relation_sql_where_statement(start, end,
  1349. ... use_start=False, use_contain=True)
  1350. "(((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')))"
  1351. >>> create_temporal_relation_sql_where_statement(start, end,
  1352. ... use_start=False, use_equal=True)
  1353. "((start_time = '2001-01-01 12:30:00' and end_time = '2001-03-31 14:30:00'))"
  1354. >>> create_temporal_relation_sql_where_statement(start, end,
  1355. ... use_start=False, use_follows=True)
  1356. "((start_time = '2001-03-31 14:30:00'))"
  1357. >>> create_temporal_relation_sql_where_statement(start, end,
  1358. ... use_start=False, use_precedes=True)
  1359. "((end_time = '2001-01-01 12:30:00'))"
  1360. >>> create_temporal_relation_sql_where_statement(start, end,
  1361. ... use_start=True, use_during=True, use_overlap=True, use_contain=True,
  1362. ... use_equal=True, use_follows=True, use_precedes=True)
  1363. "((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'))"
  1364. @endcode
  1365. """
  1366. where = "("
  1367. if use_start:
  1368. if isinstance(start, datetime):
  1369. where += "(start_time >= '%s' and start_time < '%s') " % (start, end)
  1370. else:
  1371. where += "(start_time >= %i and start_time < %i) " % (start, end)
  1372. if use_during:
  1373. if use_start:
  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_overlap:
  1384. if use_start or use_during:
  1385. where += " OR "
  1386. if isinstance(start, datetime):
  1387. where += "((start_time < '%s' and end_time > '%s' and end_time < '%s') OR " % (start, start, end)
  1388. where += "(start_time < '%s' and start_time > '%s' and end_time > '%s'))" % (end, start, end)
  1389. else:
  1390. where += "((start_time < %i and end_time > %i and end_time < %i) OR " % (start, start, end)
  1391. where += "(start_time < %i and start_time > %i and end_time > %i))" % (end, start, end)
  1392. if use_contain:
  1393. if use_start or use_during or use_overlap:
  1394. where += " OR "
  1395. if isinstance(start, datetime):
  1396. where += "((start_time < '%s' and end_time > '%s') OR " % (start, end)
  1397. where += "(start_time <= '%s' and end_time > '%s') OR " % (start, end)
  1398. where += "(start_time < '%s' and end_time >= '%s'))" % (start, end)
  1399. else:
  1400. where += "((start_time < %i and end_time > %i) OR " % (start, end)
  1401. where += "(start_time <= %i and end_time > %i) OR " % (start, end)
  1402. where += "(start_time < %i and end_time >= %i))" % (start, end)
  1403. if use_equal:
  1404. if use_start or use_during or use_overlap or use_contain:
  1405. where += " OR "
  1406. if isinstance(start, datetime):
  1407. where += "(start_time = '%s' and end_time = '%s')" % (start, end)
  1408. else:
  1409. where += "(start_time = %i and end_time = %i)" % (start, end)
  1410. if use_follows:
  1411. if use_start or use_during or use_overlap or use_contain or use_equal:
  1412. where += " OR "
  1413. if isinstance(start, datetime):
  1414. where += "(start_time = '%s')" % (end)
  1415. else:
  1416. where += "(start_time = %i)" % (end)
  1417. if use_precedes:
  1418. if use_start or use_during or use_overlap or use_contain or use_equal \
  1419. or use_follows:
  1420. where += " OR "
  1421. if isinstance(start, datetime):
  1422. where += "(end_time = '%s')" % (start)
  1423. else:
  1424. where += "(end_time = %i)" % (start)
  1425. where += ")"
  1426. # Catch empty where statement
  1427. if where == "()":
  1428. where = None
  1429. return where
  1430. ###############################################################################
  1431. if __name__ == "__main__":
  1432. import doctest
  1433. doctest.testmod()