category.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on Thu Jun 28 17:44:14 2012
  4. @author: pietro
  5. """
  6. import ctypes
  7. from operator import itemgetter
  8. import grass.lib.raster as libraster
  9. from grass.pygrass.errors import GrassError
  10. from grass.pygrass.raster.raster_type import TYPE as RTYPE
  11. class Category(list):
  12. """
  13. I would like to add the following functions:
  14. Getting the umber of cats:
  15. Rast_number_of_cats() <- Important for ith access
  16. Getting and setting the title:
  17. Rast_get_cats_title()
  18. Rast_set_cats_title()
  19. Do not use these functions for category access:
  20. Rast_get_cat()
  21. and the specialized types for CELL, FCELL and DCELL.
  22. Since these functions are working on hidden static buffer.
  23. Use the ith-get methods:
  24. Rast_get_ith_c_cat()
  25. Rast_get_ith_f_cat()
  26. Rast_get_ith_d_cat()
  27. This can be implemented using an iterator too. So that the category object
  28. provides the [] access operator to the categories, returning a tuple
  29. (label, min, max).
  30. Using this, the category object must be aware of its raster map type.
  31. Set categories using:
  32. Rast_set_c_cat()
  33. Rast_set_f_cat()
  34. Rast_set_d_cat()
  35. Misc:
  36. Rast_sort_cats()
  37. Rast_copy_cats() <- This should be wrapped so that categories from an
  38. existing Python category class are copied.
  39. >>> import grass.lib.raster as libraster
  40. >>> import ctypes
  41. >>> import grass.pygrass as pygrass
  42. >>> land = pygrass.raster.RasterRow('geology')
  43. >>> cats = pygrass.raster.Category()
  44. >>> cats.read(land) # or with cats.read(land.name, land.mapset, land.mtype)
  45. >>> cats.labels()
  46. ['pond', 'forest', 'developed', 'bare', 'paved road', 'dirt road',
  47. 'vineyard', 'agriculture', 'wetland', 'bare ground path', 'grass']
  48. >>> min_cat = ctypes.c_void_p()
  49. >>> max_cat = ctypes.c_void_p()
  50. >>> libraster.Rast_get_ith_c_cat(ctypes.byref(cats.cats), 0,
  51. ... min_cat, max_cat)
  52. """
  53. def __init__(self, name, mapset='', mtype=None, *args, **kargs):
  54. self.name = name
  55. self.mapset = mapset
  56. self.c_cats = libraster.Categories()
  57. libraster.Rast_init_cats("", ctypes.byref(self.c_cats))
  58. self._mtype = mtype
  59. self._gtype = None if mtype is None else RTYPE[mtype]['grass type']
  60. super(Category, self).__init__(*args, **kargs)
  61. def _get_mtype(self):
  62. return self._mtype
  63. def _set_mtype(self, mtype):
  64. if mtype.upper() not in ('CELL', 'FCELL', 'DCELL'):
  65. #fatal(_("Raser type: {0} not supported".format(mtype) ) )
  66. raise ValueError(_("Raser type: {0} not supported".format(mtype)))
  67. self._mtype = mtype
  68. self._gtype = RTYPE[self.mtype]['grass type']
  69. mtype = property(fget=_get_mtype, fset=_set_mtype)
  70. def _get_title(self):
  71. return libraster.Rast_get_cats_title(ctypes.byref(self.c_cats))
  72. def _set_title(self, newtitle):
  73. return libraster.Rast_set_cats_title(newtitle,
  74. ctypes.byref(self.c_cats))
  75. title = property(fget=_get_title, fset=_set_title)
  76. def __str__(self):
  77. return self.__repr__()
  78. def __list__(self):
  79. cats = []
  80. for cat in self.__iter__():
  81. cats.append(cat)
  82. return cats
  83. def __dict__(self):
  84. diz = dict()
  85. for cat in self.__iter__():
  86. label, min_cat, max_cat = cat
  87. diz[(min_cat, max_cat)] = label
  88. return diz
  89. def __repr__(self):
  90. cats = []
  91. for cat in self.__iter__():
  92. cats.append(repr(cat))
  93. return "[{0}]".format(',\n '.join(cats))
  94. def _chk_index(self, index):
  95. if type(index) == str:
  96. try:
  97. index = self.labels().index(index)
  98. except ValueError:
  99. raise KeyError(index)
  100. return index
  101. def _chk_value(self, value):
  102. if type(value) == tuple:
  103. length = len(value)
  104. if length == 2:
  105. label, min_cat = value
  106. value = (label, min_cat, None)
  107. elif length < 2 or length > 3:
  108. raise TypeError('Tuple with a length that is not supported.')
  109. else:
  110. raise TypeError('Only Tuple are supported.')
  111. return value
  112. def __getitem__(self, index):
  113. return super(Category, self).__getitem__(self._chk_index(index))
  114. def __setitem__(self, index, value):
  115. return super(Category, self).__setitem__(self._chk_index(index),
  116. self._chk_value(value))
  117. def _get_c_cat(self, index):
  118. """Returns i-th description and i-th data range from the list of
  119. category descriptions with corresponding data ranges. end points of
  120. data interval.
  121. Rast_get_ith_cat(const struct Categories * pcats,
  122. int i,
  123. void * rast1,
  124. void * rast2,
  125. RASTER_MAP_TYPE data_type
  126. )
  127. """
  128. min_cat = ctypes.pointer(RTYPE[self.mtype]['grass def']())
  129. max_cat = ctypes.pointer(RTYPE[self.mtype]['grass def']())
  130. lab = libraster.Rast_get_ith_cat(ctypes.byref(self.c_cats),
  131. index,
  132. ctypes.cast(min_cat, ctypes.c_void_p),
  133. ctypes.cast(max_cat, ctypes.c_void_p),
  134. self._gtype)
  135. # Manage C function Errors
  136. if lab == '':
  137. raise GrassError(_("Error executing: Rast_get_ith_cat"))
  138. if max_cat.contents.value == min_cat.contents.value:
  139. max_cat = None
  140. else:
  141. max_cat = max_cat.contents.value
  142. return lab, min_cat.contents.value, max_cat
  143. def _set_c_cat(self, label, min_cat, max_cat=None):
  144. """Adds the label for range min through max in category structure cats.
  145. int Rast_set_cat(const void * rast1,
  146. const void * rast2,
  147. const char * label,
  148. struct Categories * pcats,
  149. RASTER_MAP_TYPE data_type
  150. )
  151. """
  152. max_cat = min_cat if max_cat is None else max_cat
  153. min_cat = ctypes.pointer(RTYPE[self.mtype]['grass def'](min_cat))
  154. max_cat = ctypes.pointer(RTYPE[self.mtype]['grass def'](max_cat))
  155. err = libraster.Rast_set_cat(ctypes.cast(min_cat, ctypes.c_void_p),
  156. ctypes.cast(max_cat, ctypes.c_void_p),
  157. label,
  158. ctypes.byref(self.c_cats), self._gtype)
  159. # Manage C function Errors
  160. if err == 1:
  161. return None
  162. elif err == 0:
  163. raise GrassError(_("Null value detected"))
  164. elif err == -1:
  165. raise GrassError(_("Error executing: Rast_set_cat"))
  166. def __del__(self):
  167. libraster.Rast_free_cats(ctypes.byref(self.c_cats))
  168. def get_cat(self, index):
  169. return self.__getitem__(index)
  170. def set_cat(self, index, value):
  171. if index is None:
  172. self.append(value)
  173. elif index < self.__len__():
  174. self.__setitem__(index, value)
  175. else:
  176. raise TypeError("Index outside range.")
  177. def reset(self):
  178. for i in range(len(self) - 1, -1, -1):
  179. del(self[i])
  180. libraster.Rast_init_cats("", ctypes.byref(self.c_cats))
  181. def _read_cats(self):
  182. """Copy from the C struct to the list"""
  183. for i in range(self.c_cats.ncats):
  184. self.append(self._get_c_cat(i))
  185. def _write_cats(self):
  186. """Copy from the list data to the C struct"""
  187. # reset only the C struct
  188. libraster.Rast_init_cats("", ctypes.byref(self.c_cats))
  189. # write to the c struct
  190. for cat in self.__iter__():
  191. label, min_cat, max_cat = cat
  192. if max_cat is None:
  193. max_cat = min_cat
  194. self._set_c_cat(label, min_cat, max_cat)
  195. def read(self):
  196. """Read categories from a raster map
  197. The category file for raster map name in mapset is read into the
  198. cats structure. If there is an error reading the category file,
  199. a diagnostic message is printed.
  200. int Rast_read_cats(const char * name,
  201. const char * mapset,
  202. struct Categories * pcats
  203. )
  204. """
  205. self.reset()
  206. err = libraster.Rast_read_cats(self.name, self.mapset,
  207. ctypes.byref(self.c_cats))
  208. if err == -1:
  209. raise GrassError("Can not read the categories.")
  210. # copy from C struct to list
  211. self._read_cats()
  212. def write(self):
  213. """Writes the category file for the raster map name in the current
  214. mapset from the cats structure.
  215. void Rast_write_cats(const char * name,
  216. struct Categories * cats
  217. )
  218. """
  219. # copy from list to C struct
  220. self._write_cats()
  221. # write to the map
  222. libraster.Rast_write_cats(self.name, ctypes.byref(self.c_cats))
  223. def copy(self, category):
  224. """Copy from another Category class"""
  225. libraster.Rast_copy_cats(ctypes.byref(self.c_cats), # to
  226. ctypes.byref(category._cats)) # from
  227. self._read_cats()
  228. def ncats(self):
  229. return self.__len__()
  230. def set_cats_fmt(self, fmt, m1, a1, m2, a2):
  231. """Not implemented yet.
  232. void Rast_set_cats_fmt()
  233. """
  234. #TODO: add
  235. pass
  236. def read_rules(self, filename, sep=':'):
  237. """Copy categories from a rules file, default separetor is ':', the
  238. columns must be: min and/or max and label. ::
  239. 1:forest
  240. 2:road
  241. 3:urban
  242. 0.:0.5:forest
  243. 0.5:1.0:road
  244. 1.0:1.5:urban
  245. .."""
  246. self.reset()
  247. with open(filename, 'r') as f:
  248. for row in f.readlines():
  249. cat = row.strip().split(sep)
  250. if len(cat) == 2:
  251. label, min_cat = cat
  252. max_cat = None
  253. elif len(cat) == 3:
  254. label, min_cat, max_cat = cat
  255. else:
  256. raise TypeError("Row lenght is greater than 3")
  257. #import pdb; pdb.set_trace()
  258. self.append((label, min_cat, max_cat))
  259. def write_rules(self, filename, sep=':'):
  260. """Copy categories from a rules file, default separetor is ':', the
  261. columns must be: min and/or max and label. ::
  262. 1:forest
  263. 2:road
  264. 3:urban
  265. 0.:0.5:forest
  266. 0.5:1.0:road
  267. 1.0:1.5:urban
  268. .."""
  269. with open(filename, 'w') as f:
  270. cats = []
  271. for cat in self.__iter__():
  272. if cat[-1] is None:
  273. cat = cat[:-1]
  274. cats.append(sep.join([str(i) for i in cat]))
  275. f.write('\n'.join(cats))
  276. def sort(self):
  277. libraster.Rast_sort_cats(ctypes.byref(self.c_cats))
  278. def labels(self):
  279. return list(map(itemgetter(0), self))