abstract_space_time_dataset.py 95 KB

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