abstract_map_dataset.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668
  1. # -*- coding: utf-8 -*-
  2. """!@package grass.temporal
  3. @brief GRASS Python scripting module (temporal GIS functions)
  4. Temporal GIS related functions to be used in temporal GIS Python library package.
  5. Usage:
  6. >>> import grass.temporal as tgis
  7. >>> amd = tgis.AbstractMapDataset()
  8. (C) 2008-2011 by the GRASS Development Team
  9. This program is free software under the GNU General Public
  10. License (>=v2). Read the file COPYING that comes with GRASS
  11. for details.
  12. @author Soeren Gebbert
  13. """
  14. from abstract_temporal_dataset import *
  15. from datetime_math import *
  16. class AbstractMapDataset(AbstractTemporalDataset):
  17. """!This is the base class for all maps (raster, vector, raster3d).
  18. The temporal extent, the spatial extent and the metadata of maps
  19. are stored in the temporal database. Maps can be registered in the temporal
  20. database, updated and deleted.
  21. This class provides all functionalities that are needed to manage maps
  22. in the temporal database. That are:
  23. - insert() to register the map and therefore its spatio-temporal extent and metadata in the temporal database
  24. - update() to update the map spatio-temporal extent and metadata in the temporal database
  25. - unregister() to unregister the map from each space time dataset in which this map is registered
  26. - delete() to remove the map from the temporal database
  27. - Methods to set relative and absolute time stamps
  28. - Abstract methods that must be implemented in the map specific subclasses
  29. """
  30. def __init__(self):
  31. AbstractTemporalDataset.__init__(self)
  32. def get_new_stds_instance(self, ident):
  33. """!Return a new space time dataset instance that store maps with the type of this map object (rast, rast3d or vect)
  34. @param ident The identifier of the space time dataset
  35. @return The new space time dataset instance
  36. """
  37. raise ImplementationError(
  38. "This method must be implemented in the subclasses")
  39. def get_stds_register(self):
  40. """!Return the space time dataset register table name
  41. Maps can be registered in several different space time datasets.
  42. This method returns the name of the register table in the
  43. temporal database.
  44. @return The name of the stds register table
  45. """
  46. raise ImplementationError(
  47. "This method must be implemented in the subclasses")
  48. def set_stds_register(self, name):
  49. """!Set the space time dataset register table name.
  50. This table stores all space time datasets in
  51. which this map is registered.
  52. @param name The name of the register table
  53. """
  54. raise ImplementationError(
  55. "This method must be implemented in the subclasses")
  56. def check_resolution_with_current_region(self):
  57. """!Check if the raster or voxel resolution is
  58. finer than the current resolution
  59. - Return "finer" in case the raster/voxel resolution is finer
  60. than the current region
  61. - Return "coarser" in case the raster/voxel resolution is coarser
  62. than the current region
  63. Vector maps have no resolution, since they store the coordinates directly.
  64. @return "finer" or "coarser"
  65. """
  66. raise ImplementationError(
  67. "This method must be implemented in the subclasses")
  68. def has_grass_timestamp(self):
  69. """!Check if a grass file based time stamp exists for this map.
  70. @return True is the grass file based time stamped exists for this map
  71. """
  72. raise ImplementationError(
  73. "This method must be implemented in the subclasses")
  74. def write_timestamp_to_grass(self):
  75. """!Write the timestamp of this map into the map metadata
  76. in the grass file system based spatial database.
  77. """
  78. raise ImplementationError(
  79. "This method must be implemented in the subclasses")
  80. def remove_timestamp_from_grass(self):
  81. """!Remove the timestamp from the grass file
  82. system based spatial database
  83. """
  84. raise ImplementationError(
  85. "This method must be implemented in the subclasses")
  86. def map_exists(self):
  87. """!Return True in case the map exists in the grass spatial database
  88. @return True if map exists, False otherwise
  89. """
  90. raise ImplementationError(
  91. "This method must be implemented in the subclasses")
  92. def read_info(self):
  93. """!Read the map info from the grass file system based database and
  94. store the content into a dictionary
  95. """
  96. raise ImplementationError(
  97. "This method must be implemented in the subclasses")
  98. def load(self):
  99. """!Load the content of this object from the grass
  100. file system based database"""
  101. raise ImplementationError(
  102. "This method must be implemented in the subclasses")
  103. def _convert_timestamp(self):
  104. """!Convert the valid time into a grass datetime library
  105. compatible timestamp string
  106. This methods works for relative and absolute time
  107. @return the grass timestamp string
  108. """
  109. start = ""
  110. if self.is_time_absolute():
  111. start_time, end_time, tz = self.get_absolute_time()
  112. start = datetime_to_grass_datetime_string(start_time)
  113. if end_time is not None:
  114. end = datetime_to_grass_datetime_string(end_time)
  115. start += " / %s" % (end)
  116. else:
  117. start_time, end_time, unit = self.get_relative_time()
  118. start = "%i %s" % (int(start_time), unit)
  119. if end_time is not None:
  120. end = "%i %s" % (int(end_time), unit)
  121. start += " / %s" % (end)
  122. return start
  123. def get_map_id(self):
  124. """!Return the map id. The map id is the unique identifier
  125. in grass and must not be equal to the
  126. primary key identifier (id) of the map in the database.
  127. Since vector maps may have layer information,
  128. the unique id is a combination of name, layer and mapset.
  129. Use get_map_id() every time your need to access the grass map
  130. in the file system but not to identify
  131. map information in the temporal database.
  132. @return The map id "name@mapset"
  133. """
  134. return self.base.get_map_id()
  135. def build_id(self, name, mapset, layer=None):
  136. """!Convenient method to build the unique identifier
  137. Existing layer and mapset definitions in the name
  138. string will be reused
  139. @param name The name of the map
  140. @param mapset The mapset in which the map is located
  141. @param layer The layer of the vector map, use None in case no layer exists
  142. @return the id of the map as "name(:layer)@mapset"
  143. while layer is optional
  144. """
  145. # Check if the name includes any mapset
  146. if name.find("@") >= 0:
  147. name, mapset = name.split("@")
  148. # Check for layer number in map name
  149. if name.find(":") >= 0:
  150. name, layer = name.split(":")
  151. if layer is not None:
  152. return "%s:%s@%s" % (name, layer, mapset)
  153. else:
  154. return "%s@%s" % (name, mapset)
  155. def get_layer(self):
  156. """!Return the layer of the map
  157. @return the layer of the map or None in case no layer is defined
  158. """
  159. return self.base.get_layer()
  160. def print_info(self):
  161. """!Print information about this object in human readable style"""
  162. if self.get_type() == "raster":
  163. # 1 2 3 4 5 6 7
  164. # 0123456789012345678901234567890123456789012345678901234567890123456789012345678
  165. print " +-------------------- Raster Dataset ----------------------------------------+"
  166. if self.get_type() == "raster3d":
  167. # 1 2 3 4 5 6 7
  168. # 0123456789012345678901234567890123456789012345678901234567890123456789012345678
  169. print " +-------------------- 3D Raster Dataset -------------------------------------+"
  170. if self.get_type() == "vector":
  171. # 1 2 3 4 5 6 7
  172. # 0123456789012345678901234567890123456789012345678901234567890123456789012345678
  173. print " +-------------------- Vector Dataset ----------------------------------------+"
  174. print " | |"
  175. self.base.print_info()
  176. if self.is_time_absolute():
  177. self.absolute_time.print_info()
  178. if self.is_time_relative():
  179. self.relative_time.print_info()
  180. if self.is_topology_build():
  181. self.print_topology_info()
  182. self.spatial_extent.print_info()
  183. self.metadata.print_info()
  184. datasets = self.get_registered_datasets()
  185. count = 0
  186. string = ""
  187. if datasets is not None:
  188. for ds in datasets:
  189. if count > 0 and count % 3 == 0:
  190. string += "\n | ............................ "
  191. count = 0
  192. if count == 0:
  193. string += ds["id"]
  194. else:
  195. string += ",%s" % ds["id"]
  196. count += 1
  197. print " | Registered datasets ........ " + string
  198. print " +----------------------------------------------------------------------------+"
  199. def print_shell_info(self):
  200. """!Print information about this object in shell style"""
  201. self.base.print_shell_info()
  202. if self.is_time_absolute():
  203. self.absolute_time.print_shell_info()
  204. if self.is_time_relative():
  205. self.relative_time.print_shell_info()
  206. self.spatial_extent.print_shell_info()
  207. self.metadata.print_shell_info()
  208. datasets = self.get_registered_datasets()
  209. count = 0
  210. string = ""
  211. if datasets is not None:
  212. for ds in datasets:
  213. if count == 0:
  214. string += ds["id"]
  215. else:
  216. string += ",%s" % ds["id"]
  217. count += 1
  218. print "registered_datasets=" + string
  219. if self.is_topology_build():
  220. self.print_topology_shell_info()
  221. def insert(self, dbif=None, execute=True):
  222. """!Insert the map content into the database from the internal structure
  223. This functions assures that the timestamp is written to the
  224. grass file system based database in addition to the temporal database entry.
  225. @param dbif The database interface to be used
  226. @param execute If True the SQL statements will be executed.
  227. If False the prepared SQL statements are
  228. returned and must be executed by the caller.
  229. @return The SQL insert statement in case execute=False, or an empty string otherwise
  230. """
  231. self.write_timestamp_to_grass()
  232. return AbstractDataset.insert(self, dbif, execute)
  233. def update(self, dbif=None, execute=True):
  234. """!Update the map content in the database from the internal structure
  235. excluding None variables
  236. This functions assures that the timestamp is written to the
  237. grass file system based database in addition to the temporal database entry.
  238. @param dbif The database interface to be used
  239. @param execute If True the SQL statements will be executed.
  240. If False the prepared SQL statements are
  241. returned and must be executed by the caller.
  242. @return The SQL insert statement in case execute=False, or an empty string otherwise
  243. """
  244. self.write_timestamp_to_grass()
  245. return AbstractDataset.update(self, dbif, execute)
  246. def update_all(self, dbif=None, execute=True):
  247. """!Update the map content in the database from the internal structure
  248. including None variables
  249. This functions assures that the timestamp is written to the
  250. grass file system based database in addition to the temporal database entry.
  251. @param dbif The database interface to be used
  252. @param execute If True the SQL statements will be executed.
  253. If False the prepared SQL statements are
  254. returned and must be executed by the caller.
  255. @return The SQL insert statement in case execute=False, or an empty string otherwise
  256. """
  257. self.write_timestamp_to_grass()
  258. return AbstractDataset.update_all(self, dbif, execute)
  259. def set_absolute_time(self, start_time, end_time=None, timezone=None):
  260. """!Set the absolute time with start time and end time
  261. The end time is optional and must be set to None in case of time instance.
  262. This method only modifies this object and does not commit
  263. the modifications to the temporal database.
  264. @param start_time a datetime object specifying the start time of the map
  265. @param end_time a datetime object specifying the end time of the map, None in case or time instance
  266. @param timezone Thee timezone of the map (not used)
  267. """
  268. if start_time and not isinstance(start_time, datetime):
  269. if self.get_layer() is not None:
  270. core.fatal(_("Start time must be of type datetime "
  271. "for %s map <%s> with layer: %s") % \
  272. (self.get_type(), self.get_map_id(),
  273. self.get_layer()))
  274. else:
  275. core.fatal(_("Start time must be of type "
  276. "datetime ""for %s map <%s>") % \
  277. (self.get_type(), self.get_map_id()))
  278. if end_time and not isinstance(end_time, datetime):
  279. if self.get_layer():
  280. core.fatal(_("End time must be of type datetime "
  281. "for %s map <%s> with layer: %s") % \
  282. (self.get_type(), self.get_map_id(),
  283. self.get_layer()))
  284. else:
  285. core.fatal(_("End time must be of type datetime "
  286. "for %s map <%s>") % (self.get_type(),
  287. self.get_map_id()))
  288. if start_time is not None and end_time is not None:
  289. if start_time > end_time:
  290. if self.get_layer():
  291. core.fatal(_("End time must be greater than "
  292. "start time for %s map <%s> with layer: %s") %\
  293. (self.get_type(), self.get_map_id(),
  294. self.get_layer()))
  295. else:
  296. core.fatal(_("End time must be greater than "
  297. "start time for %s map <%s>") % \
  298. (self.get_type(), self.get_map_id()))
  299. else:
  300. # Do not create an interval in case start and end time are equal
  301. if start_time == end_time:
  302. end_time = None
  303. self.base.set_ttype("absolute")
  304. self.absolute_time.set_start_time(start_time)
  305. self.absolute_time.set_end_time(end_time)
  306. self.absolute_time.set_timezone(timezone)
  307. return True
  308. def update_absolute_time(self, start_time, end_time=None,
  309. timezone=None, dbif=None):
  310. """!Update the absolute time
  311. The end time is optional and must be set to None in case of time instance.
  312. This functions assures that the timestamp is written to the
  313. grass file system based database in addition to the temporal database entry.
  314. @param start_time a datetime object specifying the start time of the map
  315. @param end_time a datetime object specifying the end time of the map, None in case or time instance
  316. @param timezone Thee timezone of the map (not used)
  317. @param dbif The database interface to be used
  318. """
  319. dbif, connected = init_dbif(dbif)
  320. self.set_absolute_time(start_time, end_time, timezone)
  321. self.absolute_time.update_all(dbif)
  322. self.base.update(dbif)
  323. if connected:
  324. dbif.close()
  325. self.write_timestamp_to_grass()
  326. def set_relative_time(self, start_time, end_time, unit):
  327. """!Set the relative time interval
  328. The end time is optional and must be set to None in case of time instance.
  329. This method only modifies this object and does not commit
  330. the modifications to the temporal database.
  331. @param start_time An integer value
  332. @param end_time An integer value, None in case or time instance
  333. @param unit The unit of the relative time. Supported units:
  334. year(s), month(s), day(s), hour(s), minute(s), second(s)
  335. @return True for success and False otherwise
  336. """
  337. if not self.check_relative_time_unit(unit):
  338. if self.get_layer() is not None:
  339. core.error(_("Unsupported relative time unit type for %s map "
  340. "<%s> with layer %s: %s") % (self.get_type(),
  341. self.get_id(),
  342. self.get_layer(),
  343. unit))
  344. else:
  345. core.error(_("Unsupported relative time unit type for %s map "
  346. "<%s>: %s") % (self.get_type(), self.get_id(),
  347. unit))
  348. return False
  349. if start_time is not None and end_time is not None:
  350. if int(start_time) > int(end_time):
  351. if self.get_layer() is not None:
  352. core.error(_("End time must be greater than start time for"
  353. " %s map <%s> with layer %s") % \
  354. (self.get_type(), self.get_id(),
  355. self.get_layer()))
  356. else:
  357. core.error(_("End time must be greater than start time for"
  358. " %s map <%s>") % (self.get_type(),
  359. self.get_id()))
  360. return False
  361. else:
  362. # Do not create an interval in case start and end time are equal
  363. if start_time == end_time:
  364. end_time = None
  365. self.base.set_ttype("relative")
  366. self.relative_time.set_unit(unit)
  367. self.relative_time.set_start_time(int(start_time))
  368. if end_time is not None:
  369. self.relative_time.set_end_time(int(end_time))
  370. else:
  371. self.relative_time.set_end_time(None)
  372. return True
  373. def update_relative_time(self, start_time, end_time, unit, dbif=None):
  374. """!Update the relative time interval
  375. The end time is optional and must be set to None in case of time instance.
  376. This functions assures that the timestamp is written to the
  377. grass file system based database in addition to the temporal database entry.
  378. @param start_time An integer value
  379. @param end_time An integer value, None in case or time instance
  380. @param unit The relative time unit
  381. @param dbif The database interface to be used
  382. """
  383. dbif, connected = init_dbif(dbif)
  384. if self.set_relative_time(start_time, end_time, unit):
  385. self.relative_time.update_all(dbif)
  386. self.base.update(dbif)
  387. if connected:
  388. dbif.close()
  389. self.write_timestamp_to_grass()
  390. def set_spatial_extent(self, north, south, east, west, top=0, bottom=0):
  391. """!Set the spatial extent of the map
  392. This method only modifies this object and does not commit
  393. the modifications to the temporal database.
  394. @param north The northern edge
  395. @param south The southern edge
  396. @param east The eastern edge
  397. @param west The western edge
  398. @param top The top edge
  399. @param bottom The bottom edge
  400. """
  401. self.spatial_extent.set_spatial_extent(
  402. north, south, east, west, top, bottom)
  403. def check_valid_time(self):
  404. """!Check for correct valid time"""
  405. if self.is_time_absolute():
  406. start, end, tz = self.get_absolute_time()
  407. else:
  408. start, end, unit = self.get_relative_time()
  409. if start is not None:
  410. if end is not None:
  411. if start >= end:
  412. if self.get_layer() is not None:
  413. core.error(_("Map <%s> with layer %s has incorrect "
  414. "time interval, start time is greater "
  415. "than end time") % (self.get_map_id(),
  416. self.get_layer()))
  417. else:
  418. core.error(_("Map <%s> has incorrect time interval, "
  419. "start time is greater than end time") % \
  420. (self.get_map_id()))
  421. return False
  422. else:
  423. core.error(_("Map <%s> has incorrect start time") %
  424. (self.get_map_id()))
  425. return False
  426. return True
  427. def delete(self, dbif=None, update=True, execute=True):
  428. """!Delete a map entry from database if it exists
  429. Remove dependent entries:
  430. * Remove the map entry in each space time dataset in which this map
  431. is registered
  432. * Remove the space time dataset register table
  433. @param dbif The database interface to be used
  434. @param update Call for each unregister statement the update from
  435. registered maps of the space time dataset.
  436. This can slow down the un-registration process significantly.
  437. @param execute If True the SQL DELETE and DROP table statements will
  438. be executed.
  439. If False the prepared SQL statements are
  440. returned and must be executed by the caller.
  441. @return The SQL statements if execute=False, else an empty string,
  442. None in case of a failure
  443. """
  444. dbif, connected = init_dbif(dbif)
  445. statement = ""
  446. if self.is_in_db(dbif):
  447. # SELECT all needed information from the database
  448. self.metadata.select(dbif)
  449. # First we unregister from all dependent space time datasets
  450. statement += self.unregister(
  451. dbif=dbif, update=update, execute=False)
  452. # Remove the strds register table
  453. if self.get_stds_register() is not None:
  454. statement += "DROP TABLE " + self.get_stds_register() + ";\n"
  455. # Commented because of performance issue calling g.message thousend times
  456. #core.verbose(_("Delete %s dataset <%s> from temporal database")
  457. # % (self.get_type(), self.get_id()))
  458. # Delete yourself from the database, trigger functions will
  459. # take care of dependencies
  460. statement += self.base.get_delete_statement()
  461. if execute:
  462. dbif.execute_transaction(statement)
  463. # Remove the timestamp from the file system
  464. self.remove_timestamp_from_grass()
  465. self.reset(None)
  466. if connected:
  467. dbif.close()
  468. if execute:
  469. return ""
  470. return statement
  471. def unregister(self, dbif=None, update=True, execute=True):
  472. """! Remove the map entry in each space time dataset in which this map
  473. is registered
  474. @param dbif The database interface to be used
  475. @param update Call for each unregister statement the update from
  476. registered maps of the space time dataset. This can
  477. slow down the un-registration process significantly.
  478. @param execute If True the SQL DELETE and DROP table statements
  479. will be executed.
  480. If False the prepared SQL statements are
  481. returned and must be executed by the caller.
  482. @return The SQL statements if execute=False, else an empty string
  483. """
  484. # Commented because of performance issue calling g.message thousend times
  485. #if self.get_layer() is not None:
  486. # core.verbose(_("Unregister %(type)s map <%(map)s> with "
  487. # "layer %(layer)s from space time datasets" % \
  488. # {'type':self.get_type(), 'map':self.get_map_id(),
  489. # 'layer':self.get_layer()}))
  490. #else:
  491. # core.verbose(_("Unregister %(type)s map <%(map)s> "
  492. # "from space time datasets"
  493. # % {'type':self.get_type(), 'map':self.get_map_id()}))
  494. statement = ""
  495. dbif, connected = init_dbif(dbif)
  496. # Get all datasets in which this map is registered
  497. rows = self.get_registered_datasets(dbif)
  498. # For each stds in which the map is registered
  499. if rows is not None:
  500. for row in rows:
  501. # Create a space time dataset object to remove the map
  502. # from its register
  503. stds = self.get_new_stds_instance(row["id"])
  504. stds.metadata.select(dbif)
  505. statement += stds.unregister_map(self, dbif, False)
  506. # Take care to update the space time dataset after
  507. # the map has been unregistered
  508. if update == True and execute == True:
  509. stds.update_from_registered_maps(dbif)
  510. if execute:
  511. dbif.execute_transaction(statement)
  512. if connected:
  513. dbif.close()
  514. if execute:
  515. return ""
  516. return statement
  517. def get_registered_datasets(self, dbif=None):
  518. """!Return all space time dataset ids in which this map is registered as
  519. dictionary like rows with column "id" or None if this map is not
  520. registered in any space time dataset.
  521. @param dbif The database interface to be used
  522. @return The SQL rows with the ids of all space time datasets in which this map is registered
  523. """
  524. dbif, connected = init_dbif(dbif)
  525. rows = None
  526. try:
  527. if self.get_stds_register() is not None:
  528. # Select all stds tables in which this map is registered
  529. sql = "SELECT id FROM " + self.get_stds_register()
  530. dbif.cursor.execute(sql)
  531. rows = dbif.cursor.fetchall()
  532. except:
  533. core.error(_("Unable to select space time dataset register table "
  534. "<%s>") % (self.get_stds_register()))
  535. if connected:
  536. dbif.close()
  537. return rows