buffer.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on Fri Jun 8 18:46:34 2012
  4. @author: pietro
  5. """
  6. from raster_type import TYPE as RTYPE
  7. import ctypes
  8. import numpy as np
  9. class Buffer(np.ndarray):
  10. """shape, mtype='FCELL', buffer=None, offset=0,
  11. strides=None, order=None
  12. """
  13. def __new__(cls, shape, mtype='FCELL', buffer=None, offset=0,
  14. strides=None, order=None):
  15. #import pdb; pdb.set_trace()
  16. obj = np.ndarray.__new__(cls, shape, RTYPE[mtype]['numpy'],
  17. buffer, offset, strides, order)
  18. obj.pointer_type = ctypes.POINTER(RTYPE[mtype]['ctypes'])
  19. obj.p = obj.ctypes.data_as(obj.pointer_type)
  20. obj.mtype = mtype
  21. return obj
  22. def __array_finalize__(self, obj):
  23. if obj is None:
  24. return
  25. self.mtype = getattr(obj, 'mtype', None)
  26. self.pointer_type = getattr(obj, 'pointer_type', None)
  27. self.p = getattr(obj, 'p', None)
  28. def __array_wrap__(self, out_arr, context=None):
  29. """See:
  30. http://docs.scipy.org/doc/numpy/user/
  31. basics.subclassing.html#array-wrap-for-ufuncs"""
  32. if out_arr.dtype == np.bool:
  33. # there is not support for boolean maps, so convert into integer
  34. out_arr = out_arr.astype(np.int32)
  35. out_arr.p = out_arr.ctypes.data_as(out_arr.pointer_type)
  36. return np.ndarray.__array_wrap__(self, out_arr, context)