buffer.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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__(
  27. cls, shape, mtype="FCELL", buffer=None, offset=0, strides=None, order=None
  28. ):
  29. obj = np.ndarray.__new__(
  30. cls, shape, RTYPE[mtype]["numpy"], buffer, offset, strides, order
  31. )
  32. obj.pointer_type = ctypes.POINTER(RTYPE[mtype]["ctypes"])
  33. obj.p = obj.ctypes.data_as(obj.pointer_type)
  34. return obj
  35. def __array_finalize__(self, obj):
  36. if obj is None:
  37. return
  38. self.pointer_type = getattr(obj, "pointer_type", None)
  39. self.p = getattr(obj, "p", None)
  40. def __array_wrap__(self, out_arr, context=None):
  41. """See:
  42. http://docs.scipy.org/doc/numpy/user/
  43. basics.subclassing.html#array-wrap-for-ufuncs"""
  44. if out_arr.dtype == np.bool:
  45. # there is not support for boolean maps, so convert into integer
  46. out_arr = out_arr.astype(np.int32)
  47. out_arr.p = out_arr.ctypes.data_as(out_arr.pointer_type)
  48. return np.ndarray.__array_wrap__(self, out_arr, context)