abstract.py 13 KB

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