region.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646
  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on Fri May 25 12:57:10 2012
  4. @author: Pietro Zambelli
  5. """
  6. from __future__ import (nested_scopes, generators, division, absolute_import,
  7. with_statement, print_function, unicode_literals)
  8. import ctypes
  9. import grass.lib.gis as libgis
  10. import grass.lib.raster as libraster
  11. import grass.script as grass
  12. from grass.pygrass.errors import GrassError
  13. from grass.pygrass.shell.conversion import dict2html
  14. from grass.pygrass.utils import get_mapset_vector, get_mapset_raster
  15. test_vector_name = "Region_test_vector"
  16. test_raster_name = "Region_test_raster"
  17. class Region(object):
  18. """This class is design to easily access and modify GRASS computational
  19. region. ::
  20. >>> r = Region()
  21. >>> r.north
  22. 40.0
  23. >>> r.south
  24. 0.0
  25. >>> r.east
  26. 40.0
  27. >>> r.west
  28. 0.0
  29. >>> r.cols
  30. 20
  31. >>> r.rows
  32. 20
  33. >>> r.nsres
  34. 2.0
  35. >>> r.ewres
  36. 2.0
  37. >>> r.north = 100
  38. >>> r.east = 100
  39. >>> r.adjust(rows=True, cols=True)
  40. >>> r.nsres
  41. 5.0
  42. >>> r.ewres
  43. 5.0
  44. >>> r.cols
  45. 20
  46. >>> r.rows
  47. 20
  48. >>> r.read()
  49. >>> r.north = 100
  50. >>> r.east = 100
  51. >>> r.adjust(rows=False, cols=True)
  52. >>> r.nsres
  53. 2.0
  54. >>> r.ewres
  55. 5.0
  56. >>> r.cols
  57. 20
  58. >>> r.rows
  59. 50
  60. >>> r.read()
  61. >>> r.north = 100
  62. >>> r.east = 100
  63. >>> r.adjust(rows=True, cols=False)
  64. >>> r.nsres
  65. 5.0
  66. >>> r.ewres
  67. 2.0
  68. >>> r.cols
  69. 50
  70. >>> r.rows
  71. 20
  72. >>> r.read()
  73. >>> r.north = 100
  74. >>> r.east = 100
  75. >>> r.adjust(rows=False, cols=False)
  76. >>> r.nsres
  77. 2.0
  78. >>> r.ewres
  79. 2.0
  80. >>> r.cols
  81. 50
  82. >>> r.rows
  83. 50
  84. >>> r.read()
  85. >>> r.cols = 1000
  86. >>> r.ewres
  87. 0.04
  88. >>> r.rows = 1000
  89. >>> r.nsres
  90. 0.04
  91. ..
  92. """
  93. def __init__(self, default=False):
  94. self.c_region = libgis.Cell_head()
  95. if default:
  96. self.read_default()
  97. else:
  98. self.read()
  99. def byref(self):
  100. """Return the internal region representation as pointer"""
  101. return ctypes.pointer(self.c_region)
  102. def _set_param(self, key, value):
  103. grass.run_command('g.region', **{key: value})
  104. #----------LIMITS----------
  105. def _get_n(self):
  106. """Private function to obtain north value"""
  107. return self.c_region.north
  108. def _set_n(self, value):
  109. """Private function to set north value"""
  110. self.c_region.north = value
  111. north = property(fget=_get_n, fset=_set_n,
  112. doc="Set and obtain north coordinate")
  113. def _get_s(self):
  114. """Private function to obtain south value"""
  115. return self.c_region.south
  116. def _set_s(self, value):
  117. """Private function to set south value"""
  118. self.c_region.south = value
  119. south = property(fget=_get_s, fset=_set_s,
  120. doc="Set and obtain south coordinate")
  121. def _get_e(self):
  122. """Private function to obtain east value"""
  123. return self.c_region.east
  124. def _set_e(self, value):
  125. """Private function to set east value"""
  126. self.c_region.east = value
  127. east = property(fget=_get_e, fset=_set_e,
  128. doc="Set and obtain east coordinate")
  129. def _get_w(self):
  130. """Private function to obtain west value"""
  131. return self.c_region.west
  132. def _set_w(self, value):
  133. """Private function to set west value"""
  134. self.c_region.west = value
  135. west = property(fget=_get_w, fset=_set_w,
  136. doc="Set and obtain west coordinate")
  137. def _get_t(self):
  138. """Private function to obtain top value"""
  139. return self.c_region.top
  140. def _set_t(self, value):
  141. """Private function to set top value"""
  142. self.c_region.top = value
  143. top = property(fget=_get_t, fset=_set_t,
  144. doc="Set and obtain top value")
  145. def _get_b(self):
  146. """Private function to obtain bottom value"""
  147. return self.c_region.bottom
  148. def _set_b(self, value):
  149. """Private function to set bottom value"""
  150. self.c_region.bottom = value
  151. bottom = property(fget=_get_b, fset=_set_b,
  152. doc="Set and obtain bottom value")
  153. #----------RESOLUTION----------
  154. def _get_rows(self):
  155. """Private function to obtain rows value"""
  156. return self.c_region.rows
  157. def _set_rows(self, value):
  158. """Private function to set rows value"""
  159. self.c_region.rows = value
  160. self.adjust(rows=True)
  161. rows = property(fget=_get_rows, fset=_set_rows,
  162. doc="Set and obtain number of rows")
  163. def _get_cols(self):
  164. """Private function to obtain columns value"""
  165. return self.c_region.cols
  166. def _set_cols(self, value):
  167. """Private function to set columns value"""
  168. self.c_region.cols = value
  169. self.adjust(cols=True)
  170. cols = property(fget=_get_cols, fset=_set_cols,
  171. doc="Set and obtain number of columns")
  172. def _get_depths(self):
  173. """Private function to obtain depths value"""
  174. return self.c_region.depths
  175. def _set_depths(self, value):
  176. """Private function to set depths value"""
  177. self.c_region.depths = value
  178. depths = property(fget=_get_depths, fset=_set_depths,
  179. doc="Set and obtain number of depths")
  180. def _get_nsres(self):
  181. """Private function to obtain north-south value"""
  182. return self.c_region.ns_res
  183. def _set_nsres(self, value):
  184. """Private function to obtain north-south value"""
  185. self.c_region.ns_res = value
  186. self.adjust()
  187. nsres = property(fget=_get_nsres, fset=_set_nsres,
  188. doc="Set and obtain north-south resolution value")
  189. def _get_ewres(self):
  190. """Private function to obtain east-west value"""
  191. return self.c_region.ew_res
  192. def _set_ewres(self, value):
  193. """Private function to set east-west value"""
  194. self.c_region.ew_res = value
  195. self.adjust()
  196. ewres = property(fget=_get_ewres, fset=_set_ewres,
  197. doc="Set and obtain east-west resolution value")
  198. def _get_tbres(self):
  199. """Private function to obtain top-botton 3D value"""
  200. return self.c_region.tb_res
  201. def _set_tbres(self, value):
  202. """Private function to set top-bottom 3D value"""
  203. self.c_region.tb_res = value
  204. self.adjust()
  205. tbres = property(fget=_get_tbres, fset=_set_tbres,
  206. doc="Set and obtain top-bottom 3D value")
  207. @property
  208. def zone(self):
  209. """Return the zone of projection
  210. """
  211. return self.c_region.zone
  212. @property
  213. def proj(self):
  214. """Return a code for projection
  215. """
  216. return self.c_region.proj
  217. @property
  218. def cells(self):
  219. """Return the number of cells"""
  220. return self.rows * self.cols
  221. #----------MAGIC METHODS----------
  222. def __repr__(self):
  223. rg = "Region(north=%g, south=%g, east=%g, west=%g, "\
  224. "nsres=%g, ewres=%g, rows=%i, cols=%i, "\
  225. "cells=%i, zone=%i, proj=%i)"
  226. return rg % (self.north, self.south, self.east, self.west,
  227. self.nsres, self.ewres, self.rows, self.cols,
  228. self.cells, self.zone, self.proj)
  229. def _repr_html_(self):
  230. return dict2html(dict(self.items()), keys=self.keys(),
  231. border='1', kdec='b')
  232. def __unicode__(self):
  233. return self.__repr__()
  234. def __str__(self):
  235. return self.__unicode__()
  236. def __eq__(self, reg):
  237. """Compare two region. ::
  238. >>> r0 = Region()
  239. >>> r1 = Region()
  240. >>> r2 = Region()
  241. >>> r2.nsres = 5
  242. >>> r0 == r1
  243. True
  244. >>> r1 == r2
  245. False
  246. ..
  247. """
  248. attrs = ['north', 'south', 'west', 'east', 'top', 'bottom',
  249. 'nsres', 'ewres', 'tbres', 'rows', 'cols', 'cells',
  250. 'zone', 'proj']
  251. for attr in attrs:
  252. if getattr(self, attr) != getattr(reg, attr):
  253. return False
  254. return True
  255. def __ne__(self, other):
  256. return not self == other
  257. # Restore Python 2 hashing beaviour on Python 3
  258. __hash__ = object.__hash__
  259. def keys(self):
  260. """Return a list of valid keys. ::
  261. >>> reg = Region()
  262. >>> reg.keys() # doctest: +ELLIPSIS
  263. ['proj', 'zone', ..., 'cols', 'cells']
  264. ..
  265. """
  266. return ['proj', 'zone', 'north', 'south', 'west', 'east',
  267. 'top', 'bottom', 'nsres', 'ewres', 'tbres', 'rows',
  268. 'cols', 'cells']
  269. def items(self):
  270. """Return a list of tuple with key and value.
  271. """
  272. return [(k, self.__getattribute__(k)) for k in self.keys()]
  273. #----------METHODS----------
  274. def zoom(self, raster_name):
  275. """Shrink region until it meets non-NULL data from this raster map
  276. Warning: This will change the user GRASS region settings
  277. :param raster_name: the name of raster
  278. :type raster_name: str
  279. """
  280. self._set_param('zoom', str(raster_name))
  281. self.read()
  282. def align(self, raster_name):
  283. """Adjust region cells to cleanly align with this raster map
  284. Warning: This will change the user GRASS region settings
  285. :param raster_name: the name of raster
  286. :type raster_name: str
  287. """
  288. self._set_param('align', str(raster_name))
  289. self.read()
  290. def adjust(self, rows=False, cols=False):
  291. """Adjust rows and cols number according with the nsres and ewres
  292. resolutions. If rows or cols parameters are True, the adjust method
  293. update nsres and ewres according with the rows and cols numbers.
  294. """
  295. libgis.G_adjust_Cell_head(self.byref(), bool(rows), bool(cols))
  296. def from_vect(self, vector_name):
  297. """Adjust bounding box of region using a vector
  298. :param vector_name: the name of vector
  299. :type vector_name: str
  300. Example ::
  301. >>> reg = Region()
  302. >>> reg.from_vect(test_vector_name)
  303. >>> reg.get_bbox()
  304. Bbox(6.0, 0.0, 14.0, 0.0)
  305. >>> reg.read()
  306. >>> reg.get_bbox()
  307. Bbox(40.0, 0.0, 40.0, 0.0)
  308. ..
  309. """
  310. from grass.pygrass.vector import VectorTopo
  311. with VectorTopo(vector_name, mode='r') as vect:
  312. bbox = vect.bbox()
  313. self.set_bbox(bbox)
  314. def from_rast(self, raster_name):
  315. """Set the region from the computational region
  316. of a raster map layer.
  317. :param raster_name: the name of raster
  318. :type raster_name: str
  319. :param mapset: the mapset of raster
  320. :type mapset: str
  321. call C function `Rast_get_cellhd`
  322. Example ::
  323. >>> reg = Region()
  324. >>> reg.from_rast(test_raster_name)
  325. >>> reg.get_bbox()
  326. Bbox(50.0, 0.0, 60.0, 0.0)
  327. >>> reg.read()
  328. >>> reg.get_bbox()
  329. Bbox(40.0, 0.0, 40.0, 0.0)
  330. ..
  331. """
  332. if not raster_name:
  333. raise ValueError("Raster name or mapset are invalid")
  334. mapset = get_mapset_raster(raster_name)
  335. if mapset:
  336. libraster.Rast_get_cellhd(raster_name, mapset,
  337. self.byref())
  338. def set_raster_region(self):
  339. """Set the computational region (window) for all raster maps in the current process.
  340. Attention: All raster objects must be closed or the
  341. process will be terminated.
  342. The Raster library C function Rast_set_window() is called.
  343. """
  344. libraster.Rast_set_window(self.byref())
  345. def get_current(self):
  346. """Get the current working region of this process
  347. and store it into this Region object
  348. Previous calls to set_current() affects values returned by this function.
  349. Previous calls to read() affects values returned by this function
  350. only if the current working region is not initialized.
  351. Example:
  352. >>> r = Region()
  353. >>> r.north
  354. 40.0
  355. >>> r.north = 30
  356. >>> r.north
  357. 30.0
  358. >>> r.get_current()
  359. >>> r.north
  360. 40.0
  361. """
  362. libgis.G_get_set_window(self.byref())
  363. def set_current(self):
  364. """Set the current working region from this region object
  365. This function adjusts the values before setting the region
  366. so you don't have to call G_adjust_Cell_head().
  367. Attention: Only the current process is affected.
  368. The GRASS computational region is not affected.
  369. Example::
  370. >>> r = Region()
  371. >>> r.north
  372. 40.0
  373. >>> r.south
  374. 0.0
  375. >>> r.north = 30
  376. >>> r.south = 20
  377. >>> r.set_current()
  378. >>> r.north
  379. 30.0
  380. >>> r.south
  381. 20.0
  382. >>> r.get_current()
  383. >>> r.north
  384. 30.0
  385. >>> r.south
  386. 20.0
  387. >>> r.read(force_read=False)
  388. >>> r.north
  389. 40.0
  390. >>> r.south
  391. 0.0
  392. >>> r.read(force_read=True)
  393. >>> r.north
  394. 40.0
  395. >>> r.south
  396. 0.0
  397. """
  398. libgis.G_set_window(self.byref())
  399. def read(self, force_read=True):
  400. """
  401. Read the region into this region object
  402. Reads the region as stored in the WIND file in the user's current
  403. mapset into region.
  404. 3D values are set to defaults if not available in WIND file. An
  405. error message is printed and exit() is called if there is a problem
  406. reading the region.
  407. <b>Note:</b> GRASS applications that read or write raster maps
  408. should not use this routine since its use implies that the active
  409. module region will not be used. Programs that read or write raster
  410. map data (or vector data) can query the active module region using
  411. Rast_window_rows() and Rast_window_cols().
  412. :param force_read: If True the WIND file of the current mapset
  413. is re-readed, otherwise the initial region
  414. set at process start will be loaded from the internal
  415. static variables.
  416. :type force_read: boolean
  417. """
  418. # Force the reading of the WIND file
  419. if force_read:
  420. libgis.G_unset_window()
  421. libgis.G_get_window(self.byref())
  422. def write(self):
  423. """Writes the region from this region object
  424. This function writes this region to the Region file (WIND)
  425. in the users current mapset. This function should be
  426. carefully used, since the user will ot notice if his region
  427. was changed and would expect that only g.region will do this.
  428. Example ::
  429. >>> from copy import deepcopy
  430. >>> r = Region()
  431. >>> rn = deepcopy(r)
  432. >>> r.north = 20
  433. >>> r.south = 10
  434. >>> r.write()
  435. >>> r.read()
  436. >>> r.north
  437. 20.0
  438. >>> r.south
  439. 10.0
  440. >>> rn.write()
  441. >>> r.read()
  442. >>> r.north
  443. 40.0
  444. >>> r.south
  445. 0.0
  446. >>> r.read_default()
  447. >>> r.write()
  448. ..
  449. """
  450. self.adjust()
  451. if libgis.G_put_window(self.byref()) < 0:
  452. raise GrassError("Cannot change region (WIND file).")
  453. def read_default(self):
  454. """
  455. Get the default region
  456. Reads the default region for the location in this Region object.
  457. 3D values are set to defaults if not available in WIND file.
  458. An error message is printed and exit() is called if there is a
  459. problem reading the default region.
  460. """
  461. libgis.G_get_default_window(self.byref())
  462. def get_bbox(self):
  463. """Return a Bbox object with the extension of the region. ::
  464. >>> reg = Region()
  465. >>> reg.get_bbox()
  466. Bbox(40.0, 0.0, 40.0, 0.0)
  467. ..
  468. """
  469. from grass.pygrass.vector.basic import Bbox
  470. return Bbox(north=self.north, south=self.south,
  471. east=self.east, west=self.west,
  472. top=self.top, bottom=self.bottom)
  473. def set_bbox(self, bbox):
  474. """Set region extent from Bbox
  475. :param bbox: a Bbox object to set the extent
  476. :type bbox: Bbox object
  477. ::
  478. >>> from grass.pygrass.vector.basic import Bbox
  479. >>> b = Bbox(230963.640878, 212125.562878, 645837.437393, 628769.374393)
  480. >>> reg = Region()
  481. >>> reg.set_bbox(b)
  482. >>> reg.get_bbox()
  483. Bbox(230963.640878, 212125.562878, 645837.437393, 628769.374393)
  484. >>> reg.get_current()
  485. ..
  486. """
  487. self.north = bbox.north
  488. self.south = bbox.south
  489. self.east = bbox.east
  490. self.west = bbox.west
  491. if __name__ == "__main__":
  492. import doctest
  493. from grass.pygrass import utils
  494. from grass.script.core import run_command
  495. utils.create_test_vector_map(test_vector_name)
  496. run_command("g.region", n=50, s=0, e=60, w=0, res=1)
  497. run_command("r.mapcalc", expression="%s = 1" % (test_raster_name),
  498. overwrite=True)
  499. run_command("g.region", n=40, s=0, e=40, w=0, res=2)
  500. doctest.testmod()
  501. """Remove the generated vector map, if exist"""
  502. mset = utils.get_mapset_vector(test_vector_name, mapset='')
  503. if mset:
  504. run_command("g.remove", flags='f', type='vector', name=test_vector_name)
  505. mset = utils.get_mapset_raster(test_raster_name, mapset='')
  506. if mset:
  507. run_command("g.remove", flags='f', type='raster', name=test_raster_name)