abstract_space_time_dataset.py 64 KB

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