abstract.py 14 KB

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