buffer.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. from grass.pygrass.raster.raster_type import TYPE as RTYPE
  2. import ctypes
  3. import numpy as np
  4. _CELL = ("int", "int0", "int8", "int16", "int32", "int64")
  5. CELL = tuple([getattr(np, attr) for attr in _CELL if hasattr(np, attr)])
  6. _FCELL = "float", "float16", "float32"
  7. FCELL = tuple([getattr(np, attr) for attr in _FCELL if hasattr(np, attr)])
  8. _DCELL = "float64", "float128"
  9. DCELL = tuple([getattr(np, attr) for attr in _DCELL if hasattr(np, attr)])
  10. class Buffer(np.ndarray):
  11. """shape, mtype='FCELL', buffer=None, offset=0,
  12. strides=None, order=None
  13. """
  14. @property
  15. def mtype(self):
  16. if self.dtype in CELL:
  17. return "CELL"
  18. elif self.dtype in FCELL:
  19. return "FCELL"
  20. elif self.dtype in DCELL:
  21. return DCELL
  22. else:
  23. err = "Raster type: %r not supported by GRASS."
  24. raise TypeError(err % self.dtype)
  25. def __new__(
  26. cls, shape, mtype="FCELL", buffer=None, offset=0, strides=None, order=None
  27. ):
  28. obj = np.ndarray.__new__(
  29. cls, shape, RTYPE[mtype]["numpy"], buffer, offset, strides, order
  30. )
  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)