abstract.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  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 functions
  19. from grass.pygrass.gis.region import Region
  20. from grass.pygrass.errors import must_be_open
  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 .raster_type import TYPE as RTYPE
  27. from .category import Category
  28. from .history import History
  29. ## Define global variables to not exceed the 80 columns
  30. WARN_OVERWRITE = "Raster map <{0}> already exists and will be overwritten"
  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('elevation')
  44. >>> info # doctest: +ELLIPSIS
  45. elevation@
  46. rows: 1350
  47. cols: 1500
  48. north: 228500.0 south: 215000.0 nsres:10.0
  49. east: 645000.0 west: 630000.0 ewres:10.0
  50. range: 56, 156
  51. proj: 99
  52. ...
  53. """
  54. self.name = name
  55. self.mapset = mapset
  56. self.c_region = ctypes.pointer(libgis.Cell_head())
  57. self.c_range = ctypes.pointer(libraster.Range())
  58. def _get_range(self):
  59. libraster.Rast_read_range(self.name, self.mapset, self.c_range)
  60. def _get_raster_region(self):
  61. if self.name and self.mapset:
  62. libraster.Rast_get_cellhd(self.name, self.mapset, self.c_region)
  63. def read(self):
  64. self._get_range()
  65. self._get_raster_region()
  66. @property
  67. def north(self):
  68. return self.c_region.contents.north
  69. @property
  70. def south(self):
  71. return self.c_region.contents.south
  72. @property
  73. def east(self):
  74. return self.c_region.contents.east
  75. @property
  76. def west(self):
  77. return self.c_region.contents.west
  78. @property
  79. def top(self):
  80. return self.c_region.contents.top
  81. @property
  82. def bottom(self):
  83. return self.c_region.contents.bottom
  84. @property
  85. def rows(self):
  86. return self.c_region.contents.rows
  87. @property
  88. def cols(self):
  89. return self.c_region.contents.cols
  90. @property
  91. def nsres(self):
  92. return self.c_region.contents.ns_res
  93. @property
  94. def ewres(self):
  95. return self.c_region.contents.ew_res
  96. @property
  97. def tbres(self):
  98. return self.c_region.contents.tb_res
  99. @property
  100. def zone(self):
  101. return self.c_region.contents.zone
  102. @property
  103. def proj(self):
  104. return self.c_region.contents.proj
  105. @property
  106. def min(self):
  107. return self.c_range.contents.min
  108. @property
  109. def max(self):
  110. return self.c_range.contents.max
  111. @property
  112. def range(self):
  113. return self.c_range.contents.min, self.c_range.contents.max
  114. def __repr__(self):
  115. return INFO.format(name=self.name, mapset=self.mapset,
  116. rows=self.rows, cols=self.cols,
  117. north=self.north, south=self.south,
  118. east=self.east, west=self.west,
  119. top=self.top, bottom=self.bottom,
  120. nsres=self.nsres, ewres=self.ewres,
  121. tbres=self.tbres, zone=self.zone,
  122. proj=self.proj, min=self.min, max=self.max)
  123. def keys(self):
  124. return ['name', 'mapset', 'rows', 'cols', 'north', 'south',
  125. 'east', 'west', 'top', 'bottom', 'nsres', 'ewres', 'tbres',
  126. 'zone', 'proj', 'min', 'max']
  127. def items(self):
  128. return [(k, self.__getattribute__(k)) for k in self.keys()]
  129. def _repr_html_(self):
  130. return dict2html(dict(self.items()), keys=self.keys(),
  131. border='1', kdec='b')
  132. class RasterAbstractBase(object):
  133. """Raster_abstract_base: The base class from which all sub-classes
  134. inherit. It does not implement any row or map access methods:
  135. * Implements raster metadata information access (Type, ...)
  136. * Implements an open method that will be overwritten by the sub-classes
  137. * Implements the close method that might be overwritten by sub-classes
  138. (should work for simple row access)
  139. * Implements get and set region methods
  140. * Implements color, history and category handling
  141. * Renaming, deletion, ...
  142. """
  143. def __init__(self, name, mapset="",
  144. mode='r', mtype='FCELL', overwrite=False):
  145. """The constructor need at least the name of the map
  146. *optional* field is the `mapset`. ::
  147. >>> ele = RasterAbstractBase('elevation')
  148. >>> ele.name
  149. 'elevation'
  150. >>> ele.exist()
  151. True
  152. >>> ele.mapset
  153. 'PERMANENT'
  154. ..
  155. """
  156. self.mapset = mapset
  157. self._name = name
  158. ## Private attribute `_fd` that return the file descriptor of the map
  159. self._fd = None
  160. ## Private attribute `_rows` that return the number of rows
  161. # in active window, When the class is instanced is empty and it is set
  162. # when you open the file, using Rast_window_rows()
  163. self._rows = None
  164. ## Private attribute `_cols` that return the number of rows
  165. # in active window, When the class is instanced is empty and it is set
  166. # when you open the file, using Rast_window_cols()
  167. self._cols = None
  168. #self.region = Region()
  169. self.hist = History(self.name, self.mapset)
  170. self.cats = Category(self.name, self.mapset)
  171. self.info = Info(self.name, self.mapset)
  172. self.mode = mode
  173. self.mtype = mtype
  174. self.overwrite = overwrite
  175. def __enter__(self):
  176. self.open()
  177. return self
  178. def __exit__(self, exc_type, exc_value, traceback):
  179. self.close()
  180. def _get_mtype(self):
  181. """Private method to get the Raster type"""
  182. return self._mtype
  183. def _set_mtype(self, mtype):
  184. """Private method to change the Raster type"""
  185. if mtype.upper() not in ('CELL', 'FCELL', 'DCELL'):
  186. #fatal(_("Raser type: {0} not supported".format(mtype) ) )
  187. str_err = "Raster type: {0} not supported ('CELL','FCELL','DCELL')"
  188. raise ValueError(_(str_err).format(mtype))
  189. self._mtype = mtype
  190. self._gtype = RTYPE[self.mtype]['grass type']
  191. mtype = property(fget=_get_mtype, fset=_set_mtype)
  192. def _get_mode(self):
  193. return self._mode
  194. def _set_mode(self, mode):
  195. if mode.upper() not in ('R', 'W'):
  196. str_err = _("Mode type: {0} not supported ('r', 'w')")
  197. raise ValueError(str_err.format(mode))
  198. self._mode = mode
  199. mode = property(fget=_get_mode, fset=_set_mode)
  200. def _get_overwrite(self):
  201. return self._overwrite
  202. def _set_overwrite(self, overwrite):
  203. if overwrite not in (True, False):
  204. str_err = _("Overwrite type: {0} not supported (True/False)")
  205. raise ValueError(str_err.format(overwrite))
  206. self._overwrite = overwrite
  207. overwrite = property(fget=_get_overwrite, fset=_set_overwrite)
  208. def _get_name(self):
  209. """Private method to return the Raster name"""
  210. return self._name
  211. def _set_name(self, newname):
  212. """Private method to change the Raster name"""
  213. if not functions.is_clean_name(newname):
  214. str_err = _("Map name {0} not valid")
  215. raise ValueError(str_err.format(newname))
  216. if self.exist():
  217. self.rename(newname)
  218. self._name = newname
  219. name = property(fget=_get_name, fset=_set_name)
  220. @must_be_open
  221. def _get_cats_title(self):
  222. return self.cats.title
  223. @must_be_open
  224. def _set_cats_title(self, newtitle):
  225. self.cats.title = newtitle
  226. cats_title = property(fget=_get_cats_title, fset=_set_cats_title)
  227. def __unicode__(self):
  228. return self.name_mapset()
  229. def __str__(self):
  230. """Return the string of the object"""
  231. return self.__unicode__()
  232. def __len__(self):
  233. return self._rows
  234. def __getitem__(self, key):
  235. """Return the row of Raster object, slice allowed."""
  236. if isinstance(key, slice):
  237. #import pdb; pdb.set_trace()
  238. #Get the start, stop, and step from the slice
  239. return (self.get_row(ii) for ii in range(*key.indices(len(self))))
  240. elif isinstance(key, tuple):
  241. x, y = key
  242. return self.get(x, y)
  243. elif isinstance(key, int):
  244. if key < 0: # Handle negative indices
  245. key += self._rows
  246. if key >= self._rows:
  247. fatal(INDXOUTRANGE.format(key))
  248. raise IndexError
  249. return self.get_row(key)
  250. else:
  251. fatal("Invalid argument type.")
  252. def __iter__(self):
  253. """Return a constructor of the class"""
  254. return (self.__getitem__(irow) for irow in range(self._rows))
  255. def _repr_png_(self):
  256. return raw_figure(functions.r_export(self))
  257. def exist(self):
  258. """Return True if the map already exist, and
  259. set the mapset if were not set.
  260. call the C function `G_find_raster`. ::
  261. >>> ele = RasterAbstractBase('elevation')
  262. >>> ele.exist()
  263. True
  264. """
  265. if self.name:
  266. if self.mapset == '':
  267. mapset = functions.get_mapset_raster(self.name, self.mapset)
  268. self.mapset = mapset if mapset else ''
  269. return True if mapset else False
  270. return bool(functions.get_mapset_raster(self.name, self.mapset))
  271. else:
  272. return False
  273. def is_open(self):
  274. """Return True if the map is open False otherwise. ::
  275. >>> ele = RasterAbstractBase('elevation')
  276. >>> ele.is_open()
  277. False
  278. """
  279. return True if self._fd is not None and self._fd >= 0 else False
  280. @must_be_open
  281. def close(self):
  282. """Close the map"""
  283. libraster.Rast_close(self._fd)
  284. # update rows and cols attributes
  285. self._rows = None
  286. self._cols = None
  287. self._fd = None
  288. def remove(self):
  289. """Remove the map"""
  290. if self.is_open():
  291. self.close()
  292. functions.remove(self.name, 'rast')
  293. def fullname(self):
  294. """Return the full name of a raster map: name@mapset"""
  295. return "{name}@{mapset}".format(name=self.name, mapset=self.mapset)
  296. def name_mapset(self, name=None, mapset=None):
  297. """Return the full name of the Raster. ::
  298. >>> ele = RasterAbstractBase('elevation')
  299. >>> ele.name_mapset()
  300. 'elevation@PERMANENT'
  301. """
  302. if name is None:
  303. name = self.name
  304. if mapset is None:
  305. self.exist()
  306. mapset = self.mapset
  307. gis_env = gisenv()
  308. if mapset and mapset != gis_env['MAPSET']:
  309. return "{name}@{mapset}".format(name=name, mapset=mapset)
  310. else:
  311. return name
  312. def rename(self, newname):
  313. """Rename the map"""
  314. if self.exist():
  315. functions.rename(self.name, newname, 'rast')
  316. self._name = newname
  317. def set_from_rast(self, rastname='', mapset=''):
  318. """Set the region that will use from a map, if rastername and mapset
  319. is not specify, use itself.
  320. call C function `Rast_get_cellhd`"""
  321. if self.is_open():
  322. fatal("You cannot change the region if map is open")
  323. raise
  324. region = Region()
  325. if rastname == '':
  326. rastname = self.name
  327. if mapset == '':
  328. mapset = self.mapset
  329. libraster.Rast_get_cellhd(rastname, mapset,
  330. ctypes.byref(region._region))
  331. # update rows and cols attributes
  332. self._rows = libraster.Rast_window_rows()
  333. self._cols = libraster.Rast_window_cols()
  334. @must_be_open
  335. def get_value(self, point, region=None):
  336. """This method returns the pixel value of a given pair of coordinates:
  337. Parameters
  338. ------------
  339. point = pair of coordinates in tuple object
  340. """
  341. if not region:
  342. region = Region()
  343. row, col = functions.coor2pixel(point.coords(), region)
  344. if col < 0 or col > region.cols or row < 0 or row > region.rows:
  345. return None
  346. line = self.get_row(int(row))
  347. return line[int(col)]
  348. @must_be_open
  349. def has_cats(self):
  350. """Return True if the raster map has categories"""
  351. if self.exist():
  352. self.cats.read(self)
  353. self.close()
  354. if len(self.cats) != 0:
  355. return True
  356. return False
  357. @must_be_open
  358. def num_cats(self):
  359. """Return the number of categories"""
  360. return len(self.cats)
  361. @must_be_open
  362. def copy_cats(self, raster):
  363. """Copy categories from another raster map object"""
  364. self.cats.copy(raster.cats)
  365. @must_be_open
  366. def sort_cats(self):
  367. """Sort categories order by range"""
  368. self.cats.sort()
  369. @must_be_open
  370. def read_cats(self):
  371. """Read category from the raster map file"""
  372. self.cats.read(self)
  373. @must_be_open
  374. def write_cats(self):
  375. """Write category to the raster map file"""
  376. self.cats.write(self)
  377. @must_be_open
  378. def read_cats_rules(self, filename, sep=':'):
  379. """Read category from the raster map file"""
  380. self.cats.read_rules(filename, sep)
  381. @must_be_open
  382. def write_cats_rules(self, filename, sep=':'):
  383. """Write category to the raster map file"""
  384. self.cats.write_rules(filename, sep)
  385. @must_be_open
  386. def get_cats(self):
  387. """Return a category object"""
  388. cat = Category()
  389. cat.read(self)
  390. return cat
  391. @must_be_open
  392. def set_cats(self, category):
  393. """The internal categories are copied from this object."""
  394. self.cats.copy(category)
  395. @must_be_open
  396. def get_cat(self, label):
  397. """Return a category given an index or a label"""
  398. return self.cats[label]
  399. @must_be_open
  400. def set_cat(self, label, min_cat, max_cat=None, index=None):
  401. """Set or update a category"""
  402. self.cats.set_cat(index, (label, min_cat, max_cat))