abstract.py 11 KB

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