abstract_map_dataset.py 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932
  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, extent):
  415. """!Convenient method to set the temporal extent from a temporal extent object
  416. @param temporal_extent The temporal extent 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.RasterRelativeTime(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.VectorAbsoluteTime(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. >>> map1 = tgis.VectorDataset("A@P")
  432. >>> check = map1.set_absolute_time(datetime.datetime(2000,5,5), datetime.datetime(2005,6,6), None)
  433. >>> print map1.get_temporal_extent_as_tuple()
  434. (datetime.datetime(2000, 5, 5, 0, 0), datetime.datetime(2005, 6, 6, 0, 0))
  435. >>> map2 = tgis.RasterDataset("B@P")
  436. >>> check = map2.set_absolute_time(datetime.datetime(1990,1,1), datetime.datetime(1999,8,1), None)
  437. >>> print map2.get_temporal_extent_as_tuple()
  438. (datetime.datetime(1990, 1, 1, 0, 0), datetime.datetime(1999, 8, 1, 0, 0))
  439. >>> map2.set_temporal_extent(map1.get_temporal_extent())
  440. >>> print map2.get_temporal_extent_as_tuple()
  441. (datetime.datetime(2000, 5, 5, 0, 0), datetime.datetime(2005, 6, 6, 0, 0))
  442. @endcode
  443. """
  444. if issubclass(type(extent), RelativeTemporalExtent):
  445. start = extent.get_start_time()
  446. end = extent.get_end_time()
  447. unit = extent.get_unit()
  448. self.set_relative_time(start, end, unit)
  449. elif issubclass(type(extent), AbsoluteTemporalExtent):
  450. start = extent.get_start_time()
  451. end = extent.get_end_time()
  452. tz = extent.get_timezone()
  453. self.set_absolute_time(start, end, tz)
  454. def temporal_buffer(self, increment, update=False, dbif=None):
  455. """!Create a temporal buffer based on an increment
  456. For absolute time the increment must be a string of type "integer
  457. unit"
  458. Unit can be year, years, month, months, day, days, hour, hours,
  459. minute, minutes, day or days.
  460. @param increment This is the increment, a string in case of absolute
  461. time or an integer in case of relative time
  462. @param update Perform an immediate database update to store the
  463. modified temporal extent, otherwise only this object
  464. will be modified
  465. Usage:
  466. @code
  467. >>> import grass.temporal as tgis
  468. >>> maps = []
  469. >>> for i in range(5):
  470. ... map = tgis.RasterDataset(None)
  471. ... if i%2 == 0:
  472. ... check = map.set_relative_time(i, i + 1, 'years')
  473. ... else:
  474. ... check = map.set_relative_time(i, None, 'years')
  475. ... map.temporal_buffer(3)
  476. ... maps.append(map)
  477. >>> for map in maps:
  478. ... map.temporal_extent.print_info()
  479. +-------------------- Relative time -----------------------------------------+
  480. | Start time:................. -3
  481. | End time:................... 4
  482. | Relative time unit:......... years
  483. +-------------------- Relative time -----------------------------------------+
  484. | Start time:................. -2
  485. | End time:................... 4
  486. | Relative time unit:......... years
  487. +-------------------- Relative time -----------------------------------------+
  488. | Start time:................. -1
  489. | End time:................... 6
  490. | Relative time unit:......... years
  491. +-------------------- Relative time -----------------------------------------+
  492. | Start time:................. 0
  493. | End time:................... 6
  494. | Relative time unit:......... years
  495. +-------------------- Relative time -----------------------------------------+
  496. | Start time:................. 1
  497. | End time:................... 8
  498. | Relative time unit:......... years
  499. >>> maps = []
  500. >>> for i in range(1,5):
  501. ... map = tgis.RasterDataset(None)
  502. ... if i%2 == 0:
  503. ... check = map.set_absolute_time(datetime(2001,i,1), datetime(2001, i + 1, 1))
  504. ... else:
  505. ... check = map.set_absolute_time(datetime(2001,i,1), None)
  506. ... map.temporal_buffer("7 days")
  507. ... maps.append(map)
  508. >>> for map in maps:
  509. ... map.temporal_extent.print_info()
  510. +-------------------- Absolute time -----------------------------------------+
  511. | Start time:................. 2000-12-25 00:00:00
  512. | End time:................... 2001-01-08 00:00:00
  513. +-------------------- Absolute time -----------------------------------------+
  514. | Start time:................. 2001-01-25 00:00:00
  515. | End time:................... 2001-03-08 00:00:00
  516. +-------------------- Absolute time -----------------------------------------+
  517. | Start time:................. 2001-02-22 00:00:00
  518. | End time:................... 2001-03-08 00:00:00
  519. +-------------------- Absolute time -----------------------------------------+
  520. | Start time:................. 2001-03-25 00:00:00
  521. | End time:................... 2001-05-08 00:00:00
  522. @endcode
  523. """
  524. if self.is_time_absolute():
  525. start, end, tz = self.get_absolute_time()
  526. new_start = decrement_datetime_by_string(start, increment)
  527. if end == None:
  528. new_end = increment_datetime_by_string(start, increment)
  529. else:
  530. new_end = increment_datetime_by_string(end, increment)
  531. if update:
  532. self.update_absolute_time(new_start, new_end, tz, dbif=dbif)
  533. else:
  534. self.set_absolute_time(new_start, new_end, tz)
  535. else:
  536. start, end, unit = self.get_relative_time()
  537. new_start = start - increment
  538. if end == None:
  539. new_end = start + increment
  540. else:
  541. new_end = end + increment
  542. if update:
  543. self.update_relative_time(new_start, new_end, unit, dbif=dbif)
  544. else:
  545. self.set_relative_time(new_start, new_end, unit)
  546. def set_spatial_extent_from_values(self, north, south, east, west, top=0, bottom=0):
  547. """!Set the spatial extent of the map from values
  548. This method only modifies this object and does not commit
  549. the modifications to the temporal database.
  550. @param north The northern edge
  551. @param south The southern edge
  552. @param east The eastern edge
  553. @param west The western edge
  554. @param top The top edge
  555. @param bottom The bottom edge
  556. """
  557. self.spatial_extent.set_spatial_extent_from_values(
  558. north, south, east, west, top, bottom)
  559. def set_spatial_extent(self, spatial_extent):
  560. """!Set the spatial extent of the map
  561. This method only modifies this object and does not commit
  562. the modifications to the temporal database.
  563. @param spatial_extent An object of type SpatialExtent or its subclasses
  564. @code
  565. >>> import datetime
  566. >>> import grass.temporal as tgis
  567. >>> map = tgis.RasterDataset(None)
  568. >>> spat_ext = tgis.SpatialExtent(north=10, south=-10, east=20, west=-20, top=5, bottom=-5)
  569. >>> map.set_spatial_extent(spat_ext)
  570. >>> print map.get_spatial_extent_as_tuple()
  571. (10.0, -10.0, 20.0, -20.0, 5.0, -5.0)
  572. @endcode
  573. """
  574. self.spatial_extent.set_spatial_extent(spatial_extent)
  575. def spatial_buffer(self, size, update=False, dbif=None):
  576. """!Buffer the spatial extent by a given size in all
  577. spatial directions.
  578. @param size The buffer size, using the unit of the grass region
  579. @code
  580. >>> import grass.temporal as tgis
  581. >>> map = tgis.RasterDataset(None)
  582. >>> spat_ext = tgis.SpatialExtent(north=10, south=-10, east=20, west=-20, top=5, bottom=-5)
  583. >>> map.set_spatial_extent(spat_ext)
  584. >>> map.spatial_buffer(10)
  585. >>> print map.get_spatial_extent_as_tuple()
  586. (20.0, -20.0, 30.0, -30.0, 15.0, -15.0)
  587. @endcode
  588. """
  589. self.spatial_extent.north += size
  590. self.spatial_extent.south -= size
  591. self.spatial_extent.east += size
  592. self.spatial_extent.west -= size
  593. self.spatial_extent.top += size
  594. self.spatial_extent.bottom -= size
  595. if update:
  596. self.spatial_extent.update(dbif)
  597. def spatial_buffer_2d(self, size, update=False, dbif=None):
  598. """!Buffer the spatial extent by a given size in 2d
  599. spatial directions.
  600. @param size The buffer size, using the unit of the grass region
  601. @code
  602. >>> import grass.temporal as tgis
  603. >>> map = tgis.RasterDataset(None)
  604. >>> spat_ext = tgis.SpatialExtent(north=10, south=-10, east=20, west=-20, top=5, bottom=-5)
  605. >>> map.set_spatial_extent(spat_ext)
  606. >>> map.spatial_buffer_2d(10)
  607. >>> print map.get_spatial_extent_as_tuple()
  608. (20.0, -20.0, 30.0, -30.0, 5.0, -5.0)
  609. @endcode
  610. """
  611. self.spatial_extent.north += size
  612. self.spatial_extent.south -= size
  613. self.spatial_extent.east += size
  614. self.spatial_extent.west -= size
  615. if update:
  616. self.spatial_extent.update(dbif)
  617. def check_for_correct_time(self):
  618. """!Check for correct time"""
  619. if self.is_time_absolute():
  620. start, end, tz = self.get_absolute_time()
  621. else:
  622. start, end, unit = self.get_relative_time()
  623. if start is not None:
  624. if end is not None:
  625. if start >= end:
  626. if self.get_layer() is not None:
  627. core.error(_("Map <%(id)s> with layer %(layer)s has "
  628. "incorrect time interval, start time is "
  629. "greater than end time") % {
  630. 'id': self.get_map_id(),
  631. 'layer': self.get_layer()})
  632. else:
  633. core.error(_("Map <%s> has incorrect time interval, "
  634. "start time is greater than end time") % \
  635. (self.get_map_id()))
  636. return False
  637. else:
  638. core.error(_("Map <%s> has incorrect start time") %
  639. (self.get_map_id()))
  640. return False
  641. return True
  642. def delete(self, dbif=None, update=True, execute=True):
  643. """!Delete a map entry from database if it exists
  644. Remove dependent entries:
  645. * Remove the map entry in each space time dataset in which this map
  646. is registered
  647. * Remove the space time dataset register table
  648. @param dbif The database interface to be used
  649. @param update Call for each unregister statement the update from
  650. registered maps of the space time dataset.
  651. This can slow down the un-registration process
  652. significantly.
  653. @param execute If True the SQL DELETE and DROP table statements will
  654. be executed.
  655. If False the prepared SQL statements are
  656. returned and must be executed by the caller.
  657. @return The SQL statements if execute=False, else an empty string,
  658. None in case of a failure
  659. """
  660. dbif, connected = init_dbif(dbif)
  661. statement = ""
  662. if self.is_in_db(dbif):
  663. # SELECT all needed information from the database
  664. self.metadata.select(dbif)
  665. # First we unregister from all dependent space time datasets
  666. statement += self.unregister(
  667. dbif=dbif, update=update, execute=False)
  668. # Remove the strds register table
  669. if self.get_stds_register() is not None:
  670. statement += "DROP TABLE " + self.get_stds_register() + ";\n"
  671. # Commented because of performance issue calling g.message thousend times
  672. #core.verbose(_("Delete %s dataset <%s> from temporal database")
  673. # % (self.get_type(), self.get_id()))
  674. # Delete yourself from the database, trigger functions will
  675. # take care of dependencies
  676. statement += self.base.get_delete_statement()
  677. if execute:
  678. dbif.execute_transaction(statement)
  679. # Remove the timestamp from the file system
  680. self.remove_timestamp_from_grass()
  681. self.reset(None)
  682. if connected:
  683. dbif.close()
  684. if execute:
  685. return ""
  686. return statement
  687. def unregister(self, dbif=None, update=True, execute=True):
  688. """! Remove the map entry in each space time dataset in which this map
  689. is registered
  690. @param dbif The database interface to be used
  691. @param update Call for each unregister statement the update from
  692. registered maps of the space time dataset. This can
  693. slow down the un-registration process significantly.
  694. @param execute If True the SQL DELETE and DROP table statements
  695. will be executed.
  696. If False the prepared SQL statements are
  697. returned and must be executed by the caller.
  698. @return The SQL statements if execute=False, else an empty string
  699. """
  700. # Commented because of performance issue calling g.message thousend times
  701. #if self.get_layer() is not None:
  702. # core.verbose(_("Unregister %(type)s map <%(map)s> with "
  703. # "layer %(layer)s from space time datasets" % \
  704. # {'type':self.get_type(), 'map':self.get_map_id(),
  705. # 'layer':self.get_layer()}))
  706. #else:
  707. # core.verbose(_("Unregister %(type)s map <%(map)s> "
  708. # "from space time datasets"
  709. # % {'type':self.get_type(), 'map':self.get_map_id()}))
  710. statement = ""
  711. dbif, connected = init_dbif(dbif)
  712. # Get all datasets in which this map is registered
  713. rows = self.get_registered_datasets(dbif)
  714. # For each stds in which the map is registered
  715. if rows is not None:
  716. for row in rows:
  717. # Create a space time dataset object to remove the map
  718. # from its register
  719. stds = self.get_new_stds_instance(row["id"])
  720. stds.metadata.select(dbif)
  721. statement += stds.unregister_map(self, dbif, False)
  722. # Take care to update the space time dataset after
  723. # the map has been unregistered
  724. if update == True and execute == True:
  725. stds.update_from_registered_maps(dbif)
  726. if execute:
  727. dbif.execute_transaction(statement)
  728. if connected:
  729. dbif.close()
  730. if execute:
  731. return ""
  732. return statement
  733. def get_registered_datasets(self, dbif=None):
  734. """!Return all space time dataset ids in which this map is registered
  735. as dictionary like rows with column "id" or None if this map is not
  736. registered in any space time dataset.
  737. @param dbif The database interface to be used
  738. @return The SQL rows with the ids of all space time datasets in
  739. which this map is registered
  740. """
  741. dbif, connected = init_dbif(dbif)
  742. rows = None
  743. try:
  744. if self.get_stds_register() is not None:
  745. # Select all stds tables in which this map is registered
  746. sql = "SELECT id FROM " + self.get_stds_register()
  747. dbif.cursor.execute(sql)
  748. rows = dbif.cursor.fetchall()
  749. except:
  750. core.error(_("Unable to select space time dataset register table "
  751. "<%s>") % (self.get_stds_register()))
  752. if connected:
  753. dbif.close()
  754. return rows
  755. ###############################################################################
  756. if __name__ == "__main__":
  757. import doctest
  758. doctest.testmod()