abstract_space_time_dataset.py 95 KB

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