abstract.py 11 KB

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