abstract_space_time_dataset.py 83 KB

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