category.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  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. >>> from grass.pygrass.raster.category import Category
  42. >>> cats = Category('landuse')
  43. >>> cats.read()
  44. >>> cats.labels() # doctest: +ELLIPSIS
  45. ['undefined', 'developed', 'agriculture', ..., 'water', 'sediment']
  46. >>> cats[0]
  47. ('undefined', 0, None)
  48. >>> cats[1]
  49. ('developed', 1, None)
  50. """
  51. def __init__(self, name, mapset='', mtype='CELL', *args, **kargs):
  52. self.name = name
  53. self.mapset = mapset
  54. self.c_cats = libraster.Categories()
  55. libraster.Rast_init_cats("", ctypes.byref(self.c_cats))
  56. self._mtype = mtype
  57. self._gtype = None if mtype is None else RTYPE[mtype]['grass type']
  58. super(Category, self).__init__(*args, **kargs)
  59. def _get_mtype(self):
  60. return self._mtype
  61. def _set_mtype(self, mtype):
  62. if mtype.upper() not in ('CELL', 'FCELL', 'DCELL'):
  63. #fatal(_("Raser type: {0} not supported".format(mtype) ) )
  64. raise ValueError(_("Raster type: {0} not supported".format(mtype)))
  65. self._mtype = mtype
  66. self._gtype = RTYPE[self.mtype]['grass type']
  67. mtype = property(fget=_get_mtype, fset=_set_mtype,
  68. doc="Set or obtain raster data type")
  69. def _get_title(self):
  70. return libraster.Rast_get_cats_title(ctypes.byref(self.c_cats))
  71. def _set_title(self, newtitle):
  72. return libraster.Rast_set_cats_title(newtitle,
  73. ctypes.byref(self.c_cats))
  74. title = property(fget=_get_title, fset=_set_title,
  75. doc="Set or obtain raster 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. :param category: Category class to be copied
  226. :type category: Category object
  227. """
  228. libraster.Rast_copy_cats(ctypes.byref(self.c_cats), # to
  229. ctypes.byref(category._cats)) # from
  230. self._read_cats()
  231. def ncats(self):
  232. return self.__len__()
  233. def set_cats_fmt(self, fmt, m1, a1, m2, a2):
  234. """Not implemented yet.
  235. void Rast_set_cats_fmt()
  236. """
  237. #TODO: add
  238. pass
  239. def read_rules(self, filename, sep=':'):
  240. """Copy categories from a rules file, default separetor is ':', the
  241. columns must be: min and/or max and label. ::
  242. 1:forest
  243. 2:road
  244. 3:urban
  245. 0.:0.5:forest
  246. 0.5:1.0:road
  247. 1.0:1.5:urban
  248. :param str filename: the name of file with categories rules
  249. :param str sep: the separator used to divide values and category
  250. """
  251. self.reset()
  252. with open(filename, 'r') as f:
  253. for row in f.readlines():
  254. cat = row.strip().split(sep)
  255. if len(cat) == 2:
  256. label, min_cat = cat
  257. max_cat = None
  258. elif len(cat) == 3:
  259. label, min_cat, max_cat = cat
  260. else:
  261. raise TypeError("Row lenght is greater than 3")
  262. #import pdb; pdb.set_trace()
  263. self.append((label, min_cat, max_cat))
  264. def write_rules(self, filename, sep=':'):
  265. """Copy categories from a rules file, default separetor is ':', the
  266. columns must be: min and/or max and label. ::
  267. 1:forest
  268. 2:road
  269. 3:urban
  270. 0.:0.5:forest
  271. 0.5:1.0:road
  272. 1.0:1.5:urban
  273. :param str filename: the name of file with categories rules
  274. :param str sep: the separator used to divide values and category
  275. """
  276. with open(filename, 'w') as f:
  277. cats = []
  278. for cat in self.__iter__():
  279. if cat[-1] is None:
  280. cat = cat[:-1]
  281. cats.append(sep.join([str(i) for i in cat]))
  282. f.write('\n'.join(cats))
  283. def sort(self):
  284. libraster.Rast_sort_cats(ctypes.byref(self.c_cats))
  285. def labels(self):
  286. return list(map(itemgetter(0), self))