abstract_space_time_dataset.py 73 KB

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