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