abstract_space_time_dataset.py 99 KB

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