abstract_space_time_dataset.py 75 KB

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