abstract_space_time_dataset.py 83 KB

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