abstract_space_time_dataset.py 94 KB

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