abstract.py 14 KB

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