region.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634
  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']
  250. for attr in attrs:
  251. if getattr(self, attr) != getattr(reg, attr):
  252. return False
  253. return True
  254. def __ne__(self, other):
  255. return not self == other
  256. # Restore Python 2 hashing beaviour on Python 3
  257. __hash__ = object.__hash__
  258. def keys(self):
  259. """Return a list of valid keys. ::
  260. >>> reg = Region()
  261. >>> reg.keys() # doctest: +ELLIPSIS
  262. [u'proj', u'zone', ..., u'cols', u'cells']
  263. ..
  264. """
  265. return ['proj', 'zone', 'north', 'south', 'west', 'east',
  266. 'top', 'bottom', 'nsres', 'ewres', 'tbres', 'rows',
  267. 'cols', 'cells']
  268. def items(self):
  269. """Return a list of tuple with key and value.
  270. """
  271. return [(k, self.__getattribute__(k)) for k in self.keys()]
  272. #----------METHODS----------
  273. def zoom(self, raster_name):
  274. """Shrink region until it meets non-NULL data from this raster map
  275. Warning: This will change the user GRASS region settings
  276. :param raster_name: the name of raster
  277. :type raster_name: str
  278. """
  279. self._set_param('zoom', str(raster_name))
  280. self.read()
  281. def align(self, raster_name):
  282. """Adjust region cells to cleanly align with this raster map
  283. Warning: This will change the user GRASS region settings
  284. :param raster_name: the name of raster
  285. :type raster_name: str
  286. """
  287. self._set_param('align', str(raster_name))
  288. self.read()
  289. def adjust(self, rows=False, cols=False):
  290. """Adjust rows and cols number according with the nsres and ewres
  291. resolutions. If rows or cols parameters are True, the adjust method
  292. update nsres and ewres according with the rows and cols numbers.
  293. """
  294. libgis.G_adjust_Cell_head(self.byref(), bool(rows), bool(cols))
  295. def from_vect(self, vector_name):
  296. """Adjust bounding box of region using a vector
  297. :param vector_name: the name of vector
  298. :type vector_name: str
  299. Example ::
  300. >>> reg = Region()
  301. >>> reg.from_vect(test_vector_name)
  302. >>> reg.get_bbox()
  303. Bbox(6.0, 0.0, 14.0, 0.0)
  304. >>> reg.read()
  305. >>> reg.get_bbox()
  306. Bbox(40.0, 0.0, 40.0, 0.0)
  307. ..
  308. """
  309. from grass.pygrass.vector import VectorTopo
  310. with VectorTopo(vector_name, mode='r') as vect:
  311. bbox = vect.bbox()
  312. self.set_bbox(bbox)
  313. def from_rast(self, raster_name):
  314. """Set the region from the computational region
  315. of a raster map layer.
  316. :param raster_name: the name of raster
  317. :type raster_name: str
  318. :param mapset: the mapset of raster
  319. :type mapset: str
  320. call C function `Rast_get_cellhd`
  321. Example ::
  322. >>> reg = Region()
  323. >>> reg.from_rast(test_raster_name)
  324. >>> reg.get_bbox()
  325. Bbox(50.0, 0.0, 60.0, 0.0)
  326. >>> reg.read()
  327. >>> reg.get_bbox()
  328. Bbox(40.0, 0.0, 40.0, 0.0)
  329. ..
  330. """
  331. if not raster_name:
  332. raise ValueError("Raster name or mapset are invalid")
  333. mapset = get_mapset_raster(raster_name)
  334. if mapset:
  335. libraster.Rast_get_cellhd(raster_name, mapset,
  336. self.byref())
  337. def get_current(self):
  338. """Get the current working region of this process
  339. and store it into this Region object
  340. Previous calls to set_current() affects values returned by this function.
  341. Previous calls to read() affects values returned by this function
  342. only if the current working region is not initialized.
  343. Example:
  344. >>> r = Region()
  345. >>> r.north
  346. 40.0
  347. >>> r.north = 30
  348. >>> r.north
  349. 30.0
  350. >>> r.get_current()
  351. >>> r.north
  352. 40.0
  353. """
  354. libgis.G_get_set_window(self.byref())
  355. def set_current(self):
  356. """Set the current working region from this region object
  357. This function adjusts the values before setting the region
  358. so you don't have to call G_adjust_Cell_head().
  359. Attention: Only the current process is affected.
  360. The GRASS computational region is not affected.
  361. Example::
  362. >>> r = Region()
  363. >>> r.north
  364. 40.0
  365. >>> r.south
  366. 0.0
  367. >>> r.north = 30
  368. >>> r.south = 20
  369. >>> r.set_current()
  370. >>> r.north
  371. 30.0
  372. >>> r.south
  373. 20.0
  374. >>> r.get_current()
  375. >>> r.north
  376. 30.0
  377. >>> r.south
  378. 20.0
  379. >>> r.read(force_read=False)
  380. >>> r.north
  381. 40.0
  382. >>> r.south
  383. 0.0
  384. >>> r.read(force_read=True)
  385. >>> r.north
  386. 40.0
  387. >>> r.south
  388. 0.0
  389. """
  390. libgis.G_set_window(self.byref())
  391. def read(self, force_read=True):
  392. """
  393. Read the region into this region object
  394. Reads the region as stored in the WIND file in the user's current
  395. mapset into region.
  396. 3D values are set to defaults if not available in WIND file. An
  397. error message is printed and exit() is called if there is a problem
  398. reading the region.
  399. <b>Note:</b> GRASS applications that read or write raster maps
  400. should not use this routine since its use implies that the active
  401. module region will not be used. Programs that read or write raster
  402. map data (or vector data) can query the active module region using
  403. Rast_window_rows() and Rast_window_cols().
  404. :param force_read: If True the WIND file of the current mapset
  405. is re-readed, otherwise the initial region
  406. set at process start will be loaded from the internal
  407. static variables.
  408. :type force_read: boolean
  409. """
  410. # Force the reading of the WIND file
  411. if force_read:
  412. libgis.G_unset_window()
  413. libgis.G_get_window(self.byref())
  414. def write(self):
  415. """Writes the region from this region object
  416. This function writes this region to the Region file (WIND)
  417. in the users current mapset. This function should be
  418. carefully used, since the user will ot notice if his region
  419. was changed and would expect that only g.region will do this.
  420. Example ::
  421. >>> from copy import deepcopy
  422. >>> r = Region()
  423. >>> rn = deepcopy(r)
  424. >>> r.north = 20
  425. >>> r.south = 10
  426. >>> r.write()
  427. >>> r.read()
  428. >>> r.north
  429. 20.0
  430. >>> r.south
  431. 10.0
  432. >>> rn.write()
  433. >>> r.read()
  434. >>> r.north
  435. 40.0
  436. >>> r.south
  437. 0.0
  438. >>> r.read_default()
  439. >>> r.write()
  440. ..
  441. """
  442. self.adjust()
  443. if libgis.G_put_window(self.byref()) < 0:
  444. raise GrassError("Cannot change region (DEFAUL_WIND file).")
  445. def read_default(self):
  446. """
  447. Get the default region
  448. Reads the default region for the location in this Region object.
  449. 3D values are set to defaults if not available in WIND file.
  450. An error message is printed and exit() is called if there is a
  451. problem reading the default region.
  452. """
  453. libgis.G_get_default_window(self.byref())
  454. def get_bbox(self):
  455. """Return a Bbox object with the extension of the region. ::
  456. >>> reg = Region()
  457. >>> reg.get_bbox()
  458. Bbox(40.0, 0.0, 40.0, 0.0)
  459. ..
  460. """
  461. from grass.pygrass.vector.basic import Bbox
  462. return Bbox(north=self.north, south=self.south,
  463. east=self.east, west=self.west,
  464. top=self.top, bottom=self.bottom)
  465. def set_bbox(self, bbox):
  466. """Set region extent from Bbox
  467. :param bbox: a Bbox object to set the extent
  468. :type bbox: Bbox object
  469. ::
  470. >>> from grass.pygrass.vector.basic import Bbox
  471. >>> b = Bbox(230963.640878, 212125.562878, 645837.437393, 628769.374393)
  472. >>> reg = Region()
  473. >>> reg.set_bbox(b)
  474. >>> reg.get_bbox()
  475. Bbox(230963.640878, 212125.562878, 645837.437393, 628769.374393)
  476. >>> reg.get_current()
  477. ..
  478. """
  479. self.north = bbox.north
  480. self.south = bbox.south
  481. self.east = bbox.east
  482. self.west = bbox.west
  483. if __name__ == "__main__":
  484. import doctest
  485. from grass.pygrass import utils
  486. from grass.script.core import run_command
  487. utils.create_test_vector_map(test_vector_name)
  488. run_command("g.region", n=50, s=0, e=60, w=0, res=1)
  489. run_command("r.mapcalc", expression="%s = 1"%(test_raster_name),
  490. overwrite=True)
  491. run_command("g.region", n=40, s=0, e=40, w=0, res=2)
  492. doctest.testmod()
  493. """Remove the generated vector map, if exist"""
  494. mset = utils.get_mapset_vector(test_vector_name, mapset='')
  495. if mset:
  496. run_command("g.remove", flags='f', type='vector', name=test_vector_name)
  497. mset = utils.get_mapset_raster(test_raster_name, mapset='')
  498. if mset:
  499. run_command("g.remove", flags='f', type='raster', name=test_raster_name)