abstract_space_time_dataset.py 102 KB

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