abstract_space_time_dataset.py 95 KB

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