buffer.py 1.8 KB

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