abstract_space_time_dataset.py 101 KB

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