abstract_space_time_dataset.py 66 KB

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