abstract_map_dataset.py 37 KB

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