abstract_space_time_dataset.py 95 KB

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