region.py 18 KB

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