region.py 18 KB

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