abstract_space_time_dataset.py 83 KB

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