abstract_space_time_dataset.py 85 KB

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