abstract.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621
  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on Fri Aug 17 16:05:25 2012
  4. @author: pietro
  5. """
  6. from __future__ import (nested_scopes, generators, division, absolute_import,
  7. with_statement, print_function, unicode_literals)
  8. import ctypes
  9. #
  10. # import GRASS modules
  11. #
  12. from grass.script import fatal, gisenv
  13. import grass.lib.gis as libgis
  14. import grass.lib.raster as libraster
  15. #
  16. # import pygrass modules
  17. #
  18. from grass.pygrass import utils
  19. from grass.pygrass.gis.region import Region
  20. from grass.pygrass.errors import must_be_open, must_be_in_current_mapset
  21. from grass.pygrass.shell.conversion import dict2html
  22. from grass.pygrass.shell.show import raw_figure
  23. #
  24. # import raster classes
  25. #
  26. from grass.pygrass.raster.raster_type import TYPE as RTYPE, RTYPE_STR
  27. from grass.pygrass.raster.category import Category
  28. from grass.pygrass.raster.history import History
  29. test_raster_name = "abstract_test_map"
  30. # Define global variables to not exceed the 80 columns
  31. INDXOUTRANGE = "The index (%d) is out of range, have you open the map?."
  32. INFO = """{name}@{mapset}
  33. rows: {rows}
  34. cols: {cols}
  35. north: {north} south: {south} nsres:{nsres}
  36. east: {east} west: {west} ewres:{ewres}
  37. range: {min}, {max}
  38. proj: {proj}
  39. """
  40. class Info(object):
  41. def __init__(self, name, mapset=''):
  42. """Read the information for a raster map. ::
  43. >>> info = Info(test_raster_name)
  44. >>> info.read()
  45. >>> info # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
  46. abstract_test_map@
  47. rows: 4
  48. cols: 4
  49. north: 40.0 south: 0.0 nsres:10.0
  50. east: 40.0 west: 0.0 ewres:10.0
  51. range: 11, 44
  52. ...
  53. <BLANKLINE>
  54. """
  55. self.name = name
  56. self.mapset = mapset
  57. self.c_region = ctypes.pointer(libraster.struct_Cell_head())
  58. self.c_range = None
  59. def _get_range(self):
  60. if self.mtype == 'CELL':
  61. self.c_range = ctypes.pointer(libraster.Range())
  62. libraster.Rast_read_range(self.name, self.mapset, self.c_range)
  63. else:
  64. self.c_range = ctypes.pointer(libraster.FPRange())
  65. libraster.Rast_read_fp_range(self.name, self.mapset, self.c_range)
  66. def _get_raster_region(self):
  67. libraster.Rast_get_cellhd(self.name, self.mapset, self.c_region)
  68. def read(self):
  69. self._get_range()
  70. self._get_raster_region()
  71. @property
  72. def north(self):
  73. return self.c_region.contents.north
  74. @property
  75. def south(self):
  76. return self.c_region.contents.south
  77. @property
  78. def east(self):
  79. return self.c_region.contents.east
  80. @property
  81. def west(self):
  82. return self.c_region.contents.west
  83. @property
  84. def top(self):
  85. return self.c_region.contents.top
  86. @property
  87. def bottom(self):
  88. return self.c_region.contents.bottom
  89. @property
  90. def rows(self):
  91. return self.c_region.contents.rows
  92. @property
  93. def cols(self):
  94. return self.c_region.contents.cols
  95. @property
  96. def nsres(self):
  97. return self.c_region.contents.ns_res
  98. @property
  99. def ewres(self):
  100. return self.c_region.contents.ew_res
  101. @property
  102. def tbres(self):
  103. return self.c_region.contents.tb_res
  104. @property
  105. def zone(self):
  106. return self.c_region.contents.zone
  107. @property
  108. def proj(self):
  109. return self.c_region.contents.proj
  110. @property
  111. def min(self):
  112. if self.c_range is None:
  113. return None
  114. return self.c_range.contents.min
  115. @property
  116. def max(self):
  117. if self.c_range is None:
  118. return None
  119. return self.c_range.contents.max
  120. @property
  121. def range(self):
  122. if self.c_range is None:
  123. return None, None
  124. return self.c_range.contents.min, self.c_range.contents.max
  125. @property
  126. def mtype(self):
  127. return RTYPE_STR[libraster.Rast_map_type(self.name, self.mapset)]
  128. def _get_band_reference(self):
  129. """Get band reference identifier.
  130. :return str: band identifier (eg. S2_1) or None
  131. """
  132. band_ref = None
  133. p_filename = ctypes.c_char_p()
  134. p_band_ref = ctypes.c_char_p()
  135. ret = libraster.Rast_read_band_reference(self.name, self.mapset,
  136. ctypes.byref(p_filename),
  137. ctypes.byref(p_band_ref))
  138. if ret:
  139. band_ref = utils.decode(p_band_ref.value)
  140. libgis.G_free(p_filename)
  141. libgis.G_free(p_band_ref)
  142. return band_ref
  143. @must_be_in_current_mapset
  144. def _set_band_reference(self, band_reference):
  145. """Set/Unset band reference identifier.
  146. :param str band_reference: band reference to assign or None to remove (unset)
  147. """
  148. if band_reference:
  149. # assign
  150. from grass.bandref import BandReferenceReader, BandReferenceReaderError
  151. reader = BandReferenceReader()
  152. # determine filename (assuming that band_reference is unique!)
  153. try:
  154. filename = reader.find_file(band_reference)
  155. except BandReferenceReaderError as e:
  156. fatal("{}".format(e))
  157. raise
  158. if not filename:
  159. fatal("Band reference <{}> not found".format(band_reference))
  160. raise
  161. # write band reference
  162. libraster.Rast_write_band_reference(self.name,
  163. filename,
  164. band_reference)
  165. else:
  166. libraster.Rast_remove_band_reference(self.name)
  167. band_reference = property(fget=_get_band_reference, fset=_set_band_reference)
  168. def _get_units(self):
  169. return libraster.Rast_read_units(self.name, self.mapset)
  170. def _set_units(self, units):
  171. libraster.Rast_write_units(self.name, units)
  172. units = property(_get_units, _set_units)
  173. def _get_vdatum(self):
  174. return libraster.Rast_read_vdatum(self.name, self.mapset)
  175. def _set_vdatum(self, vdatum):
  176. libraster.Rast_write_vdatum(self.name, vdatum)
  177. vdatum = property(_get_vdatum, _set_vdatum)
  178. def __repr__(self):
  179. return INFO.format(name=self.name, mapset=self.mapset,
  180. rows=self.rows, cols=self.cols,
  181. north=self.north, south=self.south,
  182. east=self.east, west=self.west,
  183. top=self.top, bottom=self.bottom,
  184. nsres=self.nsres, ewres=self.ewres,
  185. tbres=self.tbres, zone=self.zone,
  186. proj=self.proj, min=self.min, max=self.max)
  187. def keys(self):
  188. return ['name', 'mapset', 'rows', 'cols', 'north', 'south',
  189. 'east', 'west', 'top', 'bottom', 'nsres', 'ewres', 'tbres',
  190. 'zone', 'proj', 'min', 'max']
  191. def items(self):
  192. return [(k, self.__getattribute__(k)) for k in self.keys()]
  193. def __iter__(self):
  194. return ((k, self.__getattribute__(k)) for k in self.keys())
  195. def _repr_html_(self):
  196. return dict2html(dict(self.items()), keys=self.keys(),
  197. border='1', kdec='b')
  198. class RasterAbstractBase(object):
  199. """Raster_abstract_base: The base class from which all sub-classes
  200. inherit. It does not implement any row or map access methods:
  201. * Implements raster metadata information access (Type, ...)
  202. * Implements an open method that will be overwritten by the sub-classes
  203. * Implements the close method that might be overwritten by sub-classes
  204. (should work for simple row access)
  205. * Implements get and set region methods
  206. * Implements color, history and category handling
  207. * Renaming, deletion, ...
  208. """
  209. def __init__(self, name, mapset="", *aopen, **kwopen):
  210. """The constructor need at least the name of the map
  211. *optional* field is the `mapset`.
  212. >>> ele = RasterAbstractBase(test_raster_name)
  213. >>> ele.name
  214. 'abstract_test_map'
  215. >>> ele.exist()
  216. True
  217. ..
  218. """
  219. self.mapset = mapset
  220. if not mapset:
  221. # note that @must_be_in_current_mapset requires mapset to be set
  222. mapset = libgis.G_find_raster(name, mapset)
  223. if mapset is not None:
  224. self.mapset = utils.decode(mapset)
  225. self._name = name
  226. # Private attribute `_fd` that return the file descriptor of the map
  227. self._fd = None
  228. # Private attribute `_rows` that return the number of rows
  229. # in active window, When the class is instanced is empty and it is set
  230. # when you open the file, using Rast_window_rows()
  231. self._rows = None
  232. # Private attribute `_cols` that return the number of rows
  233. # in active window, When the class is instanced is empty and it is set
  234. # when you open the file, using Rast_window_cols()
  235. self._cols = None
  236. # self.region = Region()
  237. self.hist = History(self.name, self.mapset)
  238. self.cats = Category(self.name, self.mapset)
  239. self.info = Info(self.name, self.mapset)
  240. self._aopen = aopen
  241. self._kwopen = kwopen
  242. self._mtype = 'CELL'
  243. self._mode = 'r'
  244. self._overwrite = False
  245. def __enter__(self):
  246. self.open(*self._aopen, **self._kwopen)
  247. return self
  248. def __exit__(self, exc_type, exc_value, traceback):
  249. self.close()
  250. def _get_mtype(self):
  251. """Private method to get the Raster type"""
  252. return self._mtype
  253. def _set_mtype(self, mtype):
  254. """Private method to change the Raster type"""
  255. if mtype.upper() not in ('CELL', 'FCELL', 'DCELL'):
  256. str_err = "Raster type: {0} not supported ('CELL','FCELL','DCELL')"
  257. raise ValueError(_(str_err).format(mtype))
  258. self._mtype = mtype
  259. self._gtype = RTYPE[self.mtype]['grass type']
  260. mtype = property(fget=_get_mtype, fset=_set_mtype)
  261. def _get_mode(self):
  262. return self._mode
  263. def _set_mode(self, mode):
  264. if mode.upper() not in ('R', 'W'):
  265. str_err = _("Mode type: {0} not supported ('r', 'w')")
  266. raise ValueError(str_err.format(mode))
  267. self._mode = mode
  268. mode = property(fget=_get_mode, fset=_set_mode)
  269. def _get_overwrite(self):
  270. return self._overwrite
  271. def _set_overwrite(self, overwrite):
  272. if overwrite not in (True, False):
  273. str_err = _("Overwrite type: {0} not supported (True/False)")
  274. raise ValueError(str_err.format(overwrite))
  275. self._overwrite = overwrite
  276. overwrite = property(fget=_get_overwrite, fset=_set_overwrite)
  277. def _get_name(self):
  278. """Private method to return the Raster name"""
  279. return self._name
  280. def _set_name(self, newname):
  281. """Private method to change the Raster name"""
  282. if not utils.is_clean_name(newname):
  283. str_err = _("Map name {0} not valid")
  284. raise ValueError(str_err.format(newname))
  285. if self.exist():
  286. self.rename(newname)
  287. self._name = newname
  288. name = property(fget=_get_name, fset=_set_name)
  289. @must_be_open
  290. def _get_cats_title(self):
  291. return self.cats.title
  292. @must_be_open
  293. def _set_cats_title(self, newtitle):
  294. self.cats.title = newtitle
  295. cats_title = property(fget=_get_cats_title, fset=_set_cats_title)
  296. def __unicode__(self):
  297. return self.name_mapset()
  298. def __str__(self):
  299. """Return the string of the object"""
  300. return self.__unicode__()
  301. def __len__(self):
  302. return self._rows
  303. def __getitem__(self, key):
  304. """Return the row of Raster object, slice allowed."""
  305. if isinstance(key, slice):
  306. # Get the start, stop, and step from the slice
  307. return (self.get_row(ii) for ii in range(*key.indices(len(self))))
  308. elif isinstance(key, tuple):
  309. x, y = key
  310. return self.get(x, y)
  311. elif isinstance(key, int):
  312. if not self.is_open():
  313. raise IndexError("Can not operate on a closed map. Call open() first.")
  314. if key < 0: # Handle negative indices
  315. key += self._rows
  316. if key >= self._rows:
  317. raise IndexError("The row index {0} is out of range [0, {1}).".format(key, self._rows))
  318. return self.get_row(key)
  319. else:
  320. fatal("Invalid argument type.")
  321. def __iter__(self):
  322. """Return a constructor of the class"""
  323. return (self.__getitem__(irow) for irow in range(self._rows))
  324. def _repr_png_(self):
  325. return raw_figure(utils.r_export(self))
  326. def exist(self):
  327. """Return True if the map already exist, and
  328. set the mapset if were not set.
  329. call the C function `G_find_raster`.
  330. >>> ele = RasterAbstractBase(test_raster_name)
  331. >>> ele.exist()
  332. True
  333. """
  334. if self.name:
  335. if self.mapset == '':
  336. mapset = utils.get_mapset_raster(self.name, self.mapset)
  337. self.mapset = mapset if mapset else ''
  338. return True if mapset else False
  339. return bool(utils.get_mapset_raster(self.name, self.mapset))
  340. else:
  341. return False
  342. def is_open(self):
  343. """Return True if the map is open False otherwise.
  344. >>> ele = RasterAbstractBase(test_raster_name)
  345. >>> ele.is_open()
  346. False
  347. """
  348. return True if self._fd is not None and self._fd >= 0 else False
  349. @must_be_open
  350. def close(self):
  351. """Close the map"""
  352. libraster.Rast_close(self._fd)
  353. # update rows and cols attributes
  354. self._rows = None
  355. self._cols = None
  356. self._fd = None
  357. def remove(self):
  358. """Remove the map"""
  359. if self.is_open():
  360. self.close()
  361. utils.remove(self.name, 'rast')
  362. def fullname(self):
  363. """Return the full name of a raster map: name@mapset"""
  364. return "{name}@{mapset}".format(name=self.name, mapset=self.mapset)
  365. def name_mapset(self, name=None, mapset=None):
  366. """Return the full name of the Raster.
  367. >>> ele = RasterAbstractBase(test_raster_name)
  368. >>> name = ele.name_mapset().split("@")
  369. >>> name
  370. ['abstract_test_map']
  371. """
  372. if name is None:
  373. name = self.name
  374. if mapset is None:
  375. self.exist()
  376. mapset = self.mapset
  377. gis_env = gisenv()
  378. if mapset and mapset != gis_env['MAPSET']:
  379. return "{name}@{mapset}".format(name=name, mapset=mapset)
  380. else:
  381. return name
  382. def rename(self, newname):
  383. """Rename the map"""
  384. if self.exist():
  385. utils.rename(self.name, newname, 'rast')
  386. self._name = newname
  387. def set_region_from_rast(self, rastname='', mapset=''):
  388. """Set the computational region from a map,
  389. if rastername and mapset is not specify, use itself.
  390. This region will be used by all
  391. raster map layers that are opened in the same process.
  392. The GRASS region settings will not be modified.
  393. call C function `Rast_get_cellhd`, `Rast_set_window`
  394. """
  395. if self.is_open():
  396. fatal("You cannot change the region if map is open")
  397. raise
  398. region = Region()
  399. if rastname == '':
  400. rastname = self.name
  401. if mapset == '':
  402. mapset = self.mapset
  403. libraster.Rast_get_cellhd(rastname, mapset,
  404. region.byref())
  405. self._set_raster_window(region)
  406. def set_region(self, region):
  407. """Set the computational region that can be different from the
  408. current region settings. This region will be used by all
  409. raster map layers that are opened in the same process.
  410. The GRASS region settings will not be modified.
  411. """
  412. if self.is_open():
  413. fatal("You cannot change the region if map is open")
  414. raise
  415. self._set_raster_window(region)
  416. def _set_raster_window(self, region):
  417. libraster.Rast_set_window(region.byref())
  418. # update rows and cols attributes
  419. self._rows = libraster.Rast_window_rows()
  420. self._cols = libraster.Rast_window_cols()
  421. @must_be_open
  422. def get_value(self, point, region=None):
  423. """This method returns the pixel value of a given pair of coordinates:
  424. :param point: pair of coordinates in tuple object or class object with coords() method
  425. """
  426. # Check for tuple
  427. if not isinstance(point, list) and not isinstance(point, tuple):
  428. point = point.coords()
  429. if not region:
  430. region = Region()
  431. row, col = utils.coor2pixel(point, region)
  432. if col < 0 or col > region.cols or row < 0 or row > region.rows:
  433. return None
  434. line = self.get_row(int(row))
  435. return line[int(col)]
  436. @must_be_open
  437. def has_cats(self):
  438. """Return True if the raster map has categories"""
  439. if self.exist():
  440. self.cats.read()
  441. if len(self.cats) != 0:
  442. return True
  443. return False
  444. @must_be_open
  445. def num_cats(self):
  446. """Return the number of categories"""
  447. return len(self.cats)
  448. @must_be_open
  449. def copy_cats(self, raster):
  450. """Copy categories from another raster map object"""
  451. self.cats.copy(raster.cats)
  452. @must_be_open
  453. def sort_cats(self):
  454. """Sort categories order by range"""
  455. self.cats.sort()
  456. @must_be_open
  457. def read_cats(self):
  458. """Read category from the raster map file"""
  459. self.cats.read(self)
  460. @must_be_open
  461. def write_cats(self):
  462. """Write category to the raster map file"""
  463. self.cats.write(self)
  464. @must_be_open
  465. def read_cats_rules(self, filename, sep=':'):
  466. """Read category from the raster map file"""
  467. self.cats.read_rules(filename, sep)
  468. @must_be_open
  469. def write_cats_rules(self, filename, sep=':'):
  470. """Write category to the raster map file"""
  471. self.cats.write_rules(filename, sep)
  472. @must_be_open
  473. def get_cats(self):
  474. """Return a category object"""
  475. cat = Category(name=self.name, mapset=self.mapset)
  476. cat.read()
  477. return cat
  478. @must_be_open
  479. def set_cats(self, category):
  480. """The internal categories are copied from this object."""
  481. self.cats.copy(category)
  482. @must_be_open
  483. def get_cat(self, label):
  484. """Return a category given an index or a label"""
  485. return self.cats[label]
  486. @must_be_open
  487. def set_cat(self, label, min_cat, max_cat=None, index=None):
  488. """Set or update a category"""
  489. self.cats.set_cat(index, (label, min_cat, max_cat))
  490. if __name__ == "__main__":
  491. import doctest
  492. from grass.pygrass.modules import Module
  493. Module("g.region", n=40, s=0, e=40, w=0, res=10)
  494. Module("r.mapcalc", expression="%s = row() + (10 * col())" % (test_raster_name),
  495. overwrite=True)
  496. doctest.testmod()
  497. """Remove the generated vector map, if exist"""
  498. mset = utils.get_mapset_raster(test_raster_name, mapset='')
  499. if mset:
  500. Module("g.remove", flags='f', type='raster', name=test_raster_name)