abstract_space_time_dataset.py 99 KB

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