_array_utils_impl.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. """
  2. Miscellaneous utils.
  3. """
  4. from numpy._core import asarray
  5. from numpy._core.numeric import normalize_axis_index, normalize_axis_tuple
  6. from numpy._utils import set_module
  7. __all__ = ["byte_bounds", "normalize_axis_tuple", "normalize_axis_index"]
  8. @set_module("numpy.lib.array_utils")
  9. def byte_bounds(a):
  10. """
  11. Returns pointers to the end-points of an array.
  12. Parameters
  13. ----------
  14. a : ndarray
  15. Input array. It must conform to the Python-side of the array
  16. interface.
  17. Returns
  18. -------
  19. (low, high) : tuple of 2 integers
  20. The first integer is the first byte of the array, the second
  21. integer is just past the last byte of the array. If `a` is not
  22. contiguous it will not use every byte between the (`low`, `high`)
  23. values.
  24. Examples
  25. --------
  26. >>> import numpy as np
  27. >>> I = np.eye(2, dtype='f'); I.dtype
  28. dtype('float32')
  29. >>> low, high = np.lib.array_utils.byte_bounds(I)
  30. >>> high - low == I.size*I.itemsize
  31. True
  32. >>> I = np.eye(2); I.dtype
  33. dtype('float64')
  34. >>> low, high = np.lib.array_utils.byte_bounds(I)
  35. >>> high - low == I.size*I.itemsize
  36. True
  37. """
  38. ai = a.__array_interface__
  39. a_data = ai['data'][0]
  40. astrides = ai['strides']
  41. ashape = ai['shape']
  42. bytes_a = asarray(a).dtype.itemsize
  43. a_low = a_high = a_data
  44. if astrides is None:
  45. # contiguous case
  46. a_high += a.size * bytes_a
  47. else:
  48. for shape, stride in zip(ashape, astrides):
  49. if stride < 0:
  50. a_low += (shape - 1) * stride
  51. else:
  52. a_high += (shape - 1) * stride
  53. a_high += bytes_a
  54. return a_low, a_high