abstract_space_time_dataset.py 67 KB

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