abstract.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  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 grass.pygrass.raster.raster_type import TYPE as RTYPE
  27. from grass.pygrass.raster.category import Category
  28. from grass.pygrass.raster.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.read()
  45. >>> info
  46. elevation@
  47. rows: 1350
  48. cols: 1500
  49. north: 228500.0 south: 215000.0 nsres:10.0
  50. east: 645000.0 west: 630000.0 ewres:10.0
  51. range: 56, 156
  52. proj: 99
  53. <BLANKLINE>
  54. """
  55. self.name = name
  56. self.mapset = mapset
  57. self.c_region = ctypes.pointer(libgis.Cell_head())
  58. self.c_range = ctypes.pointer(libraster.Range())
  59. def _get_range(self):
  60. libraster.Rast_read_range(self.name, self.mapset, self.c_range)
  61. def _get_raster_region(self):
  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="", *aopen, **kwopen):
  144. """The constructor need at least the name of the map
  145. *optional* field is the `mapset`.
  146. >>> ele = RasterAbstractBase('elevation')
  147. >>> ele.name
  148. u'elevation'
  149. >>> ele.exist()
  150. True
  151. >>> ele.mapset
  152. 'PERMANENT'
  153. ..
  154. """
  155. self.mapset = mapset
  156. self._name = name
  157. ## Private attribute `_fd` that return the file descriptor of the map
  158. self._fd = None
  159. ## Private attribute `_rows` that return the number of rows
  160. # in active window, When the class is instanced is empty and it is set
  161. # when you open the file, using Rast_window_rows()
  162. self._rows = None
  163. ## Private attribute `_cols` that return the number of rows
  164. # in active window, When the class is instanced is empty and it is set
  165. # when you open the file, using Rast_window_cols()
  166. self._cols = None
  167. #self.region = Region()
  168. self.hist = History(self.name, self.mapset)
  169. self.cats = Category(self.name, self.mapset)
  170. self.info = Info(self.name, self.mapset)
  171. self._aopen = aopen
  172. self._kwopen = kwopen
  173. self._mtype = 'CELL'
  174. self._mode = 'r'
  175. self._overwrite = False
  176. def __enter__(self):
  177. self.open(*self._aopen, **self._kwopen)
  178. return self
  179. def __exit__(self, exc_type, exc_value, traceback):
  180. self.close()
  181. def _get_mtype(self):
  182. """Private method to get the Raster type"""
  183. return self._mtype
  184. def _set_mtype(self, mtype):
  185. """Private method to change the Raster type"""
  186. if mtype.upper() not in ('CELL', 'FCELL', 'DCELL'):
  187. #fatal(_("Raser type: {0} not supported".format(mtype) ) )
  188. str_err = "Raster type: {0} not supported ('CELL','FCELL','DCELL')"
  189. raise ValueError(_(str_err).format(mtype))
  190. self._mtype = mtype
  191. self._gtype = RTYPE[self.mtype]['grass type']
  192. mtype = property(fget=_get_mtype, fset=_set_mtype)
  193. def _get_mode(self):
  194. return self._mode
  195. def _set_mode(self, mode):
  196. if mode.upper() not in ('R', 'W'):
  197. str_err = _("Mode type: {0} not supported ('r', 'w')")
  198. raise ValueError(str_err.format(mode))
  199. self._mode = mode
  200. mode = property(fget=_get_mode, fset=_set_mode)
  201. def _get_overwrite(self):
  202. return self._overwrite
  203. def _set_overwrite(self, overwrite):
  204. if overwrite not in (True, False):
  205. str_err = _("Overwrite type: {0} not supported (True/False)")
  206. raise ValueError(str_err.format(overwrite))
  207. self._overwrite = overwrite
  208. overwrite = property(fget=_get_overwrite, fset=_set_overwrite)
  209. def _get_name(self):
  210. """Private method to return the Raster name"""
  211. return self._name
  212. def _set_name(self, newname):
  213. """Private method to change the Raster name"""
  214. if not functions.is_clean_name(newname):
  215. str_err = _("Map name {0} not valid")
  216. raise ValueError(str_err.format(newname))
  217. if self.exist():
  218. self.rename(newname)
  219. self._name = newname
  220. name = property(fget=_get_name, fset=_set_name)
  221. @must_be_open
  222. def _get_cats_title(self):
  223. return self.cats.title
  224. @must_be_open
  225. def _set_cats_title(self, newtitle):
  226. self.cats.title = newtitle
  227. cats_title = property(fget=_get_cats_title, fset=_set_cats_title)
  228. def __unicode__(self):
  229. return self.name_mapset()
  230. def __str__(self):
  231. """Return the string of the object"""
  232. return self.__unicode__()
  233. def __len__(self):
  234. return self._rows
  235. def __getitem__(self, key):
  236. """Return the row of Raster object, slice allowed."""
  237. if isinstance(key, slice):
  238. #import pdb; pdb.set_trace()
  239. #Get the start, stop, and step from the slice
  240. return (self.get_row(ii) for ii in range(*key.indices(len(self))))
  241. elif isinstance(key, tuple):
  242. x, y = key
  243. return self.get(x, y)
  244. elif isinstance(key, int):
  245. if key < 0: # Handle negative indices
  246. key += self._rows
  247. if key >= self._rows:
  248. fatal(INDXOUTRANGE.format(key))
  249. raise IndexError
  250. return self.get_row(key)
  251. else:
  252. fatal("Invalid argument type.")
  253. def __iter__(self):
  254. """Return a constructor of the class"""
  255. return (self.__getitem__(irow) for irow in range(self._rows))
  256. def _repr_png_(self):
  257. return raw_figure(functions.r_export(self))
  258. def exist(self):
  259. """Return True if the map already exist, and
  260. set the mapset if were not set.
  261. call the C function `G_find_raster`.
  262. >>> ele = RasterAbstractBase('elevation')
  263. >>> ele.exist()
  264. True
  265. """
  266. if self.name:
  267. if self.mapset == '':
  268. mapset = functions.get_mapset_raster(self.name, self.mapset)
  269. self.mapset = mapset if mapset else ''
  270. return True if mapset else False
  271. return bool(functions.get_mapset_raster(self.name, self.mapset))
  272. else:
  273. return False
  274. def is_open(self):
  275. """Return True if the map is open False otherwise.
  276. >>> ele = RasterAbstractBase('elevation')
  277. >>> ele.is_open()
  278. False
  279. """
  280. return True if self._fd is not None and self._fd >= 0 else False
  281. @must_be_open
  282. def close(self):
  283. """Close the map"""
  284. libraster.Rast_close(self._fd)
  285. # update rows and cols attributes
  286. self._rows = None
  287. self._cols = None
  288. self._fd = None
  289. def remove(self):
  290. """Remove the map"""
  291. if self.is_open():
  292. self.close()
  293. functions.remove(self.name, 'rast')
  294. def fullname(self):
  295. """Return the full name of a raster map: name@mapset"""
  296. return "{name}@{mapset}".format(name=self.name, mapset=self.mapset)
  297. def name_mapset(self, name=None, mapset=None):
  298. """Return the full name of the Raster.
  299. >>> ele = RasterAbstractBase('elevation')
  300. >>> ele.name_mapset()
  301. u'elevation@PERMANENT'
  302. """
  303. if name is None:
  304. name = self.name
  305. if mapset is None:
  306. self.exist()
  307. mapset = self.mapset
  308. gis_env = gisenv()
  309. if mapset and mapset != gis_env['MAPSET']:
  310. return "{name}@{mapset}".format(name=name, mapset=mapset)
  311. else:
  312. return name
  313. def rename(self, newname):
  314. """Rename the map"""
  315. if self.exist():
  316. functions.rename(self.name, newname, 'rast')
  317. self._name = newname
  318. def set_from_rast(self, rastname='', mapset=''):
  319. """Set the region that will use from a map, if rastername and mapset
  320. is not specify, use itself.
  321. call C function `Rast_get_cellhd`"""
  322. if self.is_open():
  323. fatal("You cannot change the region if map is open")
  324. raise
  325. region = Region()
  326. if rastname == '':
  327. rastname = self.name
  328. if mapset == '':
  329. mapset = self.mapset
  330. libraster.Rast_get_cellhd(rastname, mapset,
  331. ctypes.byref(region._region))
  332. # update rows and cols attributes
  333. self._rows = libraster.Rast_window_rows()
  334. self._cols = libraster.Rast_window_cols()
  335. @must_be_open
  336. def get_value(self, point, region=None):
  337. """This method returns the pixel value of a given pair of coordinates:
  338. :param point: pair of coordinates in tuple object
  339. """
  340. if not region:
  341. region = Region()
  342. row, col = functions.coor2pixel(point.coords(), region)
  343. if col < 0 or col > region.cols or row < 0 or row > region.rows:
  344. return None
  345. line = self.get_row(int(row))
  346. return line[int(col)]
  347. @must_be_open
  348. def has_cats(self):
  349. """Return True if the raster map has categories"""
  350. if self.exist():
  351. self.cats.read()
  352. if len(self.cats) != 0:
  353. return True
  354. return False
  355. @must_be_open
  356. def num_cats(self):
  357. """Return the number of categories"""
  358. return len(self.cats)
  359. @must_be_open
  360. def copy_cats(self, raster):
  361. """Copy categories from another raster map object"""
  362. self.cats.copy(raster.cats)
  363. @must_be_open
  364. def sort_cats(self):
  365. """Sort categories order by range"""
  366. self.cats.sort()
  367. @must_be_open
  368. def read_cats(self):
  369. """Read category from the raster map file"""
  370. self.cats.read(self)
  371. @must_be_open
  372. def write_cats(self):
  373. """Write category to the raster map file"""
  374. self.cats.write(self)
  375. @must_be_open
  376. def read_cats_rules(self, filename, sep=':'):
  377. """Read category from the raster map file"""
  378. self.cats.read_rules(filename, sep)
  379. @must_be_open
  380. def write_cats_rules(self, filename, sep=':'):
  381. """Write category to the raster map file"""
  382. self.cats.write_rules(filename, sep)
  383. @must_be_open
  384. def get_cats(self):
  385. """Return a category object"""
  386. cat = Category()
  387. cat.read(self)
  388. return cat
  389. @must_be_open
  390. def set_cats(self, category):
  391. """The internal categories are copied from this object."""
  392. self.cats.copy(category)
  393. @must_be_open
  394. def get_cat(self, label):
  395. """Return a category given an index or a label"""
  396. return self.cats[label]
  397. @must_be_open
  398. def set_cat(self, label, min_cat, max_cat=None, index=None):
  399. """Set or update a category"""
  400. self.cats.set_cat(index, (label, min_cat, max_cat))