mixins.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. """Mixin classes for custom array types that don't inherit from ndarray."""
  2. from __future__ import division, absolute_import, print_function
  3. import sys
  4. from numpy.core import umath as um
  5. # Nothing should be exposed in the top-level NumPy module.
  6. __all__ = []
  7. def _disables_array_ufunc(obj):
  8. """True when __array_ufunc__ is set to None."""
  9. try:
  10. return obj.__array_ufunc__ is None
  11. except AttributeError:
  12. return False
  13. def _binary_method(ufunc, name):
  14. """Implement a forward binary method with a ufunc, e.g., __add__."""
  15. def func(self, other):
  16. if _disables_array_ufunc(other):
  17. return NotImplemented
  18. return ufunc(self, other)
  19. func.__name__ = '__{}__'.format(name)
  20. return func
  21. def _reflected_binary_method(ufunc, name):
  22. """Implement a reflected binary method with a ufunc, e.g., __radd__."""
  23. def func(self, other):
  24. if _disables_array_ufunc(other):
  25. return NotImplemented
  26. return ufunc(other, self)
  27. func.__name__ = '__r{}__'.format(name)
  28. return func
  29. def _inplace_binary_method(ufunc, name):
  30. """Implement an in-place binary method with a ufunc, e.g., __iadd__."""
  31. def func(self, other):
  32. return ufunc(self, other, out=(self,))
  33. func.__name__ = '__i{}__'.format(name)
  34. return func
  35. def _numeric_methods(ufunc, name):
  36. """Implement forward, reflected and inplace binary methods with a ufunc."""
  37. return (_binary_method(ufunc, name),
  38. _reflected_binary_method(ufunc, name),
  39. _inplace_binary_method(ufunc, name))
  40. def _unary_method(ufunc, name):
  41. """Implement a unary special method with a ufunc."""
  42. def func(self):
  43. return ufunc(self)
  44. func.__name__ = '__{}__'.format(name)
  45. return func
  46. class NDArrayOperatorsMixin(object):
  47. """Mixin defining all operator special methods using __array_ufunc__.
  48. This class implements the special methods for almost all of Python's
  49. builtin operators defined in the `operator` module, including comparisons
  50. (``==``, ``>``, etc.) and arithmetic (``+``, ``*``, ``-``, etc.), by
  51. deferring to the ``__array_ufunc__`` method, which subclasses must
  52. implement.
  53. It is useful for writing classes that do not inherit from `numpy.ndarray`,
  54. but that should support arithmetic and numpy universal functions like
  55. arrays as described in `A Mechanism for Overriding Ufuncs
  56. <../../neps/nep-0013-ufunc-overrides.html>`_.
  57. As an trivial example, consider this implementation of an ``ArrayLike``
  58. class that simply wraps a NumPy array and ensures that the result of any
  59. arithmetic operation is also an ``ArrayLike`` object::
  60. class ArrayLike(np.lib.mixins.NDArrayOperatorsMixin):
  61. def __init__(self, value):
  62. self.value = np.asarray(value)
  63. # One might also consider adding the built-in list type to this
  64. # list, to support operations like np.add(array_like, list)
  65. _HANDLED_TYPES = (np.ndarray, numbers.Number)
  66. def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):
  67. out = kwargs.get('out', ())
  68. for x in inputs + out:
  69. # Only support operations with instances of _HANDLED_TYPES.
  70. # Use ArrayLike instead of type(self) for isinstance to
  71. # allow subclasses that don't override __array_ufunc__ to
  72. # handle ArrayLike objects.
  73. if not isinstance(x, self._HANDLED_TYPES + (ArrayLike,)):
  74. return NotImplemented
  75. # Defer to the implementation of the ufunc on unwrapped values.
  76. inputs = tuple(x.value if isinstance(x, ArrayLike) else x
  77. for x in inputs)
  78. if out:
  79. kwargs['out'] = tuple(
  80. x.value if isinstance(x, ArrayLike) else x
  81. for x in out)
  82. result = getattr(ufunc, method)(*inputs, **kwargs)
  83. if type(result) is tuple:
  84. # multiple return values
  85. return tuple(type(self)(x) for x in result)
  86. elif method == 'at':
  87. # no return value
  88. return None
  89. else:
  90. # one return value
  91. return type(self)(result)
  92. def __repr__(self):
  93. return '%s(%r)' % (type(self).__name__, self.value)
  94. In interactions between ``ArrayLike`` objects and numbers or numpy arrays,
  95. the result is always another ``ArrayLike``:
  96. >>> x = ArrayLike([1, 2, 3])
  97. >>> x - 1
  98. ArrayLike(array([0, 1, 2]))
  99. >>> 1 - x
  100. ArrayLike(array([ 0, -1, -2]))
  101. >>> np.arange(3) - x
  102. ArrayLike(array([-1, -1, -1]))
  103. >>> x - np.arange(3)
  104. ArrayLike(array([1, 1, 1]))
  105. Note that unlike ``numpy.ndarray``, ``ArrayLike`` does not allow operations
  106. with arbitrary, unrecognized types. This ensures that interactions with
  107. ArrayLike preserve a well-defined casting hierarchy.
  108. .. versionadded:: 1.13
  109. """
  110. # Like np.ndarray, this mixin class implements "Option 1" from the ufunc
  111. # overrides NEP.
  112. # comparisons don't have reflected and in-place versions
  113. __lt__ = _binary_method(um.less, 'lt')
  114. __le__ = _binary_method(um.less_equal, 'le')
  115. __eq__ = _binary_method(um.equal, 'eq')
  116. __ne__ = _binary_method(um.not_equal, 'ne')
  117. __gt__ = _binary_method(um.greater, 'gt')
  118. __ge__ = _binary_method(um.greater_equal, 'ge')
  119. # numeric methods
  120. __add__, __radd__, __iadd__ = _numeric_methods(um.add, 'add')
  121. __sub__, __rsub__, __isub__ = _numeric_methods(um.subtract, 'sub')
  122. __mul__, __rmul__, __imul__ = _numeric_methods(um.multiply, 'mul')
  123. __matmul__, __rmatmul__, __imatmul__ = _numeric_methods(
  124. um.matmul, 'matmul')
  125. if sys.version_info.major < 3:
  126. # Python 3 uses only __truediv__ and __floordiv__
  127. __div__, __rdiv__, __idiv__ = _numeric_methods(um.divide, 'div')
  128. __truediv__, __rtruediv__, __itruediv__ = _numeric_methods(
  129. um.true_divide, 'truediv')
  130. __floordiv__, __rfloordiv__, __ifloordiv__ = _numeric_methods(
  131. um.floor_divide, 'floordiv')
  132. __mod__, __rmod__, __imod__ = _numeric_methods(um.remainder, 'mod')
  133. __divmod__ = _binary_method(um.divmod, 'divmod')
  134. __rdivmod__ = _reflected_binary_method(um.divmod, 'divmod')
  135. # __idivmod__ does not exist
  136. # TODO: handle the optional third argument for __pow__?
  137. __pow__, __rpow__, __ipow__ = _numeric_methods(um.power, 'pow')
  138. __lshift__, __rlshift__, __ilshift__ = _numeric_methods(
  139. um.left_shift, 'lshift')
  140. __rshift__, __rrshift__, __irshift__ = _numeric_methods(
  141. um.right_shift, 'rshift')
  142. __and__, __rand__, __iand__ = _numeric_methods(um.bitwise_and, 'and')
  143. __xor__, __rxor__, __ixor__ = _numeric_methods(um.bitwise_xor, 'xor')
  144. __or__, __ror__, __ior__ = _numeric_methods(um.bitwise_or, 'or')
  145. # unary methods
  146. __neg__ = _unary_method(um.negative, 'neg')
  147. __pos__ = _unary_method(um.positive, 'pos')
  148. __abs__ = _unary_method(um.absolute, 'abs')
  149. __invert__ = _unary_method(um.invert, 'invert')