abstract_map_dataset.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666
  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 ident 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 The mapset in which the map is located
  141. @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. """
  318. dbif, connected = init_dbif(dbif)
  319. self.set_absolute_time(start_time, end_time, timezone)
  320. self.absolute_time.update_all(dbif)
  321. self.base.update(dbif)
  322. if connected:
  323. dbif.close()
  324. self.write_timestamp_to_grass()
  325. def set_relative_time(self, start_time, end_time, unit):
  326. """!Set the relative time interval
  327. The end time is optional and must be set to None in case of time instance.
  328. This method only modifies this object and does not commit
  329. the modifications to the temporal database.
  330. @param start_time An integer value
  331. @param end_time An integer value, None in case or time instance
  332. @param unit The unit of the relative time. Supported units:
  333. year(s), month(s), day(s), hour(s), minute(s), second(s)
  334. @return True for success and False otherwise
  335. """
  336. if not self.check_relative_time_unit(unit):
  337. if self.get_layer() is not None:
  338. core.error(_("Unsupported relative time unit type for %s map "
  339. "<%s> with layer %s: %s") % (self.get_type(),
  340. self.get_id(),
  341. self.get_layer(),
  342. unit))
  343. else:
  344. core.error(_("Unsupported relative time unit type for %s map "
  345. "<%s>: %s") % (self.get_type(), self.get_id(),
  346. unit))
  347. return False
  348. if start_time is not None and end_time is not None:
  349. if int(start_time) > int(end_time):
  350. if self.get_layer() is not None:
  351. core.error(_("End time must be greater than start time for"
  352. " %s map <%s> with layer %s") % \
  353. (self.get_type(), self.get_id(),
  354. self.get_layer()))
  355. else:
  356. core.error(_("End time must be greater than start time for"
  357. " %s map <%s>") % (self.get_type(),
  358. self.get_id()))
  359. return False
  360. else:
  361. # Do not create an interval in case start and end time are equal
  362. if start_time == end_time:
  363. end_time = None
  364. self.base.set_ttype("relative")
  365. self.relative_time.set_unit(unit)
  366. self.relative_time.set_start_time(int(start_time))
  367. if end_time is not None:
  368. self.relative_time.set_end_time(int(end_time))
  369. else:
  370. self.relative_time.set_end_time(None)
  371. return True
  372. def update_relative_time(self, start_time, end_time, unit, dbif=None):
  373. """!Update the relative time interval
  374. The end time is optional and must be set to None in case of time instance.
  375. This functions assures that the timestamp is written to the
  376. grass file system based database in addition to the temporal database entry.
  377. @param start_time An integer value
  378. @param end_time An integer value, None in case or time instance
  379. @param dbif The database interface to be used
  380. """
  381. dbif, connected = init_dbif(dbif)
  382. if self.set_relative_time(start_time, end_time, unit):
  383. self.relative_time.update_all(dbif)
  384. self.base.update(dbif)
  385. if connected:
  386. dbif.close()
  387. self.write_timestamp_to_grass()
  388. def set_spatial_extent(self, north, south, east, west, top=0, bottom=0):
  389. """!Set the spatial extent of the map
  390. This method only modifies this object and does not commit
  391. the modifications to the temporal database.
  392. @param north The northern edge
  393. @param south The southern edge
  394. @param east The eastern edge
  395. @param west The western edge
  396. @param top The top edge
  397. @param bottom The bottom edge
  398. """
  399. self.spatial_extent.set_spatial_extent(
  400. north, south, east, west, top, bottom)
  401. def check_valid_time(self):
  402. """!Check for correct valid time"""
  403. if self.is_time_absolute():
  404. start, end, tz = self.get_absolute_time()
  405. else:
  406. start, end, unit = self.get_relative_time()
  407. if start is not None:
  408. if end is not None:
  409. if start >= end:
  410. if self.get_layer() is not None:
  411. core.error(_("Map <%s> with layer %s has incorrect "
  412. "time interval, start time is greater "
  413. "than end time") % (self.get_map_id(),
  414. self.get_layer()))
  415. else:
  416. core.error(_("Map <%s> has incorrect time interval, "
  417. "start time is greater than end time") % \
  418. (self.get_map_id()))
  419. return False
  420. else:
  421. core.error(_("Map <%s> has incorrect start time") %
  422. (self.get_map_id()))
  423. return False
  424. return True
  425. def delete(self, dbif=None, update=True, execute=True):
  426. """!Delete a map entry from database if it exists
  427. Remove dependent entries:
  428. * Remove the map entry in each space time dataset in which this map
  429. is registered
  430. * Remove the space time dataset register table
  431. @param dbif The database interface to be used
  432. @param update Call for each unregister statement the update from
  433. registered maps of the space time dataset.
  434. This can slow down the un-registration process significantly.
  435. @param execute If True the SQL DELETE and DROP table statements will
  436. be executed.
  437. If False the prepared SQL statements are
  438. returned and must be executed by the caller.
  439. @return The SQL statements if execute=False, else an empty string,
  440. None in case of a failure
  441. """
  442. dbif, connected = init_dbif(dbif)
  443. statement = ""
  444. if self.is_in_db(dbif):
  445. # SELECT all needed information from the database
  446. self.metadata.select(dbif)
  447. # First we unregister from all dependent space time datasets
  448. statement += self.unregister(
  449. dbif=dbif, update=update, execute=False)
  450. # Remove the strds register table
  451. if self.get_stds_register() is not None:
  452. statement += "DROP TABLE " + self.get_stds_register() + ";\n"
  453. # Commented because of performance issue calling g.message thousend times
  454. #core.verbose(_("Delete %s dataset <%s> from temporal database")
  455. # % (self.get_type(), self.get_id()))
  456. # Delete yourself from the database, trigger functions will
  457. # take care of dependencies
  458. statement += self.base.get_delete_statement()
  459. if execute:
  460. dbif.execute_transaction(statement)
  461. # Remove the timestamp from the file system
  462. self.remove_timestamp_from_grass()
  463. self.reset(None)
  464. if connected:
  465. dbif.close()
  466. if execute:
  467. return ""
  468. return statement
  469. def unregister(self, dbif=None, update=True, execute=True):
  470. """! Remove the map entry in each space time dataset in which this map
  471. is registered
  472. @param dbif The database interface to be used
  473. @param update Call for each unregister statement the update from
  474. registered maps of the space time dataset. This can
  475. slow down the un-registration process significantly.
  476. @param execute If True the SQL DELETE and DROP table statements
  477. will be executed.
  478. If False the prepared SQL statements are
  479. returned and must be executed by the caller.
  480. @return The SQL statements if execute=False, else an empty string
  481. """
  482. # Commented because of performance issue calling g.message thousend times
  483. #if self.get_layer() is not None:
  484. # core.verbose(_("Unregister %(type)s map <%(map)s> with "
  485. # "layer %(layer)s from space time datasets" % \
  486. # {'type':self.get_type(), 'map':self.get_map_id(),
  487. # 'layer':self.get_layer()}))
  488. #else:
  489. # core.verbose(_("Unregister %(type)s map <%(map)s> "
  490. # "from space time datasets"
  491. # % {'type':self.get_type(), 'map':self.get_map_id()}))
  492. statement = ""
  493. dbif, connected = init_dbif(dbif)
  494. # Get all datasets in which this map is registered
  495. rows = self.get_registered_datasets(dbif)
  496. # For each stds in which the map is registered
  497. if rows is not None:
  498. for row in rows:
  499. # Create a space time dataset object to remove the map
  500. # from its register
  501. stds = self.get_new_stds_instance(row["id"])
  502. stds.metadata.select(dbif)
  503. statement += stds.unregister_map(self, dbif, False)
  504. # Take care to update the space time dataset after
  505. # the map has been unregistered
  506. if update == True and execute == True:
  507. stds.update_from_registered_maps(dbif)
  508. if execute:
  509. dbif.execute_transaction(statement)
  510. if connected:
  511. dbif.close()
  512. if execute:
  513. return ""
  514. return statement
  515. def get_registered_datasets(self, dbif=None):
  516. """!Return all space time dataset ids in which this map is registered as
  517. dictionary like rows with column "id" or None if this map is not
  518. registered in any space time dataset.
  519. @param dbif The database interface to be used
  520. @return The SQL rows with the ids of all space time datasets in which this map is registered
  521. """
  522. dbif, connected = init_dbif(dbif)
  523. rows = None
  524. try:
  525. if self.get_stds_register() is not None:
  526. # Select all stds tables in which this map is registered
  527. sql = "SELECT id FROM " + self.get_stds_register()
  528. dbif.cursor.execute(sql)
  529. rows = dbif.cursor.fetchall()
  530. except:
  531. core.error(_("Unable to select space time dataset register table "
  532. "<%s>") % (self.get_stds_register()))
  533. if connected:
  534. dbif.close()
  535. return rows