abstract.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  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. from pygrass import functions
  20. from pygrass.gis.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. @must_be_open
  107. def _get_rows(self):
  108. """Private method to return the Raster name"""
  109. return self._rows
  110. def _set_unchangeable(self, new):
  111. """Private method to change the Raster name"""
  112. warning(_("Unchangeable attribute"))
  113. rows = property(fget=_get_rows, fset=_set_unchangeable)
  114. @must_be_open
  115. def _get_cols(self):
  116. """Private method to return the Raster name"""
  117. return self._cols
  118. cols = property(fget=_get_cols, fset=_set_unchangeable)
  119. @must_be_open
  120. def _get_range(self):
  121. if self.mtype == 'CELL':
  122. maprange = libraster.Range()
  123. libraster.Rast_read_range(self.name, self.mapset,
  124. ctypes.byref(maprange))
  125. self._min = libgis.CELL()
  126. self._max = libgis.CELL()
  127. self._min.value = maprange.min
  128. self._max.value = maprange.max
  129. else:
  130. maprange = libraster.FPRange()
  131. libraster.Rast_read_fp_range(self.name, self.mapset,
  132. ctypes.byref(maprange))
  133. self._min = libgis.DCELL()
  134. self._max = libgis.DCELL()
  135. libraster.Rast_get_fp_range_min_max(ctypes.byref(maprange),
  136. ctypes.byref(self._min),
  137. ctypes.byref(self._max))
  138. return self._min.value, self._max.value
  139. range = property(fget=_get_range, fset=_set_unchangeable)
  140. @must_be_open
  141. def _get_cats_title(self):
  142. return self.cats.title
  143. @must_be_open
  144. def _set_cats_title(self, newtitle):
  145. self.cats.title = newtitle
  146. cats_title = property(fget=_get_cats_title, fset=_set_cats_title)
  147. def __unicode__(self):
  148. return self.name_mapset()
  149. def __str__(self):
  150. """Return the string of the object"""
  151. return self.__unicode__()
  152. def __len__(self):
  153. return self._rows
  154. def __getitem__(self, key):
  155. """Return the row of Raster object, slice allowed."""
  156. if isinstance(key, slice):
  157. #import pdb; pdb.set_trace()
  158. #Get the start, stop, and step from the slice
  159. return (self.get_row(ii) for ii in xrange(*key.indices(len(self))))
  160. elif isinstance(key, tuple):
  161. x, y = key
  162. return self.get(x, y)
  163. elif isinstance(key, int):
  164. if key < 0: # Handle negative indices
  165. key += self._rows
  166. if key >= self._rows:
  167. fatal(INDXOUTRANGE.format(key))
  168. raise IndexError
  169. return self.get_row(key)
  170. else:
  171. fatal("Invalid argument type.")
  172. def __iter__(self):
  173. """Return a constructor of the class"""
  174. return (self.__getitem__(irow) for irow in xrange(self._rows))
  175. def exist(self):
  176. """Return True if the map already exist, and
  177. set the mapset if were not set.
  178. call the C function `G_find_raster`."""
  179. if self.name:
  180. self.mapset = functions.get_mapset_raster(self.name, self.mapset)
  181. else:
  182. return False
  183. if self.mapset:
  184. return True
  185. else:
  186. return False
  187. def is_open(self):
  188. """Return True if the map is open False otherwise"""
  189. return True if self._fd is not None and self._fd >= 0 else False
  190. @must_be_open
  191. def close(self):
  192. """Close the map"""
  193. libraster.Rast_close(self._fd)
  194. # update rows and cols attributes
  195. self._rows = None
  196. self._cols = None
  197. self._fd = None
  198. def remove(self):
  199. """Remove the map"""
  200. if self.is_open():
  201. self.close()
  202. grasscore.run_command('g.remove', rast=self.name)
  203. def name_mapset(self, name=None, mapset=None):
  204. if name is None:
  205. name = self.name
  206. if mapset is None:
  207. self.exist()
  208. mapset = self.mapset
  209. gis_env = gisenv()
  210. if mapset and mapset != gis_env['MAPSET']:
  211. return "{name}@{mapset}".format(name=name, mapset=mapset)
  212. else:
  213. return name
  214. def rename(self, newname):
  215. """Rename the map"""
  216. if self.exist():
  217. functions.rename(self.name, newname, 'rast')
  218. self._name = newname
  219. def set_from_rast(self, rastname='', mapset=''):
  220. """Set the region that will use from a map, if rastername and mapset
  221. is not specify, use itself.
  222. call C function `Rast_get_cellhd`"""
  223. if self.is_open():
  224. fatal("You cannot change the region if map is open")
  225. raise
  226. region = Region()
  227. if rastname == '':
  228. rastname = self.name
  229. if mapset == '':
  230. mapset = self.mapset
  231. libraster.Rast_get_cellhd(rastname, mapset,
  232. ctypes.byref(region._region))
  233. # update rows and cols attributes
  234. self._rows = libraster.Rast_window_rows()
  235. self._cols = libraster.Rast_window_cols()
  236. @must_be_open
  237. def get_value(self, point, region=None):
  238. """This method returns the pixel value of a given pair of coordinates:
  239. Parameters
  240. ------------
  241. point = pair of coordinates in tuple object
  242. """
  243. if not region:
  244. region = Region()
  245. x, y = functions.coor2pixel(point.coords(), region)
  246. if x < 0 or x > region.cols or y < 0 or y > region.rows:
  247. return None
  248. line = self.get_row(int(x))
  249. return line[int(y)]
  250. @must_be_open
  251. def has_cats(self):
  252. """Return True if the raster map has categories"""
  253. if self.exist():
  254. self.cats.read(self)
  255. self.close()
  256. if len(self.cats) != 0:
  257. return True
  258. return False
  259. @must_be_open
  260. def num_cats(self):
  261. """Return the number of categories"""
  262. return len(self.cats)
  263. @must_be_open
  264. def copy_cats(self, raster):
  265. """Copy categories from another raster map object"""
  266. self.cats.copy(raster.cats)
  267. @must_be_open
  268. def sort_cats(self):
  269. """Sort categories order by range"""
  270. self.cats.sort()
  271. @must_be_open
  272. def read_cats(self):
  273. """Read category from the raster map file"""
  274. self.cats.read(self)
  275. @must_be_open
  276. def write_cats(self):
  277. """Write category to the raster map file"""
  278. self.cats.write(self)
  279. @must_be_open
  280. def read_cats_rules(self, filename, sep=':'):
  281. """Read category from the raster map file"""
  282. self.cats.read_rules(filename, sep)
  283. @must_be_open
  284. def write_cats_rules(self, filename, sep=':'):
  285. """Write category to the raster map file"""
  286. self.cats.write_rules(filename, sep)
  287. @must_be_open
  288. def get_cats(self):
  289. """Return a category object"""
  290. cat = Category()
  291. cat.read(self)
  292. return cat
  293. @must_be_open
  294. def set_cats(self, category):
  295. """The internal categories are copied from this object."""
  296. self.cats.copy(category)
  297. @must_be_open
  298. def get_cat(self, label):
  299. """Return a category given an index or a label"""
  300. return self.cats[label]
  301. @must_be_open
  302. def set_cat(self, label, min_cat, max_cat=None, index=None):
  303. """Set or update a category"""
  304. self.cats.set_cat(index, (label, min_cat, max_cat))