buffer.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. # -*- coding: utf-8 -*-
  2. from grass.pygrass.raster.raster_type import TYPE as RTYPE
  3. import ctypes
  4. import numpy as np
  5. _CELL = ('int', 'int0', 'int8', 'int16', 'int32', 'int64')
  6. CELL = tuple([getattr(np, attr) for attr in _CELL if hasattr(np, attr)])
  7. _FCELL = 'float', 'float16', 'float32'
  8. FCELL = tuple([getattr(np, attr) for attr in _FCELL if hasattr(np, attr)])
  9. _DCELL = 'float64', 'float128'
  10. DCELL = tuple([getattr(np, attr) for attr in _DCELL if hasattr(np, attr)])
  11. class Buffer(np.ndarray):
  12. """shape, mtype='FCELL', buffer=None, offset=0,
  13. strides=None, order=None
  14. """
  15. @property
  16. def mtype(self):
  17. if self.dtype in CELL:
  18. return 'CELL'
  19. elif self.dtype in FCELL:
  20. return 'FCELL'
  21. elif self.dtype in DCELL:
  22. return DCELL
  23. else:
  24. err = "Raster type: %r not supported by GRASS."
  25. raise TypeError(err % self.dtype)
  26. def __new__(cls, shape, mtype='FCELL', buffer=None, offset=0,
  27. strides=None, order=None):
  28. #import pdb; pdb.set_trace()
  29. obj = np.ndarray.__new__(cls, shape, RTYPE[mtype]['numpy'],
  30. buffer, offset, strides, order)
  31. obj.pointer_type = ctypes.POINTER(RTYPE[mtype]['ctypes'])
  32. obj.p = obj.ctypes.data_as(obj.pointer_type)
  33. return obj
  34. def __array_finalize__(self, obj):
  35. if obj is None:
  36. return
  37. self.pointer_type = getattr(obj, 'pointer_type', None)
  38. self.p = getattr(obj, 'p', None)
  39. def __array_wrap__(self, out_arr, context=None):
  40. """See:
  41. http://docs.scipy.org/doc/numpy/user/
  42. basics.subclassing.html#array-wrap-for-ufuncs"""
  43. if out_arr.dtype == np.bool:
  44. # there is not support for boolean maps, so convert into integer
  45. out_arr = out_arr.astype(np.int32)
  46. out_arr.p = out_arr.ctypes.data_as(out_arr.pointer_type)
  47. return np.ndarray.__array_wrap__(self, out_arr, context)