abstract.py 11 KB

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