abstract_space_time_dataset.py 73 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866
  1. # -*- coding: utf-8 -*-
  2. """!@package grass.temporal
  3. @brief GRASS Python scripting module (temporal GIS functions)
  4. Temporal GIS related functions to be used in temporal GIS Python library package.
  5. (C) 2011-2012 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. @author Soeren Gebbert
  10. """
  11. import sys
  12. from abstract_dataset import *
  13. from temporal_granularity import *
  14. from spatio_temporal_relationships import *
  15. ###############################################################################
  16. class AbstractSpaceTimeDataset(AbstractDataset):
  17. """!Abstract space time dataset class
  18. This class represents a space time dataset. Convenient functions
  19. to select, update, insert or delete objects of this type in the SQL
  20. temporal database exists as well as functions to register or unregister
  21. raster maps.
  22. Parts of the temporal logic are implemented in the SQL temporal database,
  23. like the computation of the temporal and spatial extent as well as the
  24. collecting of metadata.
  25. """
  26. def __init__(self, ident):
  27. AbstractDataset.__init__(self)
  28. self.reset(ident)
  29. self.map_counter = 0
  30. def get_new_map_instance(self, ident=None):
  31. """!Return a new instance of a map which is associated
  32. with the type of this object
  33. @param ident The unique identifier of the new object
  34. """
  35. raise ImplementationError(
  36. "This method must be implemented in the subclasses")
  37. def create_map_register_name(self):
  38. """!Create the name of the map register table of this space time dataset
  39. The name, mapset and the map type are used to create the table name.
  40. ATTENTION: It must be assured that the base object has selected its
  41. content from the database.
  42. @return The name of the map register table
  43. """
  44. return self.base.get_name() + "_" + \
  45. self.base.get_mapset() + "_" + \
  46. self.get_new_map_instance(None).get_type() + "_register"
  47. def get_map_register(self):
  48. """!Return the name of the map register table
  49. @return The map register table name
  50. """
  51. raise ImplementationError(
  52. "This method must be implemented in the subclasses")
  53. def set_map_register(self, name):
  54. """!Set the name of the map register table
  55. This table stores all map names which are registered
  56. in this space time dataset.
  57. This method only modifies this object and does not commit
  58. the modifications to the temporal database.
  59. @param name The name of the register table
  60. """
  61. raise ImplementationError(
  62. "This method must be implemented in the subclasses")
  63. def print_self(self):
  64. """!Print the content of the internal structure to stdout"""
  65. self.base.print_self()
  66. self.temporal_extent.print_self()
  67. self.spatial_extent.print_self()
  68. self.metadata.print_self()
  69. def print_info(self):
  70. """!Print information about this class in human readable style"""
  71. if self.get_type() == "strds":
  72. # 1 2 3 4 5 6 7
  73. # 0123456789012345678901234567890123456789012345678901234567890123456789012345678
  74. print " +-------------------- Space Time Raster Dataset -----------------------------+"
  75. if self.get_type() == "str3ds":
  76. # 1 2 3 4 5 6 7
  77. # 0123456789012345678901234567890123456789012345678901234567890123456789012345678
  78. print " +-------------------- Space Time 3D Raster Dataset --------------------------+"
  79. if self.get_type() == "stvds":
  80. # 1 2 3 4 5 6 7
  81. # 0123456789012345678901234567890123456789012345678901234567890123456789012345678
  82. print " +-------------------- Space Time Vector Dataset -----------------------------+"
  83. print " | |"
  84. self.base.print_info()
  85. self.temporal_extent.print_info()
  86. self.spatial_extent.print_info()
  87. self.metadata.print_info()
  88. print " +----------------------------------------------------------------------------+"
  89. def print_shell_info(self):
  90. """!Print information about this class in shell style"""
  91. self.base.print_shell_info()
  92. self.temporal_extent.print_shell_info()
  93. self.spatial_extent.print_shell_info()
  94. self.metadata.print_shell_info()
  95. def set_initial_values(self, temporal_type, semantic_type,
  96. title=None, description=None):
  97. """!Set the initial values of the space time dataset
  98. In addition the command creation string is generated
  99. an inerted into the metadata object.
  100. This method only modifies this object and does not commit
  101. the modifications to the temporal database.
  102. The insert() function must be called to commit
  103. this content into the temporal database.
  104. @param temporal_type The temporal type of this space
  105. time dataset (absolute or relative)
  106. @param semantic_type The semantic type of this dataset
  107. @param title The title
  108. @param description The description of this dataset
  109. """
  110. if temporal_type == "absolute":
  111. self.set_time_to_absolute()
  112. elif temporal_type == "relative":
  113. self.set_time_to_relative()
  114. else:
  115. core.fatal(_("Unknown temporal type \"%s\"") % (temporal_type))
  116. self.base.set_semantic_type(semantic_type)
  117. self.metadata.set_title(title)
  118. self.metadata.set_description(description)
  119. self.metadata.set_command(self.create_command_string())
  120. def update_command_string(self, dbif=None):
  121. """!Append the current command string to any existing command string
  122. in the metadata class and calls metadata update
  123. @param dbif The database interface to be used
  124. """
  125. self.metadata.select(dbif=dbif)
  126. command = self.metadata.get_command()
  127. if command is None:
  128. command = ""
  129. command += self.create_command_string()
  130. self.metadata.set_command(command)
  131. self.metadata.update(dbif=dbif)
  132. def create_command_string(self):
  133. """!Create the command string that was used to create this
  134. space time dataset.
  135. The command string should be set with self.metadata.set_command()
  136. @return The command string
  137. """
  138. # The grass module
  139. command = "- %s -\n"%(str(datetime.today().strftime("%Y-%m-%d %H:%M:%S")))
  140. command += os.path.basename(sys.argv[0])
  141. # We will wrap the command line to fit into 80 character
  142. length = len(command)
  143. for token in sys.argv[1:]:
  144. # We need to remove specific characters
  145. token = token.replace("\'", " ")
  146. token = token.replace("\"", " ")
  147. # Check for sub strings
  148. if token.find("=") > 0:
  149. first = token.split("=")[0]
  150. second = ""
  151. for t in token.split("=")[1:]:
  152. second += t
  153. token = "%s=\"%s\""%(first, second)
  154. if length + len(token) >= 76:
  155. command += "\n %s"%(token)
  156. length = len(token) + 4
  157. else:
  158. command += " %s"%(token)
  159. length += len(token) + 1
  160. command += "\n"
  161. return command
  162. def get_semantic_type(self):
  163. """!Return the semantic type of this dataset
  164. @return The semantic type
  165. """
  166. return self.base.get_semantic_type()
  167. def get_initial_values(self):
  168. """!Return the initial values: temporal_type,
  169. semantic_type, title, description"""
  170. temporal_type = self.get_temporal_type()
  171. semantic_type = self.base.get_semantic_type()
  172. title = self.metadata.get_title()
  173. description = self.metadata.get_description()
  174. return temporal_type, semantic_type, title, description
  175. def get_granularity(self):
  176. """!Return the granularity of the space time dataset
  177. Granularity can be of absolute time or relative time.
  178. In case of absolute time a string containing an integer
  179. value and the time unit (years, months, days, hours, minuts, seconds).
  180. In case of relative time an integer value is expected.
  181. @return The granularity
  182. """
  183. return self.temporal_extent.get_granularity()
  184. def set_granularity(self, granularity):
  185. """!Set the granularity
  186. The granularity is usually computed by the space time dataset at runtime.
  187. Granularity can be of absolute time or relative time.
  188. In case of absolute time a string containing an integer
  189. value and the time unit (years, months, days, hours, minuts, seconds).
  190. In case of relative time an integer value is expected.
  191. This method only modifies this object and does not commit
  192. the modifications to the temporal database.
  193. @param granularity The granularity of the dataset
  194. """
  195. temporal_type = self.get_temporal_type()
  196. check = check_granularity_string(granularity, temporal_type)
  197. if not check:
  198. core.fatal(_("Wrong granularity: \"%s\"") % str(granularity))
  199. if temporal_type == "absolute":
  200. self.set_time_to_absolute()
  201. elif temporal_type == "relative":
  202. self.set_time_to_relative()
  203. else:
  204. core.fatal(_("Unknown temporal type \"%s\"") % (temporal_type))
  205. self.temporal_extent.set_granularity(granularity)
  206. def set_relative_time_unit(self, unit):
  207. """!Set the relative time unit which may be of type:
  208. years, months, days, hours, minutes or seconds
  209. All maps registered in a (relative time)
  210. space time dataset must have the same unit
  211. This method only modifies this object and does not commit
  212. the modifications to the temporal database.
  213. @param unit The relative time unit
  214. """
  215. temporal_type = self.get_temporal_type()
  216. if temporal_type == "relative":
  217. if not self.check_relative_time_unit(unit):
  218. core.fatal(_("Unsupported temporal unit: %s") % (unit))
  219. self.relative_time.set_unit(unit)
  220. def get_map_time(self):
  221. """!Return the type of the map time, interval, point, mixed or invalid"""
  222. return self.temporal_extent.get_map_time()
  223. def count_temporal_types(self, maps=None, dbif=None):
  224. """!Return the temporal type of the registered maps as dictionary
  225. The map list must be ordered by start time
  226. The temporal type can be:
  227. - point -> only the start time is present
  228. - interval -> start and end time
  229. - invalid -> No valid time point or interval found
  230. @param maps A sorted (start_time) list of AbstractDataset objects
  231. @param dbif The database interface to be used
  232. """
  233. if maps is None:
  234. maps = get_registered_maps_as_objects(
  235. where=None, order="start_time", dbif=dbif)
  236. time_invalid = 0
  237. time_point = 0
  238. time_interval = 0
  239. tcount = {}
  240. for i in range(len(maps)):
  241. # Check for point and interval data
  242. if maps[i].is_time_absolute():
  243. start, end, tz = maps[i].get_absolute_time()
  244. if maps[i].is_time_relative():
  245. start, end, unit = maps[i].get_relative_time()
  246. if start is not None and end is not None:
  247. time_interval += 1
  248. elif start is not None and end is None:
  249. time_point += 1
  250. else:
  251. time_invalid += 1
  252. tcount["point"] = time_point
  253. tcount["interval"] = time_interval
  254. tcount["invalid"] = time_invalid
  255. return tcount
  256. def count_gaps(self, maps=None, dbif=None):
  257. """!Count the number of gaps between temporal neighbors
  258. @param maps A sorted (start_time) list of AbstractDataset objects
  259. @param dbif The database interface to be used
  260. @return The numbers of gaps between temporal neighbors
  261. """
  262. if maps is None:
  263. maps = self.get_registered_maps_as_objects(
  264. where=None, order="start_time", dbif=dbif)
  265. gaps = 0
  266. # Check for gaps
  267. for i in range(len(maps)):
  268. if i < len(maps) - 1:
  269. relation = maps[i + 1].temporal_relation(maps[i])
  270. if relation == "after":
  271. gaps += 1
  272. return gaps
  273. def print_spatio_temporal_relationships(self, maps=None, spatial=None, dbif=None):
  274. """!Print the spatio-temporal relationships for each map of the space time dataset
  275. or for each map of the optional list of maps
  276. @param maps a ordered by start_time list of map objects, if None the registred
  277. maps of the space time dataset are used
  278. @param spatial This indicates if the spatial topology is created as well:
  279. spatial can be None (no spatial topology), "2D" using west, east,
  280. south, north or "3D" using west, east, south, north, bottom, top
  281. @param dbif The database interface to be used
  282. """
  283. if maps is None:
  284. maps = self.get_registered_maps_as_objects(
  285. where=None, order="start_time", dbif=dbif)
  286. print_spatio_temporal_topology_relationships(maps1=maps, maps2=maps,
  287. spatial=spatial, dbif=dbif)
  288. def count_temporal_relations(self, maps=None, dbif=None):
  289. """!Count the temporal relations between the registered maps.
  290. The map list must be ordered by start time.
  291. Temporal relations are counted by analysing the sparse
  292. upper right side temporal relationships matrix.
  293. @param maps A sorted (start_time) list of AbstractDataset objects
  294. @param dbif The database interface to be used
  295. @return A dictionary with counted temporal relationships
  296. """
  297. if maps is None:
  298. maps = self.get_registered_maps_as_objects(
  299. where=None, order="start_time", dbif=dbif)
  300. return count_temporal_topology_relationships(maps)
  301. def check_temporal_topology(self, maps=None, dbif=None):
  302. """!Check the temporal topology of all maps of the current space time dataset or
  303. of an optional list of maps
  304. Correct topology means, that time intervals are not overlap or
  305. that intervals does not contain other intervals.
  306. Equal time intervals are not allowed.
  307. The optional map list must be ordered by start time
  308. Allowed and not allowed temporal relationships for correct topology:
  309. @verbatim
  310. - after -> allowed
  311. - precedes -> allowed
  312. - follows -> allowed
  313. - precedes -> allowed
  314. - equal -> not allowed
  315. - during -> not allowed
  316. - contains -> not allowed
  317. - overlaps -> not allowed
  318. - overlapped -> not allowed
  319. - starts -> not allowed
  320. - finishes -> not allowed
  321. - started -> not allowed
  322. - finished -> not allowed
  323. @endverbatim
  324. @param maps An optional list of AbstractDataset objects, in case of None all maps of the space time dataset are checked
  325. @param dbif The database interface to be used
  326. @return True if topology is correct
  327. """
  328. if maps is None:
  329. maps = self.get_registered_maps_as_objects(
  330. where=None, order="start_time", dbif=dbif)
  331. relations = count_temporal_topology_relationships(maps)
  332. if relations == None:
  333. return False
  334. map_time = self.get_map_time()
  335. if map_time == "interval" or map_time == "mixed":
  336. if "equal" in relations and relations["equal"] > 0:
  337. return False
  338. if "during" in relations and relations["during"] > 0:
  339. return False
  340. if "contains" in relations and relations["contains"] > 0:
  341. return False
  342. if "overlaps" in relations and relations["overlaps"] > 0:
  343. return False
  344. if "overlapped" in relations and relations["overlapped"] > 0:
  345. return False
  346. if "starts" in relations and relations["starts"] > 0:
  347. return False
  348. if "finishes" in relations and relations["finishes"] > 0:
  349. return False
  350. if "started" in relations and relations["started"] > 0:
  351. return False
  352. if "finished" in relations and relations["finished"] > 0:
  353. return False
  354. elif map_time == "point":
  355. if "equal" in relations and relations["equal"] > 0:
  356. return False
  357. else:
  358. return False
  359. return True
  360. def sample_by_dataset(self, stds, method=None, spatial=False, dbif=None):
  361. """!Sample this space time dataset with the temporal topology
  362. of a second space time dataset
  363. The sample dataset must have "interval" as temporal map type,
  364. so all sample maps have valid interval time.
  365. In case spatial is True, the spatial overlap between
  366. temporal related maps is performed. Only
  367. temporal related and spatial overlapping maps are returned.
  368. Return all registered maps as ordered (by start_time) object list with
  369. "gap" map objects (id==None). Each list entry is a list of map objects
  370. which are potentially located in temporal relation to the actual
  371. granule of the second space time dataset.
  372. Each entry in the object list is a dict. The actual sampler
  373. map and its temporal extent (the actual granule) and
  374. the list of samples are stored:
  375. @code
  376. list = self.sample_by_dataset(stds=sampler, method=[
  377. "during","overlap","contain","equal"])
  378. for entry in list:
  379. granule = entry["granule"]
  380. maplist = entry["samples"]
  381. for map in maplist:
  382. map.select()
  383. map.print_info()
  384. @endcode
  385. A valid temporal topology (no overlapping or inclusion allowed)
  386. is needed to get correct results in case of gaps in the sample dataset.
  387. Gaps between maps are identified as unregistered maps with id==None.
  388. The objects are initialized with their id's' and the spatio-temporal extent
  389. (temporal type, start time, end time, west, east, south, north, bottom and top).
  390. In case more map information are needed, use the select()
  391. method for each listed object.
  392. @param stds The space time dataset to be used for temporal sampling
  393. @param method This option specifies what sample method should be used.
  394. In case the registered maps are of temporal point type,
  395. only the start time is used for sampling. In case of mixed
  396. of interval data the user can chose between:
  397. - start: Select maps of which the start time is
  398. located in the selection granule
  399. @verbatim
  400. map : s
  401. granule: s-----------------e
  402. map : s--------------------e
  403. granule: s-----------------e
  404. map : s--------e
  405. granule: s-----------------e
  406. @endverbatim
  407. - during: Select maps which are temporal
  408. during the selection granule
  409. @verbatim
  410. map : s-----------e
  411. granule: s-----------------e
  412. @endverbatim
  413. - overlap: Select maps which temporal overlap
  414. the selection granule
  415. @verbatim
  416. map : s-----------e
  417. granule: s-----------------e
  418. map : s-----------e
  419. granule: s----------e
  420. @endverbatim
  421. - contain: Select maps which temporally contain
  422. the selection granule
  423. @verbatim
  424. map : s-----------------e
  425. granule: s-----------e
  426. @endverbatim
  427. - equal: Select maps which temporally equal
  428. to the selection granule
  429. @verbatim
  430. map : s-----------e
  431. granule: s-----------e
  432. @endverbatim
  433. - follows: Select maps which temporally follow
  434. the selection granule
  435. @verbatim
  436. map : s-----------e
  437. granule: s-----------e
  438. @endverbatim
  439. - precedes: Select maps which temporally precedes
  440. the selection granule
  441. @verbatim
  442. map : s-----------e
  443. granule: s-----------e
  444. @endverbatim
  445. All these methods can be combined. Method must be of
  446. type tuple including the identification strings.
  447. @param spatial If set True additional the spatial overlapping
  448. is used for selection -> spatio-temporal relation.
  449. The returned map objects will have temporal and
  450. spatial extents
  451. @param dbif The database interface to be used
  452. @return A list of lists of map objects or None in case nothing was found None
  453. """
  454. use_start = False
  455. use_during = False
  456. use_overlap = False
  457. use_contain = False
  458. use_equal = False
  459. use_follows = False
  460. use_precedes = False
  461. # Initialize the methods
  462. if method is not None:
  463. for name in method:
  464. if name == "start":
  465. use_start = True
  466. if name == "during":
  467. use_during = True
  468. if name == "overlap":
  469. use_overlap = True
  470. if name == "contain":
  471. use_contain = True
  472. if name == "equal":
  473. use_equal = True
  474. if name == "follows":
  475. use_follows = True
  476. if name == "precedes":
  477. use_precedes = True
  478. else:
  479. use_during = True
  480. use_overlap = True
  481. use_contain = True
  482. use_equal = True
  483. if self.get_temporal_type() != stds.get_temporal_type():
  484. core.error(_("The space time datasets must be of "
  485. "the same temporal type"))
  486. return None
  487. if stds.get_map_time() != "interval":
  488. core.error(_("The temporal map type of the sample "
  489. "dataset must be interval"))
  490. return None
  491. # In case points of time are available, disable the interval specific methods
  492. if self.get_map_time() == "point":
  493. use_start = True
  494. use_during = False
  495. use_overlap = False
  496. use_contain = False
  497. use_equal = False
  498. use_follows = False
  499. use_precedes = False
  500. dbif, connected = init_dbif(dbif)
  501. obj_list = []
  502. sample_maps = stds.get_registered_maps_as_objects_with_gaps(
  503. where=None, dbif=dbif)
  504. for granule in sample_maps:
  505. # Read the spatial extent
  506. if spatial:
  507. granule.spatial_extent.select(dbif)
  508. start, end = granule.get_temporal_extent_as_tuple()
  509. where = create_temporal_relation_sql_where_statement(
  510. start, end, use_start,
  511. use_during, use_overlap, use_contain, use_equal, use_follows, use_precedes)
  512. maps = self.get_registered_maps_as_objects(
  513. where, "start_time", dbif)
  514. result = {}
  515. result["granule"] = granule
  516. num_samples = 0
  517. maplist = []
  518. if maps is not None:
  519. for map in maps:
  520. # Read the spatial extent
  521. if spatial:
  522. map.spatial_extent.select(dbif)
  523. # Ignore spatial disjoint maps
  524. if not granule.spatial_overlapping(map):
  525. continue
  526. num_samples += 1
  527. maplist.append(copy.copy(map))
  528. # Fill with empty map in case no spatio-temporal relations found
  529. if maps is None or num_samples == 0:
  530. map = self.get_new_map_instance(None)
  531. if self.is_time_absolute():
  532. map.set_absolute_time(start, end)
  533. elif self.is_time_relative():
  534. map.set_relative_time(start, end,
  535. self.get_relative_time_unit())
  536. maplist.append(copy.copy(map))
  537. result["samples"] = maplist
  538. obj_list.append(copy.copy(result))
  539. if connected:
  540. dbif.close()
  541. return obj_list
  542. def get_registered_maps_as_objects_by_granularity(self, gran=None, dbif=None):
  543. """!Return all registered maps as ordered (by start_time) object list with
  544. "gap" map objects (id==None) for spatio-temporal topological operations
  545. that require the temporal extent only.
  546. Each list entry is a list of map objects
  547. which are potentially located in the actual granule.
  548. The granularity of the space time dataset is used as increment in case
  549. the granule is not user defined.
  550. A valid temporal topology (no overlapping or inclusion allowed)
  551. is needed to get correct results.
  552. Space time datasets with interval time, time instances and mixed time
  553. are supported.
  554. Gaps between maps are identified as unregistered maps with id==None.
  555. The objects are initialized with their id's' and the spatio-temporal extent
  556. (temporal type, start time, end time, west, east, south, north, bottom and top).
  557. In case more map information are needed, use the select()
  558. method for each listed object.
  559. @param gran The granularity string to be used, if None the granularity of
  560. the space time dataset is used.
  561. Absolute time has
  562. the format "number unit", relative time has the format "number".
  563. The unit in case of absolute time can be one of "second, seconds,
  564. minute, minutes, hour, hours, day, days, week, weeks, month, months,
  565. year, years". The unit of the relative time granule is always the
  566. space time dataset unit and can not be changed.
  567. @param dbif The database interface to be used
  568. @return ordered object list, or None in case nothing found
  569. """
  570. dbif, connected = init_dbif(dbif)
  571. obj_list = []
  572. if gran is None:
  573. gran = self.get_granularity()
  574. check = check_granularity_string(gran, self.get_temporal_type())
  575. if not check:
  576. core.fatal(_("Wrong granularity: \"%s\"") % str(gran))
  577. start, end = self.get_temporal_extent_as_tuple()
  578. if start is None or end is None:
  579. return None
  580. # Time instances and mixed time
  581. is_irregular = False
  582. # We need to adjust the end time in case the the dataset has no
  583. # interval time, so we can catch time instances at the end
  584. if self.get_map_time() != "interval":
  585. is_irregular = True
  586. if self.is_time_absolute():
  587. end = increment_datetime_by_string(end, gran)
  588. else:
  589. end = end + gran
  590. while start < end:
  591. if self.is_time_absolute():
  592. next = increment_datetime_by_string(start, gran)
  593. else:
  594. next = start + gran
  595. # First we search for intervals that are are equal the granule or contain it
  596. where = create_temporal_relation_sql_where_statement(
  597. start=start, end=next, use_start=False, use_during=False,
  598. use_overlap=False, use_contain=True, use_equal=True,
  599. use_follows=False, use_precedes=False)
  600. rows = self.get_registered_maps("id", where, "start_time", dbif)
  601. found_gap = False
  602. if rows is not None and len(rows) != 0:
  603. if len(rows) > 1:
  604. core.warning(_("More than one map found in a granule. "
  605. "Temporal granularity seems to be invalid or"
  606. " the chosen granularity is not a greatest "
  607. "common divider of all intervals and gaps "
  608. "in the dataset."))
  609. maplist = []
  610. for row in rows:
  611. map = self.get_new_map_instance(row["id"])
  612. if self.is_time_absolute():
  613. map.set_absolute_time(start, next)
  614. elif self.is_time_relative():
  615. map.set_relative_time(start, next,
  616. self.get_relative_time_unit())
  617. maplist.append(copy.copy(map))
  618. obj_list.append(copy.copy(maplist))
  619. else:
  620. # We may found a gap or a gap after a time instance
  621. found_gap = True
  622. # Searching for time instances and intervals that are during the
  623. # current granule or overlapping it
  624. where = create_temporal_relation_sql_where_statement(
  625. start=start, end=next, use_start=True, use_during=True,
  626. use_overlap=True, use_contain=False, use_equal=False,
  627. use_follows=False, use_precedes=False)
  628. rows = self.get_registered_maps("id,start_time,end_time", where, "start_time", dbif)
  629. if rows is not None and len(rows) != 0:
  630. # No gap if we found something in the granule with intervaltime
  631. if len(rows) > 1:
  632. core.warning(_("More than one map found in a granule. "
  633. "Temporal granularity seems to be invalid or"
  634. " the chosen granularity is not a greatest "
  635. "common divider of all time instances "
  636. "in the dataset."))
  637. maplist = []
  638. count = 0
  639. for row in rows:
  640. if count == 0:
  641. if row["end_time"] is not None or row["start_time"] != start:
  642. found_gap = False
  643. count += 1
  644. map = self.get_new_map_instance(row["id"])
  645. if self.is_time_absolute():
  646. if row["end_time"] is not None or row["start_time"] != start:
  647. map.set_absolute_time(start, next)
  648. else:
  649. map.set_absolute_time(start, None)
  650. elif self.is_time_relative():
  651. if row["end_time"] is not None or row["start_time"] != start:
  652. map.set_relative_time(start, next,
  653. self.get_relative_time_unit())
  654. else:
  655. map.set_relative_time(start, None,
  656. self.get_relative_time_unit())
  657. maplist.append(copy.copy(map))
  658. obj_list.append(copy.copy(maplist))
  659. # In case of irregular time (point, mixed) the last granule
  660. # does not belong to the dataset and will be ignored
  661. if is_irregular:
  662. if next == end:
  663. found_gap = False
  664. # Gap handling
  665. if found_gap:
  666. # Append a map object with None as id to indicate a gap
  667. map = self.get_new_map_instance(None)
  668. if self.is_time_absolute():
  669. map.set_absolute_time(start, next)
  670. elif self.is_time_relative():
  671. map.set_relative_time(start, next,
  672. self.get_relative_time_unit())
  673. maplist = []
  674. maplist.append(copy.copy(map))
  675. obj_list.append(copy.copy(maplist))
  676. start = next
  677. if connected:
  678. dbif.close()
  679. if obj_list:
  680. return obj_list
  681. return None
  682. def get_registered_maps_as_objects_with_gaps(self, where=None, dbif=None):
  683. """!Return all or a subset of the registered maps as
  684. ordered (by start_time) object list with
  685. "gap" map objects (id==None) for spatio-temporal topological operations
  686. that require the spatio-temporal extent only.
  687. Gaps between maps are identified as maps with id==None
  688. The objects are initialized with their id's' and the spatio-temporal extent
  689. (temporal type, start time, end time, west, east, south, north, bottom and top).
  690. In case more map information are needed, use the select()
  691. method for each listed object.
  692. @param where The SQL where statement to select a
  693. subset of the registered maps without "WHERE"
  694. @param dbif The database interface to be used
  695. @return ordered object list, in case nothing found None is returned
  696. """
  697. dbif, connected = init_dbif(dbif)
  698. obj_list = []
  699. maps = self.get_registered_maps_as_objects(where, "start_time", dbif)
  700. if maps is not None and len(maps) > 0:
  701. for i in range(len(maps)):
  702. obj_list.append(maps[i])
  703. # Detect and insert gaps
  704. if i < len(maps) - 1:
  705. relation = maps[i + 1].temporal_relation(maps[i])
  706. if relation == "after":
  707. start1, end1 = maps[i].get_temporal_extent_as_tuple()
  708. start2, end2 = maps[i + 1].get_temporal_extent_as_tuple()
  709. end = start2
  710. if end1 is not None:
  711. start = end1
  712. else:
  713. start = start1
  714. map = self.get_new_map_instance(None)
  715. if self.is_time_absolute():
  716. map.set_absolute_time(start, end)
  717. elif self.is_time_relative():
  718. map.set_relative_time(start, end,
  719. self.get_relative_time_unit())
  720. obj_list.append(copy.copy(map))
  721. if connected:
  722. dbif.close()
  723. return obj_list
  724. def get_registered_maps_as_objects_with_temporal_topology(self, where=None, order="start_time",
  725. dbif=None):
  726. """!Return all or a subset of the registered maps as ordered object list with
  727. spatio-temporal topological relationship informations.
  728. The objects are initialized with their id's' and the spatio-temporal extent
  729. (temporal type, start time, end time, west, east, south, north, bottom and top).
  730. In case more map information are needed, use the select()
  731. method for each listed object.
  732. @param where The SQL where statement to select a subset of
  733. the registered maps without "WHERE"
  734. @param order The SQL order statement to be used to order the
  735. objects in the list without "ORDER BY"
  736. @param dbif The database interface to be used
  737. @return The ordered map object list,
  738. In case nothing found None is returned
  739. """
  740. dbif, connected = init_dbif(dbif)
  741. obj_list = self.get_registered_maps_as_objects(where, order, dbif)
  742. tb = SpatioTemporalTopologyBuilder()
  743. tb.build(obj_list)
  744. if connected:
  745. dbif.close()
  746. return obj_list
  747. def get_registered_maps_as_objects(self, where=None, order="start_time",
  748. dbif=None):
  749. """!Return all or a subset of the registered maps as ordered object list for
  750. spatio-temporal topological operations that require the spatio-temporal extent only
  751. The objects are initialized with their id's' and the spatio-temporal extent
  752. (temporal type, start time, end time, west, east, south, north, bottom and top).
  753. In case more map information are needed, use the select()
  754. method for each listed object.
  755. @param where The SQL where statement to select a subset of
  756. the registered maps without "WHERE"
  757. @param order The SQL order statement to be used to order the
  758. objects in the list without "ORDER BY"
  759. @param dbif The database interface to be used
  760. @return The ordered map object list,
  761. In case nothing found None is returned
  762. """
  763. dbif, connected = init_dbif(dbif)
  764. obj_list = []
  765. # Older temporal databases have no bottom and top columns
  766. # in their views so we need a work around to set the full
  767. # spatial extent as well
  768. has_bt_columns = True
  769. try:
  770. rows = self.get_registered_maps(
  771. "id,start_time,end_time, west,east,south,north,bottom,top",
  772. where, order, dbif)
  773. except:
  774. try:
  775. dbif.rollback()
  776. rows = self.get_registered_maps(
  777. "id,start_time,end_time",
  778. where, order, dbif)
  779. has_bt_columns = False
  780. core.warning(_("Old temporal database format. The top and bottom column"\
  781. " is missing in the views, using a work around."))
  782. except:
  783. raise
  784. if rows is not None:
  785. for row in rows:
  786. map = self.get_new_map_instance(row["id"])
  787. if self.is_time_absolute():
  788. map.set_absolute_time(row["start_time"], row["end_time"])
  789. elif self.is_time_relative():
  790. map.set_relative_time(row["start_time"], row["end_time"],
  791. self.get_relative_time_unit())
  792. # The fast way
  793. if has_bt_columns:
  794. map.set_spatial_extent(west=row["west"], east=row["east"],
  795. south=row["south"],north=row["north"], bottom=row["bottom"],
  796. top=row["top"])
  797. # The slow work around
  798. else:
  799. map.spatial_extent.select(dbif)
  800. obj_list.append(copy.copy(map))
  801. if connected:
  802. dbif.close()
  803. return obj_list
  804. def get_registered_maps(self, columns=None, where=None, order=None, dbif=None):
  805. """!Return SQL rows of all registered maps.
  806. In case columns are not specified, each row includes all columns
  807. specified in the datatype specific view.
  808. @param columns Columns to be selected as SQL compliant string
  809. @param where The SQL where statement to select a subset
  810. of the registered maps without "WHERE"
  811. @param order The SQL order statement to be used to order the
  812. objects in the list without "ORDER BY"
  813. @param dbif The database interface to be used
  814. @return SQL rows of all registered maps,
  815. In case nothing found None is returned
  816. """
  817. dbif, connected = init_dbif(dbif)
  818. rows = None
  819. if self.get_map_register() is not None:
  820. # Use the correct temporal table
  821. if self.get_temporal_type() == "absolute":
  822. map_view = self.get_new_map_instance(
  823. None).get_type() + "_view_abs_time"
  824. else:
  825. map_view = self.get_new_map_instance(
  826. None).get_type() + "_view_rel_time"
  827. if columns is not None and columns != "":
  828. sql = "SELECT %s FROM %s WHERE %s.id IN (SELECT id FROM %s)" %\
  829. (columns, map_view, map_view, self.get_map_register())
  830. else:
  831. sql = "SELECT * FROM %s WHERE %s.id IN (SELECT id FROM %s)" % \
  832. (map_view, map_view, self.get_map_register())
  833. if where is not None and where != "":
  834. sql += " AND (%s)" % (where.split(";")[0])
  835. if order is not None and order != "":
  836. sql += " ORDER BY %s" % (order.split(";")[0])
  837. try:
  838. dbif.cursor.execute(sql)
  839. rows = dbif.cursor.fetchall()
  840. except:
  841. if connected:
  842. dbif.close()
  843. core.error(_("Unable to get map ids from register table <%s>")
  844. % (self.get_map_register()))
  845. raise
  846. if connected:
  847. dbif.close()
  848. return rows
  849. def shift(self, gran, dbif=None):
  850. """!Temporally shift each registered map with the provided granularity
  851. @param gran The granularity to be used for shifting
  852. @param dbif The database interface to be used
  853. @return True something to shift, False nothing to shift or wrong granularity
  854. """
  855. if not check_granularity_string(gran, self.get_temporal_type()):
  856. self.error(_("Wrong granularity format: %s"%(gran)))
  857. return False
  858. dbif, connected = init_dbif(dbif)
  859. maps = self.get_registered_maps_as_objects(dbif=dbif)
  860. if maps is None:
  861. return False
  862. date_list = []
  863. # We need to make a dry run to avoid a break
  864. # in the middle of the update process when the increment
  865. # results in wrong number of days in a month
  866. for map in maps:
  867. start, end = map.get_temporal_extent_as_tuple()
  868. if self.is_time_absolute():
  869. start = increment_datetime_by_string(start, gran)
  870. if end is not None:
  871. end = increment_datetime_by_string(end, gran)
  872. elif self.is_time_relative():
  873. start = start + int(gran)
  874. if end is not None:
  875. end = end + int(gran)
  876. date_list.append((start, end))
  877. self. _update_map_timestamps(maps, date_list, dbif)
  878. if connected:
  879. dbif.close()
  880. return True
  881. def snap(self, dbif=None):
  882. """!For each registered map snap the end time to the start time of its
  883. temporal nearest neighbor in the future
  884. Maps with equal time stamps are not snapped
  885. @param dbif The database interface to be used
  886. """
  887. dbif, connected = init_dbif(dbif)
  888. maps = self.get_registered_maps_as_objects(dbif=dbif)
  889. if maps is None:
  890. return
  891. date_list = []
  892. for i in range(len(maps) - 1):
  893. start, end = maps[i].get_temporal_extent_as_tuple()
  894. start_next, end = maps[i + 1].get_temporal_extent_as_tuple()
  895. # Maps with equal time stamps can not be snapped
  896. if start != start_next:
  897. date_list.append((start, start_next))
  898. else:
  899. # Keep the original time stamps
  900. date_list.append((start, end))
  901. # Last map
  902. start, end = maps[-1].get_temporal_extent_as_tuple()
  903. # We increment the start time with the dataset
  904. # granularity if the end time is None
  905. if end is None:
  906. if self.is_time_absolute():
  907. end = increment_datetime_by_string(start, self.get_granularity())
  908. elif self.is_time_relative():
  909. end = start + self.get_granularity()
  910. date_list.append((start, end))
  911. self. _update_map_timestamps(maps, date_list, dbif)
  912. if connected:
  913. dbif.close()
  914. def _update_map_timestamps(self, maps, date_list, dbif):
  915. """!Update the timestamps of maps with the start and end time
  916. stored in the date_list.
  917. The number of dates in the list must be equal to the number
  918. of maps.
  919. @param maps A list of map objects
  920. @param date_list A list with date tuples (start_time, end_time)
  921. @param dbif The database interface to be used
  922. """
  923. datatsets_to_modify = {}
  924. # Now update the maps
  925. count = 0
  926. for map in maps:
  927. start = date_list[count][0]
  928. end = date_list[count][1]
  929. map.select(dbif)
  930. count += 1
  931. if self.is_time_absolute():
  932. map.update_absolute_time(start_time=start, end_time=end, dbif=dbif)
  933. elif self.is_time_relative():
  934. map.update_relative_time(start_time=start, end_time=end,
  935. unit=self.get_relative_time_unit(), dbif=dbif)
  936. # Save the datasets that must be updated
  937. datasets = map.get_registered_datasets(dbif)
  938. if datasets:
  939. for dataset in datasets:
  940. datatsets_to_modify[dataset["id"]] = dataset["id"]
  941. self.update_from_registered_maps(dbif)
  942. # Update affected datasets
  943. if datatsets_to_modify:
  944. for dataset in datatsets_to_modify:
  945. if dataset != self.get_id():
  946. ds = self.get_new_instance(ident=dataset)
  947. ds.select(dbif)
  948. ds.update_from_registered_maps(dbif)
  949. def rename(self, ident, dbif=None):
  950. """!Rename the space time dataset
  951. This method renames the space time dataset, the map register table
  952. and updates the entries in registered maps stds register.
  953. @param ident The new identifier "name@mapset"
  954. @param dbif The database interface to be used
  955. """
  956. dbif, connected = init_dbif(dbif)
  957. # SELECT all needed information from the database
  958. self.select(dbif)
  959. # We need to select the registered maps here
  960. maps = self.get_registered_maps_as_objects(None, "start_time", dbif)
  961. # Safe old identifier
  962. old_ident = self.get_id()
  963. # We need to rename the old table
  964. old_map_register_table = self.get_map_register()
  965. # Set new identifier
  966. self.set_id(ident)
  967. # Create map register table name from new identifier
  968. new_map_register_table = self.create_map_register_name()
  969. # Set new map register table name
  970. self.set_map_register(new_map_register_table)
  971. # Get the update statement, we update the table entry of the old identifier
  972. statement = self.update(dbif, execute=False, ident=old_ident)
  973. # We need to rename the raster register table
  974. statement += "ALTER TABLE %s RENAME TO \'%s\';\n"%\
  975. (old_map_register_table, new_map_register_table)
  976. # We need to rename the space time dataset in the maps register table
  977. if maps:
  978. for map in maps:
  979. map.select()
  980. statement += "UPDATE %s SET id = \'%s\' WHERE id = \'%s\';\n"%\
  981. (map.get_stds_register(), ident, old_ident)
  982. # Execute the accumulated statements
  983. dbif.execute_transaction(statement)
  984. if connected:
  985. dbif.close()
  986. def delete(self, dbif=None, execute=True):
  987. """!Delete a space time dataset from the temporal database
  988. This method removes the space time dataset from the temporal
  989. database and drops its map register table
  990. @param dbif The database interface to be used
  991. @param execute If True the SQL DELETE and DROP table
  992. statements will be executed.
  993. If False the prepared SQL statements are returned
  994. and must be executed by the caller.
  995. @return The SQL statements if execute == False, else an empty string
  996. """
  997. # First we need to check if maps are registered in this dataset and
  998. # unregister them
  999. # Commented because of performance issue calling g.message thousend times
  1000. #core.verbose(_("Delete space time %s dataset <%s> from temporal "
  1001. # "database") % \
  1002. # (self.get_new_map_instance(ident=None).get_type(),
  1003. # self.get_id()))
  1004. statement = ""
  1005. dbif, connected = init_dbif(dbif)
  1006. # SELECT all needed information from the database
  1007. self.metadata.select(dbif)
  1008. if self.get_map_register() is not None:
  1009. core.verbose(_("Drop map register table: %s") % (
  1010. self.get_map_register()))
  1011. rows = self.get_registered_maps("id", None, None, dbif)
  1012. # Unregister each registered map in the table
  1013. if rows is not None:
  1014. for row in rows:
  1015. # Unregister map
  1016. map = self.get_new_map_instance(row["id"])
  1017. statement += self.unregister_map(
  1018. map=map, dbif=dbif, execute=False)
  1019. # Safe the DROP table statement
  1020. statement += "DROP TABLE " + self.get_map_register() + ";\n"
  1021. # Remove the primary key, the foreign keys will be removed by trigger
  1022. statement += self.base.get_delete_statement()
  1023. if execute:
  1024. dbif.execute_transaction(statement)
  1025. self.reset(None)
  1026. if connected:
  1027. dbif.close()
  1028. if execute:
  1029. return ""
  1030. return statement
  1031. def register_map(self, map, dbif=None):
  1032. """!Register a map in the space time dataset.
  1033. This method takes care of the registration of a map
  1034. in a space time dataset.
  1035. In case the map is already registered this function
  1036. will break with a warning and return False.
  1037. This method raises a ScriptError in case of a fatal error
  1038. @param map The AbstractMapDataset object that should be registered
  1039. @param dbif The database interface to be used
  1040. @return True if success, False otherwise
  1041. """
  1042. dbif, connected = init_dbif(dbif)
  1043. if map.is_in_db(dbif) == False:
  1044. dbif.close()
  1045. core.fatal(_("Only maps with absolute or relative valid time can "
  1046. "be registered"))
  1047. # Commented because of performance issue calling g.message thousend times
  1048. #if map.get_layer():
  1049. # core.verbose(_("Register %s map <%s> with layer %s in space "
  1050. # "time %s dataset <%s>") % (map.get_type(),
  1051. # map.get_map_id(),
  1052. # map.get_layer(),
  1053. # map.get_type(),
  1054. # self.get_id()))
  1055. #else:
  1056. # core.verbose(_("Register %s map <%s> in space time %s "
  1057. # "dataset <%s>") % (map.get_type(), map.get_map_id(),
  1058. # map.get_type(), self.get_id()))
  1059. # First select all data from the database
  1060. map.select(dbif)
  1061. if not map.check_for_correct_time():
  1062. if map.get_layer():
  1063. core.fatal(_("Map <%s> with layer %s has invalid time")
  1064. % (map.get_map_id(), map.get_layer()))
  1065. else:
  1066. core.fatal(_("Map <%s> has invalid time") % (map.get_map_id()))
  1067. map_id = map.base.get_id()
  1068. map_name = map.base.get_name()
  1069. map_mapset = map.base.get_mapset()
  1070. map_register_table = map.get_stds_register()
  1071. map_rel_time_unit = map.get_relative_time_unit()
  1072. map_ttype = map.get_temporal_type()
  1073. #print "Map register table", map_register_table
  1074. # Get basic info
  1075. stds_name = self.base.get_name()
  1076. stds_mapset = self.base.get_mapset()
  1077. stds_register_table = self.get_map_register()
  1078. stds_ttype = self.get_temporal_type()
  1079. # The gathered SQL statemets are stroed here
  1080. statement = ""
  1081. # Check temporal types
  1082. if stds_ttype != map_ttype:
  1083. if map.get_layer():
  1084. core.fatal(_("Temporal type of space time dataset <%s> and "
  1085. "map <%s> with layer %s are different") % \
  1086. (self.get_id(), map.get_map_id(), map.get_layer()))
  1087. else:
  1088. core.fatal(_("Temporal type of space time dataset <%s> and "
  1089. "map <%s> are different") % \
  1090. (self.get_id(), map.get_map_id()))
  1091. # In case no map has been registered yet, set the
  1092. # relative time unit from the first map
  1093. if (self.metadata.get_number_of_maps() is None or \
  1094. self.metadata.get_number_of_maps() == 0) and \
  1095. self.map_counter == 0 and self.is_time_relative():
  1096. self.set_relative_time_unit(map_rel_time_unit)
  1097. statement += self.relative_time.get_update_all_statement_mogrified(
  1098. dbif)
  1099. # Commented because of performance issue calling g.message thousend times
  1100. #core.verbose(_("Set temporal unit for space time %s dataset "
  1101. # "<%s> to %s") % (map.get_type(), self.get_id(),
  1102. # map_rel_time_unit))
  1103. stds_rel_time_unit = self.get_relative_time_unit()
  1104. # Check the relative time unit
  1105. if self.is_time_relative() and (stds_rel_time_unit != map_rel_time_unit):
  1106. if map.get_layer():
  1107. core.fatal(_("Relative time units of space time dataset "
  1108. "<%s> and map <%s> with layer %s are different") %\
  1109. (self.get_id(), map.get_map_id(), map.get_layer()))
  1110. else:
  1111. core.fatal(_("Relative time units of space time dataset "
  1112. "<%s> and map <%s> are different") % \
  1113. (self.get_id(), map.get_map_id()))
  1114. if stds_mapset != map_mapset:
  1115. dbif.close()
  1116. core.fatal(_("Only maps from the same mapset can be registered"))
  1117. # Check if map is already registered
  1118. if stds_register_table is not None:
  1119. if dbif.dbmi.paramstyle == "qmark":
  1120. sql = "SELECT id FROM " + \
  1121. stds_register_table + " WHERE id = (?)"
  1122. else:
  1123. sql = "SELECT id FROM " + \
  1124. stds_register_table + " WHERE id = (%s)"
  1125. try:
  1126. dbif.cursor.execute(sql, (map_id,))
  1127. row = dbif.cursor.fetchone()
  1128. except:
  1129. core.warning(_("Error in strds_register_table request"))
  1130. raise
  1131. if row is not None and row[0] == map_id:
  1132. if connected == True:
  1133. dbif.close()
  1134. if map.get_layer() is not None:
  1135. core.warning(_("Map <%s> with layer %s is already "
  1136. "registered.") % (map.get_map_id(),
  1137. map.get_layer()))
  1138. else:
  1139. core.warning(_("Map <%s> is already registered.")
  1140. % (map.get_map_id()))
  1141. return False
  1142. # Create tables
  1143. sql_path = get_sql_template_path()
  1144. # We need to create the map raster register table precedes we can register the map
  1145. if map_register_table is None:
  1146. # Create a unique id
  1147. uuid_rand = "map_" + str(uuid.uuid4()).replace("-", "")
  1148. map_register_table = uuid_rand + "_" + \
  1149. self.get_type() + "_register"
  1150. # Read the SQL template
  1151. sql = open(os.path.join(sql_path,
  1152. "map_stds_register_table_template.sql"),
  1153. 'r').read()
  1154. # Create the raster, raster3d and vector tables
  1155. sql = sql.replace("GRASS_MAP", map.get_type())
  1156. sql = sql.replace("MAP_NAME", map_name + "_" + map_mapset)
  1157. sql = sql.replace("TABLE_NAME", uuid_rand)
  1158. sql = sql.replace("MAP_ID", map_id)
  1159. sql = sql.replace("STDS", self.get_type())
  1160. statement += sql
  1161. # Set the stds register table name and put it into the DB
  1162. map.set_stds_register(map_register_table)
  1163. statement += map.metadata.get_update_statement_mogrified(dbif)
  1164. # Commented because of performance issue calling g.message thousend times
  1165. #if map.get_layer():
  1166. # core.verbose(_("Created register table <%s> for "
  1167. # "%s map <%s> with layer %s") %
  1168. # (map_register_table, map.get_type(),
  1169. # map.get_map_id(), map.get_layer()))
  1170. #else:
  1171. # core.verbose(_("Created register table <%s> for %s map <%s>") %
  1172. # (map_register_table, map.get_type(),
  1173. # map.get_map_id()))
  1174. # We need to create the table and register it
  1175. if stds_register_table is None:
  1176. # Create table name
  1177. stds_register_table = self.create_map_register_name()
  1178. # Read the SQL template
  1179. sql = open(os.path.join(sql_path,
  1180. "stds_map_register_table_template.sql"),
  1181. 'r').read()
  1182. # Create the raster, raster3d and vector tables
  1183. sql = sql.replace("GRASS_MAP", map.get_type())
  1184. sql = sql.replace("SPACETIME_NAME", stds_name + "_" + stds_mapset)
  1185. sql = sql.replace("SPACETIME_ID", self.base.get_id())
  1186. sql = sql.replace("STDS", self.get_type())
  1187. statement += sql
  1188. # Set the map register table name and put it into the DB
  1189. self.set_map_register(stds_register_table)
  1190. statement += self.metadata.get_update_statement_mogrified(dbif)
  1191. # Commented because of performance issue calling g.message thousend times
  1192. #core.verbose(_("Created register table <%s> for space "
  1193. # "time %s dataset <%s>") %
  1194. # (stds_register_table, map.get_type(), self.get_id()))
  1195. # We need to execute the statement at this time
  1196. if statement != "":
  1197. dbif.execute_transaction(statement)
  1198. statement = ""
  1199. # Register the stds in the map stds register table
  1200. # Check if the entry is already there
  1201. if dbif.dbmi.paramstyle == "qmark":
  1202. sql = "SELECT id FROM " + map_register_table + " WHERE id = ?"
  1203. else:
  1204. sql = "SELECT id FROM " + map_register_table + " WHERE id = %s"
  1205. try:
  1206. dbif.cursor.execute(sql, (self.base.get_id(),))
  1207. row = dbif.cursor.fetchone()
  1208. except:
  1209. row = None
  1210. # In case of no entry make a new one
  1211. if row is None:
  1212. if dbif.dbmi.paramstyle == "qmark":
  1213. sql = "INSERT INTO " + map_register_table + \
  1214. " (id) " + "VALUES (?);\n"
  1215. else:
  1216. sql = "INSERT INTO " + map_register_table + \
  1217. " (id) " + "VALUES (%s);\n"
  1218. statement += dbif.mogrify_sql_statement(
  1219. (sql, (self.base.get_id(),)))
  1220. # Now put the raster name in the stds map register table
  1221. if dbif.dbmi.paramstyle == "qmark":
  1222. sql = "INSERT INTO " + stds_register_table + \
  1223. " (id) " + "VALUES (?);\n"
  1224. else:
  1225. sql = "INSERT INTO " + stds_register_table + \
  1226. " (id) " + "VALUES (%s);\n"
  1227. statement += dbif.mogrify_sql_statement((sql, (map_id,)))
  1228. # Now execute the insert transaction
  1229. dbif.execute_transaction(statement)
  1230. if connected:
  1231. dbif.close()
  1232. # increase the counter
  1233. self.map_counter += 1
  1234. return True
  1235. def unregister_map(self, map, dbif=None, execute=True):
  1236. """!Unregister a map from the space time dataset.
  1237. This method takes care of the un-registration of a map
  1238. from a space time dataset.
  1239. @param map The map object to unregister
  1240. @param dbif The database interface to be used
  1241. @param execute If True the SQL DELETE and DROP table
  1242. statements will be executed.
  1243. If False the prepared SQL statements are
  1244. returned and must be executed by the caller.
  1245. @return The SQL statements if execute == False, else an empty
  1246. string, None in case of a failure
  1247. """
  1248. statement = ""
  1249. dbif, connected = init_dbif(dbif)
  1250. # First select needed data from the database
  1251. map.metadata.select(dbif)
  1252. map_id = map.get_id()
  1253. map_register_table = map.get_stds_register()
  1254. stds_register_table = self.get_map_register()
  1255. # Commented because of performance issue calling g.message thousend times
  1256. #if map.get_layer() is not None:
  1257. # core.verbose(_("Unregister %s map <%s> with layer %s") % \
  1258. # (map.get_type(), map.get_map_id(), map.get_layer()))
  1259. #else:
  1260. # core.verbose(_("Unregister %s map <%s>") % (
  1261. # map.get_type(), map.get_map_id()))
  1262. # Check if the map is registered in the space time raster dataset
  1263. if map_register_table is not None:
  1264. if dbif.dbmi.paramstyle == "qmark":
  1265. sql = "SELECT id FROM " + map_register_table + " WHERE id = ?"
  1266. else:
  1267. sql = "SELECT id FROM " + map_register_table + " WHERE id = %s"
  1268. try:
  1269. dbif.cursor.execute(sql, (self.base.get_id(),))
  1270. row = dbif.cursor.fetchone()
  1271. except:
  1272. row = None
  1273. # Break if the map is not registered
  1274. if row is None:
  1275. if map.get_layer() is not None:
  1276. core.warning(_("Map <%s> with layer %s is not registered "
  1277. "in space time dataset <%s>") % \
  1278. (map.get_map_id(), map.get_layer(),
  1279. self.base.get_id()))
  1280. else:
  1281. core.warning(_("Map <%s> is not registered in space "
  1282. "time dataset <%s>") % (map.get_map_id(),
  1283. self.base.get_id()))
  1284. if connected == True:
  1285. dbif.close()
  1286. return ""
  1287. # Remove the space time raster dataset from the raster dataset register
  1288. if map_register_table is not None:
  1289. if dbif.dbmi.paramstyle == "qmark":
  1290. sql = "DELETE FROM " + map_register_table + " WHERE id = ?;\n"
  1291. else:
  1292. sql = "DELETE FROM " + map_register_table + " WHERE id = %s;\n"
  1293. statement += dbif.mogrify_sql_statement(
  1294. (sql, (self.base.get_id(),)))
  1295. # Remove the raster map from the space time raster dataset register
  1296. if stds_register_table is not None:
  1297. if dbif.dbmi.paramstyle == "qmark":
  1298. sql = "DELETE FROM " + stds_register_table + " WHERE id = ?;\n"
  1299. else:
  1300. sql = "DELETE FROM " + \
  1301. stds_register_table + " WHERE id = %s;\n"
  1302. statement += dbif.mogrify_sql_statement((sql, (map_id,)))
  1303. if execute:
  1304. dbif.execute_transaction(statement)
  1305. if connected:
  1306. dbif.close()
  1307. # decrease the counter
  1308. self.map_counter -= 1
  1309. if execute:
  1310. return ""
  1311. return statement
  1312. def update_from_registered_maps(self, dbif=None):
  1313. """!This methods updates the spatial and temporal extent as well as
  1314. type specific metadata. It should always been called after maps are registered
  1315. or unregistered/deleted from the space time dataset.
  1316. The update of the temporal extent checks if the end time is set correctly.
  1317. In case the registered maps have no valid end time (None) the maximum start time
  1318. will be used. If the end time is earlier than the maximum start time, it will
  1319. be replaced by the maximum start time.
  1320. An other solution to automate this is to use the deactivated trigger
  1321. in the SQL files. But this will result in a huge performance issue
  1322. in case many maps are registered (>1000).
  1323. @param dbif The database interface to be used
  1324. """
  1325. core.verbose(_("Update metadata, spatial and temporal extent from "
  1326. "all registered maps of <%s>") % (self.get_id()))
  1327. # Nothing to do if the register is not present
  1328. if not self.get_map_register():
  1329. return
  1330. dbif, connected = init_dbif(dbif)
  1331. map_time = None
  1332. use_start_time = False
  1333. # Get basic info
  1334. stds_name = self.base.get_name()
  1335. stds_mapset = self.base.get_mapset()
  1336. sql_path = get_sql_template_path()
  1337. #We create a transaction
  1338. sql_script = ""
  1339. # Update the spatial and temporal extent from registered maps
  1340. # Read the SQL template
  1341. sql = open(os.path.join(sql_path,
  1342. "update_stds_spatial_temporal_extent_template.sql"),
  1343. 'r').read()
  1344. sql = sql.replace(
  1345. "GRASS_MAP", self.get_new_map_instance(None).get_type())
  1346. sql = sql.replace("SPACETIME_NAME", stds_name + "_" + stds_mapset)
  1347. sql = sql.replace("SPACETIME_ID", self.base.get_id())
  1348. sql = sql.replace("STDS", self.get_type())
  1349. sql_script += sql
  1350. sql_script += "\n"
  1351. # Update type specific metadata
  1352. sql = open(os.path.join(sql_path, "update_" +
  1353. self.get_type() + "_metadata_template.sql"), 'r').read()
  1354. sql = sql.replace(
  1355. "GRASS_MAP", self.get_new_map_instance(None).get_type())
  1356. sql = sql.replace("SPACETIME_NAME", stds_name + "_" + stds_mapset)
  1357. sql = sql.replace("SPACETIME_ID", self.base.get_id())
  1358. sql = sql.replace("STDS", self.get_type())
  1359. sql_script += sql
  1360. sql_script += "\n"
  1361. dbif.execute_transaction(sql_script)
  1362. # Read and validate the selected end time
  1363. self.select()
  1364. if self.is_time_absolute():
  1365. start_time, end_time, tz = self.get_absolute_time()
  1366. else:
  1367. start_time, end_time, unit = self.get_relative_time()
  1368. # In case no end time is set, use the maximum start time of
  1369. # all registered maps as end time
  1370. if end_time is None:
  1371. use_start_time = True
  1372. else:
  1373. # Check if the end time is smaller than the maximum start time
  1374. if self.is_time_absolute():
  1375. sql = """SELECT max(start_time) FROM GRASS_MAP_absolute_time
  1376. WHERE GRASS_MAP_absolute_time.id IN
  1377. (SELECT id FROM SPACETIME_NAME_GRASS_MAP_register);"""
  1378. sql = sql.replace("GRASS_MAP", self.get_new_map_instance(
  1379. None).get_type())
  1380. sql = sql.replace("SPACETIME_NAME",
  1381. stds_name + "_" + stds_mapset)
  1382. else:
  1383. sql = """SELECT max(start_time) FROM GRASS_MAP_relative_time
  1384. WHERE GRASS_MAP_relative_time.id IN
  1385. (SELECT id FROM SPACETIME_NAME_GRASS_MAP_register);"""
  1386. sql = sql.replace("GRASS_MAP", self.get_new_map_instance(
  1387. None).get_type())
  1388. sql = sql.replace("SPACETIME_NAME",
  1389. stds_name + "_" + stds_mapset)
  1390. dbif.cursor.execute(sql)
  1391. row = dbif.cursor.fetchone()
  1392. if row is not None:
  1393. # This seems to be a bug in sqlite3 Python driver
  1394. if dbif.dbmi.__name__ == "sqlite3":
  1395. tstring = row[0]
  1396. # Convert the unicode string into the datetime format
  1397. if self.is_time_absolute():
  1398. if tstring.find(":") > 0:
  1399. time_format = "%Y-%m-%d %H:%M:%S"
  1400. else:
  1401. time_format = "%Y-%m-%d"
  1402. max_start_time = datetime.strptime(
  1403. tstring, time_format)
  1404. else:
  1405. max_start_time = row[0]
  1406. else:
  1407. max_start_time = row[0]
  1408. if end_time < max_start_time:
  1409. use_start_time = True
  1410. # Set the maximum start time as end time
  1411. if use_start_time:
  1412. if self.is_time_absolute():
  1413. sql = """UPDATE STDS_absolute_time SET end_time =
  1414. (SELECT max(start_time) FROM GRASS_MAP_absolute_time WHERE
  1415. GRASS_MAP_absolute_time.id IN
  1416. (SELECT id FROM SPACETIME_NAME_GRASS_MAP_register)
  1417. ) WHERE id = 'SPACETIME_ID';"""
  1418. sql = sql.replace("GRASS_MAP", self.get_new_map_instance(
  1419. None).get_type())
  1420. sql = sql.replace("SPACETIME_NAME",
  1421. stds_name + "_" + stds_mapset)
  1422. sql = sql.replace("SPACETIME_ID", self.base.get_id())
  1423. sql = sql.replace("STDS", self.get_type())
  1424. elif self.is_time_relative():
  1425. sql = """UPDATE STDS_relative_time SET end_time =
  1426. (SELECT max(start_time) FROM GRASS_MAP_relative_time WHERE
  1427. GRASS_MAP_relative_time.id IN
  1428. (SELECT id FROM SPACETIME_NAME_GRASS_MAP_register)
  1429. ) WHERE id = 'SPACETIME_ID';"""
  1430. sql = sql.replace("GRASS_MAP", self.get_new_map_instance(
  1431. None).get_type())
  1432. sql = sql.replace("SPACETIME_NAME",
  1433. stds_name + "_" + stds_mapset)
  1434. sql = sql.replace("SPACETIME_ID", self.base.get_id())
  1435. sql = sql.replace("STDS", self.get_type())
  1436. dbif.execute_transaction(sql)
  1437. # Count the temporal map types
  1438. maps = self.get_registered_maps_as_objects(dbif=dbif)
  1439. tlist = self.count_temporal_types(maps)
  1440. if tlist["interval"] > 0 and tlist["point"] == 0 and \
  1441. tlist["invalid"] == 0:
  1442. map_time = "interval"
  1443. elif tlist["interval"] == 0 and tlist["point"] > 0 and \
  1444. tlist["invalid"] == 0:
  1445. map_time = "point"
  1446. elif tlist["interval"] > 0 and tlist["point"] > 0 and \
  1447. tlist["invalid"] == 0:
  1448. map_time = "mixed"
  1449. else:
  1450. map_time = "invalid"
  1451. # Compute the granularity
  1452. if map_time != "invalid":
  1453. # Smallest supported temporal resolution
  1454. if self.is_time_absolute():
  1455. gran = compute_absolute_time_granularity(maps)
  1456. elif self.is_time_relative():
  1457. gran = compute_relative_time_granularity(maps)
  1458. else:
  1459. gran = None
  1460. # Set the map time type and update the time objects
  1461. self.temporal_extent.select(dbif)
  1462. self.metadata.select(dbif)
  1463. if self.metadata.get_number_of_maps() > 0:
  1464. self.temporal_extent.set_map_time(map_time)
  1465. self.temporal_extent.set_granularity(gran)
  1466. else:
  1467. self.temporal_extent.set_map_time(None)
  1468. self.temporal_extent.set_granularity(None)
  1469. self.temporal_extent.update_all(dbif)
  1470. if connected:
  1471. dbif.close()