category.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  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(_("Raster 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. doc="Set or obtain raster data type")
  71. def _get_title(self):
  72. return libraster.Rast_get_cats_title(ctypes.byref(self.c_cats))
  73. def _set_title(self, newtitle):
  74. return libraster.Rast_set_cats_title(newtitle,
  75. ctypes.byref(self.c_cats))
  76. title = property(fget=_get_title, fset=_set_title,
  77. doc="Set or obtain raster title")
  78. def __str__(self):
  79. return self.__repr__()
  80. def __list__(self):
  81. cats = []
  82. for cat in self.__iter__():
  83. cats.append(cat)
  84. return cats
  85. def __dict__(self):
  86. diz = dict()
  87. for cat in self.__iter__():
  88. label, min_cat, max_cat = cat
  89. diz[(min_cat, max_cat)] = label
  90. return diz
  91. def __repr__(self):
  92. cats = []
  93. for cat in self.__iter__():
  94. cats.append(repr(cat))
  95. return "[{0}]".format(',\n '.join(cats))
  96. def _chk_index(self, index):
  97. if type(index) == str:
  98. try:
  99. index = self.labels().index(index)
  100. except ValueError:
  101. raise KeyError(index)
  102. return index
  103. def _chk_value(self, value):
  104. if type(value) == tuple:
  105. length = len(value)
  106. if length == 2:
  107. label, min_cat = value
  108. value = (label, min_cat, None)
  109. elif length < 2 or length > 3:
  110. raise TypeError('Tuple with a length that is not supported.')
  111. else:
  112. raise TypeError('Only Tuple are supported.')
  113. return value
  114. def __getitem__(self, index):
  115. return super(Category, self).__getitem__(self._chk_index(index))
  116. def __setitem__(self, index, value):
  117. return super(Category, self).__setitem__(self._chk_index(index),
  118. self._chk_value(value))
  119. def _get_c_cat(self, index):
  120. """Returns i-th description and i-th data range from the list of
  121. category descriptions with corresponding data ranges. end points of
  122. data interval.
  123. Rast_get_ith_cat(const struct Categories * pcats,
  124. int i,
  125. void * rast1,
  126. void * rast2,
  127. RASTER_MAP_TYPE data_type
  128. )
  129. """
  130. min_cat = ctypes.pointer(RTYPE[self.mtype]['grass def']())
  131. max_cat = ctypes.pointer(RTYPE[self.mtype]['grass def']())
  132. lab = libraster.Rast_get_ith_cat(ctypes.byref(self.c_cats),
  133. index,
  134. ctypes.cast(min_cat, ctypes.c_void_p),
  135. ctypes.cast(max_cat, ctypes.c_void_p),
  136. self._gtype)
  137. # Manage C function Errors
  138. if lab == '':
  139. raise GrassError(_("Error executing: Rast_get_ith_cat"))
  140. if max_cat.contents.value == min_cat.contents.value:
  141. max_cat = None
  142. else:
  143. max_cat = max_cat.contents.value
  144. return lab, min_cat.contents.value, max_cat
  145. def _set_c_cat(self, label, min_cat, max_cat=None):
  146. """Adds the label for range min through max in category structure cats.
  147. int Rast_set_cat(const void * rast1,
  148. const void * rast2,
  149. const char * label,
  150. struct Categories * pcats,
  151. RASTER_MAP_TYPE data_type
  152. )
  153. """
  154. max_cat = min_cat if max_cat is None else max_cat
  155. min_cat = ctypes.pointer(RTYPE[self.mtype]['grass def'](min_cat))
  156. max_cat = ctypes.pointer(RTYPE[self.mtype]['grass def'](max_cat))
  157. err = libraster.Rast_set_cat(ctypes.cast(min_cat, ctypes.c_void_p),
  158. ctypes.cast(max_cat, ctypes.c_void_p),
  159. label,
  160. ctypes.byref(self.c_cats), self._gtype)
  161. # Manage C function Errors
  162. if err == 1:
  163. return None
  164. elif err == 0:
  165. raise GrassError(_("Null value detected"))
  166. elif err == -1:
  167. raise GrassError(_("Error executing: Rast_set_cat"))
  168. def __del__(self):
  169. libraster.Rast_free_cats(ctypes.byref(self.c_cats))
  170. def get_cat(self, index):
  171. return self.__getitem__(index)
  172. def set_cat(self, index, value):
  173. if index is None:
  174. self.append(value)
  175. elif index < self.__len__():
  176. self.__setitem__(index, value)
  177. else:
  178. raise TypeError("Index outside range.")
  179. def reset(self):
  180. for i in range(len(self) - 1, -1, -1):
  181. del(self[i])
  182. libraster.Rast_init_cats("", ctypes.byref(self.c_cats))
  183. def _read_cats(self):
  184. """Copy from the C struct to the list"""
  185. for i in range(self.c_cats.ncats):
  186. self.append(self._get_c_cat(i))
  187. def _write_cats(self):
  188. """Copy from the list data to the C struct"""
  189. # reset only the C struct
  190. libraster.Rast_init_cats("", ctypes.byref(self.c_cats))
  191. # write to the c struct
  192. for cat in self.__iter__():
  193. label, min_cat, max_cat = cat
  194. if max_cat is None:
  195. max_cat = min_cat
  196. self._set_c_cat(label, min_cat, max_cat)
  197. def read(self):
  198. """Read categories from a raster map
  199. The category file for raster map name in mapset is read into the
  200. cats structure. If there is an error reading the category file,
  201. a diagnostic message is printed.
  202. int Rast_read_cats(const char * name,
  203. const char * mapset,
  204. struct Categories * pcats
  205. )
  206. """
  207. self.reset()
  208. err = libraster.Rast_read_cats(self.name, self.mapset,
  209. ctypes.byref(self.c_cats))
  210. if err == -1:
  211. raise GrassError("Can not read the categories.")
  212. # copy from C struct to list
  213. self._read_cats()
  214. def write(self):
  215. """Writes the category file for the raster map name in the current
  216. mapset from the cats structure.
  217. void Rast_write_cats(const char * name,
  218. struct Categories * cats
  219. )
  220. """
  221. # copy from list to C struct
  222. self._write_cats()
  223. # write to the map
  224. libraster.Rast_write_cats(self.name, ctypes.byref(self.c_cats))
  225. def copy(self, category):
  226. """Copy from another Category class
  227. :param category: Category class to be copied
  228. :type category: Category object
  229. """
  230. libraster.Rast_copy_cats(ctypes.byref(self.c_cats), # to
  231. ctypes.byref(category._cats)) # from
  232. self._read_cats()
  233. def ncats(self):
  234. return self.__len__()
  235. def set_cats_fmt(self, fmt, m1, a1, m2, a2):
  236. """Not implemented yet.
  237. void Rast_set_cats_fmt()
  238. """
  239. #TODO: add
  240. pass
  241. def read_rules(self, filename, sep=':'):
  242. """Copy categories from a rules file, default separetor is ':', the
  243. columns must be: min and/or max and label. ::
  244. 1:forest
  245. 2:road
  246. 3:urban
  247. 0.:0.5:forest
  248. 0.5:1.0:road
  249. 1.0:1.5:urban
  250. :param filename: the name of file with categories rules
  251. :type filename: str
  252. :param sep: the separator used to divide values and category
  253. :type sep: str
  254. ..
  255. """
  256. self.reset()
  257. with open(filename, 'r') as f:
  258. for row in f.readlines():
  259. cat = row.strip().split(sep)
  260. if len(cat) == 2:
  261. label, min_cat = cat
  262. max_cat = None
  263. elif len(cat) == 3:
  264. label, min_cat, max_cat = cat
  265. else:
  266. raise TypeError("Row lenght is greater than 3")
  267. #import pdb; pdb.set_trace()
  268. self.append((label, min_cat, max_cat))
  269. def write_rules(self, filename, sep=':'):
  270. """Copy categories from a rules file, default separetor is ':', the
  271. columns must be: min and/or max and label. ::
  272. 1:forest
  273. 2:road
  274. 3:urban
  275. 0.:0.5:forest
  276. 0.5:1.0:road
  277. 1.0:1.5:urban
  278. :param filename: the name of file with categories rules
  279. :type filename: str
  280. :param sep: the separator used to divide values and category
  281. :type sep: str
  282. ..
  283. """
  284. with open(filename, 'w') as f:
  285. cats = []
  286. for cat in self.__iter__():
  287. if cat[-1] is None:
  288. cat = cat[:-1]
  289. cats.append(sep.join([str(i) for i in cat]))
  290. f.write('\n'.join(cats))
  291. def sort(self):
  292. libraster.Rast_sort_cats(ctypes.byref(self.c_cats))
  293. def labels(self):
  294. return list(map(itemgetter(0), self))