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