abstract_map_dataset.py 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921
  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. (C) 2008-2011 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. @author Soeren Gebbert
  10. """
  11. from abstract_dataset import *
  12. from datetime_math import *
  13. class AbstractMapDataset(AbstractDataset):
  14. """!This is the base class for all maps (raster, vector, raster3d).
  15. The temporal extent, the spatial extent and the metadata of maps
  16. are stored in the temporal database. Maps can be registered in the
  17. temporal database, updated and deleted.
  18. This class provides all functionalities that are needed to manage maps
  19. in the temporal database. That are:
  20. - insert() to register the map and therefore its spatio-temporal extent
  21. and metadata in the temporal database
  22. - update() to update the map spatio-temporal extent and metadata in the
  23. temporal database
  24. - unregister() to unregister the map from each space time dataset in
  25. 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
  29. subclasses
  30. """
  31. __metaclass__ = ABCMeta
  32. def __init__(self):
  33. AbstractDataset.__init__(self)
  34. @abstractmethod
  35. def get_new_stds_instance(self, ident):
  36. """!Return a new space time dataset instance that store maps with the
  37. type of this map object (rast, rast3d or vect)
  38. @param ident The identifier of the space time dataset
  39. @return The new space time dataset instance
  40. """
  41. @abstractmethod
  42. def get_stds_register(self):
  43. """!Return the space time dataset register table name
  44. Maps can be registered in several different space time datasets.
  45. This method returns the name of the register table in the
  46. temporal database.
  47. @return The name of the stds register table
  48. """
  49. @abstractmethod
  50. def set_stds_register(self, name):
  51. """!Set the space time dataset register table name.
  52. This table stores all space time datasets in
  53. which this map is registered.
  54. @param name The name of the register table
  55. """
  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
  64. directly.
  65. @return "finer" or "coarser"
  66. """
  67. raise ImplementationError(
  68. "This method must be implemented in the subclasses")
  69. @abstractmethod
  70. def has_grass_timestamp(self):
  71. """!Check if a grass file based time stamp exists for this map.
  72. @return True is the grass file based time stamped exists for this
  73. map
  74. """
  75. @abstractmethod
  76. def write_timestamp_to_grass(self):
  77. """!Write the timestamp of this map into the map metadata
  78. in the grass file system based spatial database.
  79. """
  80. @abstractmethod
  81. def remove_timestamp_from_grass(self):
  82. """!Remove the timestamp from the grass file
  83. system based spatial database
  84. """
  85. @abstractmethod
  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. @abstractmethod
  91. def read_info(self):
  92. """!Read the map info from the grass file system based database and
  93. store the content into a dictionary
  94. """
  95. @abstractmethod
  96. def load(self):
  97. """!Load the content of this object from the grass
  98. file system based database"""
  99. def _convert_timestamp(self):
  100. """!Convert the valid time into a grass datetime library
  101. compatible timestamp string
  102. This methods works for relative and absolute time
  103. @return the grass timestamp string
  104. """
  105. start = ""
  106. if self.is_time_absolute():
  107. start_time, end_time, tz = self.get_absolute_time()
  108. start = datetime_to_grass_datetime_string(start_time)
  109. if end_time is not None:
  110. end = datetime_to_grass_datetime_string(end_time)
  111. start += " / %s" % (end)
  112. else:
  113. start_time, end_time, unit = self.get_relative_time()
  114. start = "%i %s" % (int(start_time), unit)
  115. if end_time is not None:
  116. end = "%i %s" % (int(end_time), unit)
  117. start += " / %s" % (end)
  118. return start
  119. def get_map_id(self):
  120. """!Return the map id. The map id is the unique identifier
  121. in grass and must not be equal to the
  122. primary key identifier (id) of the map in the database.
  123. Since vector maps may have layer information,
  124. the unique id is a combination of name, layer and mapset.
  125. Use get_map_id() every time your need to access the grass map
  126. in the file system but not to identify
  127. map information in the temporal database.
  128. @return The map id "name@mapset"
  129. """
  130. return self.base.get_map_id()
  131. def build_id(self, name, mapset, layer=None):
  132. """!Convenient method to build the unique identifier
  133. Existing layer and mapset definitions in the name
  134. string will be reused
  135. @param name The name of the map
  136. @param mapset The mapset in which the map is located
  137. @param layer The layer of the vector map, use None in case no
  138. layer exists
  139. @return the id of the map as "name(:layer)@mapset"
  140. while layer is optional
  141. """
  142. # Check if the name includes any mapset
  143. if name.find("@") >= 0:
  144. name, mapset = name.split("@")
  145. # Check for layer number in map name
  146. if name.find(":") >= 0:
  147. name, layer = name.split(":")
  148. if layer is not None:
  149. return "%s:%s@%s" % (name, layer, mapset)
  150. else:
  151. return "%s@%s" % (name, mapset)
  152. def get_layer(self):
  153. """!Return the layer of the map
  154. @return the layer of the map or None in case no layer is defined
  155. """
  156. return self.base.get_layer()
  157. def print_self(self):
  158. """!Print the content of the internal structure to stdout"""
  159. self.base.print_self()
  160. self.temporal_extent.print_self()
  161. self.spatial_extent.print_self()
  162. self.metadata.print_self()
  163. def print_info(self):
  164. """!Print information about this object in human readable style"""
  165. if self.get_type() == "raster":
  166. # 1 2 3 4 5 6 7
  167. # 0123456789012345678901234567890123456789012345678901234567890123456789012345678
  168. print " +-------------------- Raster Dataset ----------------------------------------+"
  169. if self.get_type() == "raster3d":
  170. # 1 2 3 4 5 6 7
  171. # 0123456789012345678901234567890123456789012345678901234567890123456789012345678
  172. print " +-------------------- 3D Raster Dataset -------------------------------------+"
  173. if self.get_type() == "vector":
  174. # 1 2 3 4 5 6 7
  175. # 0123456789012345678901234567890123456789012345678901234567890123456789012345678
  176. print " +-------------------- Vector Dataset ----------------------------------------+"
  177. print " | |"
  178. self.base.print_info()
  179. self.temporal_extent.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. self.temporal_extent.print_shell_info()
  203. self.spatial_extent.print_shell_info()
  204. self.metadata.print_shell_info()
  205. datasets = self.get_registered_datasets()
  206. count = 0
  207. string = ""
  208. if datasets is not None:
  209. for ds in datasets:
  210. if count == 0:
  211. string += ds["id"]
  212. else:
  213. string += ",%s" % ds["id"]
  214. count += 1
  215. print "registered_datasets=" + string
  216. if self.is_topology_build():
  217. self.print_topology_shell_info()
  218. def insert(self, dbif=None, execute=True):
  219. """!Insert the map content into the database from the internal
  220. structure
  221. This functions assures that the timestamp is written to the
  222. grass file system based database in addition to the temporal
  223. database entry.
  224. @param dbif The database interface to be used
  225. @param execute If True the SQL statements will be executed.
  226. If False the prepared SQL statements are
  227. returned and must be executed by the caller.
  228. @return The SQL insert statement in case execute=False, or an
  229. 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
  238. database entry.
  239. @param dbif The database interface to be used
  240. @param execute If True the SQL statements will be executed.
  241. If False the prepared SQL statements are
  242. returned and must be executed by the caller.
  243. @return The SQL insert statement in case execute=False, or an
  244. empty string otherwise
  245. """
  246. self.write_timestamp_to_grass()
  247. return AbstractDataset.update(self, dbif, execute)
  248. def update_all(self, dbif=None, execute=True):
  249. """!Update the map content in the database from the internal structure
  250. including None variables
  251. This functions assures that the timestamp is written to the
  252. grass file system based database in addition to the temporal
  253. database entry.
  254. @param dbif The database interface to be used
  255. @param execute If True the SQL statements will be executed.
  256. If False the prepared SQL statements are
  257. returned and must be executed by the caller.
  258. @return The SQL insert statement in case execute=False, or an
  259. empty string otherwise
  260. """
  261. self.write_timestamp_to_grass()
  262. return AbstractDataset.update_all(self, dbif, execute)
  263. def set_time_to_absolute(self):
  264. """!Set the temporal type to absolute"""
  265. self.base.set_ttype("absolute")
  266. def set_time_to_relative(self):
  267. """!Set the temporal type to relative"""
  268. self.base.set_ttype("relative")
  269. def set_absolute_time(self, start_time, end_time=None, timezone=None):
  270. """!Set the absolute time with start time and end time
  271. The end time is optional and must be set to None in case of time
  272. instance.
  273. This method only modifies this object and does not commit
  274. the modifications to the temporal database.
  275. @param start_time a datetime object specifying the start time of the
  276. map
  277. @param end_time a datetime object specifying the end time of the
  278. map, None in case or time instance
  279. @param timezone Thee timezone of the map (not used)
  280. """
  281. if start_time and not isinstance(start_time, datetime):
  282. if self.get_layer() is not None:
  283. core.fatal(_("Start time must be of type datetime for %(type)s"
  284. " map <%(id)s> with layer: %(l)s") % {
  285. 'type': self.get_type(), 'id': self.get_map_id(),
  286. 'l': self.get_layer()})
  287. else:
  288. core.fatal(_("Start time must be of type datetime for "
  289. "%(type)s map <%(id)s>") % {
  290. 'type': self.get_type(), 'id': self.get_map_id()})
  291. if end_time and not isinstance(end_time, datetime):
  292. if self.get_layer():
  293. core.fatal(_("End time must be of type datetime for %(type)s "
  294. "map <%(id)s> with layer: %(l)s") % {
  295. 'type': self.get_type(), 'id': self.get_map_id(),
  296. 'l': self.get_layer()})
  297. else:
  298. core.fatal(_("End time must be of type datetime for "
  299. "%(type)s map <%(id)s>") % {
  300. 'type': self.get_type(), 'id': self.get_map_id()})
  301. if start_time is not None and end_time is not None:
  302. if start_time > end_time:
  303. if self.get_layer():
  304. core.fatal(_("End time must be greater than start time for"
  305. " %(type)s map <%(id)s> with layer: %(l)s") % {
  306. 'type': self.get_type(),
  307. 'id': self.get_map_id(),
  308. 'l': self.get_layer()})
  309. else:
  310. core.fatal(_("End time must be greater than start time "
  311. "for %(type)s map <%(id)s>") % {
  312. 'type': self.get_type(),
  313. 'id': self.get_map_id()})
  314. else:
  315. # Do not create an interval in case start and end time are
  316. # equal
  317. if start_time == end_time:
  318. end_time = None
  319. self.base.set_ttype("absolute")
  320. self.absolute_time.set_start_time(start_time)
  321. self.absolute_time.set_end_time(end_time)
  322. self.absolute_time.set_timezone(timezone)
  323. return True
  324. def update_absolute_time(self, start_time, end_time=None,
  325. timezone=None, dbif=None):
  326. """!Update the absolute time
  327. The end time is optional and must be set to None in case of time
  328. instance.
  329. This functions assures that the timestamp is written to the
  330. grass file system based database in addition to the temporal
  331. database entry.
  332. @param start_time a datetime object specifying the start time of
  333. the map
  334. @param end_time a datetime object specifying the end time of the
  335. map, None in case or time instance
  336. @param timezone Thee timezone of the map (not used)
  337. @param dbif The database interface to be used
  338. """
  339. dbif, connected = init_dbif(dbif)
  340. self.set_absolute_time(start_time, end_time, timezone)
  341. self.absolute_time.update_all(dbif)
  342. self.base.update(dbif)
  343. if connected:
  344. dbif.close()
  345. self.write_timestamp_to_grass()
  346. def set_relative_time(self, start_time, end_time, unit):
  347. """!Set the relative time interval
  348. The end time is optional and must be set to None in case of time
  349. instance.
  350. This method only modifies this object and does not commit
  351. the modifications to the temporal database.
  352. @param start_time An integer value
  353. @param end_time An integer value, None in case or time instance
  354. @param unit The unit of the relative time. Supported units:
  355. year(s), month(s), day(s), hour(s), minute(s), second(s)
  356. @return True for success and False otherwise
  357. """
  358. if not self.check_relative_time_unit(unit):
  359. if self.get_layer() is not None:
  360. core.error(_("Unsupported relative time unit type for %(type)s"
  361. " map <%(id)s> with layer %(l)s: %(u)s") % {
  362. 'type': self.get_type(), 'id': self.get_id(),
  363. 'l': self.get_layer(), 'u': unit})
  364. else:
  365. core.error(_("Unsupported relative time unit type for %(type)s"
  366. " map <%(id)s>: %(u)s") % {
  367. 'type': self.get_type(), 'id': self.get_id(),
  368. 'u': unit})
  369. return False
  370. if start_time is not None and end_time is not None:
  371. if int(start_time) > int(end_time):
  372. if self.get_layer() is not None:
  373. core.error(_("End time must be greater than start time for"
  374. " %(type)s map <%(id)s> with layer %(l)s") % \
  375. {'type': self.get_type(), 'id': self.get_id(),
  376. 'l': self.get_layer()})
  377. else:
  378. core.error(_("End time must be greater than start time for"
  379. " %(type)s map <%(id)s>") % {
  380. 'type': self.get_type(), 'id': self.get_id()})
  381. return False
  382. else:
  383. # Do not create an interval in case start and end time are
  384. # equal
  385. if start_time == end_time:
  386. end_time = None
  387. self.base.set_ttype("relative")
  388. self.relative_time.set_unit(unit)
  389. self.relative_time.set_start_time(int(start_time))
  390. if end_time is not None:
  391. self.relative_time.set_end_time(int(end_time))
  392. else:
  393. self.relative_time.set_end_time(None)
  394. return True
  395. def update_relative_time(self, start_time, end_time, unit, dbif=None):
  396. """!Update the relative time interval
  397. The end time is optional and must be set to None in case of time
  398. instance.
  399. This functions assures that the timestamp is written to the
  400. grass file system based database in addition to the temporal
  401. database entry.
  402. @param start_time An integer value
  403. @param end_time An integer value, None in case or time instance
  404. @param unit The relative time unit
  405. @param dbif The database interface to be used
  406. """
  407. dbif, connected = init_dbif(dbif)
  408. if self.set_relative_time(start_time, end_time, unit):
  409. self.relative_time.update_all(dbif)
  410. self.base.update(dbif)
  411. if connected:
  412. dbif.close()
  413. self.write_timestamp_to_grass()
  414. def set_temporal_extent(self, temporal_extent):
  415. """!Convenient method to set the temporal extent from a temporal extent object
  416. @param temporal_extent The temporal axtent that should be set for this object
  417. @code
  418. >>> import datetime
  419. >>> import grass.temporal as tgis
  420. >>> map = tgis.RasterDataset(None)
  421. >>> temp_ext = tgis.RelativeTemporalExtent(start_time=1, end_time=2, unit="years")
  422. >>> map.set_temporal_extent(temp_ext)
  423. >>> print map.get_temporal_extent_as_tuple()
  424. (1, 2)
  425. >>> map = tgis.VectorDataset(None)
  426. >>> temp_ext = tgis.AbsoluteTemporalExtent(start_time=datetime.datetime(2000, 1, 1),
  427. ... end_time=datetime.datetime(2001, 1, 1))
  428. >>> map.set_temporal_extent(temp_ext)
  429. >>> print map.get_temporal_extent_as_tuple()
  430. (datetime.datetime(2000, 1, 1, 0, 0), datetime.datetime(2001, 1, 1, 0, 0))
  431. @endcode
  432. """
  433. if issubclass(RelativeTemporalExtent, type(temporal_extent)):
  434. start = temporal_extent.get_start_time()
  435. end = temporal_extent.get_end_time()
  436. unit = temporal_extent.get_unit()
  437. self.set_relative_time(start, end, unit)
  438. elif issubclass(AbsoluteTemporalExtent, type(temporal_extent)):
  439. start = temporal_extent.get_start_time()
  440. end = temporal_extent.get_end_time()
  441. tz = temporal_extent.get_timezone()
  442. self.set_absolute_time(start, end, tz)
  443. def temporal_buffer(self, increment, update=False, dbif=None):
  444. """!Create a temporal buffer based on an increment
  445. For absolute time the increment must be a string of type "integer
  446. unit"
  447. Unit can be year, years, month, months, day, days, hour, hours,
  448. minute, minutes, day or days.
  449. @param increment This is the increment, a string in case of absolute
  450. time or an integer in case of relative time
  451. @param update Perform an immediate database update to store the
  452. modified temporal extent, otherwise only this object
  453. will be modified
  454. Usage:
  455. @code
  456. >>> import grass.temporal as tgis
  457. >>> maps = []
  458. >>> for i in range(5):
  459. ... map = tgis.RasterDataset(None)
  460. ... if i%2 == 0:
  461. ... check = map.set_relative_time(i, i + 1, 'years')
  462. ... else:
  463. ... check = map.set_relative_time(i, None, 'years')
  464. ... map.temporal_buffer(3)
  465. ... maps.append(map)
  466. >>> for map in maps:
  467. ... map.temporal_extent.print_info()
  468. +-------------------- Relative time -----------------------------------------+
  469. | Start time:................. -3
  470. | End time:................... 4
  471. | Relative time unit:......... years
  472. +-------------------- Relative time -----------------------------------------+
  473. | Start time:................. -2
  474. | End time:................... 4
  475. | Relative time unit:......... years
  476. +-------------------- Relative time -----------------------------------------+
  477. | Start time:................. -1
  478. | End time:................... 6
  479. | Relative time unit:......... years
  480. +-------------------- Relative time -----------------------------------------+
  481. | Start time:................. 0
  482. | End time:................... 6
  483. | Relative time unit:......... years
  484. +-------------------- Relative time -----------------------------------------+
  485. | Start time:................. 1
  486. | End time:................... 8
  487. | Relative time unit:......... years
  488. >>> maps = []
  489. >>> for i in range(1,5):
  490. ... map = tgis.RasterDataset(None)
  491. ... if i%2 == 0:
  492. ... check = map.set_absolute_time(datetime(2001,i,1), datetime(2001, i + 1, 1))
  493. ... else:
  494. ... check = map.set_absolute_time(datetime(2001,i,1), None)
  495. ... map.temporal_buffer("7 days")
  496. ... maps.append(map)
  497. >>> for map in maps:
  498. ... map.temporal_extent.print_info()
  499. +-------------------- Absolute time -----------------------------------------+
  500. | Start time:................. 2000-12-25 00:00:00
  501. | End time:................... 2001-01-08 00:00:00
  502. +-------------------- Absolute time -----------------------------------------+
  503. | Start time:................. 2001-01-25 00:00:00
  504. | End time:................... 2001-03-08 00:00:00
  505. +-------------------- Absolute time -----------------------------------------+
  506. | Start time:................. 2001-02-22 00:00:00
  507. | End time:................... 2001-03-08 00:00:00
  508. +-------------------- Absolute time -----------------------------------------+
  509. | Start time:................. 2001-03-25 00:00:00
  510. | End time:................... 2001-05-08 00:00:00
  511. @endcode
  512. """
  513. if self.is_time_absolute():
  514. start, end, tz = self.get_absolute_time()
  515. new_start = decrement_datetime_by_string(start, increment)
  516. if end == None:
  517. new_end = increment_datetime_by_string(start, increment)
  518. else:
  519. new_end = increment_datetime_by_string(end, increment)
  520. if update:
  521. self.update_absolute_time(new_start, new_end, tz, dbif=dbif)
  522. else:
  523. self.set_absolute_time(new_start, new_end, tz)
  524. else:
  525. start, end, unit = self.get_relative_time()
  526. new_start = start - increment
  527. if end == None:
  528. new_end = start + increment
  529. else:
  530. new_end = end + increment
  531. if update:
  532. self.update_relative_time(new_start, new_end, unit, dbif=dbif)
  533. else:
  534. self.set_relative_time(new_start, new_end, unit)
  535. def set_spatial_extent_from_values(self, north, south, east, west, top=0, bottom=0):
  536. """!Set the spatial extent of the map from values
  537. This method only modifies this object and does not commit
  538. the modifications to the temporal database.
  539. @param north The northern edge
  540. @param south The southern edge
  541. @param east The eastern edge
  542. @param west The western edge
  543. @param top The top edge
  544. @param bottom The bottom edge
  545. """
  546. self.spatial_extent.set_spatial_extent_from_values(
  547. north, south, east, west, top, bottom)
  548. def set_spatial_extent(self, spatial_extent):
  549. """!Set the spatial extent of the map
  550. This method only modifies this object and does not commit
  551. the modifications to the temporal database.
  552. @param spatial_extent An object of type SpatialExtent or its subclasses
  553. @code
  554. >>> import datetime
  555. >>> import grass.temporal as tgis
  556. >>> map = tgis.RasterDataset(None)
  557. >>> spat_ext = tgis.SpatialExtent(north=10, south=-10, east=20, west=-20, top=5, bottom=-5)
  558. >>> map.set_spatial_extent(spat_ext)
  559. >>> print map.get_spatial_extent_as_tuple()
  560. (10.0, -10.0, 20.0, -20.0, 5.0, -5.0)
  561. @endcode
  562. """
  563. self.spatial_extent.set_spatial_extent(spatial_extent)
  564. def spatial_buffer(self, size, update=False, dbif=None):
  565. """!Buffer the spatial extent by a given size in all
  566. spatial directions.
  567. @param size The buffer size, using the unit of the grass region
  568. @code
  569. >>> import grass.temporal as tgis
  570. >>> map = tgis.RasterDataset(None)
  571. >>> spat_ext = tgis.SpatialExtent(north=10, south=-10, east=20, west=-20, top=5, bottom=-5)
  572. >>> map.set_spatial_extent(spat_ext)
  573. >>> map.spatial_buffer(10)
  574. >>> print map.get_spatial_extent_as_tuple()
  575. (20.0, -20.0, 30.0, -30.0, 15.0, -15.0)
  576. @endcode
  577. """
  578. self.spatial_extent.north += size
  579. self.spatial_extent.south -= size
  580. self.spatial_extent.east += size
  581. self.spatial_extent.west -= size
  582. self.spatial_extent.top += size
  583. self.spatial_extent.bottom -= size
  584. if update:
  585. self.spatial_extent.update(dbif)
  586. def spatial_buffer_2d(self, size, update=False, dbif=None):
  587. """!Buffer the spatial extent by a given size in 2d
  588. spatial directions.
  589. @param size The buffer size, using the unit of the grass region
  590. @code
  591. >>> import grass.temporal as tgis
  592. >>> map = tgis.RasterDataset(None)
  593. >>> spat_ext = tgis.SpatialExtent(north=10, south=-10, east=20, west=-20, top=5, bottom=-5)
  594. >>> map.set_spatial_extent(spat_ext)
  595. >>> map.spatial_buffer_2d(10)
  596. >>> print map.get_spatial_extent_as_tuple()
  597. (20.0, -20.0, 30.0, -30.0, 5.0, -5.0)
  598. @endcode
  599. """
  600. self.spatial_extent.north += size
  601. self.spatial_extent.south -= size
  602. self.spatial_extent.east += size
  603. self.spatial_extent.west -= size
  604. if update:
  605. self.spatial_extent.update(dbif)
  606. def check_for_correct_time(self):
  607. """!Check for correct time"""
  608. if self.is_time_absolute():
  609. start, end, tz = self.get_absolute_time()
  610. else:
  611. start, end, unit = self.get_relative_time()
  612. if start is not None:
  613. if end is not None:
  614. if start >= end:
  615. if self.get_layer() is not None:
  616. core.error(_("Map <%(id)s> with layer %(layer)s has "
  617. "incorrect time interval, start time is "
  618. "greater than end time") % {
  619. 'id': self.get_map_id(),
  620. 'layer': self.get_layer()})
  621. else:
  622. core.error(_("Map <%s> has incorrect time interval, "
  623. "start time is greater than end time") % \
  624. (self.get_map_id()))
  625. return False
  626. else:
  627. core.error(_("Map <%s> has incorrect start time") %
  628. (self.get_map_id()))
  629. return False
  630. return True
  631. def delete(self, dbif=None, update=True, execute=True):
  632. """!Delete a map entry from database if it exists
  633. Remove dependent entries:
  634. * Remove the map entry in each space time dataset in which this map
  635. is registered
  636. * Remove the space time dataset register table
  637. @param dbif The database interface to be used
  638. @param update Call for each unregister statement the update from
  639. registered maps of the space time dataset.
  640. This can slow down the un-registration process
  641. significantly.
  642. @param execute If True the SQL DELETE and DROP table statements will
  643. be executed.
  644. If False the prepared SQL statements are
  645. returned and must be executed by the caller.
  646. @return The SQL statements if execute=False, else an empty string,
  647. None in case of a failure
  648. """
  649. dbif, connected = init_dbif(dbif)
  650. statement = ""
  651. if self.is_in_db(dbif):
  652. # SELECT all needed information from the database
  653. self.metadata.select(dbif)
  654. # First we unregister from all dependent space time datasets
  655. statement += self.unregister(
  656. dbif=dbif, update=update, execute=False)
  657. # Remove the strds register table
  658. if self.get_stds_register() is not None:
  659. statement += "DROP TABLE " + self.get_stds_register() + ";\n"
  660. # Commented because of performance issue calling g.message thousend times
  661. #core.verbose(_("Delete %s dataset <%s> from temporal database")
  662. # % (self.get_type(), self.get_id()))
  663. # Delete yourself from the database, trigger functions will
  664. # take care of dependencies
  665. statement += self.base.get_delete_statement()
  666. if execute:
  667. dbif.execute_transaction(statement)
  668. # Remove the timestamp from the file system
  669. self.remove_timestamp_from_grass()
  670. self.reset(None)
  671. if connected:
  672. dbif.close()
  673. if execute:
  674. return ""
  675. return statement
  676. def unregister(self, dbif=None, update=True, execute=True):
  677. """! Remove the map entry in each space time dataset in which this map
  678. is registered
  679. @param dbif The database interface to be used
  680. @param update Call for each unregister statement the update from
  681. registered maps of the space time dataset. This can
  682. slow down the un-registration process significantly.
  683. @param execute If True the SQL DELETE and DROP table statements
  684. will be executed.
  685. If False the prepared SQL statements are
  686. returned and must be executed by the caller.
  687. @return The SQL statements if execute=False, else an empty string
  688. """
  689. # Commented because of performance issue calling g.message thousend times
  690. #if self.get_layer() is not None:
  691. # core.verbose(_("Unregister %(type)s map <%(map)s> with "
  692. # "layer %(layer)s from space time datasets" % \
  693. # {'type':self.get_type(), 'map':self.get_map_id(),
  694. # 'layer':self.get_layer()}))
  695. #else:
  696. # core.verbose(_("Unregister %(type)s map <%(map)s> "
  697. # "from space time datasets"
  698. # % {'type':self.get_type(), 'map':self.get_map_id()}))
  699. statement = ""
  700. dbif, connected = init_dbif(dbif)
  701. # Get all datasets in which this map is registered
  702. rows = self.get_registered_datasets(dbif)
  703. # For each stds in which the map is registered
  704. if rows is not None:
  705. for row in rows:
  706. # Create a space time dataset object to remove the map
  707. # from its register
  708. stds = self.get_new_stds_instance(row["id"])
  709. stds.metadata.select(dbif)
  710. statement += stds.unregister_map(self, dbif, False)
  711. # Take care to update the space time dataset after
  712. # the map has been unregistered
  713. if update == True and execute == True:
  714. stds.update_from_registered_maps(dbif)
  715. if execute:
  716. dbif.execute_transaction(statement)
  717. if connected:
  718. dbif.close()
  719. if execute:
  720. return ""
  721. return statement
  722. def get_registered_datasets(self, dbif=None):
  723. """!Return all space time dataset ids in which this map is registered
  724. as dictionary like rows with column "id" or None if this map is not
  725. registered in any space time dataset.
  726. @param dbif The database interface to be used
  727. @return The SQL rows with the ids of all space time datasets in
  728. which this map is registered
  729. """
  730. dbif, connected = init_dbif(dbif)
  731. rows = None
  732. try:
  733. if self.get_stds_register() is not None:
  734. # Select all stds tables in which this map is registered
  735. sql = "SELECT id FROM " + self.get_stds_register()
  736. dbif.cursor.execute(sql)
  737. rows = dbif.cursor.fetchall()
  738. except:
  739. core.error(_("Unable to select space time dataset register table "
  740. "<%s>") % (self.get_stds_register()))
  741. if connected:
  742. dbif.close()
  743. return rows
  744. ###############################################################################
  745. if __name__ == "__main__":
  746. import doctest
  747. doctest.testmod()