abstract.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  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. ## 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. class RasterAbstractBase(object):
  33. """Raster_abstract_base: The base class from which all sub-classes
  34. inherit. It does not implement any row or map access methods:
  35. * Implements raster metadata information access (Type, ...)
  36. * Implements an open method that will be overwritten by the sub-classes
  37. * Implements the close method that might be overwritten by sub-classes
  38. (should work for simple row access)
  39. * Implements get and set region methods
  40. * Implements color, history and category handling
  41. * Renaming, deletion, ...
  42. """
  43. def __init__(self, name, mapset=""):
  44. """The constructor need at least the name of the map
  45. *optional* field is the `mapset`. ::
  46. >>> land = RasterAbstractBase('landcover_1m')
  47. >>> land.name
  48. 'landcover_1m'
  49. >>> land.mapset
  50. ''
  51. >>> land.exist()
  52. True
  53. >>> land.mapset
  54. 'PERMANENT'
  55. ..
  56. """
  57. self.mapset = mapset
  58. #self.region = Region()
  59. self.cats = Category()
  60. self._name = name
  61. ## Private attribute `_fd` that return the file descriptor of the map
  62. self._fd = None
  63. ## Private attribute `_rows` that return the number of rows
  64. # in active window, When the class is instanced is empty and it is set
  65. # when you open the file, using Rast_window_rows()
  66. self._rows = None
  67. ## Private attribute `_cols` that return the number of rows
  68. # in active window, When the class is instanced is empty and it is set
  69. # when you open the file, using Rast_window_cols()
  70. self._cols = None
  71. def _get_mtype(self):
  72. return self._mtype
  73. def _set_mtype(self, mtype):
  74. if mtype.upper() not in ('CELL', 'FCELL', 'DCELL'):
  75. #fatal(_("Raser type: {0} not supported".format(mtype) ) )
  76. str_err = "Raster type: {0} not supported ('CELL','FCELL','DCELL')"
  77. raise ValueError(_(str_err).format(mtype))
  78. self._mtype = mtype
  79. self._gtype = RTYPE[self.mtype]['grass type']
  80. mtype = property(fget=_get_mtype, fset=_set_mtype)
  81. def _get_mode(self):
  82. return self._mode
  83. def _set_mode(self, mode):
  84. if mode.upper() not in ('R', 'W'):
  85. str_err = _("Mode type: {0} not supported ('r', 'w')")
  86. raise ValueError(str_err.format(mode))
  87. self._mode = mode
  88. mode = property(fget=_get_mode, fset=_set_mode)
  89. def _get_overwrite(self):
  90. return self._overwrite
  91. def _set_overwrite(self, overwrite):
  92. if overwrite not in (True, False):
  93. str_err = _("Overwrite type: {0} not supported (True/False)")
  94. raise ValueError(str_err.format(overwrite))
  95. self._overwrite = overwrite
  96. overwrite = property(fget=_get_overwrite, fset=_set_overwrite)
  97. def _get_name(self):
  98. """Private method to return the Raster name"""
  99. return self._name
  100. def _set_name(self, newname):
  101. """Private method to change the Raster name"""
  102. if not functions.is_clean_name(newname):
  103. str_err = _("Map name {0} not valid")
  104. raise ValueError(str_err.format(newname))
  105. if self.exist():
  106. self.rename(newname)
  107. self._name = newname
  108. name = property(fget=_get_name, fset=_set_name)
  109. @must_be_open
  110. def _get_rows(self):
  111. """Private method to return the Raster name"""
  112. return self._rows
  113. def _set_unchangeable(self, new):
  114. """Private method to change the Raster name"""
  115. warning(_("Unchangeable attribute"))
  116. rows = property(fget=_get_rows, fset=_set_unchangeable)
  117. @must_be_open
  118. def _get_cols(self):
  119. """Private method to return the Raster name"""
  120. return self._cols
  121. cols = property(fget=_get_cols, fset=_set_unchangeable)
  122. @must_be_open
  123. def _get_range(self):
  124. if self.mtype == 'CELL':
  125. maprange = libraster.Range()
  126. libraster.Rast_read_range(self.name, self.mapset,
  127. ctypes.byref(maprange))
  128. self._min = libgis.CELL()
  129. self._max = libgis.CELL()
  130. self._min.value = maprange.min
  131. self._max.value = maprange.max
  132. else:
  133. maprange = libraster.FPRange()
  134. libraster.Rast_read_fp_range(self.name, self.mapset,
  135. ctypes.byref(maprange))
  136. self._min = libgis.DCELL()
  137. self._max = libgis.DCELL()
  138. libraster.Rast_get_fp_range_min_max(ctypes.byref(maprange),
  139. ctypes.byref(self._min),
  140. ctypes.byref(self._max))
  141. return self._min.value, self._max.value
  142. range = property(fget=_get_range, fset=_set_unchangeable)
  143. @must_be_open
  144. def _get_cats_title(self):
  145. return self.cats.title
  146. @must_be_open
  147. def _set_cats_title(self, newtitle):
  148. self.cats.title = newtitle
  149. cats_title = property(fget=_get_cats_title, fset=_set_cats_title)
  150. def __unicode__(self):
  151. return self.name_mapset()
  152. def __str__(self):
  153. """Return the string of the object"""
  154. return self.__unicode__()
  155. def __len__(self):
  156. return self._rows
  157. def __getitem__(self, key):
  158. """Return the row of Raster object, slice allowed."""
  159. if isinstance(key, slice):
  160. #import pdb; pdb.set_trace()
  161. #Get the start, stop, and step from the slice
  162. return (self.get_row(ii) for ii in xrange(*key.indices(len(self))))
  163. elif isinstance(key, tuple):
  164. x, y = key
  165. return self.get(x, y)
  166. elif isinstance(key, int):
  167. if key < 0: # Handle negative indices
  168. key += self._rows
  169. if key >= self._rows:
  170. fatal(INDXOUTRANGE.format(key))
  171. raise IndexError
  172. return self.get_row(key)
  173. else:
  174. fatal("Invalid argument type.")
  175. def __iter__(self):
  176. """Return a constructor of the class"""
  177. return (self.__getitem__(irow) for irow in xrange(self._rows))
  178. def exist(self):
  179. """Return True if the map already exist, and
  180. set the mapset if were not set.
  181. call the C function `G_find_raster`."""
  182. if self.name:
  183. self.mapset = functions.get_mapset_raster(self.name, self.mapset)
  184. else:
  185. return False
  186. if self.mapset:
  187. return True
  188. else:
  189. return False
  190. def is_open(self):
  191. """Return True if the map is open False otherwise"""
  192. return True if self._fd is not None and self._fd >= 0 else False
  193. @must_be_open
  194. def close(self):
  195. """Close the map"""
  196. libraster.Rast_close(self._fd)
  197. # update rows and cols attributes
  198. self._rows = None
  199. self._cols = None
  200. self._fd = None
  201. def remove(self):
  202. """Remove the map"""
  203. if self.is_open():
  204. self.close()
  205. grasscore.run_command('g.remove', rast=self.name)
  206. def name_mapset(self, name=None, mapset=None):
  207. if name is None:
  208. name = self.name
  209. if mapset is None:
  210. self.exist()
  211. mapset = self.mapset
  212. gis_env = gisenv()
  213. if mapset and mapset != gis_env['MAPSET']:
  214. return "{name}@{mapset}".format(name=name, mapset=mapset)
  215. else:
  216. return name
  217. def rename(self, newname):
  218. """Rename the map"""
  219. if self.exist():
  220. functions.rename(self.name, newname, 'rast')
  221. self._name = newname
  222. def set_from_rast(self, rastname='', mapset=''):
  223. """Set the region that will use from a map, if rastername and mapset
  224. is not specify, use itself.
  225. call C function `Rast_get_cellhd`"""
  226. if self.is_open():
  227. fatal("You cannot change the region if map is open")
  228. raise
  229. region = Region()
  230. if rastname == '':
  231. rastname = self.name
  232. if mapset == '':
  233. mapset = self.mapset
  234. libraster.Rast_get_cellhd(rastname, mapset,
  235. ctypes.byref(region._region))
  236. # update rows and cols attributes
  237. self._rows = libraster.Rast_window_rows()
  238. self._cols = libraster.Rast_window_cols()
  239. @must_be_open
  240. def get_value(self, point, region=None):
  241. """This method returns the pixel value of a given pair of coordinates:
  242. Parameters
  243. ------------
  244. point = pair of coordinates in tuple object
  245. """
  246. if not region:
  247. region = Region()
  248. x, y = functions.coor2pixel(point.coords(), region)
  249. if x < 0 or x > region.cols or y < 0 or y > region.rows:
  250. return None
  251. line = self.get_row(int(x))
  252. return line[int(y)]
  253. @must_be_open
  254. def has_cats(self):
  255. """Return True if the raster map has categories"""
  256. if self.exist():
  257. self.cats.read(self)
  258. self.close()
  259. if len(self.cats) != 0:
  260. return True
  261. return False
  262. @must_be_open
  263. def num_cats(self):
  264. """Return the number of categories"""
  265. return len(self.cats)
  266. @must_be_open
  267. def copy_cats(self, raster):
  268. """Copy categories from another raster map object"""
  269. self.cats.copy(raster.cats)
  270. @must_be_open
  271. def sort_cats(self):
  272. """Sort categories order by range"""
  273. self.cats.sort()
  274. @must_be_open
  275. def read_cats(self):
  276. """Read category from the raster map file"""
  277. self.cats.read(self)
  278. @must_be_open
  279. def write_cats(self):
  280. """Write category to the raster map file"""
  281. self.cats.write(self)
  282. @must_be_open
  283. def read_cats_rules(self, filename, sep=':'):
  284. """Read category from the raster map file"""
  285. self.cats.read_rules(filename, sep)
  286. @must_be_open
  287. def write_cats_rules(self, filename, sep=':'):
  288. """Write category to the raster map file"""
  289. self.cats.write_rules(filename, sep)
  290. @must_be_open
  291. def get_cats(self):
  292. """Return a category object"""
  293. cat = Category()
  294. cat.read(self)
  295. return cat
  296. @must_be_open
  297. def set_cats(self, category):
  298. """The internal categories are copied from this object."""
  299. self.cats.copy(category)
  300. @must_be_open
  301. def get_cat(self, label):
  302. """Return a category given an index or a label"""
  303. return self.cats[label]
  304. @must_be_open
  305. def set_cat(self, label, min_cat, max_cat=None, index=None):
  306. """Set or update a category"""
  307. self.cats.set_cat(index, (label, min_cat, max_cat))