abstract_space_time_dataset.py 99 KB

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