id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
170,015
from __future__ import annotations from ._dtypes import _floating_dtypes, _numeric_dtypes from ._manipulation_functions import reshape from ._array_object import Array from ..core.numeric import normalize_axis_tuple from typing import TYPE_CHECKING from typing import NamedTuple import numpy.linalg import numpy as np _numeric_dtypes = ( float32, float64, int8, int16, int32, int64, uint8, uint16, uint32, uint64, ) class Array: """ n-d array object for the array API namespace. See the docstring of :py:obj:`np.ndarray <numpy.ndarray>` for more information. This is a wrapper around numpy.ndarray that restricts the usage to only those things that are required by the array API namespace. Note, attributes on this object that start with a single underscore are not part of the API specification and should only be used internally. This object should not be constructed directly. Rather, use one of the creation functions, such as asarray(). """ _array: np.ndarray # Use a custom constructor instead of __init__, as manually initializing # this class is not supported API. def _new(cls, x, /): """ This is a private method for initializing the array API Array object. Functions outside of the array_api submodule should not use this method. Use one of the creation functions instead, such as ``asarray``. """ obj = super().__new__(cls) # Note: The spec does not have array scalars, only 0-D arrays. if isinstance(x, np.generic): # Convert the array scalar to a 0-D array x = np.asarray(x) if x.dtype not in _all_dtypes: raise TypeError( f"The array_api namespace does not support the dtype '{x.dtype}'" ) obj._array = x return obj # Prevent Array() from working def __new__(cls, *args, **kwargs): raise TypeError( "The array_api Array object should not be instantiated directly. Use an array creation function, such as asarray(), instead." ) # These functions are not required by the spec, but are implemented for # the sake of usability. def __str__(self: Array, /) -> str: """ Performs the operation __str__. """ return self._array.__str__().replace("array", "Array") def __repr__(self: Array, /) -> str: """ Performs the operation __repr__. """ suffix = f", dtype={self.dtype.name})" if 0 in self.shape: prefix = "empty(" mid = str(self.shape) else: prefix = "Array(" mid = np.array2string(self._array, separator=', ', prefix=prefix, suffix=suffix) return prefix + mid + suffix # This function is not required by the spec, but we implement it here for # convenience so that np.asarray(np.array_api.Array) will work. def __array__(self, dtype: None | np.dtype[Any] = None) -> npt.NDArray[Any]: """ Warning: this method is NOT part of the array API spec. Implementers of other libraries need not include it, and users should not assume it will be present in other implementations. """ return np.asarray(self._array, dtype=dtype) # These are various helper functions to make the array behavior match the # spec in places where it either deviates from or is more strict than # NumPy behavior def _check_allowed_dtypes(self, other: bool | int | float | Array, dtype_category: str, op: str) -> Array: """ Helper function for operators to only allow specific input dtypes Use like other = self._check_allowed_dtypes(other, 'numeric', '__add__') if other is NotImplemented: return other """ if self.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") if isinstance(other, (int, float, bool)): other = self._promote_scalar(other) elif isinstance(other, Array): if other.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") else: return NotImplemented # This will raise TypeError for type combinations that are not allowed # to promote in the spec (even if the NumPy array operator would # promote them). res_dtype = _result_type(self.dtype, other.dtype) if op.startswith("__i"): # Note: NumPy will allow in-place operators in some cases where # the type promoted operator does not match the left-hand side # operand. For example, # >>> a = np.array(1, dtype=np.int8) # >>> a += np.array(1, dtype=np.int16) # The spec explicitly disallows this. if res_dtype != self.dtype: raise TypeError( f"Cannot perform {op} with dtypes {self.dtype} and {other.dtype}" ) return other # Helper function to match the type promotion rules in the spec def _promote_scalar(self, scalar): """ Returns a promoted version of a Python scalar appropriate for use with operations on self. This may raise an OverflowError in cases where the scalar is an integer that is too large to fit in a NumPy integer dtype, or TypeError when the scalar type is incompatible with the dtype of self. """ # Note: Only Python scalar types that match the array dtype are # allowed. if isinstance(scalar, bool): if self.dtype not in _boolean_dtypes: raise TypeError( "Python bool scalars can only be promoted with bool arrays" ) elif isinstance(scalar, int): if self.dtype in _boolean_dtypes: raise TypeError( "Python int scalars cannot be promoted with bool arrays" ) elif isinstance(scalar, float): if self.dtype not in _floating_dtypes: raise TypeError( "Python float scalars can only be promoted with floating-point arrays." ) else: raise TypeError("'scalar' must be a Python scalar") # Note: scalars are unconditionally cast to the same dtype as the # array. # Note: the spec only specifies integer-dtype/int promotion # behavior for integers within the bounds of the integer dtype. # Outside of those bounds we use the default NumPy behavior (either # cast or raise OverflowError). return Array._new(np.array(scalar, self.dtype)) def _normalize_two_args(x1, x2) -> Tuple[Array, Array]: """ Normalize inputs to two arg functions to fix type promotion rules NumPy deviates from the spec type promotion rules in cases where one argument is 0-dimensional and the other is not. For example: >>> import numpy as np >>> a = np.array([1.0], dtype=np.float32) >>> b = np.array(1.0, dtype=np.float64) >>> np.add(a, b) # The spec says this should be float64 array([2.], dtype=float32) To fix this, we add a dimension to the 0-dimension array before passing it through. This works because a dimension would be added anyway from broadcasting, so the resulting shape is the same, but this prevents NumPy from not promoting the dtype. """ # Another option would be to use signature=(x1.dtype, x2.dtype, None), # but that only works for ufuncs, so we would have to call the ufuncs # directly in the operator methods. One should also note that this # sort of trick wouldn't work for functions like searchsorted, which # don't do normal broadcasting, but there aren't any functions like # that in the array API namespace. if x1.ndim == 0 and x2.ndim != 0: # The _array[None] workaround was chosen because it is relatively # performant. broadcast_to(x1._array, x2.shape) is much slower. We # could also manually type promote x2, but that is more complicated # and about the same performance as this. x1 = Array._new(x1._array[None]) elif x2.ndim == 0 and x1.ndim != 0: x2 = Array._new(x2._array[None]) return (x1, x2) # Note: A large fraction of allowed indices are disallowed here (see the # docstring below) def _validate_index(self, key): """ Validate an index according to the array API. The array API specification only requires a subset of indices that are supported by NumPy. This function will reject any index that is allowed by NumPy but not required by the array API specification. We always raise ``IndexError`` on such indices (the spec does not require any specific behavior on them, but this makes the NumPy array API namespace a minimal implementation of the spec). See https://data-apis.org/array-api/latest/API_specification/indexing.html for the full list of required indexing behavior This function raises IndexError if the index ``key`` is invalid. It only raises ``IndexError`` on indices that are not already rejected by NumPy, as NumPy will already raise the appropriate error on such indices. ``shape`` may be None, in which case, only cases that are independent of the array shape are checked. The following cases are allowed by NumPy, but not specified by the array API specification: - Indices to not include an implicit ellipsis at the end. That is, every axis of an array must be explicitly indexed or an ellipsis included. This behaviour is sometimes referred to as flat indexing. - The start and stop of a slice may not be out of bounds. In particular, for a slice ``i:j:k`` on an axis of size ``n``, only the following are allowed: - ``i`` or ``j`` omitted (``None``). - ``-n <= i <= max(0, n - 1)``. - For ``k > 0`` or ``k`` omitted (``None``), ``-n <= j <= n``. - For ``k < 0``, ``-n - 1 <= j <= max(0, n - 1)``. - Boolean array indices are not allowed as part of a larger tuple index. - Integer array indices are not allowed (with the exception of 0-D arrays, which are treated the same as scalars). Additionally, it should be noted that indices that would return a scalar in NumPy will return a 0-D array. Array scalars are not allowed in the specification, only 0-D arrays. This is done in the ``Array._new`` constructor, not this function. """ _key = key if isinstance(key, tuple) else (key,) for i in _key: if isinstance(i, bool) or not ( isinstance(i, SupportsIndex) # i.e. ints or isinstance(i, slice) or i == Ellipsis or i is None or isinstance(i, Array) or isinstance(i, np.ndarray) ): raise IndexError( f"Single-axes index {i} has {type(i)=}, but only " "integers, slices (:), ellipsis (...), newaxis (None), " "zero-dimensional integer arrays and boolean arrays " "are specified in the Array API." ) nonexpanding_key = [] single_axes = [] n_ellipsis = 0 key_has_mask = False for i in _key: if i is not None: nonexpanding_key.append(i) if isinstance(i, Array) or isinstance(i, np.ndarray): if i.dtype in _boolean_dtypes: key_has_mask = True single_axes.append(i) else: # i must not be an array here, to avoid elementwise equals if i == Ellipsis: n_ellipsis += 1 else: single_axes.append(i) n_single_axes = len(single_axes) if n_ellipsis > 1: return # handled by ndarray elif n_ellipsis == 0: # Note boolean masks must be the sole index, which we check for # later on. if not key_has_mask and n_single_axes < self.ndim: raise IndexError( f"{self.ndim=}, but the multi-axes index only specifies " f"{n_single_axes} dimensions. If this was intentional, " "add a trailing ellipsis (...) which expands into as many " "slices (:) as necessary - this is what np.ndarray arrays " "implicitly do, but such flat indexing behaviour is not " "specified in the Array API." ) if n_ellipsis == 0: indexed_shape = self.shape else: ellipsis_start = None for pos, i in enumerate(nonexpanding_key): if not (isinstance(i, Array) or isinstance(i, np.ndarray)): if i == Ellipsis: ellipsis_start = pos break assert ellipsis_start is not None # sanity check ellipsis_end = self.ndim - (n_single_axes - ellipsis_start) indexed_shape = ( self.shape[:ellipsis_start] + self.shape[ellipsis_end:] ) for i, side in zip(single_axes, indexed_shape): if isinstance(i, slice): if side == 0: f_range = "0 (or None)" else: f_range = f"between -{side} and {side - 1} (or None)" if i.start is not None: try: start = operator.index(i.start) except TypeError: pass # handled by ndarray else: if not (-side <= start <= side): raise IndexError( f"Slice {i} contains {start=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds starts are not specified in " "the Array API)" ) if i.stop is not None: try: stop = operator.index(i.stop) except TypeError: pass # handled by ndarray else: if not (-side <= stop <= side): raise IndexError( f"Slice {i} contains {stop=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds stops are not specified in " "the Array API)" ) elif isinstance(i, Array): if i.dtype in _boolean_dtypes and len(_key) != 1: assert isinstance(key, tuple) # sanity check raise IndexError( f"Single-axes index {i} is a boolean array and " f"{len(key)=}, but masking is only specified in the " "Array API when the array is the sole index." ) elif i.dtype in _integer_dtypes and i.ndim != 0: raise IndexError( f"Single-axes index {i} is a non-zero-dimensional " "integer array, but advanced integer indexing is not " "specified in the Array API." ) elif isinstance(i, tuple): raise IndexError( f"Single-axes index {i} is a tuple, but nested tuple " "indices are not specified in the Array API." ) # Everything below this line is required by the spec. def __abs__(self: Array, /) -> Array: """ Performs the operation __abs__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __abs__") res = self._array.__abs__() return self.__class__._new(res) def __add__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __add__. """ other = self._check_allowed_dtypes(other, "numeric", "__add__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__add__(other._array) return self.__class__._new(res) def __and__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __and__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__and__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__and__(other._array) return self.__class__._new(res) def __array_namespace__( self: Array, /, *, api_version: Optional[str] = None ) -> types.ModuleType: if api_version is not None and not api_version.startswith("2021."): raise ValueError(f"Unrecognized array API version: {api_version!r}") return array_api def __bool__(self: Array, /) -> bool: """ Performs the operation __bool__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("bool is only allowed on arrays with 0 dimensions") if self.dtype not in _boolean_dtypes: raise ValueError("bool is only allowed on boolean arrays") res = self._array.__bool__() return res def __dlpack__(self: Array, /, *, stream: None = None) -> PyCapsule: """ Performs the operation __dlpack__. """ return self._array.__dlpack__(stream=stream) def __dlpack_device__(self: Array, /) -> Tuple[IntEnum, int]: """ Performs the operation __dlpack_device__. """ # Note: device support is required for this return self._array.__dlpack_device__() def __eq__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __eq__. """ # Even though "all" dtypes are allowed, we still require them to be # promotable with each other. other = self._check_allowed_dtypes(other, "all", "__eq__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__eq__(other._array) return self.__class__._new(res) def __float__(self: Array, /) -> float: """ Performs the operation __float__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("float is only allowed on arrays with 0 dimensions") if self.dtype not in _floating_dtypes: raise ValueError("float is only allowed on floating-point arrays") res = self._array.__float__() return res def __floordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __floordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__floordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__floordiv__(other._array) return self.__class__._new(res) def __ge__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ge__. """ other = self._check_allowed_dtypes(other, "numeric", "__ge__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ge__(other._array) return self.__class__._new(res) def __getitem__( self: Array, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], /, ) -> Array: """ Performs the operation __getitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array res = self._array.__getitem__(key) return self._new(res) def __gt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __gt__. """ other = self._check_allowed_dtypes(other, "numeric", "__gt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__gt__(other._array) return self.__class__._new(res) def __int__(self: Array, /) -> int: """ Performs the operation __int__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("int is only allowed on arrays with 0 dimensions") if self.dtype not in _integer_dtypes: raise ValueError("int is only allowed on integer arrays") res = self._array.__int__() return res def __index__(self: Array, /) -> int: """ Performs the operation __index__. """ res = self._array.__index__() return res def __invert__(self: Array, /) -> Array: """ Performs the operation __invert__. """ if self.dtype not in _integer_or_boolean_dtypes: raise TypeError("Only integer or boolean dtypes are allowed in __invert__") res = self._array.__invert__() return self.__class__._new(res) def __le__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __le__. """ other = self._check_allowed_dtypes(other, "numeric", "__le__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__le__(other._array) return self.__class__._new(res) def __lshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __lshift__. """ other = self._check_allowed_dtypes(other, "integer", "__lshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lshift__(other._array) return self.__class__._new(res) def __lt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __lt__. """ other = self._check_allowed_dtypes(other, "numeric", "__lt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lt__(other._array) return self.__class__._new(res) def __matmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __matmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__matmul__") if other is NotImplemented: return other res = self._array.__matmul__(other._array) return self.__class__._new(res) def __mod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mod__. """ other = self._check_allowed_dtypes(other, "numeric", "__mod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mod__(other._array) return self.__class__._new(res) def __mul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mul__. """ other = self._check_allowed_dtypes(other, "numeric", "__mul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mul__(other._array) return self.__class__._new(res) def __ne__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __ne__. """ other = self._check_allowed_dtypes(other, "all", "__ne__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ne__(other._array) return self.__class__._new(res) def __neg__(self: Array, /) -> Array: """ Performs the operation __neg__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __neg__") res = self._array.__neg__() return self.__class__._new(res) def __or__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __or__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__or__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__or__(other._array) return self.__class__._new(res) def __pos__(self: Array, /) -> Array: """ Performs the operation __pos__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __pos__") res = self._array.__pos__() return self.__class__._new(res) def __pow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __pow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__pow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow type promotion rules for 0-d # arrays, so we use pow() here instead. return pow(self, other) def __rshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rshift__(other._array) return self.__class__._new(res) def __setitem__( self, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], value: Union[int, float, bool, Array], /, ) -> None: """ Performs the operation __setitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array self._array.__setitem__(key, asarray(value)._array) def __sub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __sub__. """ other = self._check_allowed_dtypes(other, "numeric", "__sub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__sub__(other._array) return self.__class__._new(res) # PEP 484 requires int to be a subtype of float, but __truediv__ should # not accept int. def __truediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __truediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__truediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__truediv__(other._array) return self.__class__._new(res) def __xor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __xor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__xor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__xor__(other._array) return self.__class__._new(res) def __iadd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __iadd__. """ other = self._check_allowed_dtypes(other, "numeric", "__iadd__") if other is NotImplemented: return other self._array.__iadd__(other._array) return self def __radd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __radd__. """ other = self._check_allowed_dtypes(other, "numeric", "__radd__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__radd__(other._array) return self.__class__._new(res) def __iand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __iand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__iand__") if other is NotImplemented: return other self._array.__iand__(other._array) return self def __rand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rand__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rand__(other._array) return self.__class__._new(res) def __ifloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ifloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__ifloordiv__") if other is NotImplemented: return other self._array.__ifloordiv__(other._array) return self def __rfloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rfloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__rfloordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rfloordiv__(other._array) return self.__class__._new(res) def __ilshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __ilshift__. """ other = self._check_allowed_dtypes(other, "integer", "__ilshift__") if other is NotImplemented: return other self._array.__ilshift__(other._array) return self def __rlshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rlshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rlshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rlshift__(other._array) return self.__class__._new(res) def __imatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __imatmul__. """ # Note: NumPy does not implement __imatmul__. # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__imatmul__") if other is NotImplemented: return other # __imatmul__ can only be allowed when it would not change the shape # of self. other_shape = other.shape if self.shape == () or other_shape == (): raise ValueError("@= requires at least one dimension") if len(other_shape) == 1 or other_shape[-1] != other_shape[-2]: raise ValueError("@= cannot change the shape of the input array") self._array[:] = self._array.__matmul__(other._array) return self def __rmatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __rmatmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__rmatmul__") if other is NotImplemented: return other res = self._array.__rmatmul__(other._array) return self.__class__._new(res) def __imod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imod__. """ other = self._check_allowed_dtypes(other, "numeric", "__imod__") if other is NotImplemented: return other self._array.__imod__(other._array) return self def __rmod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmod__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmod__(other._array) return self.__class__._new(res) def __imul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imul__. """ other = self._check_allowed_dtypes(other, "numeric", "__imul__") if other is NotImplemented: return other self._array.__imul__(other._array) return self def __rmul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmul__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmul__(other._array) return self.__class__._new(res) def __ior__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ior__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ior__") if other is NotImplemented: return other self._array.__ior__(other._array) return self def __ror__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ror__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ror__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ror__(other._array) return self.__class__._new(res) def __ipow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ipow__. """ other = self._check_allowed_dtypes(other, "numeric", "__ipow__") if other is NotImplemented: return other self._array.__ipow__(other._array) return self def __rpow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rpow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__rpow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow the spec type promotion rules # for 0-d arrays, so we use pow() here instead. return pow(other, self) def __irshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __irshift__. """ other = self._check_allowed_dtypes(other, "integer", "__irshift__") if other is NotImplemented: return other self._array.__irshift__(other._array) return self def __rrshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rrshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rrshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rrshift__(other._array) return self.__class__._new(res) def __isub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __isub__. """ other = self._check_allowed_dtypes(other, "numeric", "__isub__") if other is NotImplemented: return other self._array.__isub__(other._array) return self def __rsub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rsub__. """ other = self._check_allowed_dtypes(other, "numeric", "__rsub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rsub__(other._array) return self.__class__._new(res) def __itruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __itruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__itruediv__") if other is NotImplemented: return other self._array.__itruediv__(other._array) return self def __rtruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __rtruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__rtruediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rtruediv__(other._array) return self.__class__._new(res) def __ixor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ixor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ixor__") if other is NotImplemented: return other self._array.__ixor__(other._array) return self def __rxor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rxor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rxor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rxor__(other._array) return self.__class__._new(res) def to_device(self: Array, device: Device, /, stream: None = None) -> Array: if stream is not None: raise ValueError("The stream argument to to_device() is not supported") if device == 'cpu': return self raise ValueError(f"Unsupported device {device!r}") def dtype(self) -> Dtype: """ Array API compatible wrapper for :py:meth:`np.ndarray.dtype <numpy.ndarray.dtype>`. See its docstring for more information. """ return self._array.dtype def device(self) -> Device: return "cpu" # Note: mT is new in array API spec (see matrix_transpose) def mT(self) -> Array: from .linalg import matrix_transpose return matrix_transpose(self) def ndim(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.ndim <numpy.ndarray.ndim>`. See its docstring for more information. """ return self._array.ndim def shape(self) -> Tuple[int, ...]: """ Array API compatible wrapper for :py:meth:`np.ndarray.shape <numpy.ndarray.shape>`. See its docstring for more information. """ return self._array.shape def size(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.size <numpy.ndarray.size>`. See its docstring for more information. """ return self._array.size def T(self) -> Array: """ Array API compatible wrapper for :py:meth:`np.ndarray.T <numpy.ndarray.T>`. See its docstring for more information. """ # Note: T only works on 2-dimensional arrays. See the corresponding # note in the specification: # https://data-apis.org/array-api/latest/API_specification/array_object.html#t if self.ndim != 2: raise ValueError("x.T requires x to have 2 dimensions. Use x.mT to transpose stacks of matrices and permute_dims() to permute dimensions.") return self.__class__._new(self._array.T) def tensordot(x1: Array, x2: Array, /, *, axes: Union[int, Tuple[Sequence[int], Sequence[int]]] = 2) -> Array: # Note: the restriction to numeric dtypes only is different from # np.tensordot. if x1.dtype not in _numeric_dtypes or x2.dtype not in _numeric_dtypes: raise TypeError('Only numeric dtypes are allowed in tensordot') return Array._new(np.tensordot(x1._array, x2._array, axes=axes))
null
170,016
from __future__ import annotations from ._dtypes import _floating_dtypes, _numeric_dtypes from ._manipulation_functions import reshape from ._array_object import Array from ..core.numeric import normalize_axis_tuple from typing import TYPE_CHECKING from typing import NamedTuple import numpy.linalg import numpy as np _numeric_dtypes = ( float32, float64, int8, int16, int32, int64, uint8, uint16, uint32, uint64, ) class Array: """ n-d array object for the array API namespace. See the docstring of :py:obj:`np.ndarray <numpy.ndarray>` for more information. This is a wrapper around numpy.ndarray that restricts the usage to only those things that are required by the array API namespace. Note, attributes on this object that start with a single underscore are not part of the API specification and should only be used internally. This object should not be constructed directly. Rather, use one of the creation functions, such as asarray(). """ _array: np.ndarray # Use a custom constructor instead of __init__, as manually initializing # this class is not supported API. def _new(cls, x, /): """ This is a private method for initializing the array API Array object. Functions outside of the array_api submodule should not use this method. Use one of the creation functions instead, such as ``asarray``. """ obj = super().__new__(cls) # Note: The spec does not have array scalars, only 0-D arrays. if isinstance(x, np.generic): # Convert the array scalar to a 0-D array x = np.asarray(x) if x.dtype not in _all_dtypes: raise TypeError( f"The array_api namespace does not support the dtype '{x.dtype}'" ) obj._array = x return obj # Prevent Array() from working def __new__(cls, *args, **kwargs): raise TypeError( "The array_api Array object should not be instantiated directly. Use an array creation function, such as asarray(), instead." ) # These functions are not required by the spec, but are implemented for # the sake of usability. def __str__(self: Array, /) -> str: """ Performs the operation __str__. """ return self._array.__str__().replace("array", "Array") def __repr__(self: Array, /) -> str: """ Performs the operation __repr__. """ suffix = f", dtype={self.dtype.name})" if 0 in self.shape: prefix = "empty(" mid = str(self.shape) else: prefix = "Array(" mid = np.array2string(self._array, separator=', ', prefix=prefix, suffix=suffix) return prefix + mid + suffix # This function is not required by the spec, but we implement it here for # convenience so that np.asarray(np.array_api.Array) will work. def __array__(self, dtype: None | np.dtype[Any] = None) -> npt.NDArray[Any]: """ Warning: this method is NOT part of the array API spec. Implementers of other libraries need not include it, and users should not assume it will be present in other implementations. """ return np.asarray(self._array, dtype=dtype) # These are various helper functions to make the array behavior match the # spec in places where it either deviates from or is more strict than # NumPy behavior def _check_allowed_dtypes(self, other: bool | int | float | Array, dtype_category: str, op: str) -> Array: """ Helper function for operators to only allow specific input dtypes Use like other = self._check_allowed_dtypes(other, 'numeric', '__add__') if other is NotImplemented: return other """ if self.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") if isinstance(other, (int, float, bool)): other = self._promote_scalar(other) elif isinstance(other, Array): if other.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") else: return NotImplemented # This will raise TypeError for type combinations that are not allowed # to promote in the spec (even if the NumPy array operator would # promote them). res_dtype = _result_type(self.dtype, other.dtype) if op.startswith("__i"): # Note: NumPy will allow in-place operators in some cases where # the type promoted operator does not match the left-hand side # operand. For example, # >>> a = np.array(1, dtype=np.int8) # >>> a += np.array(1, dtype=np.int16) # The spec explicitly disallows this. if res_dtype != self.dtype: raise TypeError( f"Cannot perform {op} with dtypes {self.dtype} and {other.dtype}" ) return other # Helper function to match the type promotion rules in the spec def _promote_scalar(self, scalar): """ Returns a promoted version of a Python scalar appropriate for use with operations on self. This may raise an OverflowError in cases where the scalar is an integer that is too large to fit in a NumPy integer dtype, or TypeError when the scalar type is incompatible with the dtype of self. """ # Note: Only Python scalar types that match the array dtype are # allowed. if isinstance(scalar, bool): if self.dtype not in _boolean_dtypes: raise TypeError( "Python bool scalars can only be promoted with bool arrays" ) elif isinstance(scalar, int): if self.dtype in _boolean_dtypes: raise TypeError( "Python int scalars cannot be promoted with bool arrays" ) elif isinstance(scalar, float): if self.dtype not in _floating_dtypes: raise TypeError( "Python float scalars can only be promoted with floating-point arrays." ) else: raise TypeError("'scalar' must be a Python scalar") # Note: scalars are unconditionally cast to the same dtype as the # array. # Note: the spec only specifies integer-dtype/int promotion # behavior for integers within the bounds of the integer dtype. # Outside of those bounds we use the default NumPy behavior (either # cast or raise OverflowError). return Array._new(np.array(scalar, self.dtype)) def _normalize_two_args(x1, x2) -> Tuple[Array, Array]: """ Normalize inputs to two arg functions to fix type promotion rules NumPy deviates from the spec type promotion rules in cases where one argument is 0-dimensional and the other is not. For example: >>> import numpy as np >>> a = np.array([1.0], dtype=np.float32) >>> b = np.array(1.0, dtype=np.float64) >>> np.add(a, b) # The spec says this should be float64 array([2.], dtype=float32) To fix this, we add a dimension to the 0-dimension array before passing it through. This works because a dimension would be added anyway from broadcasting, so the resulting shape is the same, but this prevents NumPy from not promoting the dtype. """ # Another option would be to use signature=(x1.dtype, x2.dtype, None), # but that only works for ufuncs, so we would have to call the ufuncs # directly in the operator methods. One should also note that this # sort of trick wouldn't work for functions like searchsorted, which # don't do normal broadcasting, but there aren't any functions like # that in the array API namespace. if x1.ndim == 0 and x2.ndim != 0: # The _array[None] workaround was chosen because it is relatively # performant. broadcast_to(x1._array, x2.shape) is much slower. We # could also manually type promote x2, but that is more complicated # and about the same performance as this. x1 = Array._new(x1._array[None]) elif x2.ndim == 0 and x1.ndim != 0: x2 = Array._new(x2._array[None]) return (x1, x2) # Note: A large fraction of allowed indices are disallowed here (see the # docstring below) def _validate_index(self, key): """ Validate an index according to the array API. The array API specification only requires a subset of indices that are supported by NumPy. This function will reject any index that is allowed by NumPy but not required by the array API specification. We always raise ``IndexError`` on such indices (the spec does not require any specific behavior on them, but this makes the NumPy array API namespace a minimal implementation of the spec). See https://data-apis.org/array-api/latest/API_specification/indexing.html for the full list of required indexing behavior This function raises IndexError if the index ``key`` is invalid. It only raises ``IndexError`` on indices that are not already rejected by NumPy, as NumPy will already raise the appropriate error on such indices. ``shape`` may be None, in which case, only cases that are independent of the array shape are checked. The following cases are allowed by NumPy, but not specified by the array API specification: - Indices to not include an implicit ellipsis at the end. That is, every axis of an array must be explicitly indexed or an ellipsis included. This behaviour is sometimes referred to as flat indexing. - The start and stop of a slice may not be out of bounds. In particular, for a slice ``i:j:k`` on an axis of size ``n``, only the following are allowed: - ``i`` or ``j`` omitted (``None``). - ``-n <= i <= max(0, n - 1)``. - For ``k > 0`` or ``k`` omitted (``None``), ``-n <= j <= n``. - For ``k < 0``, ``-n - 1 <= j <= max(0, n - 1)``. - Boolean array indices are not allowed as part of a larger tuple index. - Integer array indices are not allowed (with the exception of 0-D arrays, which are treated the same as scalars). Additionally, it should be noted that indices that would return a scalar in NumPy will return a 0-D array. Array scalars are not allowed in the specification, only 0-D arrays. This is done in the ``Array._new`` constructor, not this function. """ _key = key if isinstance(key, tuple) else (key,) for i in _key: if isinstance(i, bool) or not ( isinstance(i, SupportsIndex) # i.e. ints or isinstance(i, slice) or i == Ellipsis or i is None or isinstance(i, Array) or isinstance(i, np.ndarray) ): raise IndexError( f"Single-axes index {i} has {type(i)=}, but only " "integers, slices (:), ellipsis (...), newaxis (None), " "zero-dimensional integer arrays and boolean arrays " "are specified in the Array API." ) nonexpanding_key = [] single_axes = [] n_ellipsis = 0 key_has_mask = False for i in _key: if i is not None: nonexpanding_key.append(i) if isinstance(i, Array) or isinstance(i, np.ndarray): if i.dtype in _boolean_dtypes: key_has_mask = True single_axes.append(i) else: # i must not be an array here, to avoid elementwise equals if i == Ellipsis: n_ellipsis += 1 else: single_axes.append(i) n_single_axes = len(single_axes) if n_ellipsis > 1: return # handled by ndarray elif n_ellipsis == 0: # Note boolean masks must be the sole index, which we check for # later on. if not key_has_mask and n_single_axes < self.ndim: raise IndexError( f"{self.ndim=}, but the multi-axes index only specifies " f"{n_single_axes} dimensions. If this was intentional, " "add a trailing ellipsis (...) which expands into as many " "slices (:) as necessary - this is what np.ndarray arrays " "implicitly do, but such flat indexing behaviour is not " "specified in the Array API." ) if n_ellipsis == 0: indexed_shape = self.shape else: ellipsis_start = None for pos, i in enumerate(nonexpanding_key): if not (isinstance(i, Array) or isinstance(i, np.ndarray)): if i == Ellipsis: ellipsis_start = pos break assert ellipsis_start is not None # sanity check ellipsis_end = self.ndim - (n_single_axes - ellipsis_start) indexed_shape = ( self.shape[:ellipsis_start] + self.shape[ellipsis_end:] ) for i, side in zip(single_axes, indexed_shape): if isinstance(i, slice): if side == 0: f_range = "0 (or None)" else: f_range = f"between -{side} and {side - 1} (or None)" if i.start is not None: try: start = operator.index(i.start) except TypeError: pass # handled by ndarray else: if not (-side <= start <= side): raise IndexError( f"Slice {i} contains {start=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds starts are not specified in " "the Array API)" ) if i.stop is not None: try: stop = operator.index(i.stop) except TypeError: pass # handled by ndarray else: if not (-side <= stop <= side): raise IndexError( f"Slice {i} contains {stop=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds stops are not specified in " "the Array API)" ) elif isinstance(i, Array): if i.dtype in _boolean_dtypes and len(_key) != 1: assert isinstance(key, tuple) # sanity check raise IndexError( f"Single-axes index {i} is a boolean array and " f"{len(key)=}, but masking is only specified in the " "Array API when the array is the sole index." ) elif i.dtype in _integer_dtypes and i.ndim != 0: raise IndexError( f"Single-axes index {i} is a non-zero-dimensional " "integer array, but advanced integer indexing is not " "specified in the Array API." ) elif isinstance(i, tuple): raise IndexError( f"Single-axes index {i} is a tuple, but nested tuple " "indices are not specified in the Array API." ) # Everything below this line is required by the spec. def __abs__(self: Array, /) -> Array: """ Performs the operation __abs__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __abs__") res = self._array.__abs__() return self.__class__._new(res) def __add__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __add__. """ other = self._check_allowed_dtypes(other, "numeric", "__add__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__add__(other._array) return self.__class__._new(res) def __and__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __and__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__and__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__and__(other._array) return self.__class__._new(res) def __array_namespace__( self: Array, /, *, api_version: Optional[str] = None ) -> types.ModuleType: if api_version is not None and not api_version.startswith("2021."): raise ValueError(f"Unrecognized array API version: {api_version!r}") return array_api def __bool__(self: Array, /) -> bool: """ Performs the operation __bool__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("bool is only allowed on arrays with 0 dimensions") if self.dtype not in _boolean_dtypes: raise ValueError("bool is only allowed on boolean arrays") res = self._array.__bool__() return res def __dlpack__(self: Array, /, *, stream: None = None) -> PyCapsule: """ Performs the operation __dlpack__. """ return self._array.__dlpack__(stream=stream) def __dlpack_device__(self: Array, /) -> Tuple[IntEnum, int]: """ Performs the operation __dlpack_device__. """ # Note: device support is required for this return self._array.__dlpack_device__() def __eq__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __eq__. """ # Even though "all" dtypes are allowed, we still require them to be # promotable with each other. other = self._check_allowed_dtypes(other, "all", "__eq__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__eq__(other._array) return self.__class__._new(res) def __float__(self: Array, /) -> float: """ Performs the operation __float__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("float is only allowed on arrays with 0 dimensions") if self.dtype not in _floating_dtypes: raise ValueError("float is only allowed on floating-point arrays") res = self._array.__float__() return res def __floordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __floordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__floordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__floordiv__(other._array) return self.__class__._new(res) def __ge__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ge__. """ other = self._check_allowed_dtypes(other, "numeric", "__ge__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ge__(other._array) return self.__class__._new(res) def __getitem__( self: Array, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], /, ) -> Array: """ Performs the operation __getitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array res = self._array.__getitem__(key) return self._new(res) def __gt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __gt__. """ other = self._check_allowed_dtypes(other, "numeric", "__gt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__gt__(other._array) return self.__class__._new(res) def __int__(self: Array, /) -> int: """ Performs the operation __int__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("int is only allowed on arrays with 0 dimensions") if self.dtype not in _integer_dtypes: raise ValueError("int is only allowed on integer arrays") res = self._array.__int__() return res def __index__(self: Array, /) -> int: """ Performs the operation __index__. """ res = self._array.__index__() return res def __invert__(self: Array, /) -> Array: """ Performs the operation __invert__. """ if self.dtype not in _integer_or_boolean_dtypes: raise TypeError("Only integer or boolean dtypes are allowed in __invert__") res = self._array.__invert__() return self.__class__._new(res) def __le__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __le__. """ other = self._check_allowed_dtypes(other, "numeric", "__le__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__le__(other._array) return self.__class__._new(res) def __lshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __lshift__. """ other = self._check_allowed_dtypes(other, "integer", "__lshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lshift__(other._array) return self.__class__._new(res) def __lt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __lt__. """ other = self._check_allowed_dtypes(other, "numeric", "__lt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lt__(other._array) return self.__class__._new(res) def __matmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __matmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__matmul__") if other is NotImplemented: return other res = self._array.__matmul__(other._array) return self.__class__._new(res) def __mod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mod__. """ other = self._check_allowed_dtypes(other, "numeric", "__mod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mod__(other._array) return self.__class__._new(res) def __mul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mul__. """ other = self._check_allowed_dtypes(other, "numeric", "__mul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mul__(other._array) return self.__class__._new(res) def __ne__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __ne__. """ other = self._check_allowed_dtypes(other, "all", "__ne__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ne__(other._array) return self.__class__._new(res) def __neg__(self: Array, /) -> Array: """ Performs the operation __neg__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __neg__") res = self._array.__neg__() return self.__class__._new(res) def __or__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __or__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__or__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__or__(other._array) return self.__class__._new(res) def __pos__(self: Array, /) -> Array: """ Performs the operation __pos__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __pos__") res = self._array.__pos__() return self.__class__._new(res) def __pow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __pow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__pow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow type promotion rules for 0-d # arrays, so we use pow() here instead. return pow(self, other) def __rshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rshift__(other._array) return self.__class__._new(res) def __setitem__( self, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], value: Union[int, float, bool, Array], /, ) -> None: """ Performs the operation __setitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array self._array.__setitem__(key, asarray(value)._array) def __sub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __sub__. """ other = self._check_allowed_dtypes(other, "numeric", "__sub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__sub__(other._array) return self.__class__._new(res) # PEP 484 requires int to be a subtype of float, but __truediv__ should # not accept int. def __truediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __truediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__truediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__truediv__(other._array) return self.__class__._new(res) def __xor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __xor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__xor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__xor__(other._array) return self.__class__._new(res) def __iadd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __iadd__. """ other = self._check_allowed_dtypes(other, "numeric", "__iadd__") if other is NotImplemented: return other self._array.__iadd__(other._array) return self def __radd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __radd__. """ other = self._check_allowed_dtypes(other, "numeric", "__radd__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__radd__(other._array) return self.__class__._new(res) def __iand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __iand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__iand__") if other is NotImplemented: return other self._array.__iand__(other._array) return self def __rand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rand__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rand__(other._array) return self.__class__._new(res) def __ifloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ifloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__ifloordiv__") if other is NotImplemented: return other self._array.__ifloordiv__(other._array) return self def __rfloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rfloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__rfloordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rfloordiv__(other._array) return self.__class__._new(res) def __ilshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __ilshift__. """ other = self._check_allowed_dtypes(other, "integer", "__ilshift__") if other is NotImplemented: return other self._array.__ilshift__(other._array) return self def __rlshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rlshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rlshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rlshift__(other._array) return self.__class__._new(res) def __imatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __imatmul__. """ # Note: NumPy does not implement __imatmul__. # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__imatmul__") if other is NotImplemented: return other # __imatmul__ can only be allowed when it would not change the shape # of self. other_shape = other.shape if self.shape == () or other_shape == (): raise ValueError("@= requires at least one dimension") if len(other_shape) == 1 or other_shape[-1] != other_shape[-2]: raise ValueError("@= cannot change the shape of the input array") self._array[:] = self._array.__matmul__(other._array) return self def __rmatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __rmatmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__rmatmul__") if other is NotImplemented: return other res = self._array.__rmatmul__(other._array) return self.__class__._new(res) def __imod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imod__. """ other = self._check_allowed_dtypes(other, "numeric", "__imod__") if other is NotImplemented: return other self._array.__imod__(other._array) return self def __rmod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmod__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmod__(other._array) return self.__class__._new(res) def __imul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imul__. """ other = self._check_allowed_dtypes(other, "numeric", "__imul__") if other is NotImplemented: return other self._array.__imul__(other._array) return self def __rmul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmul__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmul__(other._array) return self.__class__._new(res) def __ior__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ior__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ior__") if other is NotImplemented: return other self._array.__ior__(other._array) return self def __ror__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ror__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ror__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ror__(other._array) return self.__class__._new(res) def __ipow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ipow__. """ other = self._check_allowed_dtypes(other, "numeric", "__ipow__") if other is NotImplemented: return other self._array.__ipow__(other._array) return self def __rpow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rpow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__rpow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow the spec type promotion rules # for 0-d arrays, so we use pow() here instead. return pow(other, self) def __irshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __irshift__. """ other = self._check_allowed_dtypes(other, "integer", "__irshift__") if other is NotImplemented: return other self._array.__irshift__(other._array) return self def __rrshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rrshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rrshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rrshift__(other._array) return self.__class__._new(res) def __isub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __isub__. """ other = self._check_allowed_dtypes(other, "numeric", "__isub__") if other is NotImplemented: return other self._array.__isub__(other._array) return self def __rsub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rsub__. """ other = self._check_allowed_dtypes(other, "numeric", "__rsub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rsub__(other._array) return self.__class__._new(res) def __itruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __itruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__itruediv__") if other is NotImplemented: return other self._array.__itruediv__(other._array) return self def __rtruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __rtruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__rtruediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rtruediv__(other._array) return self.__class__._new(res) def __ixor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ixor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ixor__") if other is NotImplemented: return other self._array.__ixor__(other._array) return self def __rxor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rxor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rxor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rxor__(other._array) return self.__class__._new(res) def to_device(self: Array, device: Device, /, stream: None = None) -> Array: if stream is not None: raise ValueError("The stream argument to to_device() is not supported") if device == 'cpu': return self raise ValueError(f"Unsupported device {device!r}") def dtype(self) -> Dtype: """ Array API compatible wrapper for :py:meth:`np.ndarray.dtype <numpy.ndarray.dtype>`. See its docstring for more information. """ return self._array.dtype def device(self) -> Device: return "cpu" # Note: mT is new in array API spec (see matrix_transpose) def mT(self) -> Array: from .linalg import matrix_transpose return matrix_transpose(self) def ndim(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.ndim <numpy.ndarray.ndim>`. See its docstring for more information. """ return self._array.ndim def shape(self) -> Tuple[int, ...]: """ Array API compatible wrapper for :py:meth:`np.ndarray.shape <numpy.ndarray.shape>`. See its docstring for more information. """ return self._array.shape def size(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.size <numpy.ndarray.size>`. See its docstring for more information. """ return self._array.size def T(self) -> Array: """ Array API compatible wrapper for :py:meth:`np.ndarray.T <numpy.ndarray.T>`. See its docstring for more information. """ # Note: T only works on 2-dimensional arrays. See the corresponding # note in the specification: # https://data-apis.org/array-api/latest/API_specification/array_object.html#t if self.ndim != 2: raise ValueError("x.T requires x to have 2 dimensions. Use x.mT to transpose stacks of matrices and permute_dims() to permute dimensions.") return self.__class__._new(self._array.T) The provided code snippet includes necessary dependencies for implementing the `trace` function. Write a Python function `def trace(x: Array, /, *, offset: int = 0) -> Array` to solve the following problem: Array API compatible wrapper for :py:func:`np.trace <numpy.trace>`. See its docstring for more information. Here is the function: def trace(x: Array, /, *, offset: int = 0) -> Array: """ Array API compatible wrapper for :py:func:`np.trace <numpy.trace>`. See its docstring for more information. """ if x.dtype not in _numeric_dtypes: raise TypeError('Only numeric dtypes are allowed in trace') # Note: trace always operates on the last two axes, whereas np.trace # operates on the first two axes by default return Array._new(np.asarray(np.trace(x._array, offset=offset, axis1=-2, axis2=-1)))
Array API compatible wrapper for :py:func:`np.trace <numpy.trace>`. See its docstring for more information.
170,017
from __future__ import annotations from ._dtypes import _floating_dtypes, _numeric_dtypes from ._manipulation_functions import reshape from ._array_object import Array from ..core.numeric import normalize_axis_tuple from typing import TYPE_CHECKING from typing import NamedTuple import numpy.linalg import numpy as np _numeric_dtypes = ( float32, float64, int8, int16, int32, int64, uint8, uint16, uint32, uint64, ) class Array: """ n-d array object for the array API namespace. See the docstring of :py:obj:`np.ndarray <numpy.ndarray>` for more information. This is a wrapper around numpy.ndarray that restricts the usage to only those things that are required by the array API namespace. Note, attributes on this object that start with a single underscore are not part of the API specification and should only be used internally. This object should not be constructed directly. Rather, use one of the creation functions, such as asarray(). """ _array: np.ndarray # Use a custom constructor instead of __init__, as manually initializing # this class is not supported API. def _new(cls, x, /): """ This is a private method for initializing the array API Array object. Functions outside of the array_api submodule should not use this method. Use one of the creation functions instead, such as ``asarray``. """ obj = super().__new__(cls) # Note: The spec does not have array scalars, only 0-D arrays. if isinstance(x, np.generic): # Convert the array scalar to a 0-D array x = np.asarray(x) if x.dtype not in _all_dtypes: raise TypeError( f"The array_api namespace does not support the dtype '{x.dtype}'" ) obj._array = x return obj # Prevent Array() from working def __new__(cls, *args, **kwargs): raise TypeError( "The array_api Array object should not be instantiated directly. Use an array creation function, such as asarray(), instead." ) # These functions are not required by the spec, but are implemented for # the sake of usability. def __str__(self: Array, /) -> str: """ Performs the operation __str__. """ return self._array.__str__().replace("array", "Array") def __repr__(self: Array, /) -> str: """ Performs the operation __repr__. """ suffix = f", dtype={self.dtype.name})" if 0 in self.shape: prefix = "empty(" mid = str(self.shape) else: prefix = "Array(" mid = np.array2string(self._array, separator=', ', prefix=prefix, suffix=suffix) return prefix + mid + suffix # This function is not required by the spec, but we implement it here for # convenience so that np.asarray(np.array_api.Array) will work. def __array__(self, dtype: None | np.dtype[Any] = None) -> npt.NDArray[Any]: """ Warning: this method is NOT part of the array API spec. Implementers of other libraries need not include it, and users should not assume it will be present in other implementations. """ return np.asarray(self._array, dtype=dtype) # These are various helper functions to make the array behavior match the # spec in places where it either deviates from or is more strict than # NumPy behavior def _check_allowed_dtypes(self, other: bool | int | float | Array, dtype_category: str, op: str) -> Array: """ Helper function for operators to only allow specific input dtypes Use like other = self._check_allowed_dtypes(other, 'numeric', '__add__') if other is NotImplemented: return other """ if self.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") if isinstance(other, (int, float, bool)): other = self._promote_scalar(other) elif isinstance(other, Array): if other.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") else: return NotImplemented # This will raise TypeError for type combinations that are not allowed # to promote in the spec (even if the NumPy array operator would # promote them). res_dtype = _result_type(self.dtype, other.dtype) if op.startswith("__i"): # Note: NumPy will allow in-place operators in some cases where # the type promoted operator does not match the left-hand side # operand. For example, # >>> a = np.array(1, dtype=np.int8) # >>> a += np.array(1, dtype=np.int16) # The spec explicitly disallows this. if res_dtype != self.dtype: raise TypeError( f"Cannot perform {op} with dtypes {self.dtype} and {other.dtype}" ) return other # Helper function to match the type promotion rules in the spec def _promote_scalar(self, scalar): """ Returns a promoted version of a Python scalar appropriate for use with operations on self. This may raise an OverflowError in cases where the scalar is an integer that is too large to fit in a NumPy integer dtype, or TypeError when the scalar type is incompatible with the dtype of self. """ # Note: Only Python scalar types that match the array dtype are # allowed. if isinstance(scalar, bool): if self.dtype not in _boolean_dtypes: raise TypeError( "Python bool scalars can only be promoted with bool arrays" ) elif isinstance(scalar, int): if self.dtype in _boolean_dtypes: raise TypeError( "Python int scalars cannot be promoted with bool arrays" ) elif isinstance(scalar, float): if self.dtype not in _floating_dtypes: raise TypeError( "Python float scalars can only be promoted with floating-point arrays." ) else: raise TypeError("'scalar' must be a Python scalar") # Note: scalars are unconditionally cast to the same dtype as the # array. # Note: the spec only specifies integer-dtype/int promotion # behavior for integers within the bounds of the integer dtype. # Outside of those bounds we use the default NumPy behavior (either # cast or raise OverflowError). return Array._new(np.array(scalar, self.dtype)) def _normalize_two_args(x1, x2) -> Tuple[Array, Array]: """ Normalize inputs to two arg functions to fix type promotion rules NumPy deviates from the spec type promotion rules in cases where one argument is 0-dimensional and the other is not. For example: >>> import numpy as np >>> a = np.array([1.0], dtype=np.float32) >>> b = np.array(1.0, dtype=np.float64) >>> np.add(a, b) # The spec says this should be float64 array([2.], dtype=float32) To fix this, we add a dimension to the 0-dimension array before passing it through. This works because a dimension would be added anyway from broadcasting, so the resulting shape is the same, but this prevents NumPy from not promoting the dtype. """ # Another option would be to use signature=(x1.dtype, x2.dtype, None), # but that only works for ufuncs, so we would have to call the ufuncs # directly in the operator methods. One should also note that this # sort of trick wouldn't work for functions like searchsorted, which # don't do normal broadcasting, but there aren't any functions like # that in the array API namespace. if x1.ndim == 0 and x2.ndim != 0: # The _array[None] workaround was chosen because it is relatively # performant. broadcast_to(x1._array, x2.shape) is much slower. We # could also manually type promote x2, but that is more complicated # and about the same performance as this. x1 = Array._new(x1._array[None]) elif x2.ndim == 0 and x1.ndim != 0: x2 = Array._new(x2._array[None]) return (x1, x2) # Note: A large fraction of allowed indices are disallowed here (see the # docstring below) def _validate_index(self, key): """ Validate an index according to the array API. The array API specification only requires a subset of indices that are supported by NumPy. This function will reject any index that is allowed by NumPy but not required by the array API specification. We always raise ``IndexError`` on such indices (the spec does not require any specific behavior on them, but this makes the NumPy array API namespace a minimal implementation of the spec). See https://data-apis.org/array-api/latest/API_specification/indexing.html for the full list of required indexing behavior This function raises IndexError if the index ``key`` is invalid. It only raises ``IndexError`` on indices that are not already rejected by NumPy, as NumPy will already raise the appropriate error on such indices. ``shape`` may be None, in which case, only cases that are independent of the array shape are checked. The following cases are allowed by NumPy, but not specified by the array API specification: - Indices to not include an implicit ellipsis at the end. That is, every axis of an array must be explicitly indexed or an ellipsis included. This behaviour is sometimes referred to as flat indexing. - The start and stop of a slice may not be out of bounds. In particular, for a slice ``i:j:k`` on an axis of size ``n``, only the following are allowed: - ``i`` or ``j`` omitted (``None``). - ``-n <= i <= max(0, n - 1)``. - For ``k > 0`` or ``k`` omitted (``None``), ``-n <= j <= n``. - For ``k < 0``, ``-n - 1 <= j <= max(0, n - 1)``. - Boolean array indices are not allowed as part of a larger tuple index. - Integer array indices are not allowed (with the exception of 0-D arrays, which are treated the same as scalars). Additionally, it should be noted that indices that would return a scalar in NumPy will return a 0-D array. Array scalars are not allowed in the specification, only 0-D arrays. This is done in the ``Array._new`` constructor, not this function. """ _key = key if isinstance(key, tuple) else (key,) for i in _key: if isinstance(i, bool) or not ( isinstance(i, SupportsIndex) # i.e. ints or isinstance(i, slice) or i == Ellipsis or i is None or isinstance(i, Array) or isinstance(i, np.ndarray) ): raise IndexError( f"Single-axes index {i} has {type(i)=}, but only " "integers, slices (:), ellipsis (...), newaxis (None), " "zero-dimensional integer arrays and boolean arrays " "are specified in the Array API." ) nonexpanding_key = [] single_axes = [] n_ellipsis = 0 key_has_mask = False for i in _key: if i is not None: nonexpanding_key.append(i) if isinstance(i, Array) or isinstance(i, np.ndarray): if i.dtype in _boolean_dtypes: key_has_mask = True single_axes.append(i) else: # i must not be an array here, to avoid elementwise equals if i == Ellipsis: n_ellipsis += 1 else: single_axes.append(i) n_single_axes = len(single_axes) if n_ellipsis > 1: return # handled by ndarray elif n_ellipsis == 0: # Note boolean masks must be the sole index, which we check for # later on. if not key_has_mask and n_single_axes < self.ndim: raise IndexError( f"{self.ndim=}, but the multi-axes index only specifies " f"{n_single_axes} dimensions. If this was intentional, " "add a trailing ellipsis (...) which expands into as many " "slices (:) as necessary - this is what np.ndarray arrays " "implicitly do, but such flat indexing behaviour is not " "specified in the Array API." ) if n_ellipsis == 0: indexed_shape = self.shape else: ellipsis_start = None for pos, i in enumerate(nonexpanding_key): if not (isinstance(i, Array) or isinstance(i, np.ndarray)): if i == Ellipsis: ellipsis_start = pos break assert ellipsis_start is not None # sanity check ellipsis_end = self.ndim - (n_single_axes - ellipsis_start) indexed_shape = ( self.shape[:ellipsis_start] + self.shape[ellipsis_end:] ) for i, side in zip(single_axes, indexed_shape): if isinstance(i, slice): if side == 0: f_range = "0 (or None)" else: f_range = f"between -{side} and {side - 1} (or None)" if i.start is not None: try: start = operator.index(i.start) except TypeError: pass # handled by ndarray else: if not (-side <= start <= side): raise IndexError( f"Slice {i} contains {start=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds starts are not specified in " "the Array API)" ) if i.stop is not None: try: stop = operator.index(i.stop) except TypeError: pass # handled by ndarray else: if not (-side <= stop <= side): raise IndexError( f"Slice {i} contains {stop=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds stops are not specified in " "the Array API)" ) elif isinstance(i, Array): if i.dtype in _boolean_dtypes and len(_key) != 1: assert isinstance(key, tuple) # sanity check raise IndexError( f"Single-axes index {i} is a boolean array and " f"{len(key)=}, but masking is only specified in the " "Array API when the array is the sole index." ) elif i.dtype in _integer_dtypes and i.ndim != 0: raise IndexError( f"Single-axes index {i} is a non-zero-dimensional " "integer array, but advanced integer indexing is not " "specified in the Array API." ) elif isinstance(i, tuple): raise IndexError( f"Single-axes index {i} is a tuple, but nested tuple " "indices are not specified in the Array API." ) # Everything below this line is required by the spec. def __abs__(self: Array, /) -> Array: """ Performs the operation __abs__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __abs__") res = self._array.__abs__() return self.__class__._new(res) def __add__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __add__. """ other = self._check_allowed_dtypes(other, "numeric", "__add__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__add__(other._array) return self.__class__._new(res) def __and__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __and__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__and__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__and__(other._array) return self.__class__._new(res) def __array_namespace__( self: Array, /, *, api_version: Optional[str] = None ) -> types.ModuleType: if api_version is not None and not api_version.startswith("2021."): raise ValueError(f"Unrecognized array API version: {api_version!r}") return array_api def __bool__(self: Array, /) -> bool: """ Performs the operation __bool__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("bool is only allowed on arrays with 0 dimensions") if self.dtype not in _boolean_dtypes: raise ValueError("bool is only allowed on boolean arrays") res = self._array.__bool__() return res def __dlpack__(self: Array, /, *, stream: None = None) -> PyCapsule: """ Performs the operation __dlpack__. """ return self._array.__dlpack__(stream=stream) def __dlpack_device__(self: Array, /) -> Tuple[IntEnum, int]: """ Performs the operation __dlpack_device__. """ # Note: device support is required for this return self._array.__dlpack_device__() def __eq__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __eq__. """ # Even though "all" dtypes are allowed, we still require them to be # promotable with each other. other = self._check_allowed_dtypes(other, "all", "__eq__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__eq__(other._array) return self.__class__._new(res) def __float__(self: Array, /) -> float: """ Performs the operation __float__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("float is only allowed on arrays with 0 dimensions") if self.dtype not in _floating_dtypes: raise ValueError("float is only allowed on floating-point arrays") res = self._array.__float__() return res def __floordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __floordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__floordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__floordiv__(other._array) return self.__class__._new(res) def __ge__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ge__. """ other = self._check_allowed_dtypes(other, "numeric", "__ge__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ge__(other._array) return self.__class__._new(res) def __getitem__( self: Array, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], /, ) -> Array: """ Performs the operation __getitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array res = self._array.__getitem__(key) return self._new(res) def __gt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __gt__. """ other = self._check_allowed_dtypes(other, "numeric", "__gt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__gt__(other._array) return self.__class__._new(res) def __int__(self: Array, /) -> int: """ Performs the operation __int__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("int is only allowed on arrays with 0 dimensions") if self.dtype not in _integer_dtypes: raise ValueError("int is only allowed on integer arrays") res = self._array.__int__() return res def __index__(self: Array, /) -> int: """ Performs the operation __index__. """ res = self._array.__index__() return res def __invert__(self: Array, /) -> Array: """ Performs the operation __invert__. """ if self.dtype not in _integer_or_boolean_dtypes: raise TypeError("Only integer or boolean dtypes are allowed in __invert__") res = self._array.__invert__() return self.__class__._new(res) def __le__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __le__. """ other = self._check_allowed_dtypes(other, "numeric", "__le__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__le__(other._array) return self.__class__._new(res) def __lshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __lshift__. """ other = self._check_allowed_dtypes(other, "integer", "__lshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lshift__(other._array) return self.__class__._new(res) def __lt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __lt__. """ other = self._check_allowed_dtypes(other, "numeric", "__lt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lt__(other._array) return self.__class__._new(res) def __matmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __matmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__matmul__") if other is NotImplemented: return other res = self._array.__matmul__(other._array) return self.__class__._new(res) def __mod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mod__. """ other = self._check_allowed_dtypes(other, "numeric", "__mod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mod__(other._array) return self.__class__._new(res) def __mul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mul__. """ other = self._check_allowed_dtypes(other, "numeric", "__mul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mul__(other._array) return self.__class__._new(res) def __ne__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __ne__. """ other = self._check_allowed_dtypes(other, "all", "__ne__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ne__(other._array) return self.__class__._new(res) def __neg__(self: Array, /) -> Array: """ Performs the operation __neg__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __neg__") res = self._array.__neg__() return self.__class__._new(res) def __or__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __or__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__or__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__or__(other._array) return self.__class__._new(res) def __pos__(self: Array, /) -> Array: """ Performs the operation __pos__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __pos__") res = self._array.__pos__() return self.__class__._new(res) def __pow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __pow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__pow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow type promotion rules for 0-d # arrays, so we use pow() here instead. return pow(self, other) def __rshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rshift__(other._array) return self.__class__._new(res) def __setitem__( self, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], value: Union[int, float, bool, Array], /, ) -> None: """ Performs the operation __setitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array self._array.__setitem__(key, asarray(value)._array) def __sub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __sub__. """ other = self._check_allowed_dtypes(other, "numeric", "__sub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__sub__(other._array) return self.__class__._new(res) # PEP 484 requires int to be a subtype of float, but __truediv__ should # not accept int. def __truediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __truediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__truediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__truediv__(other._array) return self.__class__._new(res) def __xor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __xor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__xor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__xor__(other._array) return self.__class__._new(res) def __iadd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __iadd__. """ other = self._check_allowed_dtypes(other, "numeric", "__iadd__") if other is NotImplemented: return other self._array.__iadd__(other._array) return self def __radd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __radd__. """ other = self._check_allowed_dtypes(other, "numeric", "__radd__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__radd__(other._array) return self.__class__._new(res) def __iand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __iand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__iand__") if other is NotImplemented: return other self._array.__iand__(other._array) return self def __rand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rand__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rand__(other._array) return self.__class__._new(res) def __ifloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ifloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__ifloordiv__") if other is NotImplemented: return other self._array.__ifloordiv__(other._array) return self def __rfloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rfloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__rfloordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rfloordiv__(other._array) return self.__class__._new(res) def __ilshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __ilshift__. """ other = self._check_allowed_dtypes(other, "integer", "__ilshift__") if other is NotImplemented: return other self._array.__ilshift__(other._array) return self def __rlshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rlshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rlshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rlshift__(other._array) return self.__class__._new(res) def __imatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __imatmul__. """ # Note: NumPy does not implement __imatmul__. # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__imatmul__") if other is NotImplemented: return other # __imatmul__ can only be allowed when it would not change the shape # of self. other_shape = other.shape if self.shape == () or other_shape == (): raise ValueError("@= requires at least one dimension") if len(other_shape) == 1 or other_shape[-1] != other_shape[-2]: raise ValueError("@= cannot change the shape of the input array") self._array[:] = self._array.__matmul__(other._array) return self def __rmatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __rmatmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__rmatmul__") if other is NotImplemented: return other res = self._array.__rmatmul__(other._array) return self.__class__._new(res) def __imod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imod__. """ other = self._check_allowed_dtypes(other, "numeric", "__imod__") if other is NotImplemented: return other self._array.__imod__(other._array) return self def __rmod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmod__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmod__(other._array) return self.__class__._new(res) def __imul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imul__. """ other = self._check_allowed_dtypes(other, "numeric", "__imul__") if other is NotImplemented: return other self._array.__imul__(other._array) return self def __rmul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmul__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmul__(other._array) return self.__class__._new(res) def __ior__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ior__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ior__") if other is NotImplemented: return other self._array.__ior__(other._array) return self def __ror__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ror__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ror__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ror__(other._array) return self.__class__._new(res) def __ipow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ipow__. """ other = self._check_allowed_dtypes(other, "numeric", "__ipow__") if other is NotImplemented: return other self._array.__ipow__(other._array) return self def __rpow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rpow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__rpow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow the spec type promotion rules # for 0-d arrays, so we use pow() here instead. return pow(other, self) def __irshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __irshift__. """ other = self._check_allowed_dtypes(other, "integer", "__irshift__") if other is NotImplemented: return other self._array.__irshift__(other._array) return self def __rrshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rrshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rrshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rrshift__(other._array) return self.__class__._new(res) def __isub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __isub__. """ other = self._check_allowed_dtypes(other, "numeric", "__isub__") if other is NotImplemented: return other self._array.__isub__(other._array) return self def __rsub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rsub__. """ other = self._check_allowed_dtypes(other, "numeric", "__rsub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rsub__(other._array) return self.__class__._new(res) def __itruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __itruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__itruediv__") if other is NotImplemented: return other self._array.__itruediv__(other._array) return self def __rtruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __rtruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__rtruediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rtruediv__(other._array) return self.__class__._new(res) def __ixor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ixor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ixor__") if other is NotImplemented: return other self._array.__ixor__(other._array) return self def __rxor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rxor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rxor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rxor__(other._array) return self.__class__._new(res) def to_device(self: Array, device: Device, /, stream: None = None) -> Array: if stream is not None: raise ValueError("The stream argument to to_device() is not supported") if device == 'cpu': return self raise ValueError(f"Unsupported device {device!r}") def dtype(self) -> Dtype: """ Array API compatible wrapper for :py:meth:`np.ndarray.dtype <numpy.ndarray.dtype>`. See its docstring for more information. """ return self._array.dtype def device(self) -> Device: return "cpu" # Note: mT is new in array API spec (see matrix_transpose) def mT(self) -> Array: from .linalg import matrix_transpose return matrix_transpose(self) def ndim(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.ndim <numpy.ndarray.ndim>`. See its docstring for more information. """ return self._array.ndim def shape(self) -> Tuple[int, ...]: """ Array API compatible wrapper for :py:meth:`np.ndarray.shape <numpy.ndarray.shape>`. See its docstring for more information. """ return self._array.shape def size(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.size <numpy.ndarray.size>`. See its docstring for more information. """ return self._array.size def T(self) -> Array: """ Array API compatible wrapper for :py:meth:`np.ndarray.T <numpy.ndarray.T>`. See its docstring for more information. """ # Note: T only works on 2-dimensional arrays. See the corresponding # note in the specification: # https://data-apis.org/array-api/latest/API_specification/array_object.html#t if self.ndim != 2: raise ValueError("x.T requires x to have 2 dimensions. Use x.mT to transpose stacks of matrices and permute_dims() to permute dimensions.") return self.__class__._new(self._array.T) def vecdot(x1: Array, x2: Array, /, *, axis: int = -1) -> Array: if x1.dtype not in _numeric_dtypes or x2.dtype not in _numeric_dtypes: raise TypeError('Only numeric dtypes are allowed in vecdot') ndim = max(x1.ndim, x2.ndim) x1_shape = (1,)*(ndim - x1.ndim) + tuple(x1.shape) x2_shape = (1,)*(ndim - x2.ndim) + tuple(x2.shape) if x1_shape[axis] != x2_shape[axis]: raise ValueError("x1 and x2 must have the same size along the given axis") x1_, x2_ = np.broadcast_arrays(x1._array, x2._array) x1_ = np.moveaxis(x1_, axis, -1) x2_ = np.moveaxis(x2_, axis, -1) res = x1_[..., None, :] @ x2_[..., None] return Array._new(res[..., 0, 0])
null
170,018
from __future__ import annotations from ._dtypes import _floating_dtypes, _numeric_dtypes from ._manipulation_functions import reshape from ._array_object import Array from ..core.numeric import normalize_axis_tuple from typing import TYPE_CHECKING from typing import NamedTuple import numpy.linalg import numpy as np _floating_dtypes = (float32, float64) def reshape(x: Array, /, shape: Tuple[int, ...]) -> Array: """ Array API compatible wrapper for :py:func:`np.reshape <numpy.reshape>`. See its docstring for more information. """ return Array._new(np.reshape(x._array, shape)) class Array: """ n-d array object for the array API namespace. See the docstring of :py:obj:`np.ndarray <numpy.ndarray>` for more information. This is a wrapper around numpy.ndarray that restricts the usage to only those things that are required by the array API namespace. Note, attributes on this object that start with a single underscore are not part of the API specification and should only be used internally. This object should not be constructed directly. Rather, use one of the creation functions, such as asarray(). """ _array: np.ndarray # Use a custom constructor instead of __init__, as manually initializing # this class is not supported API. def _new(cls, x, /): """ This is a private method for initializing the array API Array object. Functions outside of the array_api submodule should not use this method. Use one of the creation functions instead, such as ``asarray``. """ obj = super().__new__(cls) # Note: The spec does not have array scalars, only 0-D arrays. if isinstance(x, np.generic): # Convert the array scalar to a 0-D array x = np.asarray(x) if x.dtype not in _all_dtypes: raise TypeError( f"The array_api namespace does not support the dtype '{x.dtype}'" ) obj._array = x return obj # Prevent Array() from working def __new__(cls, *args, **kwargs): raise TypeError( "The array_api Array object should not be instantiated directly. Use an array creation function, such as asarray(), instead." ) # These functions are not required by the spec, but are implemented for # the sake of usability. def __str__(self: Array, /) -> str: """ Performs the operation __str__. """ return self._array.__str__().replace("array", "Array") def __repr__(self: Array, /) -> str: """ Performs the operation __repr__. """ suffix = f", dtype={self.dtype.name})" if 0 in self.shape: prefix = "empty(" mid = str(self.shape) else: prefix = "Array(" mid = np.array2string(self._array, separator=', ', prefix=prefix, suffix=suffix) return prefix + mid + suffix # This function is not required by the spec, but we implement it here for # convenience so that np.asarray(np.array_api.Array) will work. def __array__(self, dtype: None | np.dtype[Any] = None) -> npt.NDArray[Any]: """ Warning: this method is NOT part of the array API spec. Implementers of other libraries need not include it, and users should not assume it will be present in other implementations. """ return np.asarray(self._array, dtype=dtype) # These are various helper functions to make the array behavior match the # spec in places where it either deviates from or is more strict than # NumPy behavior def _check_allowed_dtypes(self, other: bool | int | float | Array, dtype_category: str, op: str) -> Array: """ Helper function for operators to only allow specific input dtypes Use like other = self._check_allowed_dtypes(other, 'numeric', '__add__') if other is NotImplemented: return other """ if self.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") if isinstance(other, (int, float, bool)): other = self._promote_scalar(other) elif isinstance(other, Array): if other.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") else: return NotImplemented # This will raise TypeError for type combinations that are not allowed # to promote in the spec (even if the NumPy array operator would # promote them). res_dtype = _result_type(self.dtype, other.dtype) if op.startswith("__i"): # Note: NumPy will allow in-place operators in some cases where # the type promoted operator does not match the left-hand side # operand. For example, # >>> a = np.array(1, dtype=np.int8) # >>> a += np.array(1, dtype=np.int16) # The spec explicitly disallows this. if res_dtype != self.dtype: raise TypeError( f"Cannot perform {op} with dtypes {self.dtype} and {other.dtype}" ) return other # Helper function to match the type promotion rules in the spec def _promote_scalar(self, scalar): """ Returns a promoted version of a Python scalar appropriate for use with operations on self. This may raise an OverflowError in cases where the scalar is an integer that is too large to fit in a NumPy integer dtype, or TypeError when the scalar type is incompatible with the dtype of self. """ # Note: Only Python scalar types that match the array dtype are # allowed. if isinstance(scalar, bool): if self.dtype not in _boolean_dtypes: raise TypeError( "Python bool scalars can only be promoted with bool arrays" ) elif isinstance(scalar, int): if self.dtype in _boolean_dtypes: raise TypeError( "Python int scalars cannot be promoted with bool arrays" ) elif isinstance(scalar, float): if self.dtype not in _floating_dtypes: raise TypeError( "Python float scalars can only be promoted with floating-point arrays." ) else: raise TypeError("'scalar' must be a Python scalar") # Note: scalars are unconditionally cast to the same dtype as the # array. # Note: the spec only specifies integer-dtype/int promotion # behavior for integers within the bounds of the integer dtype. # Outside of those bounds we use the default NumPy behavior (either # cast or raise OverflowError). return Array._new(np.array(scalar, self.dtype)) def _normalize_two_args(x1, x2) -> Tuple[Array, Array]: """ Normalize inputs to two arg functions to fix type promotion rules NumPy deviates from the spec type promotion rules in cases where one argument is 0-dimensional and the other is not. For example: >>> import numpy as np >>> a = np.array([1.0], dtype=np.float32) >>> b = np.array(1.0, dtype=np.float64) >>> np.add(a, b) # The spec says this should be float64 array([2.], dtype=float32) To fix this, we add a dimension to the 0-dimension array before passing it through. This works because a dimension would be added anyway from broadcasting, so the resulting shape is the same, but this prevents NumPy from not promoting the dtype. """ # Another option would be to use signature=(x1.dtype, x2.dtype, None), # but that only works for ufuncs, so we would have to call the ufuncs # directly in the operator methods. One should also note that this # sort of trick wouldn't work for functions like searchsorted, which # don't do normal broadcasting, but there aren't any functions like # that in the array API namespace. if x1.ndim == 0 and x2.ndim != 0: # The _array[None] workaround was chosen because it is relatively # performant. broadcast_to(x1._array, x2.shape) is much slower. We # could also manually type promote x2, but that is more complicated # and about the same performance as this. x1 = Array._new(x1._array[None]) elif x2.ndim == 0 and x1.ndim != 0: x2 = Array._new(x2._array[None]) return (x1, x2) # Note: A large fraction of allowed indices are disallowed here (see the # docstring below) def _validate_index(self, key): """ Validate an index according to the array API. The array API specification only requires a subset of indices that are supported by NumPy. This function will reject any index that is allowed by NumPy but not required by the array API specification. We always raise ``IndexError`` on such indices (the spec does not require any specific behavior on them, but this makes the NumPy array API namespace a minimal implementation of the spec). See https://data-apis.org/array-api/latest/API_specification/indexing.html for the full list of required indexing behavior This function raises IndexError if the index ``key`` is invalid. It only raises ``IndexError`` on indices that are not already rejected by NumPy, as NumPy will already raise the appropriate error on such indices. ``shape`` may be None, in which case, only cases that are independent of the array shape are checked. The following cases are allowed by NumPy, but not specified by the array API specification: - Indices to not include an implicit ellipsis at the end. That is, every axis of an array must be explicitly indexed or an ellipsis included. This behaviour is sometimes referred to as flat indexing. - The start and stop of a slice may not be out of bounds. In particular, for a slice ``i:j:k`` on an axis of size ``n``, only the following are allowed: - ``i`` or ``j`` omitted (``None``). - ``-n <= i <= max(0, n - 1)``. - For ``k > 0`` or ``k`` omitted (``None``), ``-n <= j <= n``. - For ``k < 0``, ``-n - 1 <= j <= max(0, n - 1)``. - Boolean array indices are not allowed as part of a larger tuple index. - Integer array indices are not allowed (with the exception of 0-D arrays, which are treated the same as scalars). Additionally, it should be noted that indices that would return a scalar in NumPy will return a 0-D array. Array scalars are not allowed in the specification, only 0-D arrays. This is done in the ``Array._new`` constructor, not this function. """ _key = key if isinstance(key, tuple) else (key,) for i in _key: if isinstance(i, bool) or not ( isinstance(i, SupportsIndex) # i.e. ints or isinstance(i, slice) or i == Ellipsis or i is None or isinstance(i, Array) or isinstance(i, np.ndarray) ): raise IndexError( f"Single-axes index {i} has {type(i)=}, but only " "integers, slices (:), ellipsis (...), newaxis (None), " "zero-dimensional integer arrays and boolean arrays " "are specified in the Array API." ) nonexpanding_key = [] single_axes = [] n_ellipsis = 0 key_has_mask = False for i in _key: if i is not None: nonexpanding_key.append(i) if isinstance(i, Array) or isinstance(i, np.ndarray): if i.dtype in _boolean_dtypes: key_has_mask = True single_axes.append(i) else: # i must not be an array here, to avoid elementwise equals if i == Ellipsis: n_ellipsis += 1 else: single_axes.append(i) n_single_axes = len(single_axes) if n_ellipsis > 1: return # handled by ndarray elif n_ellipsis == 0: # Note boolean masks must be the sole index, which we check for # later on. if not key_has_mask and n_single_axes < self.ndim: raise IndexError( f"{self.ndim=}, but the multi-axes index only specifies " f"{n_single_axes} dimensions. If this was intentional, " "add a trailing ellipsis (...) which expands into as many " "slices (:) as necessary - this is what np.ndarray arrays " "implicitly do, but such flat indexing behaviour is not " "specified in the Array API." ) if n_ellipsis == 0: indexed_shape = self.shape else: ellipsis_start = None for pos, i in enumerate(nonexpanding_key): if not (isinstance(i, Array) or isinstance(i, np.ndarray)): if i == Ellipsis: ellipsis_start = pos break assert ellipsis_start is not None # sanity check ellipsis_end = self.ndim - (n_single_axes - ellipsis_start) indexed_shape = ( self.shape[:ellipsis_start] + self.shape[ellipsis_end:] ) for i, side in zip(single_axes, indexed_shape): if isinstance(i, slice): if side == 0: f_range = "0 (or None)" else: f_range = f"between -{side} and {side - 1} (or None)" if i.start is not None: try: start = operator.index(i.start) except TypeError: pass # handled by ndarray else: if not (-side <= start <= side): raise IndexError( f"Slice {i} contains {start=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds starts are not specified in " "the Array API)" ) if i.stop is not None: try: stop = operator.index(i.stop) except TypeError: pass # handled by ndarray else: if not (-side <= stop <= side): raise IndexError( f"Slice {i} contains {stop=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds stops are not specified in " "the Array API)" ) elif isinstance(i, Array): if i.dtype in _boolean_dtypes and len(_key) != 1: assert isinstance(key, tuple) # sanity check raise IndexError( f"Single-axes index {i} is a boolean array and " f"{len(key)=}, but masking is only specified in the " "Array API when the array is the sole index." ) elif i.dtype in _integer_dtypes and i.ndim != 0: raise IndexError( f"Single-axes index {i} is a non-zero-dimensional " "integer array, but advanced integer indexing is not " "specified in the Array API." ) elif isinstance(i, tuple): raise IndexError( f"Single-axes index {i} is a tuple, but nested tuple " "indices are not specified in the Array API." ) # Everything below this line is required by the spec. def __abs__(self: Array, /) -> Array: """ Performs the operation __abs__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __abs__") res = self._array.__abs__() return self.__class__._new(res) def __add__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __add__. """ other = self._check_allowed_dtypes(other, "numeric", "__add__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__add__(other._array) return self.__class__._new(res) def __and__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __and__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__and__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__and__(other._array) return self.__class__._new(res) def __array_namespace__( self: Array, /, *, api_version: Optional[str] = None ) -> types.ModuleType: if api_version is not None and not api_version.startswith("2021."): raise ValueError(f"Unrecognized array API version: {api_version!r}") return array_api def __bool__(self: Array, /) -> bool: """ Performs the operation __bool__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("bool is only allowed on arrays with 0 dimensions") if self.dtype not in _boolean_dtypes: raise ValueError("bool is only allowed on boolean arrays") res = self._array.__bool__() return res def __dlpack__(self: Array, /, *, stream: None = None) -> PyCapsule: """ Performs the operation __dlpack__. """ return self._array.__dlpack__(stream=stream) def __dlpack_device__(self: Array, /) -> Tuple[IntEnum, int]: """ Performs the operation __dlpack_device__. """ # Note: device support is required for this return self._array.__dlpack_device__() def __eq__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __eq__. """ # Even though "all" dtypes are allowed, we still require them to be # promotable with each other. other = self._check_allowed_dtypes(other, "all", "__eq__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__eq__(other._array) return self.__class__._new(res) def __float__(self: Array, /) -> float: """ Performs the operation __float__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("float is only allowed on arrays with 0 dimensions") if self.dtype not in _floating_dtypes: raise ValueError("float is only allowed on floating-point arrays") res = self._array.__float__() return res def __floordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __floordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__floordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__floordiv__(other._array) return self.__class__._new(res) def __ge__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ge__. """ other = self._check_allowed_dtypes(other, "numeric", "__ge__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ge__(other._array) return self.__class__._new(res) def __getitem__( self: Array, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], /, ) -> Array: """ Performs the operation __getitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array res = self._array.__getitem__(key) return self._new(res) def __gt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __gt__. """ other = self._check_allowed_dtypes(other, "numeric", "__gt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__gt__(other._array) return self.__class__._new(res) def __int__(self: Array, /) -> int: """ Performs the operation __int__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("int is only allowed on arrays with 0 dimensions") if self.dtype not in _integer_dtypes: raise ValueError("int is only allowed on integer arrays") res = self._array.__int__() return res def __index__(self: Array, /) -> int: """ Performs the operation __index__. """ res = self._array.__index__() return res def __invert__(self: Array, /) -> Array: """ Performs the operation __invert__. """ if self.dtype not in _integer_or_boolean_dtypes: raise TypeError("Only integer or boolean dtypes are allowed in __invert__") res = self._array.__invert__() return self.__class__._new(res) def __le__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __le__. """ other = self._check_allowed_dtypes(other, "numeric", "__le__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__le__(other._array) return self.__class__._new(res) def __lshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __lshift__. """ other = self._check_allowed_dtypes(other, "integer", "__lshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lshift__(other._array) return self.__class__._new(res) def __lt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __lt__. """ other = self._check_allowed_dtypes(other, "numeric", "__lt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lt__(other._array) return self.__class__._new(res) def __matmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __matmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__matmul__") if other is NotImplemented: return other res = self._array.__matmul__(other._array) return self.__class__._new(res) def __mod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mod__. """ other = self._check_allowed_dtypes(other, "numeric", "__mod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mod__(other._array) return self.__class__._new(res) def __mul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mul__. """ other = self._check_allowed_dtypes(other, "numeric", "__mul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mul__(other._array) return self.__class__._new(res) def __ne__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __ne__. """ other = self._check_allowed_dtypes(other, "all", "__ne__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ne__(other._array) return self.__class__._new(res) def __neg__(self: Array, /) -> Array: """ Performs the operation __neg__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __neg__") res = self._array.__neg__() return self.__class__._new(res) def __or__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __or__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__or__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__or__(other._array) return self.__class__._new(res) def __pos__(self: Array, /) -> Array: """ Performs the operation __pos__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __pos__") res = self._array.__pos__() return self.__class__._new(res) def __pow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __pow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__pow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow type promotion rules for 0-d # arrays, so we use pow() here instead. return pow(self, other) def __rshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rshift__(other._array) return self.__class__._new(res) def __setitem__( self, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], value: Union[int, float, bool, Array], /, ) -> None: """ Performs the operation __setitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array self._array.__setitem__(key, asarray(value)._array) def __sub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __sub__. """ other = self._check_allowed_dtypes(other, "numeric", "__sub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__sub__(other._array) return self.__class__._new(res) # PEP 484 requires int to be a subtype of float, but __truediv__ should # not accept int. def __truediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __truediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__truediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__truediv__(other._array) return self.__class__._new(res) def __xor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __xor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__xor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__xor__(other._array) return self.__class__._new(res) def __iadd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __iadd__. """ other = self._check_allowed_dtypes(other, "numeric", "__iadd__") if other is NotImplemented: return other self._array.__iadd__(other._array) return self def __radd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __radd__. """ other = self._check_allowed_dtypes(other, "numeric", "__radd__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__radd__(other._array) return self.__class__._new(res) def __iand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __iand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__iand__") if other is NotImplemented: return other self._array.__iand__(other._array) return self def __rand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rand__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rand__(other._array) return self.__class__._new(res) def __ifloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ifloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__ifloordiv__") if other is NotImplemented: return other self._array.__ifloordiv__(other._array) return self def __rfloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rfloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__rfloordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rfloordiv__(other._array) return self.__class__._new(res) def __ilshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __ilshift__. """ other = self._check_allowed_dtypes(other, "integer", "__ilshift__") if other is NotImplemented: return other self._array.__ilshift__(other._array) return self def __rlshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rlshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rlshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rlshift__(other._array) return self.__class__._new(res) def __imatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __imatmul__. """ # Note: NumPy does not implement __imatmul__. # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__imatmul__") if other is NotImplemented: return other # __imatmul__ can only be allowed when it would not change the shape # of self. other_shape = other.shape if self.shape == () or other_shape == (): raise ValueError("@= requires at least one dimension") if len(other_shape) == 1 or other_shape[-1] != other_shape[-2]: raise ValueError("@= cannot change the shape of the input array") self._array[:] = self._array.__matmul__(other._array) return self def __rmatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __rmatmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__rmatmul__") if other is NotImplemented: return other res = self._array.__rmatmul__(other._array) return self.__class__._new(res) def __imod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imod__. """ other = self._check_allowed_dtypes(other, "numeric", "__imod__") if other is NotImplemented: return other self._array.__imod__(other._array) return self def __rmod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmod__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmod__(other._array) return self.__class__._new(res) def __imul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imul__. """ other = self._check_allowed_dtypes(other, "numeric", "__imul__") if other is NotImplemented: return other self._array.__imul__(other._array) return self def __rmul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmul__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmul__(other._array) return self.__class__._new(res) def __ior__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ior__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ior__") if other is NotImplemented: return other self._array.__ior__(other._array) return self def __ror__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ror__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ror__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ror__(other._array) return self.__class__._new(res) def __ipow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ipow__. """ other = self._check_allowed_dtypes(other, "numeric", "__ipow__") if other is NotImplemented: return other self._array.__ipow__(other._array) return self def __rpow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rpow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__rpow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow the spec type promotion rules # for 0-d arrays, so we use pow() here instead. return pow(other, self) def __irshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __irshift__. """ other = self._check_allowed_dtypes(other, "integer", "__irshift__") if other is NotImplemented: return other self._array.__irshift__(other._array) return self def __rrshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rrshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rrshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rrshift__(other._array) return self.__class__._new(res) def __isub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __isub__. """ other = self._check_allowed_dtypes(other, "numeric", "__isub__") if other is NotImplemented: return other self._array.__isub__(other._array) return self def __rsub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rsub__. """ other = self._check_allowed_dtypes(other, "numeric", "__rsub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rsub__(other._array) return self.__class__._new(res) def __itruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __itruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__itruediv__") if other is NotImplemented: return other self._array.__itruediv__(other._array) return self def __rtruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __rtruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__rtruediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rtruediv__(other._array) return self.__class__._new(res) def __ixor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ixor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ixor__") if other is NotImplemented: return other self._array.__ixor__(other._array) return self def __rxor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rxor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rxor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rxor__(other._array) return self.__class__._new(res) def to_device(self: Array, device: Device, /, stream: None = None) -> Array: if stream is not None: raise ValueError("The stream argument to to_device() is not supported") if device == 'cpu': return self raise ValueError(f"Unsupported device {device!r}") def dtype(self) -> Dtype: """ Array API compatible wrapper for :py:meth:`np.ndarray.dtype <numpy.ndarray.dtype>`. See its docstring for more information. """ return self._array.dtype def device(self) -> Device: return "cpu" # Note: mT is new in array API spec (see matrix_transpose) def mT(self) -> Array: from .linalg import matrix_transpose return matrix_transpose(self) def ndim(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.ndim <numpy.ndarray.ndim>`. See its docstring for more information. """ return self._array.ndim def shape(self) -> Tuple[int, ...]: """ Array API compatible wrapper for :py:meth:`np.ndarray.shape <numpy.ndarray.shape>`. See its docstring for more information. """ return self._array.shape def size(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.size <numpy.ndarray.size>`. See its docstring for more information. """ return self._array.size def T(self) -> Array: """ Array API compatible wrapper for :py:meth:`np.ndarray.T <numpy.ndarray.T>`. See its docstring for more information. """ # Note: T only works on 2-dimensional arrays. See the corresponding # note in the specification: # https://data-apis.org/array-api/latest/API_specification/array_object.html#t if self.ndim != 2: raise ValueError("x.T requires x to have 2 dimensions. Use x.mT to transpose stacks of matrices and permute_dims() to permute dimensions.") return self.__class__._new(self._array.T) def normalize_axis_tuple(axis, ndim, argname=None, allow_duplicate=False): """ Normalizes an axis argument into a tuple of non-negative integer axes. This handles shorthands such as ``1`` and converts them to ``(1,)``, as well as performing the handling of negative indices covered by `normalize_axis_index`. By default, this forbids axes from being specified multiple times. Used internally by multi-axis-checking logic. .. versionadded:: 1.13.0 Parameters ---------- axis : int, iterable of int The un-normalized index or indices of the axis. ndim : int The number of dimensions of the array that `axis` should be normalized against. argname : str, optional A prefix to put before the error message, typically the name of the argument. allow_duplicate : bool, optional If False, the default, disallow an axis from being specified twice. Returns ------- normalized_axes : tuple of int The normalized axis index, such that `0 <= normalized_axis < ndim` Raises ------ AxisError If any axis provided is out of range ValueError If an axis is repeated See also -------- normalize_axis_index : normalizing a single scalar axis """ # Optimization to speed-up the most common cases. if type(axis) not in (tuple, list): try: axis = [operator.index(axis)] except TypeError: pass # Going via an iterator directly is slower than via list comprehension. axis = tuple([normalize_axis_index(ax, ndim, argname) for ax in axis]) if not allow_duplicate and len(set(axis)) != len(axis): if argname: raise ValueError('repeated axis in `{}` argument'.format(argname)) else: raise ValueError('repeated axis') return axis The provided code snippet includes necessary dependencies for implementing the `vector_norm` function. Write a Python function `def vector_norm(x: Array, /, *, axis: Optional[Union[int, Tuple[int, ...]]] = None, keepdims: bool = False, ord: Optional[Union[int, float]] = 2) -> Array` to solve the following problem: Array API compatible wrapper for :py:func:`np.linalg.norm <numpy.linalg.norm>`. See its docstring for more information. Here is the function: def vector_norm(x: Array, /, *, axis: Optional[Union[int, Tuple[int, ...]]] = None, keepdims: bool = False, ord: Optional[Union[int, float]] = 2) -> Array: """ Array API compatible wrapper for :py:func:`np.linalg.norm <numpy.linalg.norm>`. See its docstring for more information. """ # Note: the restriction to floating-point dtypes only is different from # np.linalg.norm. if x.dtype not in _floating_dtypes: raise TypeError('Only floating-point dtypes are allowed in norm') # np.linalg.norm tries to do a matrix norm whenever axis is a 2-tuple or # when axis=None and the input is 2-D, so to force a vector norm, we make # it so the input is 1-D (for axis=None), or reshape so that norm is done # on a single dimension. a = x._array if axis is None: # Note: np.linalg.norm() doesn't handle 0-D arrays a = a.ravel() _axis = 0 elif isinstance(axis, tuple): # Note: The axis argument supports any number of axes, whereas # np.linalg.norm() only supports a single axis for vector norm. normalized_axis = normalize_axis_tuple(axis, x.ndim) rest = tuple(i for i in range(a.ndim) if i not in normalized_axis) newshape = axis + rest a = np.transpose(a, newshape).reshape( (np.prod([a.shape[i] for i in axis], dtype=int), *[a.shape[i] for i in rest])) _axis = 0 else: _axis = axis res = Array._new(np.linalg.norm(a, axis=_axis, ord=ord)) if keepdims: # We can't reuse np.linalg.norm(keepdims) because of the reshape hacks # above to avoid matrix norm logic. shape = list(x.shape) _axis = normalize_axis_tuple(range(x.ndim) if axis is None else axis, x.ndim) for i in _axis: shape[i] = 1 res = reshape(res, tuple(shape)) return res
Array API compatible wrapper for :py:func:`np.linalg.norm <numpy.linalg.norm>`. See its docstring for more information.
170,019
from __future__ import annotations from ._dtypes import ( _boolean_dtypes, _floating_dtypes, _integer_dtypes, _integer_or_boolean_dtypes, _numeric_dtypes, _result_type, ) from ._array_object import Array import numpy as np _numeric_dtypes = ( float32, float64, int8, int16, int32, int64, uint8, uint16, uint32, uint64, ) class Array: """ n-d array object for the array API namespace. See the docstring of :py:obj:`np.ndarray <numpy.ndarray>` for more information. This is a wrapper around numpy.ndarray that restricts the usage to only those things that are required by the array API namespace. Note, attributes on this object that start with a single underscore are not part of the API specification and should only be used internally. This object should not be constructed directly. Rather, use one of the creation functions, such as asarray(). """ _array: np.ndarray # Use a custom constructor instead of __init__, as manually initializing # this class is not supported API. def _new(cls, x, /): """ This is a private method for initializing the array API Array object. Functions outside of the array_api submodule should not use this method. Use one of the creation functions instead, such as ``asarray``. """ obj = super().__new__(cls) # Note: The spec does not have array scalars, only 0-D arrays. if isinstance(x, np.generic): # Convert the array scalar to a 0-D array x = np.asarray(x) if x.dtype not in _all_dtypes: raise TypeError( f"The array_api namespace does not support the dtype '{x.dtype}'" ) obj._array = x return obj # Prevent Array() from working def __new__(cls, *args, **kwargs): raise TypeError( "The array_api Array object should not be instantiated directly. Use an array creation function, such as asarray(), instead." ) # These functions are not required by the spec, but are implemented for # the sake of usability. def __str__(self: Array, /) -> str: """ Performs the operation __str__. """ return self._array.__str__().replace("array", "Array") def __repr__(self: Array, /) -> str: """ Performs the operation __repr__. """ suffix = f", dtype={self.dtype.name})" if 0 in self.shape: prefix = "empty(" mid = str(self.shape) else: prefix = "Array(" mid = np.array2string(self._array, separator=', ', prefix=prefix, suffix=suffix) return prefix + mid + suffix # This function is not required by the spec, but we implement it here for # convenience so that np.asarray(np.array_api.Array) will work. def __array__(self, dtype: None | np.dtype[Any] = None) -> npt.NDArray[Any]: """ Warning: this method is NOT part of the array API spec. Implementers of other libraries need not include it, and users should not assume it will be present in other implementations. """ return np.asarray(self._array, dtype=dtype) # These are various helper functions to make the array behavior match the # spec in places where it either deviates from or is more strict than # NumPy behavior def _check_allowed_dtypes(self, other: bool | int | float | Array, dtype_category: str, op: str) -> Array: """ Helper function for operators to only allow specific input dtypes Use like other = self._check_allowed_dtypes(other, 'numeric', '__add__') if other is NotImplemented: return other """ if self.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") if isinstance(other, (int, float, bool)): other = self._promote_scalar(other) elif isinstance(other, Array): if other.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") else: return NotImplemented # This will raise TypeError for type combinations that are not allowed # to promote in the spec (even if the NumPy array operator would # promote them). res_dtype = _result_type(self.dtype, other.dtype) if op.startswith("__i"): # Note: NumPy will allow in-place operators in some cases where # the type promoted operator does not match the left-hand side # operand. For example, # >>> a = np.array(1, dtype=np.int8) # >>> a += np.array(1, dtype=np.int16) # The spec explicitly disallows this. if res_dtype != self.dtype: raise TypeError( f"Cannot perform {op} with dtypes {self.dtype} and {other.dtype}" ) return other # Helper function to match the type promotion rules in the spec def _promote_scalar(self, scalar): """ Returns a promoted version of a Python scalar appropriate for use with operations on self. This may raise an OverflowError in cases where the scalar is an integer that is too large to fit in a NumPy integer dtype, or TypeError when the scalar type is incompatible with the dtype of self. """ # Note: Only Python scalar types that match the array dtype are # allowed. if isinstance(scalar, bool): if self.dtype not in _boolean_dtypes: raise TypeError( "Python bool scalars can only be promoted with bool arrays" ) elif isinstance(scalar, int): if self.dtype in _boolean_dtypes: raise TypeError( "Python int scalars cannot be promoted with bool arrays" ) elif isinstance(scalar, float): if self.dtype not in _floating_dtypes: raise TypeError( "Python float scalars can only be promoted with floating-point arrays." ) else: raise TypeError("'scalar' must be a Python scalar") # Note: scalars are unconditionally cast to the same dtype as the # array. # Note: the spec only specifies integer-dtype/int promotion # behavior for integers within the bounds of the integer dtype. # Outside of those bounds we use the default NumPy behavior (either # cast or raise OverflowError). return Array._new(np.array(scalar, self.dtype)) def _normalize_two_args(x1, x2) -> Tuple[Array, Array]: """ Normalize inputs to two arg functions to fix type promotion rules NumPy deviates from the spec type promotion rules in cases where one argument is 0-dimensional and the other is not. For example: >>> import numpy as np >>> a = np.array([1.0], dtype=np.float32) >>> b = np.array(1.0, dtype=np.float64) >>> np.add(a, b) # The spec says this should be float64 array([2.], dtype=float32) To fix this, we add a dimension to the 0-dimension array before passing it through. This works because a dimension would be added anyway from broadcasting, so the resulting shape is the same, but this prevents NumPy from not promoting the dtype. """ # Another option would be to use signature=(x1.dtype, x2.dtype, None), # but that only works for ufuncs, so we would have to call the ufuncs # directly in the operator methods. One should also note that this # sort of trick wouldn't work for functions like searchsorted, which # don't do normal broadcasting, but there aren't any functions like # that in the array API namespace. if x1.ndim == 0 and x2.ndim != 0: # The _array[None] workaround was chosen because it is relatively # performant. broadcast_to(x1._array, x2.shape) is much slower. We # could also manually type promote x2, but that is more complicated # and about the same performance as this. x1 = Array._new(x1._array[None]) elif x2.ndim == 0 and x1.ndim != 0: x2 = Array._new(x2._array[None]) return (x1, x2) # Note: A large fraction of allowed indices are disallowed here (see the # docstring below) def _validate_index(self, key): """ Validate an index according to the array API. The array API specification only requires a subset of indices that are supported by NumPy. This function will reject any index that is allowed by NumPy but not required by the array API specification. We always raise ``IndexError`` on such indices (the spec does not require any specific behavior on them, but this makes the NumPy array API namespace a minimal implementation of the spec). See https://data-apis.org/array-api/latest/API_specification/indexing.html for the full list of required indexing behavior This function raises IndexError if the index ``key`` is invalid. It only raises ``IndexError`` on indices that are not already rejected by NumPy, as NumPy will already raise the appropriate error on such indices. ``shape`` may be None, in which case, only cases that are independent of the array shape are checked. The following cases are allowed by NumPy, but not specified by the array API specification: - Indices to not include an implicit ellipsis at the end. That is, every axis of an array must be explicitly indexed or an ellipsis included. This behaviour is sometimes referred to as flat indexing. - The start and stop of a slice may not be out of bounds. In particular, for a slice ``i:j:k`` on an axis of size ``n``, only the following are allowed: - ``i`` or ``j`` omitted (``None``). - ``-n <= i <= max(0, n - 1)``. - For ``k > 0`` or ``k`` omitted (``None``), ``-n <= j <= n``. - For ``k < 0``, ``-n - 1 <= j <= max(0, n - 1)``. - Boolean array indices are not allowed as part of a larger tuple index. - Integer array indices are not allowed (with the exception of 0-D arrays, which are treated the same as scalars). Additionally, it should be noted that indices that would return a scalar in NumPy will return a 0-D array. Array scalars are not allowed in the specification, only 0-D arrays. This is done in the ``Array._new`` constructor, not this function. """ _key = key if isinstance(key, tuple) else (key,) for i in _key: if isinstance(i, bool) or not ( isinstance(i, SupportsIndex) # i.e. ints or isinstance(i, slice) or i == Ellipsis or i is None or isinstance(i, Array) or isinstance(i, np.ndarray) ): raise IndexError( f"Single-axes index {i} has {type(i)=}, but only " "integers, slices (:), ellipsis (...), newaxis (None), " "zero-dimensional integer arrays and boolean arrays " "are specified in the Array API." ) nonexpanding_key = [] single_axes = [] n_ellipsis = 0 key_has_mask = False for i in _key: if i is not None: nonexpanding_key.append(i) if isinstance(i, Array) or isinstance(i, np.ndarray): if i.dtype in _boolean_dtypes: key_has_mask = True single_axes.append(i) else: # i must not be an array here, to avoid elementwise equals if i == Ellipsis: n_ellipsis += 1 else: single_axes.append(i) n_single_axes = len(single_axes) if n_ellipsis > 1: return # handled by ndarray elif n_ellipsis == 0: # Note boolean masks must be the sole index, which we check for # later on. if not key_has_mask and n_single_axes < self.ndim: raise IndexError( f"{self.ndim=}, but the multi-axes index only specifies " f"{n_single_axes} dimensions. If this was intentional, " "add a trailing ellipsis (...) which expands into as many " "slices (:) as necessary - this is what np.ndarray arrays " "implicitly do, but such flat indexing behaviour is not " "specified in the Array API." ) if n_ellipsis == 0: indexed_shape = self.shape else: ellipsis_start = None for pos, i in enumerate(nonexpanding_key): if not (isinstance(i, Array) or isinstance(i, np.ndarray)): if i == Ellipsis: ellipsis_start = pos break assert ellipsis_start is not None # sanity check ellipsis_end = self.ndim - (n_single_axes - ellipsis_start) indexed_shape = ( self.shape[:ellipsis_start] + self.shape[ellipsis_end:] ) for i, side in zip(single_axes, indexed_shape): if isinstance(i, slice): if side == 0: f_range = "0 (or None)" else: f_range = f"between -{side} and {side - 1} (or None)" if i.start is not None: try: start = operator.index(i.start) except TypeError: pass # handled by ndarray else: if not (-side <= start <= side): raise IndexError( f"Slice {i} contains {start=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds starts are not specified in " "the Array API)" ) if i.stop is not None: try: stop = operator.index(i.stop) except TypeError: pass # handled by ndarray else: if not (-side <= stop <= side): raise IndexError( f"Slice {i} contains {stop=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds stops are not specified in " "the Array API)" ) elif isinstance(i, Array): if i.dtype in _boolean_dtypes and len(_key) != 1: assert isinstance(key, tuple) # sanity check raise IndexError( f"Single-axes index {i} is a boolean array and " f"{len(key)=}, but masking is only specified in the " "Array API when the array is the sole index." ) elif i.dtype in _integer_dtypes and i.ndim != 0: raise IndexError( f"Single-axes index {i} is a non-zero-dimensional " "integer array, but advanced integer indexing is not " "specified in the Array API." ) elif isinstance(i, tuple): raise IndexError( f"Single-axes index {i} is a tuple, but nested tuple " "indices are not specified in the Array API." ) # Everything below this line is required by the spec. def __abs__(self: Array, /) -> Array: """ Performs the operation __abs__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __abs__") res = self._array.__abs__() return self.__class__._new(res) def __add__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __add__. """ other = self._check_allowed_dtypes(other, "numeric", "__add__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__add__(other._array) return self.__class__._new(res) def __and__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __and__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__and__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__and__(other._array) return self.__class__._new(res) def __array_namespace__( self: Array, /, *, api_version: Optional[str] = None ) -> types.ModuleType: if api_version is not None and not api_version.startswith("2021."): raise ValueError(f"Unrecognized array API version: {api_version!r}") return array_api def __bool__(self: Array, /) -> bool: """ Performs the operation __bool__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("bool is only allowed on arrays with 0 dimensions") if self.dtype not in _boolean_dtypes: raise ValueError("bool is only allowed on boolean arrays") res = self._array.__bool__() return res def __dlpack__(self: Array, /, *, stream: None = None) -> PyCapsule: """ Performs the operation __dlpack__. """ return self._array.__dlpack__(stream=stream) def __dlpack_device__(self: Array, /) -> Tuple[IntEnum, int]: """ Performs the operation __dlpack_device__. """ # Note: device support is required for this return self._array.__dlpack_device__() def __eq__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __eq__. """ # Even though "all" dtypes are allowed, we still require them to be # promotable with each other. other = self._check_allowed_dtypes(other, "all", "__eq__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__eq__(other._array) return self.__class__._new(res) def __float__(self: Array, /) -> float: """ Performs the operation __float__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("float is only allowed on arrays with 0 dimensions") if self.dtype not in _floating_dtypes: raise ValueError("float is only allowed on floating-point arrays") res = self._array.__float__() return res def __floordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __floordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__floordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__floordiv__(other._array) return self.__class__._new(res) def __ge__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ge__. """ other = self._check_allowed_dtypes(other, "numeric", "__ge__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ge__(other._array) return self.__class__._new(res) def __getitem__( self: Array, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], /, ) -> Array: """ Performs the operation __getitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array res = self._array.__getitem__(key) return self._new(res) def __gt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __gt__. """ other = self._check_allowed_dtypes(other, "numeric", "__gt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__gt__(other._array) return self.__class__._new(res) def __int__(self: Array, /) -> int: """ Performs the operation __int__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("int is only allowed on arrays with 0 dimensions") if self.dtype not in _integer_dtypes: raise ValueError("int is only allowed on integer arrays") res = self._array.__int__() return res def __index__(self: Array, /) -> int: """ Performs the operation __index__. """ res = self._array.__index__() return res def __invert__(self: Array, /) -> Array: """ Performs the operation __invert__. """ if self.dtype not in _integer_or_boolean_dtypes: raise TypeError("Only integer or boolean dtypes are allowed in __invert__") res = self._array.__invert__() return self.__class__._new(res) def __le__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __le__. """ other = self._check_allowed_dtypes(other, "numeric", "__le__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__le__(other._array) return self.__class__._new(res) def __lshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __lshift__. """ other = self._check_allowed_dtypes(other, "integer", "__lshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lshift__(other._array) return self.__class__._new(res) def __lt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __lt__. """ other = self._check_allowed_dtypes(other, "numeric", "__lt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lt__(other._array) return self.__class__._new(res) def __matmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __matmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__matmul__") if other is NotImplemented: return other res = self._array.__matmul__(other._array) return self.__class__._new(res) def __mod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mod__. """ other = self._check_allowed_dtypes(other, "numeric", "__mod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mod__(other._array) return self.__class__._new(res) def __mul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mul__. """ other = self._check_allowed_dtypes(other, "numeric", "__mul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mul__(other._array) return self.__class__._new(res) def __ne__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __ne__. """ other = self._check_allowed_dtypes(other, "all", "__ne__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ne__(other._array) return self.__class__._new(res) def __neg__(self: Array, /) -> Array: """ Performs the operation __neg__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __neg__") res = self._array.__neg__() return self.__class__._new(res) def __or__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __or__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__or__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__or__(other._array) return self.__class__._new(res) def __pos__(self: Array, /) -> Array: """ Performs the operation __pos__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __pos__") res = self._array.__pos__() return self.__class__._new(res) def __pow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __pow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__pow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow type promotion rules for 0-d # arrays, so we use pow() here instead. return pow(self, other) def __rshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rshift__(other._array) return self.__class__._new(res) def __setitem__( self, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], value: Union[int, float, bool, Array], /, ) -> None: """ Performs the operation __setitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array self._array.__setitem__(key, asarray(value)._array) def __sub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __sub__. """ other = self._check_allowed_dtypes(other, "numeric", "__sub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__sub__(other._array) return self.__class__._new(res) # PEP 484 requires int to be a subtype of float, but __truediv__ should # not accept int. def __truediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __truediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__truediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__truediv__(other._array) return self.__class__._new(res) def __xor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __xor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__xor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__xor__(other._array) return self.__class__._new(res) def __iadd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __iadd__. """ other = self._check_allowed_dtypes(other, "numeric", "__iadd__") if other is NotImplemented: return other self._array.__iadd__(other._array) return self def __radd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __radd__. """ other = self._check_allowed_dtypes(other, "numeric", "__radd__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__radd__(other._array) return self.__class__._new(res) def __iand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __iand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__iand__") if other is NotImplemented: return other self._array.__iand__(other._array) return self def __rand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rand__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rand__(other._array) return self.__class__._new(res) def __ifloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ifloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__ifloordiv__") if other is NotImplemented: return other self._array.__ifloordiv__(other._array) return self def __rfloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rfloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__rfloordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rfloordiv__(other._array) return self.__class__._new(res) def __ilshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __ilshift__. """ other = self._check_allowed_dtypes(other, "integer", "__ilshift__") if other is NotImplemented: return other self._array.__ilshift__(other._array) return self def __rlshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rlshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rlshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rlshift__(other._array) return self.__class__._new(res) def __imatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __imatmul__. """ # Note: NumPy does not implement __imatmul__. # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__imatmul__") if other is NotImplemented: return other # __imatmul__ can only be allowed when it would not change the shape # of self. other_shape = other.shape if self.shape == () or other_shape == (): raise ValueError("@= requires at least one dimension") if len(other_shape) == 1 or other_shape[-1] != other_shape[-2]: raise ValueError("@= cannot change the shape of the input array") self._array[:] = self._array.__matmul__(other._array) return self def __rmatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __rmatmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__rmatmul__") if other is NotImplemented: return other res = self._array.__rmatmul__(other._array) return self.__class__._new(res) def __imod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imod__. """ other = self._check_allowed_dtypes(other, "numeric", "__imod__") if other is NotImplemented: return other self._array.__imod__(other._array) return self def __rmod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmod__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmod__(other._array) return self.__class__._new(res) def __imul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imul__. """ other = self._check_allowed_dtypes(other, "numeric", "__imul__") if other is NotImplemented: return other self._array.__imul__(other._array) return self def __rmul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmul__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmul__(other._array) return self.__class__._new(res) def __ior__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ior__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ior__") if other is NotImplemented: return other self._array.__ior__(other._array) return self def __ror__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ror__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ror__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ror__(other._array) return self.__class__._new(res) def __ipow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ipow__. """ other = self._check_allowed_dtypes(other, "numeric", "__ipow__") if other is NotImplemented: return other self._array.__ipow__(other._array) return self def __rpow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rpow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__rpow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow the spec type promotion rules # for 0-d arrays, so we use pow() here instead. return pow(other, self) def __irshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __irshift__. """ other = self._check_allowed_dtypes(other, "integer", "__irshift__") if other is NotImplemented: return other self._array.__irshift__(other._array) return self def __rrshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rrshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rrshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rrshift__(other._array) return self.__class__._new(res) def __isub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __isub__. """ other = self._check_allowed_dtypes(other, "numeric", "__isub__") if other is NotImplemented: return other self._array.__isub__(other._array) return self def __rsub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rsub__. """ other = self._check_allowed_dtypes(other, "numeric", "__rsub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rsub__(other._array) return self.__class__._new(res) def __itruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __itruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__itruediv__") if other is NotImplemented: return other self._array.__itruediv__(other._array) return self def __rtruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __rtruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__rtruediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rtruediv__(other._array) return self.__class__._new(res) def __ixor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ixor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ixor__") if other is NotImplemented: return other self._array.__ixor__(other._array) return self def __rxor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rxor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rxor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rxor__(other._array) return self.__class__._new(res) def to_device(self: Array, device: Device, /, stream: None = None) -> Array: if stream is not None: raise ValueError("The stream argument to to_device() is not supported") if device == 'cpu': return self raise ValueError(f"Unsupported device {device!r}") def dtype(self) -> Dtype: """ Array API compatible wrapper for :py:meth:`np.ndarray.dtype <numpy.ndarray.dtype>`. See its docstring for more information. """ return self._array.dtype def device(self) -> Device: return "cpu" # Note: mT is new in array API spec (see matrix_transpose) def mT(self) -> Array: from .linalg import matrix_transpose return matrix_transpose(self) def ndim(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.ndim <numpy.ndarray.ndim>`. See its docstring for more information. """ return self._array.ndim def shape(self) -> Tuple[int, ...]: """ Array API compatible wrapper for :py:meth:`np.ndarray.shape <numpy.ndarray.shape>`. See its docstring for more information. """ return self._array.shape def size(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.size <numpy.ndarray.size>`. See its docstring for more information. """ return self._array.size def T(self) -> Array: """ Array API compatible wrapper for :py:meth:`np.ndarray.T <numpy.ndarray.T>`. See its docstring for more information. """ # Note: T only works on 2-dimensional arrays. See the corresponding # note in the specification: # https://data-apis.org/array-api/latest/API_specification/array_object.html#t if self.ndim != 2: raise ValueError("x.T requires x to have 2 dimensions. Use x.mT to transpose stacks of matrices and permute_dims() to permute dimensions.") return self.__class__._new(self._array.T) The provided code snippet includes necessary dependencies for implementing the `abs` function. Write a Python function `def abs(x: Array, /) -> Array` to solve the following problem: Array API compatible wrapper for :py:func:`np.abs <numpy.abs>`. See its docstring for more information. Here is the function: def abs(x: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.abs <numpy.abs>`. See its docstring for more information. """ if x.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in abs") return Array._new(np.abs(x._array))
Array API compatible wrapper for :py:func:`np.abs <numpy.abs>`. See its docstring for more information.
170,020
from __future__ import annotations from ._dtypes import ( _boolean_dtypes, _floating_dtypes, _integer_dtypes, _integer_or_boolean_dtypes, _numeric_dtypes, _result_type, ) from ._array_object import Array import numpy as np _floating_dtypes = (float32, float64) class Array: """ n-d array object for the array API namespace. See the docstring of :py:obj:`np.ndarray <numpy.ndarray>` for more information. This is a wrapper around numpy.ndarray that restricts the usage to only those things that are required by the array API namespace. Note, attributes on this object that start with a single underscore are not part of the API specification and should only be used internally. This object should not be constructed directly. Rather, use one of the creation functions, such as asarray(). """ _array: np.ndarray # Use a custom constructor instead of __init__, as manually initializing # this class is not supported API. def _new(cls, x, /): """ This is a private method for initializing the array API Array object. Functions outside of the array_api submodule should not use this method. Use one of the creation functions instead, such as ``asarray``. """ obj = super().__new__(cls) # Note: The spec does not have array scalars, only 0-D arrays. if isinstance(x, np.generic): # Convert the array scalar to a 0-D array x = np.asarray(x) if x.dtype not in _all_dtypes: raise TypeError( f"The array_api namespace does not support the dtype '{x.dtype}'" ) obj._array = x return obj # Prevent Array() from working def __new__(cls, *args, **kwargs): raise TypeError( "The array_api Array object should not be instantiated directly. Use an array creation function, such as asarray(), instead." ) # These functions are not required by the spec, but are implemented for # the sake of usability. def __str__(self: Array, /) -> str: """ Performs the operation __str__. """ return self._array.__str__().replace("array", "Array") def __repr__(self: Array, /) -> str: """ Performs the operation __repr__. """ suffix = f", dtype={self.dtype.name})" if 0 in self.shape: prefix = "empty(" mid = str(self.shape) else: prefix = "Array(" mid = np.array2string(self._array, separator=', ', prefix=prefix, suffix=suffix) return prefix + mid + suffix # This function is not required by the spec, but we implement it here for # convenience so that np.asarray(np.array_api.Array) will work. def __array__(self, dtype: None | np.dtype[Any] = None) -> npt.NDArray[Any]: """ Warning: this method is NOT part of the array API spec. Implementers of other libraries need not include it, and users should not assume it will be present in other implementations. """ return np.asarray(self._array, dtype=dtype) # These are various helper functions to make the array behavior match the # spec in places where it either deviates from or is more strict than # NumPy behavior def _check_allowed_dtypes(self, other: bool | int | float | Array, dtype_category: str, op: str) -> Array: """ Helper function for operators to only allow specific input dtypes Use like other = self._check_allowed_dtypes(other, 'numeric', '__add__') if other is NotImplemented: return other """ if self.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") if isinstance(other, (int, float, bool)): other = self._promote_scalar(other) elif isinstance(other, Array): if other.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") else: return NotImplemented # This will raise TypeError for type combinations that are not allowed # to promote in the spec (even if the NumPy array operator would # promote them). res_dtype = _result_type(self.dtype, other.dtype) if op.startswith("__i"): # Note: NumPy will allow in-place operators in some cases where # the type promoted operator does not match the left-hand side # operand. For example, # >>> a = np.array(1, dtype=np.int8) # >>> a += np.array(1, dtype=np.int16) # The spec explicitly disallows this. if res_dtype != self.dtype: raise TypeError( f"Cannot perform {op} with dtypes {self.dtype} and {other.dtype}" ) return other # Helper function to match the type promotion rules in the spec def _promote_scalar(self, scalar): """ Returns a promoted version of a Python scalar appropriate for use with operations on self. This may raise an OverflowError in cases where the scalar is an integer that is too large to fit in a NumPy integer dtype, or TypeError when the scalar type is incompatible with the dtype of self. """ # Note: Only Python scalar types that match the array dtype are # allowed. if isinstance(scalar, bool): if self.dtype not in _boolean_dtypes: raise TypeError( "Python bool scalars can only be promoted with bool arrays" ) elif isinstance(scalar, int): if self.dtype in _boolean_dtypes: raise TypeError( "Python int scalars cannot be promoted with bool arrays" ) elif isinstance(scalar, float): if self.dtype not in _floating_dtypes: raise TypeError( "Python float scalars can only be promoted with floating-point arrays." ) else: raise TypeError("'scalar' must be a Python scalar") # Note: scalars are unconditionally cast to the same dtype as the # array. # Note: the spec only specifies integer-dtype/int promotion # behavior for integers within the bounds of the integer dtype. # Outside of those bounds we use the default NumPy behavior (either # cast or raise OverflowError). return Array._new(np.array(scalar, self.dtype)) def _normalize_two_args(x1, x2) -> Tuple[Array, Array]: """ Normalize inputs to two arg functions to fix type promotion rules NumPy deviates from the spec type promotion rules in cases where one argument is 0-dimensional and the other is not. For example: >>> import numpy as np >>> a = np.array([1.0], dtype=np.float32) >>> b = np.array(1.0, dtype=np.float64) >>> np.add(a, b) # The spec says this should be float64 array([2.], dtype=float32) To fix this, we add a dimension to the 0-dimension array before passing it through. This works because a dimension would be added anyway from broadcasting, so the resulting shape is the same, but this prevents NumPy from not promoting the dtype. """ # Another option would be to use signature=(x1.dtype, x2.dtype, None), # but that only works for ufuncs, so we would have to call the ufuncs # directly in the operator methods. One should also note that this # sort of trick wouldn't work for functions like searchsorted, which # don't do normal broadcasting, but there aren't any functions like # that in the array API namespace. if x1.ndim == 0 and x2.ndim != 0: # The _array[None] workaround was chosen because it is relatively # performant. broadcast_to(x1._array, x2.shape) is much slower. We # could also manually type promote x2, but that is more complicated # and about the same performance as this. x1 = Array._new(x1._array[None]) elif x2.ndim == 0 and x1.ndim != 0: x2 = Array._new(x2._array[None]) return (x1, x2) # Note: A large fraction of allowed indices are disallowed here (see the # docstring below) def _validate_index(self, key): """ Validate an index according to the array API. The array API specification only requires a subset of indices that are supported by NumPy. This function will reject any index that is allowed by NumPy but not required by the array API specification. We always raise ``IndexError`` on such indices (the spec does not require any specific behavior on them, but this makes the NumPy array API namespace a minimal implementation of the spec). See https://data-apis.org/array-api/latest/API_specification/indexing.html for the full list of required indexing behavior This function raises IndexError if the index ``key`` is invalid. It only raises ``IndexError`` on indices that are not already rejected by NumPy, as NumPy will already raise the appropriate error on such indices. ``shape`` may be None, in which case, only cases that are independent of the array shape are checked. The following cases are allowed by NumPy, but not specified by the array API specification: - Indices to not include an implicit ellipsis at the end. That is, every axis of an array must be explicitly indexed or an ellipsis included. This behaviour is sometimes referred to as flat indexing. - The start and stop of a slice may not be out of bounds. In particular, for a slice ``i:j:k`` on an axis of size ``n``, only the following are allowed: - ``i`` or ``j`` omitted (``None``). - ``-n <= i <= max(0, n - 1)``. - For ``k > 0`` or ``k`` omitted (``None``), ``-n <= j <= n``. - For ``k < 0``, ``-n - 1 <= j <= max(0, n - 1)``. - Boolean array indices are not allowed as part of a larger tuple index. - Integer array indices are not allowed (with the exception of 0-D arrays, which are treated the same as scalars). Additionally, it should be noted that indices that would return a scalar in NumPy will return a 0-D array. Array scalars are not allowed in the specification, only 0-D arrays. This is done in the ``Array._new`` constructor, not this function. """ _key = key if isinstance(key, tuple) else (key,) for i in _key: if isinstance(i, bool) or not ( isinstance(i, SupportsIndex) # i.e. ints or isinstance(i, slice) or i == Ellipsis or i is None or isinstance(i, Array) or isinstance(i, np.ndarray) ): raise IndexError( f"Single-axes index {i} has {type(i)=}, but only " "integers, slices (:), ellipsis (...), newaxis (None), " "zero-dimensional integer arrays and boolean arrays " "are specified in the Array API." ) nonexpanding_key = [] single_axes = [] n_ellipsis = 0 key_has_mask = False for i in _key: if i is not None: nonexpanding_key.append(i) if isinstance(i, Array) or isinstance(i, np.ndarray): if i.dtype in _boolean_dtypes: key_has_mask = True single_axes.append(i) else: # i must not be an array here, to avoid elementwise equals if i == Ellipsis: n_ellipsis += 1 else: single_axes.append(i) n_single_axes = len(single_axes) if n_ellipsis > 1: return # handled by ndarray elif n_ellipsis == 0: # Note boolean masks must be the sole index, which we check for # later on. if not key_has_mask and n_single_axes < self.ndim: raise IndexError( f"{self.ndim=}, but the multi-axes index only specifies " f"{n_single_axes} dimensions. If this was intentional, " "add a trailing ellipsis (...) which expands into as many " "slices (:) as necessary - this is what np.ndarray arrays " "implicitly do, but such flat indexing behaviour is not " "specified in the Array API." ) if n_ellipsis == 0: indexed_shape = self.shape else: ellipsis_start = None for pos, i in enumerate(nonexpanding_key): if not (isinstance(i, Array) or isinstance(i, np.ndarray)): if i == Ellipsis: ellipsis_start = pos break assert ellipsis_start is not None # sanity check ellipsis_end = self.ndim - (n_single_axes - ellipsis_start) indexed_shape = ( self.shape[:ellipsis_start] + self.shape[ellipsis_end:] ) for i, side in zip(single_axes, indexed_shape): if isinstance(i, slice): if side == 0: f_range = "0 (or None)" else: f_range = f"between -{side} and {side - 1} (or None)" if i.start is not None: try: start = operator.index(i.start) except TypeError: pass # handled by ndarray else: if not (-side <= start <= side): raise IndexError( f"Slice {i} contains {start=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds starts are not specified in " "the Array API)" ) if i.stop is not None: try: stop = operator.index(i.stop) except TypeError: pass # handled by ndarray else: if not (-side <= stop <= side): raise IndexError( f"Slice {i} contains {stop=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds stops are not specified in " "the Array API)" ) elif isinstance(i, Array): if i.dtype in _boolean_dtypes and len(_key) != 1: assert isinstance(key, tuple) # sanity check raise IndexError( f"Single-axes index {i} is a boolean array and " f"{len(key)=}, but masking is only specified in the " "Array API when the array is the sole index." ) elif i.dtype in _integer_dtypes and i.ndim != 0: raise IndexError( f"Single-axes index {i} is a non-zero-dimensional " "integer array, but advanced integer indexing is not " "specified in the Array API." ) elif isinstance(i, tuple): raise IndexError( f"Single-axes index {i} is a tuple, but nested tuple " "indices are not specified in the Array API." ) # Everything below this line is required by the spec. def __abs__(self: Array, /) -> Array: """ Performs the operation __abs__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __abs__") res = self._array.__abs__() return self.__class__._new(res) def __add__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __add__. """ other = self._check_allowed_dtypes(other, "numeric", "__add__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__add__(other._array) return self.__class__._new(res) def __and__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __and__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__and__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__and__(other._array) return self.__class__._new(res) def __array_namespace__( self: Array, /, *, api_version: Optional[str] = None ) -> types.ModuleType: if api_version is not None and not api_version.startswith("2021."): raise ValueError(f"Unrecognized array API version: {api_version!r}") return array_api def __bool__(self: Array, /) -> bool: """ Performs the operation __bool__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("bool is only allowed on arrays with 0 dimensions") if self.dtype not in _boolean_dtypes: raise ValueError("bool is only allowed on boolean arrays") res = self._array.__bool__() return res def __dlpack__(self: Array, /, *, stream: None = None) -> PyCapsule: """ Performs the operation __dlpack__. """ return self._array.__dlpack__(stream=stream) def __dlpack_device__(self: Array, /) -> Tuple[IntEnum, int]: """ Performs the operation __dlpack_device__. """ # Note: device support is required for this return self._array.__dlpack_device__() def __eq__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __eq__. """ # Even though "all" dtypes are allowed, we still require them to be # promotable with each other. other = self._check_allowed_dtypes(other, "all", "__eq__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__eq__(other._array) return self.__class__._new(res) def __float__(self: Array, /) -> float: """ Performs the operation __float__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("float is only allowed on arrays with 0 dimensions") if self.dtype not in _floating_dtypes: raise ValueError("float is only allowed on floating-point arrays") res = self._array.__float__() return res def __floordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __floordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__floordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__floordiv__(other._array) return self.__class__._new(res) def __ge__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ge__. """ other = self._check_allowed_dtypes(other, "numeric", "__ge__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ge__(other._array) return self.__class__._new(res) def __getitem__( self: Array, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], /, ) -> Array: """ Performs the operation __getitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array res = self._array.__getitem__(key) return self._new(res) def __gt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __gt__. """ other = self._check_allowed_dtypes(other, "numeric", "__gt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__gt__(other._array) return self.__class__._new(res) def __int__(self: Array, /) -> int: """ Performs the operation __int__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("int is only allowed on arrays with 0 dimensions") if self.dtype not in _integer_dtypes: raise ValueError("int is only allowed on integer arrays") res = self._array.__int__() return res def __index__(self: Array, /) -> int: """ Performs the operation __index__. """ res = self._array.__index__() return res def __invert__(self: Array, /) -> Array: """ Performs the operation __invert__. """ if self.dtype not in _integer_or_boolean_dtypes: raise TypeError("Only integer or boolean dtypes are allowed in __invert__") res = self._array.__invert__() return self.__class__._new(res) def __le__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __le__. """ other = self._check_allowed_dtypes(other, "numeric", "__le__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__le__(other._array) return self.__class__._new(res) def __lshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __lshift__. """ other = self._check_allowed_dtypes(other, "integer", "__lshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lshift__(other._array) return self.__class__._new(res) def __lt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __lt__. """ other = self._check_allowed_dtypes(other, "numeric", "__lt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lt__(other._array) return self.__class__._new(res) def __matmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __matmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__matmul__") if other is NotImplemented: return other res = self._array.__matmul__(other._array) return self.__class__._new(res) def __mod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mod__. """ other = self._check_allowed_dtypes(other, "numeric", "__mod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mod__(other._array) return self.__class__._new(res) def __mul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mul__. """ other = self._check_allowed_dtypes(other, "numeric", "__mul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mul__(other._array) return self.__class__._new(res) def __ne__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __ne__. """ other = self._check_allowed_dtypes(other, "all", "__ne__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ne__(other._array) return self.__class__._new(res) def __neg__(self: Array, /) -> Array: """ Performs the operation __neg__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __neg__") res = self._array.__neg__() return self.__class__._new(res) def __or__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __or__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__or__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__or__(other._array) return self.__class__._new(res) def __pos__(self: Array, /) -> Array: """ Performs the operation __pos__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __pos__") res = self._array.__pos__() return self.__class__._new(res) def __pow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __pow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__pow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow type promotion rules for 0-d # arrays, so we use pow() here instead. return pow(self, other) def __rshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rshift__(other._array) return self.__class__._new(res) def __setitem__( self, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], value: Union[int, float, bool, Array], /, ) -> None: """ Performs the operation __setitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array self._array.__setitem__(key, asarray(value)._array) def __sub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __sub__. """ other = self._check_allowed_dtypes(other, "numeric", "__sub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__sub__(other._array) return self.__class__._new(res) # PEP 484 requires int to be a subtype of float, but __truediv__ should # not accept int. def __truediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __truediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__truediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__truediv__(other._array) return self.__class__._new(res) def __xor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __xor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__xor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__xor__(other._array) return self.__class__._new(res) def __iadd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __iadd__. """ other = self._check_allowed_dtypes(other, "numeric", "__iadd__") if other is NotImplemented: return other self._array.__iadd__(other._array) return self def __radd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __radd__. """ other = self._check_allowed_dtypes(other, "numeric", "__radd__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__radd__(other._array) return self.__class__._new(res) def __iand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __iand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__iand__") if other is NotImplemented: return other self._array.__iand__(other._array) return self def __rand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rand__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rand__(other._array) return self.__class__._new(res) def __ifloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ifloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__ifloordiv__") if other is NotImplemented: return other self._array.__ifloordiv__(other._array) return self def __rfloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rfloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__rfloordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rfloordiv__(other._array) return self.__class__._new(res) def __ilshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __ilshift__. """ other = self._check_allowed_dtypes(other, "integer", "__ilshift__") if other is NotImplemented: return other self._array.__ilshift__(other._array) return self def __rlshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rlshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rlshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rlshift__(other._array) return self.__class__._new(res) def __imatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __imatmul__. """ # Note: NumPy does not implement __imatmul__. # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__imatmul__") if other is NotImplemented: return other # __imatmul__ can only be allowed when it would not change the shape # of self. other_shape = other.shape if self.shape == () or other_shape == (): raise ValueError("@= requires at least one dimension") if len(other_shape) == 1 or other_shape[-1] != other_shape[-2]: raise ValueError("@= cannot change the shape of the input array") self._array[:] = self._array.__matmul__(other._array) return self def __rmatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __rmatmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__rmatmul__") if other is NotImplemented: return other res = self._array.__rmatmul__(other._array) return self.__class__._new(res) def __imod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imod__. """ other = self._check_allowed_dtypes(other, "numeric", "__imod__") if other is NotImplemented: return other self._array.__imod__(other._array) return self def __rmod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmod__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmod__(other._array) return self.__class__._new(res) def __imul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imul__. """ other = self._check_allowed_dtypes(other, "numeric", "__imul__") if other is NotImplemented: return other self._array.__imul__(other._array) return self def __rmul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmul__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmul__(other._array) return self.__class__._new(res) def __ior__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ior__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ior__") if other is NotImplemented: return other self._array.__ior__(other._array) return self def __ror__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ror__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ror__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ror__(other._array) return self.__class__._new(res) def __ipow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ipow__. """ other = self._check_allowed_dtypes(other, "numeric", "__ipow__") if other is NotImplemented: return other self._array.__ipow__(other._array) return self def __rpow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rpow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__rpow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow the spec type promotion rules # for 0-d arrays, so we use pow() here instead. return pow(other, self) def __irshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __irshift__. """ other = self._check_allowed_dtypes(other, "integer", "__irshift__") if other is NotImplemented: return other self._array.__irshift__(other._array) return self def __rrshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rrshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rrshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rrshift__(other._array) return self.__class__._new(res) def __isub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __isub__. """ other = self._check_allowed_dtypes(other, "numeric", "__isub__") if other is NotImplemented: return other self._array.__isub__(other._array) return self def __rsub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rsub__. """ other = self._check_allowed_dtypes(other, "numeric", "__rsub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rsub__(other._array) return self.__class__._new(res) def __itruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __itruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__itruediv__") if other is NotImplemented: return other self._array.__itruediv__(other._array) return self def __rtruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __rtruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__rtruediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rtruediv__(other._array) return self.__class__._new(res) def __ixor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ixor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ixor__") if other is NotImplemented: return other self._array.__ixor__(other._array) return self def __rxor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rxor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rxor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rxor__(other._array) return self.__class__._new(res) def to_device(self: Array, device: Device, /, stream: None = None) -> Array: if stream is not None: raise ValueError("The stream argument to to_device() is not supported") if device == 'cpu': return self raise ValueError(f"Unsupported device {device!r}") def dtype(self) -> Dtype: """ Array API compatible wrapper for :py:meth:`np.ndarray.dtype <numpy.ndarray.dtype>`. See its docstring for more information. """ return self._array.dtype def device(self) -> Device: return "cpu" # Note: mT is new in array API spec (see matrix_transpose) def mT(self) -> Array: from .linalg import matrix_transpose return matrix_transpose(self) def ndim(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.ndim <numpy.ndarray.ndim>`. See its docstring for more information. """ return self._array.ndim def shape(self) -> Tuple[int, ...]: """ Array API compatible wrapper for :py:meth:`np.ndarray.shape <numpy.ndarray.shape>`. See its docstring for more information. """ return self._array.shape def size(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.size <numpy.ndarray.size>`. See its docstring for more information. """ return self._array.size def T(self) -> Array: """ Array API compatible wrapper for :py:meth:`np.ndarray.T <numpy.ndarray.T>`. See its docstring for more information. """ # Note: T only works on 2-dimensional arrays. See the corresponding # note in the specification: # https://data-apis.org/array-api/latest/API_specification/array_object.html#t if self.ndim != 2: raise ValueError("x.T requires x to have 2 dimensions. Use x.mT to transpose stacks of matrices and permute_dims() to permute dimensions.") return self.__class__._new(self._array.T) The provided code snippet includes necessary dependencies for implementing the `acos` function. Write a Python function `def acos(x: Array, /) -> Array` to solve the following problem: Array API compatible wrapper for :py:func:`np.arccos <numpy.arccos>`. See its docstring for more information. Here is the function: def acos(x: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.arccos <numpy.arccos>`. See its docstring for more information. """ if x.dtype not in _floating_dtypes: raise TypeError("Only floating-point dtypes are allowed in acos") return Array._new(np.arccos(x._array))
Array API compatible wrapper for :py:func:`np.arccos <numpy.arccos>`. See its docstring for more information.
170,021
from __future__ import annotations from ._dtypes import ( _boolean_dtypes, _floating_dtypes, _integer_dtypes, _integer_or_boolean_dtypes, _numeric_dtypes, _result_type, ) from ._array_object import Array import numpy as np _floating_dtypes = (float32, float64) class Array: """ n-d array object for the array API namespace. See the docstring of :py:obj:`np.ndarray <numpy.ndarray>` for more information. This is a wrapper around numpy.ndarray that restricts the usage to only those things that are required by the array API namespace. Note, attributes on this object that start with a single underscore are not part of the API specification and should only be used internally. This object should not be constructed directly. Rather, use one of the creation functions, such as asarray(). """ _array: np.ndarray # Use a custom constructor instead of __init__, as manually initializing # this class is not supported API. def _new(cls, x, /): """ This is a private method for initializing the array API Array object. Functions outside of the array_api submodule should not use this method. Use one of the creation functions instead, such as ``asarray``. """ obj = super().__new__(cls) # Note: The spec does not have array scalars, only 0-D arrays. if isinstance(x, np.generic): # Convert the array scalar to a 0-D array x = np.asarray(x) if x.dtype not in _all_dtypes: raise TypeError( f"The array_api namespace does not support the dtype '{x.dtype}'" ) obj._array = x return obj # Prevent Array() from working def __new__(cls, *args, **kwargs): raise TypeError( "The array_api Array object should not be instantiated directly. Use an array creation function, such as asarray(), instead." ) # These functions are not required by the spec, but are implemented for # the sake of usability. def __str__(self: Array, /) -> str: """ Performs the operation __str__. """ return self._array.__str__().replace("array", "Array") def __repr__(self: Array, /) -> str: """ Performs the operation __repr__. """ suffix = f", dtype={self.dtype.name})" if 0 in self.shape: prefix = "empty(" mid = str(self.shape) else: prefix = "Array(" mid = np.array2string(self._array, separator=', ', prefix=prefix, suffix=suffix) return prefix + mid + suffix # This function is not required by the spec, but we implement it here for # convenience so that np.asarray(np.array_api.Array) will work. def __array__(self, dtype: None | np.dtype[Any] = None) -> npt.NDArray[Any]: """ Warning: this method is NOT part of the array API spec. Implementers of other libraries need not include it, and users should not assume it will be present in other implementations. """ return np.asarray(self._array, dtype=dtype) # These are various helper functions to make the array behavior match the # spec in places where it either deviates from or is more strict than # NumPy behavior def _check_allowed_dtypes(self, other: bool | int | float | Array, dtype_category: str, op: str) -> Array: """ Helper function for operators to only allow specific input dtypes Use like other = self._check_allowed_dtypes(other, 'numeric', '__add__') if other is NotImplemented: return other """ if self.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") if isinstance(other, (int, float, bool)): other = self._promote_scalar(other) elif isinstance(other, Array): if other.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") else: return NotImplemented # This will raise TypeError for type combinations that are not allowed # to promote in the spec (even if the NumPy array operator would # promote them). res_dtype = _result_type(self.dtype, other.dtype) if op.startswith("__i"): # Note: NumPy will allow in-place operators in some cases where # the type promoted operator does not match the left-hand side # operand. For example, # >>> a = np.array(1, dtype=np.int8) # >>> a += np.array(1, dtype=np.int16) # The spec explicitly disallows this. if res_dtype != self.dtype: raise TypeError( f"Cannot perform {op} with dtypes {self.dtype} and {other.dtype}" ) return other # Helper function to match the type promotion rules in the spec def _promote_scalar(self, scalar): """ Returns a promoted version of a Python scalar appropriate for use with operations on self. This may raise an OverflowError in cases where the scalar is an integer that is too large to fit in a NumPy integer dtype, or TypeError when the scalar type is incompatible with the dtype of self. """ # Note: Only Python scalar types that match the array dtype are # allowed. if isinstance(scalar, bool): if self.dtype not in _boolean_dtypes: raise TypeError( "Python bool scalars can only be promoted with bool arrays" ) elif isinstance(scalar, int): if self.dtype in _boolean_dtypes: raise TypeError( "Python int scalars cannot be promoted with bool arrays" ) elif isinstance(scalar, float): if self.dtype not in _floating_dtypes: raise TypeError( "Python float scalars can only be promoted with floating-point arrays." ) else: raise TypeError("'scalar' must be a Python scalar") # Note: scalars are unconditionally cast to the same dtype as the # array. # Note: the spec only specifies integer-dtype/int promotion # behavior for integers within the bounds of the integer dtype. # Outside of those bounds we use the default NumPy behavior (either # cast or raise OverflowError). return Array._new(np.array(scalar, self.dtype)) def _normalize_two_args(x1, x2) -> Tuple[Array, Array]: """ Normalize inputs to two arg functions to fix type promotion rules NumPy deviates from the spec type promotion rules in cases where one argument is 0-dimensional and the other is not. For example: >>> import numpy as np >>> a = np.array([1.0], dtype=np.float32) >>> b = np.array(1.0, dtype=np.float64) >>> np.add(a, b) # The spec says this should be float64 array([2.], dtype=float32) To fix this, we add a dimension to the 0-dimension array before passing it through. This works because a dimension would be added anyway from broadcasting, so the resulting shape is the same, but this prevents NumPy from not promoting the dtype. """ # Another option would be to use signature=(x1.dtype, x2.dtype, None), # but that only works for ufuncs, so we would have to call the ufuncs # directly in the operator methods. One should also note that this # sort of trick wouldn't work for functions like searchsorted, which # don't do normal broadcasting, but there aren't any functions like # that in the array API namespace. if x1.ndim == 0 and x2.ndim != 0: # The _array[None] workaround was chosen because it is relatively # performant. broadcast_to(x1._array, x2.shape) is much slower. We # could also manually type promote x2, but that is more complicated # and about the same performance as this. x1 = Array._new(x1._array[None]) elif x2.ndim == 0 and x1.ndim != 0: x2 = Array._new(x2._array[None]) return (x1, x2) # Note: A large fraction of allowed indices are disallowed here (see the # docstring below) def _validate_index(self, key): """ Validate an index according to the array API. The array API specification only requires a subset of indices that are supported by NumPy. This function will reject any index that is allowed by NumPy but not required by the array API specification. We always raise ``IndexError`` on such indices (the spec does not require any specific behavior on them, but this makes the NumPy array API namespace a minimal implementation of the spec). See https://data-apis.org/array-api/latest/API_specification/indexing.html for the full list of required indexing behavior This function raises IndexError if the index ``key`` is invalid. It only raises ``IndexError`` on indices that are not already rejected by NumPy, as NumPy will already raise the appropriate error on such indices. ``shape`` may be None, in which case, only cases that are independent of the array shape are checked. The following cases are allowed by NumPy, but not specified by the array API specification: - Indices to not include an implicit ellipsis at the end. That is, every axis of an array must be explicitly indexed or an ellipsis included. This behaviour is sometimes referred to as flat indexing. - The start and stop of a slice may not be out of bounds. In particular, for a slice ``i:j:k`` on an axis of size ``n``, only the following are allowed: - ``i`` or ``j`` omitted (``None``). - ``-n <= i <= max(0, n - 1)``. - For ``k > 0`` or ``k`` omitted (``None``), ``-n <= j <= n``. - For ``k < 0``, ``-n - 1 <= j <= max(0, n - 1)``. - Boolean array indices are not allowed as part of a larger tuple index. - Integer array indices are not allowed (with the exception of 0-D arrays, which are treated the same as scalars). Additionally, it should be noted that indices that would return a scalar in NumPy will return a 0-D array. Array scalars are not allowed in the specification, only 0-D arrays. This is done in the ``Array._new`` constructor, not this function. """ _key = key if isinstance(key, tuple) else (key,) for i in _key: if isinstance(i, bool) or not ( isinstance(i, SupportsIndex) # i.e. ints or isinstance(i, slice) or i == Ellipsis or i is None or isinstance(i, Array) or isinstance(i, np.ndarray) ): raise IndexError( f"Single-axes index {i} has {type(i)=}, but only " "integers, slices (:), ellipsis (...), newaxis (None), " "zero-dimensional integer arrays and boolean arrays " "are specified in the Array API." ) nonexpanding_key = [] single_axes = [] n_ellipsis = 0 key_has_mask = False for i in _key: if i is not None: nonexpanding_key.append(i) if isinstance(i, Array) or isinstance(i, np.ndarray): if i.dtype in _boolean_dtypes: key_has_mask = True single_axes.append(i) else: # i must not be an array here, to avoid elementwise equals if i == Ellipsis: n_ellipsis += 1 else: single_axes.append(i) n_single_axes = len(single_axes) if n_ellipsis > 1: return # handled by ndarray elif n_ellipsis == 0: # Note boolean masks must be the sole index, which we check for # later on. if not key_has_mask and n_single_axes < self.ndim: raise IndexError( f"{self.ndim=}, but the multi-axes index only specifies " f"{n_single_axes} dimensions. If this was intentional, " "add a trailing ellipsis (...) which expands into as many " "slices (:) as necessary - this is what np.ndarray arrays " "implicitly do, but such flat indexing behaviour is not " "specified in the Array API." ) if n_ellipsis == 0: indexed_shape = self.shape else: ellipsis_start = None for pos, i in enumerate(nonexpanding_key): if not (isinstance(i, Array) or isinstance(i, np.ndarray)): if i == Ellipsis: ellipsis_start = pos break assert ellipsis_start is not None # sanity check ellipsis_end = self.ndim - (n_single_axes - ellipsis_start) indexed_shape = ( self.shape[:ellipsis_start] + self.shape[ellipsis_end:] ) for i, side in zip(single_axes, indexed_shape): if isinstance(i, slice): if side == 0: f_range = "0 (or None)" else: f_range = f"between -{side} and {side - 1} (or None)" if i.start is not None: try: start = operator.index(i.start) except TypeError: pass # handled by ndarray else: if not (-side <= start <= side): raise IndexError( f"Slice {i} contains {start=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds starts are not specified in " "the Array API)" ) if i.stop is not None: try: stop = operator.index(i.stop) except TypeError: pass # handled by ndarray else: if not (-side <= stop <= side): raise IndexError( f"Slice {i} contains {stop=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds stops are not specified in " "the Array API)" ) elif isinstance(i, Array): if i.dtype in _boolean_dtypes and len(_key) != 1: assert isinstance(key, tuple) # sanity check raise IndexError( f"Single-axes index {i} is a boolean array and " f"{len(key)=}, but masking is only specified in the " "Array API when the array is the sole index." ) elif i.dtype in _integer_dtypes and i.ndim != 0: raise IndexError( f"Single-axes index {i} is a non-zero-dimensional " "integer array, but advanced integer indexing is not " "specified in the Array API." ) elif isinstance(i, tuple): raise IndexError( f"Single-axes index {i} is a tuple, but nested tuple " "indices are not specified in the Array API." ) # Everything below this line is required by the spec. def __abs__(self: Array, /) -> Array: """ Performs the operation __abs__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __abs__") res = self._array.__abs__() return self.__class__._new(res) def __add__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __add__. """ other = self._check_allowed_dtypes(other, "numeric", "__add__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__add__(other._array) return self.__class__._new(res) def __and__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __and__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__and__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__and__(other._array) return self.__class__._new(res) def __array_namespace__( self: Array, /, *, api_version: Optional[str] = None ) -> types.ModuleType: if api_version is not None and not api_version.startswith("2021."): raise ValueError(f"Unrecognized array API version: {api_version!r}") return array_api def __bool__(self: Array, /) -> bool: """ Performs the operation __bool__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("bool is only allowed on arrays with 0 dimensions") if self.dtype not in _boolean_dtypes: raise ValueError("bool is only allowed on boolean arrays") res = self._array.__bool__() return res def __dlpack__(self: Array, /, *, stream: None = None) -> PyCapsule: """ Performs the operation __dlpack__. """ return self._array.__dlpack__(stream=stream) def __dlpack_device__(self: Array, /) -> Tuple[IntEnum, int]: """ Performs the operation __dlpack_device__. """ # Note: device support is required for this return self._array.__dlpack_device__() def __eq__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __eq__. """ # Even though "all" dtypes are allowed, we still require them to be # promotable with each other. other = self._check_allowed_dtypes(other, "all", "__eq__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__eq__(other._array) return self.__class__._new(res) def __float__(self: Array, /) -> float: """ Performs the operation __float__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("float is only allowed on arrays with 0 dimensions") if self.dtype not in _floating_dtypes: raise ValueError("float is only allowed on floating-point arrays") res = self._array.__float__() return res def __floordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __floordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__floordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__floordiv__(other._array) return self.__class__._new(res) def __ge__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ge__. """ other = self._check_allowed_dtypes(other, "numeric", "__ge__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ge__(other._array) return self.__class__._new(res) def __getitem__( self: Array, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], /, ) -> Array: """ Performs the operation __getitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array res = self._array.__getitem__(key) return self._new(res) def __gt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __gt__. """ other = self._check_allowed_dtypes(other, "numeric", "__gt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__gt__(other._array) return self.__class__._new(res) def __int__(self: Array, /) -> int: """ Performs the operation __int__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("int is only allowed on arrays with 0 dimensions") if self.dtype not in _integer_dtypes: raise ValueError("int is only allowed on integer arrays") res = self._array.__int__() return res def __index__(self: Array, /) -> int: """ Performs the operation __index__. """ res = self._array.__index__() return res def __invert__(self: Array, /) -> Array: """ Performs the operation __invert__. """ if self.dtype not in _integer_or_boolean_dtypes: raise TypeError("Only integer or boolean dtypes are allowed in __invert__") res = self._array.__invert__() return self.__class__._new(res) def __le__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __le__. """ other = self._check_allowed_dtypes(other, "numeric", "__le__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__le__(other._array) return self.__class__._new(res) def __lshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __lshift__. """ other = self._check_allowed_dtypes(other, "integer", "__lshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lshift__(other._array) return self.__class__._new(res) def __lt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __lt__. """ other = self._check_allowed_dtypes(other, "numeric", "__lt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lt__(other._array) return self.__class__._new(res) def __matmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __matmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__matmul__") if other is NotImplemented: return other res = self._array.__matmul__(other._array) return self.__class__._new(res) def __mod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mod__. """ other = self._check_allowed_dtypes(other, "numeric", "__mod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mod__(other._array) return self.__class__._new(res) def __mul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mul__. """ other = self._check_allowed_dtypes(other, "numeric", "__mul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mul__(other._array) return self.__class__._new(res) def __ne__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __ne__. """ other = self._check_allowed_dtypes(other, "all", "__ne__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ne__(other._array) return self.__class__._new(res) def __neg__(self: Array, /) -> Array: """ Performs the operation __neg__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __neg__") res = self._array.__neg__() return self.__class__._new(res) def __or__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __or__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__or__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__or__(other._array) return self.__class__._new(res) def __pos__(self: Array, /) -> Array: """ Performs the operation __pos__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __pos__") res = self._array.__pos__() return self.__class__._new(res) def __pow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __pow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__pow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow type promotion rules for 0-d # arrays, so we use pow() here instead. return pow(self, other) def __rshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rshift__(other._array) return self.__class__._new(res) def __setitem__( self, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], value: Union[int, float, bool, Array], /, ) -> None: """ Performs the operation __setitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array self._array.__setitem__(key, asarray(value)._array) def __sub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __sub__. """ other = self._check_allowed_dtypes(other, "numeric", "__sub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__sub__(other._array) return self.__class__._new(res) # PEP 484 requires int to be a subtype of float, but __truediv__ should # not accept int. def __truediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __truediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__truediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__truediv__(other._array) return self.__class__._new(res) def __xor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __xor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__xor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__xor__(other._array) return self.__class__._new(res) def __iadd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __iadd__. """ other = self._check_allowed_dtypes(other, "numeric", "__iadd__") if other is NotImplemented: return other self._array.__iadd__(other._array) return self def __radd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __radd__. """ other = self._check_allowed_dtypes(other, "numeric", "__radd__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__radd__(other._array) return self.__class__._new(res) def __iand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __iand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__iand__") if other is NotImplemented: return other self._array.__iand__(other._array) return self def __rand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rand__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rand__(other._array) return self.__class__._new(res) def __ifloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ifloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__ifloordiv__") if other is NotImplemented: return other self._array.__ifloordiv__(other._array) return self def __rfloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rfloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__rfloordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rfloordiv__(other._array) return self.__class__._new(res) def __ilshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __ilshift__. """ other = self._check_allowed_dtypes(other, "integer", "__ilshift__") if other is NotImplemented: return other self._array.__ilshift__(other._array) return self def __rlshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rlshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rlshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rlshift__(other._array) return self.__class__._new(res) def __imatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __imatmul__. """ # Note: NumPy does not implement __imatmul__. # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__imatmul__") if other is NotImplemented: return other # __imatmul__ can only be allowed when it would not change the shape # of self. other_shape = other.shape if self.shape == () or other_shape == (): raise ValueError("@= requires at least one dimension") if len(other_shape) == 1 or other_shape[-1] != other_shape[-2]: raise ValueError("@= cannot change the shape of the input array") self._array[:] = self._array.__matmul__(other._array) return self def __rmatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __rmatmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__rmatmul__") if other is NotImplemented: return other res = self._array.__rmatmul__(other._array) return self.__class__._new(res) def __imod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imod__. """ other = self._check_allowed_dtypes(other, "numeric", "__imod__") if other is NotImplemented: return other self._array.__imod__(other._array) return self def __rmod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmod__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmod__(other._array) return self.__class__._new(res) def __imul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imul__. """ other = self._check_allowed_dtypes(other, "numeric", "__imul__") if other is NotImplemented: return other self._array.__imul__(other._array) return self def __rmul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmul__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmul__(other._array) return self.__class__._new(res) def __ior__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ior__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ior__") if other is NotImplemented: return other self._array.__ior__(other._array) return self def __ror__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ror__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ror__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ror__(other._array) return self.__class__._new(res) def __ipow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ipow__. """ other = self._check_allowed_dtypes(other, "numeric", "__ipow__") if other is NotImplemented: return other self._array.__ipow__(other._array) return self def __rpow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rpow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__rpow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow the spec type promotion rules # for 0-d arrays, so we use pow() here instead. return pow(other, self) def __irshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __irshift__. """ other = self._check_allowed_dtypes(other, "integer", "__irshift__") if other is NotImplemented: return other self._array.__irshift__(other._array) return self def __rrshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rrshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rrshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rrshift__(other._array) return self.__class__._new(res) def __isub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __isub__. """ other = self._check_allowed_dtypes(other, "numeric", "__isub__") if other is NotImplemented: return other self._array.__isub__(other._array) return self def __rsub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rsub__. """ other = self._check_allowed_dtypes(other, "numeric", "__rsub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rsub__(other._array) return self.__class__._new(res) def __itruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __itruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__itruediv__") if other is NotImplemented: return other self._array.__itruediv__(other._array) return self def __rtruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __rtruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__rtruediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rtruediv__(other._array) return self.__class__._new(res) def __ixor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ixor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ixor__") if other is NotImplemented: return other self._array.__ixor__(other._array) return self def __rxor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rxor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rxor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rxor__(other._array) return self.__class__._new(res) def to_device(self: Array, device: Device, /, stream: None = None) -> Array: if stream is not None: raise ValueError("The stream argument to to_device() is not supported") if device == 'cpu': return self raise ValueError(f"Unsupported device {device!r}") def dtype(self) -> Dtype: """ Array API compatible wrapper for :py:meth:`np.ndarray.dtype <numpy.ndarray.dtype>`. See its docstring for more information. """ return self._array.dtype def device(self) -> Device: return "cpu" # Note: mT is new in array API spec (see matrix_transpose) def mT(self) -> Array: from .linalg import matrix_transpose return matrix_transpose(self) def ndim(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.ndim <numpy.ndarray.ndim>`. See its docstring for more information. """ return self._array.ndim def shape(self) -> Tuple[int, ...]: """ Array API compatible wrapper for :py:meth:`np.ndarray.shape <numpy.ndarray.shape>`. See its docstring for more information. """ return self._array.shape def size(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.size <numpy.ndarray.size>`. See its docstring for more information. """ return self._array.size def T(self) -> Array: """ Array API compatible wrapper for :py:meth:`np.ndarray.T <numpy.ndarray.T>`. See its docstring for more information. """ # Note: T only works on 2-dimensional arrays. See the corresponding # note in the specification: # https://data-apis.org/array-api/latest/API_specification/array_object.html#t if self.ndim != 2: raise ValueError("x.T requires x to have 2 dimensions. Use x.mT to transpose stacks of matrices and permute_dims() to permute dimensions.") return self.__class__._new(self._array.T) The provided code snippet includes necessary dependencies for implementing the `acosh` function. Write a Python function `def acosh(x: Array, /) -> Array` to solve the following problem: Array API compatible wrapper for :py:func:`np.arccosh <numpy.arccosh>`. See its docstring for more information. Here is the function: def acosh(x: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.arccosh <numpy.arccosh>`. See its docstring for more information. """ if x.dtype not in _floating_dtypes: raise TypeError("Only floating-point dtypes are allowed in acosh") return Array._new(np.arccosh(x._array))
Array API compatible wrapper for :py:func:`np.arccosh <numpy.arccosh>`. See its docstring for more information.
170,022
from __future__ import annotations from ._dtypes import ( _boolean_dtypes, _floating_dtypes, _integer_dtypes, _integer_or_boolean_dtypes, _numeric_dtypes, _result_type, ) from ._array_object import Array import numpy as np _numeric_dtypes = ( float32, float64, int8, int16, int32, int64, uint8, uint16, uint32, uint64, ) def _result_type(type1, type2): if (type1, type2) in _promotion_table: return _promotion_table[type1, type2] raise TypeError(f"{type1} and {type2} cannot be type promoted together") class Array: """ n-d array object for the array API namespace. See the docstring of :py:obj:`np.ndarray <numpy.ndarray>` for more information. This is a wrapper around numpy.ndarray that restricts the usage to only those things that are required by the array API namespace. Note, attributes on this object that start with a single underscore are not part of the API specification and should only be used internally. This object should not be constructed directly. Rather, use one of the creation functions, such as asarray(). """ _array: np.ndarray # Use a custom constructor instead of __init__, as manually initializing # this class is not supported API. def _new(cls, x, /): """ This is a private method for initializing the array API Array object. Functions outside of the array_api submodule should not use this method. Use one of the creation functions instead, such as ``asarray``. """ obj = super().__new__(cls) # Note: The spec does not have array scalars, only 0-D arrays. if isinstance(x, np.generic): # Convert the array scalar to a 0-D array x = np.asarray(x) if x.dtype not in _all_dtypes: raise TypeError( f"The array_api namespace does not support the dtype '{x.dtype}'" ) obj._array = x return obj # Prevent Array() from working def __new__(cls, *args, **kwargs): raise TypeError( "The array_api Array object should not be instantiated directly. Use an array creation function, such as asarray(), instead." ) # These functions are not required by the spec, but are implemented for # the sake of usability. def __str__(self: Array, /) -> str: """ Performs the operation __str__. """ return self._array.__str__().replace("array", "Array") def __repr__(self: Array, /) -> str: """ Performs the operation __repr__. """ suffix = f", dtype={self.dtype.name})" if 0 in self.shape: prefix = "empty(" mid = str(self.shape) else: prefix = "Array(" mid = np.array2string(self._array, separator=', ', prefix=prefix, suffix=suffix) return prefix + mid + suffix # This function is not required by the spec, but we implement it here for # convenience so that np.asarray(np.array_api.Array) will work. def __array__(self, dtype: None | np.dtype[Any] = None) -> npt.NDArray[Any]: """ Warning: this method is NOT part of the array API spec. Implementers of other libraries need not include it, and users should not assume it will be present in other implementations. """ return np.asarray(self._array, dtype=dtype) # These are various helper functions to make the array behavior match the # spec in places where it either deviates from or is more strict than # NumPy behavior def _check_allowed_dtypes(self, other: bool | int | float | Array, dtype_category: str, op: str) -> Array: """ Helper function for operators to only allow specific input dtypes Use like other = self._check_allowed_dtypes(other, 'numeric', '__add__') if other is NotImplemented: return other """ if self.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") if isinstance(other, (int, float, bool)): other = self._promote_scalar(other) elif isinstance(other, Array): if other.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") else: return NotImplemented # This will raise TypeError for type combinations that are not allowed # to promote in the spec (even if the NumPy array operator would # promote them). res_dtype = _result_type(self.dtype, other.dtype) if op.startswith("__i"): # Note: NumPy will allow in-place operators in some cases where # the type promoted operator does not match the left-hand side # operand. For example, # >>> a = np.array(1, dtype=np.int8) # >>> a += np.array(1, dtype=np.int16) # The spec explicitly disallows this. if res_dtype != self.dtype: raise TypeError( f"Cannot perform {op} with dtypes {self.dtype} and {other.dtype}" ) return other # Helper function to match the type promotion rules in the spec def _promote_scalar(self, scalar): """ Returns a promoted version of a Python scalar appropriate for use with operations on self. This may raise an OverflowError in cases where the scalar is an integer that is too large to fit in a NumPy integer dtype, or TypeError when the scalar type is incompatible with the dtype of self. """ # Note: Only Python scalar types that match the array dtype are # allowed. if isinstance(scalar, bool): if self.dtype not in _boolean_dtypes: raise TypeError( "Python bool scalars can only be promoted with bool arrays" ) elif isinstance(scalar, int): if self.dtype in _boolean_dtypes: raise TypeError( "Python int scalars cannot be promoted with bool arrays" ) elif isinstance(scalar, float): if self.dtype not in _floating_dtypes: raise TypeError( "Python float scalars can only be promoted with floating-point arrays." ) else: raise TypeError("'scalar' must be a Python scalar") # Note: scalars are unconditionally cast to the same dtype as the # array. # Note: the spec only specifies integer-dtype/int promotion # behavior for integers within the bounds of the integer dtype. # Outside of those bounds we use the default NumPy behavior (either # cast or raise OverflowError). return Array._new(np.array(scalar, self.dtype)) def _normalize_two_args(x1, x2) -> Tuple[Array, Array]: """ Normalize inputs to two arg functions to fix type promotion rules NumPy deviates from the spec type promotion rules in cases where one argument is 0-dimensional and the other is not. For example: >>> import numpy as np >>> a = np.array([1.0], dtype=np.float32) >>> b = np.array(1.0, dtype=np.float64) >>> np.add(a, b) # The spec says this should be float64 array([2.], dtype=float32) To fix this, we add a dimension to the 0-dimension array before passing it through. This works because a dimension would be added anyway from broadcasting, so the resulting shape is the same, but this prevents NumPy from not promoting the dtype. """ # Another option would be to use signature=(x1.dtype, x2.dtype, None), # but that only works for ufuncs, so we would have to call the ufuncs # directly in the operator methods. One should also note that this # sort of trick wouldn't work for functions like searchsorted, which # don't do normal broadcasting, but there aren't any functions like # that in the array API namespace. if x1.ndim == 0 and x2.ndim != 0: # The _array[None] workaround was chosen because it is relatively # performant. broadcast_to(x1._array, x2.shape) is much slower. We # could also manually type promote x2, but that is more complicated # and about the same performance as this. x1 = Array._new(x1._array[None]) elif x2.ndim == 0 and x1.ndim != 0: x2 = Array._new(x2._array[None]) return (x1, x2) # Note: A large fraction of allowed indices are disallowed here (see the # docstring below) def _validate_index(self, key): """ Validate an index according to the array API. The array API specification only requires a subset of indices that are supported by NumPy. This function will reject any index that is allowed by NumPy but not required by the array API specification. We always raise ``IndexError`` on such indices (the spec does not require any specific behavior on them, but this makes the NumPy array API namespace a minimal implementation of the spec). See https://data-apis.org/array-api/latest/API_specification/indexing.html for the full list of required indexing behavior This function raises IndexError if the index ``key`` is invalid. It only raises ``IndexError`` on indices that are not already rejected by NumPy, as NumPy will already raise the appropriate error on such indices. ``shape`` may be None, in which case, only cases that are independent of the array shape are checked. The following cases are allowed by NumPy, but not specified by the array API specification: - Indices to not include an implicit ellipsis at the end. That is, every axis of an array must be explicitly indexed or an ellipsis included. This behaviour is sometimes referred to as flat indexing. - The start and stop of a slice may not be out of bounds. In particular, for a slice ``i:j:k`` on an axis of size ``n``, only the following are allowed: - ``i`` or ``j`` omitted (``None``). - ``-n <= i <= max(0, n - 1)``. - For ``k > 0`` or ``k`` omitted (``None``), ``-n <= j <= n``. - For ``k < 0``, ``-n - 1 <= j <= max(0, n - 1)``. - Boolean array indices are not allowed as part of a larger tuple index. - Integer array indices are not allowed (with the exception of 0-D arrays, which are treated the same as scalars). Additionally, it should be noted that indices that would return a scalar in NumPy will return a 0-D array. Array scalars are not allowed in the specification, only 0-D arrays. This is done in the ``Array._new`` constructor, not this function. """ _key = key if isinstance(key, tuple) else (key,) for i in _key: if isinstance(i, bool) or not ( isinstance(i, SupportsIndex) # i.e. ints or isinstance(i, slice) or i == Ellipsis or i is None or isinstance(i, Array) or isinstance(i, np.ndarray) ): raise IndexError( f"Single-axes index {i} has {type(i)=}, but only " "integers, slices (:), ellipsis (...), newaxis (None), " "zero-dimensional integer arrays and boolean arrays " "are specified in the Array API." ) nonexpanding_key = [] single_axes = [] n_ellipsis = 0 key_has_mask = False for i in _key: if i is not None: nonexpanding_key.append(i) if isinstance(i, Array) or isinstance(i, np.ndarray): if i.dtype in _boolean_dtypes: key_has_mask = True single_axes.append(i) else: # i must not be an array here, to avoid elementwise equals if i == Ellipsis: n_ellipsis += 1 else: single_axes.append(i) n_single_axes = len(single_axes) if n_ellipsis > 1: return # handled by ndarray elif n_ellipsis == 0: # Note boolean masks must be the sole index, which we check for # later on. if not key_has_mask and n_single_axes < self.ndim: raise IndexError( f"{self.ndim=}, but the multi-axes index only specifies " f"{n_single_axes} dimensions. If this was intentional, " "add a trailing ellipsis (...) which expands into as many " "slices (:) as necessary - this is what np.ndarray arrays " "implicitly do, but such flat indexing behaviour is not " "specified in the Array API." ) if n_ellipsis == 0: indexed_shape = self.shape else: ellipsis_start = None for pos, i in enumerate(nonexpanding_key): if not (isinstance(i, Array) or isinstance(i, np.ndarray)): if i == Ellipsis: ellipsis_start = pos break assert ellipsis_start is not None # sanity check ellipsis_end = self.ndim - (n_single_axes - ellipsis_start) indexed_shape = ( self.shape[:ellipsis_start] + self.shape[ellipsis_end:] ) for i, side in zip(single_axes, indexed_shape): if isinstance(i, slice): if side == 0: f_range = "0 (or None)" else: f_range = f"between -{side} and {side - 1} (or None)" if i.start is not None: try: start = operator.index(i.start) except TypeError: pass # handled by ndarray else: if not (-side <= start <= side): raise IndexError( f"Slice {i} contains {start=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds starts are not specified in " "the Array API)" ) if i.stop is not None: try: stop = operator.index(i.stop) except TypeError: pass # handled by ndarray else: if not (-side <= stop <= side): raise IndexError( f"Slice {i} contains {stop=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds stops are not specified in " "the Array API)" ) elif isinstance(i, Array): if i.dtype in _boolean_dtypes and len(_key) != 1: assert isinstance(key, tuple) # sanity check raise IndexError( f"Single-axes index {i} is a boolean array and " f"{len(key)=}, but masking is only specified in the " "Array API when the array is the sole index." ) elif i.dtype in _integer_dtypes and i.ndim != 0: raise IndexError( f"Single-axes index {i} is a non-zero-dimensional " "integer array, but advanced integer indexing is not " "specified in the Array API." ) elif isinstance(i, tuple): raise IndexError( f"Single-axes index {i} is a tuple, but nested tuple " "indices are not specified in the Array API." ) # Everything below this line is required by the spec. def __abs__(self: Array, /) -> Array: """ Performs the operation __abs__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __abs__") res = self._array.__abs__() return self.__class__._new(res) def __add__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __add__. """ other = self._check_allowed_dtypes(other, "numeric", "__add__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__add__(other._array) return self.__class__._new(res) def __and__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __and__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__and__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__and__(other._array) return self.__class__._new(res) def __array_namespace__( self: Array, /, *, api_version: Optional[str] = None ) -> types.ModuleType: if api_version is not None and not api_version.startswith("2021."): raise ValueError(f"Unrecognized array API version: {api_version!r}") return array_api def __bool__(self: Array, /) -> bool: """ Performs the operation __bool__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("bool is only allowed on arrays with 0 dimensions") if self.dtype not in _boolean_dtypes: raise ValueError("bool is only allowed on boolean arrays") res = self._array.__bool__() return res def __dlpack__(self: Array, /, *, stream: None = None) -> PyCapsule: """ Performs the operation __dlpack__. """ return self._array.__dlpack__(stream=stream) def __dlpack_device__(self: Array, /) -> Tuple[IntEnum, int]: """ Performs the operation __dlpack_device__. """ # Note: device support is required for this return self._array.__dlpack_device__() def __eq__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __eq__. """ # Even though "all" dtypes are allowed, we still require them to be # promotable with each other. other = self._check_allowed_dtypes(other, "all", "__eq__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__eq__(other._array) return self.__class__._new(res) def __float__(self: Array, /) -> float: """ Performs the operation __float__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("float is only allowed on arrays with 0 dimensions") if self.dtype not in _floating_dtypes: raise ValueError("float is only allowed on floating-point arrays") res = self._array.__float__() return res def __floordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __floordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__floordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__floordiv__(other._array) return self.__class__._new(res) def __ge__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ge__. """ other = self._check_allowed_dtypes(other, "numeric", "__ge__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ge__(other._array) return self.__class__._new(res) def __getitem__( self: Array, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], /, ) -> Array: """ Performs the operation __getitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array res = self._array.__getitem__(key) return self._new(res) def __gt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __gt__. """ other = self._check_allowed_dtypes(other, "numeric", "__gt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__gt__(other._array) return self.__class__._new(res) def __int__(self: Array, /) -> int: """ Performs the operation __int__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("int is only allowed on arrays with 0 dimensions") if self.dtype not in _integer_dtypes: raise ValueError("int is only allowed on integer arrays") res = self._array.__int__() return res def __index__(self: Array, /) -> int: """ Performs the operation __index__. """ res = self._array.__index__() return res def __invert__(self: Array, /) -> Array: """ Performs the operation __invert__. """ if self.dtype not in _integer_or_boolean_dtypes: raise TypeError("Only integer or boolean dtypes are allowed in __invert__") res = self._array.__invert__() return self.__class__._new(res) def __le__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __le__. """ other = self._check_allowed_dtypes(other, "numeric", "__le__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__le__(other._array) return self.__class__._new(res) def __lshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __lshift__. """ other = self._check_allowed_dtypes(other, "integer", "__lshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lshift__(other._array) return self.__class__._new(res) def __lt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __lt__. """ other = self._check_allowed_dtypes(other, "numeric", "__lt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lt__(other._array) return self.__class__._new(res) def __matmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __matmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__matmul__") if other is NotImplemented: return other res = self._array.__matmul__(other._array) return self.__class__._new(res) def __mod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mod__. """ other = self._check_allowed_dtypes(other, "numeric", "__mod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mod__(other._array) return self.__class__._new(res) def __mul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mul__. """ other = self._check_allowed_dtypes(other, "numeric", "__mul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mul__(other._array) return self.__class__._new(res) def __ne__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __ne__. """ other = self._check_allowed_dtypes(other, "all", "__ne__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ne__(other._array) return self.__class__._new(res) def __neg__(self: Array, /) -> Array: """ Performs the operation __neg__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __neg__") res = self._array.__neg__() return self.__class__._new(res) def __or__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __or__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__or__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__or__(other._array) return self.__class__._new(res) def __pos__(self: Array, /) -> Array: """ Performs the operation __pos__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __pos__") res = self._array.__pos__() return self.__class__._new(res) def __pow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __pow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__pow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow type promotion rules for 0-d # arrays, so we use pow() here instead. return pow(self, other) def __rshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rshift__(other._array) return self.__class__._new(res) def __setitem__( self, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], value: Union[int, float, bool, Array], /, ) -> None: """ Performs the operation __setitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array self._array.__setitem__(key, asarray(value)._array) def __sub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __sub__. """ other = self._check_allowed_dtypes(other, "numeric", "__sub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__sub__(other._array) return self.__class__._new(res) # PEP 484 requires int to be a subtype of float, but __truediv__ should # not accept int. def __truediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __truediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__truediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__truediv__(other._array) return self.__class__._new(res) def __xor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __xor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__xor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__xor__(other._array) return self.__class__._new(res) def __iadd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __iadd__. """ other = self._check_allowed_dtypes(other, "numeric", "__iadd__") if other is NotImplemented: return other self._array.__iadd__(other._array) return self def __radd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __radd__. """ other = self._check_allowed_dtypes(other, "numeric", "__radd__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__radd__(other._array) return self.__class__._new(res) def __iand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __iand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__iand__") if other is NotImplemented: return other self._array.__iand__(other._array) return self def __rand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rand__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rand__(other._array) return self.__class__._new(res) def __ifloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ifloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__ifloordiv__") if other is NotImplemented: return other self._array.__ifloordiv__(other._array) return self def __rfloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rfloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__rfloordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rfloordiv__(other._array) return self.__class__._new(res) def __ilshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __ilshift__. """ other = self._check_allowed_dtypes(other, "integer", "__ilshift__") if other is NotImplemented: return other self._array.__ilshift__(other._array) return self def __rlshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rlshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rlshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rlshift__(other._array) return self.__class__._new(res) def __imatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __imatmul__. """ # Note: NumPy does not implement __imatmul__. # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__imatmul__") if other is NotImplemented: return other # __imatmul__ can only be allowed when it would not change the shape # of self. other_shape = other.shape if self.shape == () or other_shape == (): raise ValueError("@= requires at least one dimension") if len(other_shape) == 1 or other_shape[-1] != other_shape[-2]: raise ValueError("@= cannot change the shape of the input array") self._array[:] = self._array.__matmul__(other._array) return self def __rmatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __rmatmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__rmatmul__") if other is NotImplemented: return other res = self._array.__rmatmul__(other._array) return self.__class__._new(res) def __imod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imod__. """ other = self._check_allowed_dtypes(other, "numeric", "__imod__") if other is NotImplemented: return other self._array.__imod__(other._array) return self def __rmod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmod__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmod__(other._array) return self.__class__._new(res) def __imul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imul__. """ other = self._check_allowed_dtypes(other, "numeric", "__imul__") if other is NotImplemented: return other self._array.__imul__(other._array) return self def __rmul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmul__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmul__(other._array) return self.__class__._new(res) def __ior__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ior__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ior__") if other is NotImplemented: return other self._array.__ior__(other._array) return self def __ror__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ror__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ror__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ror__(other._array) return self.__class__._new(res) def __ipow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ipow__. """ other = self._check_allowed_dtypes(other, "numeric", "__ipow__") if other is NotImplemented: return other self._array.__ipow__(other._array) return self def __rpow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rpow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__rpow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow the spec type promotion rules # for 0-d arrays, so we use pow() here instead. return pow(other, self) def __irshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __irshift__. """ other = self._check_allowed_dtypes(other, "integer", "__irshift__") if other is NotImplemented: return other self._array.__irshift__(other._array) return self def __rrshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rrshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rrshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rrshift__(other._array) return self.__class__._new(res) def __isub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __isub__. """ other = self._check_allowed_dtypes(other, "numeric", "__isub__") if other is NotImplemented: return other self._array.__isub__(other._array) return self def __rsub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rsub__. """ other = self._check_allowed_dtypes(other, "numeric", "__rsub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rsub__(other._array) return self.__class__._new(res) def __itruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __itruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__itruediv__") if other is NotImplemented: return other self._array.__itruediv__(other._array) return self def __rtruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __rtruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__rtruediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rtruediv__(other._array) return self.__class__._new(res) def __ixor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ixor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ixor__") if other is NotImplemented: return other self._array.__ixor__(other._array) return self def __rxor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rxor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rxor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rxor__(other._array) return self.__class__._new(res) def to_device(self: Array, device: Device, /, stream: None = None) -> Array: if stream is not None: raise ValueError("The stream argument to to_device() is not supported") if device == 'cpu': return self raise ValueError(f"Unsupported device {device!r}") def dtype(self) -> Dtype: """ Array API compatible wrapper for :py:meth:`np.ndarray.dtype <numpy.ndarray.dtype>`. See its docstring for more information. """ return self._array.dtype def device(self) -> Device: return "cpu" # Note: mT is new in array API spec (see matrix_transpose) def mT(self) -> Array: from .linalg import matrix_transpose return matrix_transpose(self) def ndim(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.ndim <numpy.ndarray.ndim>`. See its docstring for more information. """ return self._array.ndim def shape(self) -> Tuple[int, ...]: """ Array API compatible wrapper for :py:meth:`np.ndarray.shape <numpy.ndarray.shape>`. See its docstring for more information. """ return self._array.shape def size(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.size <numpy.ndarray.size>`. See its docstring for more information. """ return self._array.size def T(self) -> Array: """ Array API compatible wrapper for :py:meth:`np.ndarray.T <numpy.ndarray.T>`. See its docstring for more information. """ # Note: T only works on 2-dimensional arrays. See the corresponding # note in the specification: # https://data-apis.org/array-api/latest/API_specification/array_object.html#t if self.ndim != 2: raise ValueError("x.T requires x to have 2 dimensions. Use x.mT to transpose stacks of matrices and permute_dims() to permute dimensions.") return self.__class__._new(self._array.T) The provided code snippet includes necessary dependencies for implementing the `add` function. Write a Python function `def add(x1: Array, x2: Array, /) -> Array` to solve the following problem: Array API compatible wrapper for :py:func:`np.add <numpy.add>`. See its docstring for more information. Here is the function: def add(x1: Array, x2: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.add <numpy.add>`. See its docstring for more information. """ if x1.dtype not in _numeric_dtypes or x2.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in add") # Call result type here just to raise on disallowed type combinations _result_type(x1.dtype, x2.dtype) x1, x2 = Array._normalize_two_args(x1, x2) return Array._new(np.add(x1._array, x2._array))
Array API compatible wrapper for :py:func:`np.add <numpy.add>`. See its docstring for more information.
170,023
from __future__ import annotations from ._dtypes import ( _boolean_dtypes, _floating_dtypes, _integer_dtypes, _integer_or_boolean_dtypes, _numeric_dtypes, _result_type, ) from ._array_object import Array import numpy as np _floating_dtypes = (float32, float64) class Array: """ n-d array object for the array API namespace. See the docstring of :py:obj:`np.ndarray <numpy.ndarray>` for more information. This is a wrapper around numpy.ndarray that restricts the usage to only those things that are required by the array API namespace. Note, attributes on this object that start with a single underscore are not part of the API specification and should only be used internally. This object should not be constructed directly. Rather, use one of the creation functions, such as asarray(). """ _array: np.ndarray # Use a custom constructor instead of __init__, as manually initializing # this class is not supported API. def _new(cls, x, /): """ This is a private method for initializing the array API Array object. Functions outside of the array_api submodule should not use this method. Use one of the creation functions instead, such as ``asarray``. """ obj = super().__new__(cls) # Note: The spec does not have array scalars, only 0-D arrays. if isinstance(x, np.generic): # Convert the array scalar to a 0-D array x = np.asarray(x) if x.dtype not in _all_dtypes: raise TypeError( f"The array_api namespace does not support the dtype '{x.dtype}'" ) obj._array = x return obj # Prevent Array() from working def __new__(cls, *args, **kwargs): raise TypeError( "The array_api Array object should not be instantiated directly. Use an array creation function, such as asarray(), instead." ) # These functions are not required by the spec, but are implemented for # the sake of usability. def __str__(self: Array, /) -> str: """ Performs the operation __str__. """ return self._array.__str__().replace("array", "Array") def __repr__(self: Array, /) -> str: """ Performs the operation __repr__. """ suffix = f", dtype={self.dtype.name})" if 0 in self.shape: prefix = "empty(" mid = str(self.shape) else: prefix = "Array(" mid = np.array2string(self._array, separator=', ', prefix=prefix, suffix=suffix) return prefix + mid + suffix # This function is not required by the spec, but we implement it here for # convenience so that np.asarray(np.array_api.Array) will work. def __array__(self, dtype: None | np.dtype[Any] = None) -> npt.NDArray[Any]: """ Warning: this method is NOT part of the array API spec. Implementers of other libraries need not include it, and users should not assume it will be present in other implementations. """ return np.asarray(self._array, dtype=dtype) # These are various helper functions to make the array behavior match the # spec in places where it either deviates from or is more strict than # NumPy behavior def _check_allowed_dtypes(self, other: bool | int | float | Array, dtype_category: str, op: str) -> Array: """ Helper function for operators to only allow specific input dtypes Use like other = self._check_allowed_dtypes(other, 'numeric', '__add__') if other is NotImplemented: return other """ if self.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") if isinstance(other, (int, float, bool)): other = self._promote_scalar(other) elif isinstance(other, Array): if other.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") else: return NotImplemented # This will raise TypeError for type combinations that are not allowed # to promote in the spec (even if the NumPy array operator would # promote them). res_dtype = _result_type(self.dtype, other.dtype) if op.startswith("__i"): # Note: NumPy will allow in-place operators in some cases where # the type promoted operator does not match the left-hand side # operand. For example, # >>> a = np.array(1, dtype=np.int8) # >>> a += np.array(1, dtype=np.int16) # The spec explicitly disallows this. if res_dtype != self.dtype: raise TypeError( f"Cannot perform {op} with dtypes {self.dtype} and {other.dtype}" ) return other # Helper function to match the type promotion rules in the spec def _promote_scalar(self, scalar): """ Returns a promoted version of a Python scalar appropriate for use with operations on self. This may raise an OverflowError in cases where the scalar is an integer that is too large to fit in a NumPy integer dtype, or TypeError when the scalar type is incompatible with the dtype of self. """ # Note: Only Python scalar types that match the array dtype are # allowed. if isinstance(scalar, bool): if self.dtype not in _boolean_dtypes: raise TypeError( "Python bool scalars can only be promoted with bool arrays" ) elif isinstance(scalar, int): if self.dtype in _boolean_dtypes: raise TypeError( "Python int scalars cannot be promoted with bool arrays" ) elif isinstance(scalar, float): if self.dtype not in _floating_dtypes: raise TypeError( "Python float scalars can only be promoted with floating-point arrays." ) else: raise TypeError("'scalar' must be a Python scalar") # Note: scalars are unconditionally cast to the same dtype as the # array. # Note: the spec only specifies integer-dtype/int promotion # behavior for integers within the bounds of the integer dtype. # Outside of those bounds we use the default NumPy behavior (either # cast or raise OverflowError). return Array._new(np.array(scalar, self.dtype)) def _normalize_two_args(x1, x2) -> Tuple[Array, Array]: """ Normalize inputs to two arg functions to fix type promotion rules NumPy deviates from the spec type promotion rules in cases where one argument is 0-dimensional and the other is not. For example: >>> import numpy as np >>> a = np.array([1.0], dtype=np.float32) >>> b = np.array(1.0, dtype=np.float64) >>> np.add(a, b) # The spec says this should be float64 array([2.], dtype=float32) To fix this, we add a dimension to the 0-dimension array before passing it through. This works because a dimension would be added anyway from broadcasting, so the resulting shape is the same, but this prevents NumPy from not promoting the dtype. """ # Another option would be to use signature=(x1.dtype, x2.dtype, None), # but that only works for ufuncs, so we would have to call the ufuncs # directly in the operator methods. One should also note that this # sort of trick wouldn't work for functions like searchsorted, which # don't do normal broadcasting, but there aren't any functions like # that in the array API namespace. if x1.ndim == 0 and x2.ndim != 0: # The _array[None] workaround was chosen because it is relatively # performant. broadcast_to(x1._array, x2.shape) is much slower. We # could also manually type promote x2, but that is more complicated # and about the same performance as this. x1 = Array._new(x1._array[None]) elif x2.ndim == 0 and x1.ndim != 0: x2 = Array._new(x2._array[None]) return (x1, x2) # Note: A large fraction of allowed indices are disallowed here (see the # docstring below) def _validate_index(self, key): """ Validate an index according to the array API. The array API specification only requires a subset of indices that are supported by NumPy. This function will reject any index that is allowed by NumPy but not required by the array API specification. We always raise ``IndexError`` on such indices (the spec does not require any specific behavior on them, but this makes the NumPy array API namespace a minimal implementation of the spec). See https://data-apis.org/array-api/latest/API_specification/indexing.html for the full list of required indexing behavior This function raises IndexError if the index ``key`` is invalid. It only raises ``IndexError`` on indices that are not already rejected by NumPy, as NumPy will already raise the appropriate error on such indices. ``shape`` may be None, in which case, only cases that are independent of the array shape are checked. The following cases are allowed by NumPy, but not specified by the array API specification: - Indices to not include an implicit ellipsis at the end. That is, every axis of an array must be explicitly indexed or an ellipsis included. This behaviour is sometimes referred to as flat indexing. - The start and stop of a slice may not be out of bounds. In particular, for a slice ``i:j:k`` on an axis of size ``n``, only the following are allowed: - ``i`` or ``j`` omitted (``None``). - ``-n <= i <= max(0, n - 1)``. - For ``k > 0`` or ``k`` omitted (``None``), ``-n <= j <= n``. - For ``k < 0``, ``-n - 1 <= j <= max(0, n - 1)``. - Boolean array indices are not allowed as part of a larger tuple index. - Integer array indices are not allowed (with the exception of 0-D arrays, which are treated the same as scalars). Additionally, it should be noted that indices that would return a scalar in NumPy will return a 0-D array. Array scalars are not allowed in the specification, only 0-D arrays. This is done in the ``Array._new`` constructor, not this function. """ _key = key if isinstance(key, tuple) else (key,) for i in _key: if isinstance(i, bool) or not ( isinstance(i, SupportsIndex) # i.e. ints or isinstance(i, slice) or i == Ellipsis or i is None or isinstance(i, Array) or isinstance(i, np.ndarray) ): raise IndexError( f"Single-axes index {i} has {type(i)=}, but only " "integers, slices (:), ellipsis (...), newaxis (None), " "zero-dimensional integer arrays and boolean arrays " "are specified in the Array API." ) nonexpanding_key = [] single_axes = [] n_ellipsis = 0 key_has_mask = False for i in _key: if i is not None: nonexpanding_key.append(i) if isinstance(i, Array) or isinstance(i, np.ndarray): if i.dtype in _boolean_dtypes: key_has_mask = True single_axes.append(i) else: # i must not be an array here, to avoid elementwise equals if i == Ellipsis: n_ellipsis += 1 else: single_axes.append(i) n_single_axes = len(single_axes) if n_ellipsis > 1: return # handled by ndarray elif n_ellipsis == 0: # Note boolean masks must be the sole index, which we check for # later on. if not key_has_mask and n_single_axes < self.ndim: raise IndexError( f"{self.ndim=}, but the multi-axes index only specifies " f"{n_single_axes} dimensions. If this was intentional, " "add a trailing ellipsis (...) which expands into as many " "slices (:) as necessary - this is what np.ndarray arrays " "implicitly do, but such flat indexing behaviour is not " "specified in the Array API." ) if n_ellipsis == 0: indexed_shape = self.shape else: ellipsis_start = None for pos, i in enumerate(nonexpanding_key): if not (isinstance(i, Array) or isinstance(i, np.ndarray)): if i == Ellipsis: ellipsis_start = pos break assert ellipsis_start is not None # sanity check ellipsis_end = self.ndim - (n_single_axes - ellipsis_start) indexed_shape = ( self.shape[:ellipsis_start] + self.shape[ellipsis_end:] ) for i, side in zip(single_axes, indexed_shape): if isinstance(i, slice): if side == 0: f_range = "0 (or None)" else: f_range = f"between -{side} and {side - 1} (or None)" if i.start is not None: try: start = operator.index(i.start) except TypeError: pass # handled by ndarray else: if not (-side <= start <= side): raise IndexError( f"Slice {i} contains {start=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds starts are not specified in " "the Array API)" ) if i.stop is not None: try: stop = operator.index(i.stop) except TypeError: pass # handled by ndarray else: if not (-side <= stop <= side): raise IndexError( f"Slice {i} contains {stop=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds stops are not specified in " "the Array API)" ) elif isinstance(i, Array): if i.dtype in _boolean_dtypes and len(_key) != 1: assert isinstance(key, tuple) # sanity check raise IndexError( f"Single-axes index {i} is a boolean array and " f"{len(key)=}, but masking is only specified in the " "Array API when the array is the sole index." ) elif i.dtype in _integer_dtypes and i.ndim != 0: raise IndexError( f"Single-axes index {i} is a non-zero-dimensional " "integer array, but advanced integer indexing is not " "specified in the Array API." ) elif isinstance(i, tuple): raise IndexError( f"Single-axes index {i} is a tuple, but nested tuple " "indices are not specified in the Array API." ) # Everything below this line is required by the spec. def __abs__(self: Array, /) -> Array: """ Performs the operation __abs__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __abs__") res = self._array.__abs__() return self.__class__._new(res) def __add__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __add__. """ other = self._check_allowed_dtypes(other, "numeric", "__add__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__add__(other._array) return self.__class__._new(res) def __and__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __and__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__and__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__and__(other._array) return self.__class__._new(res) def __array_namespace__( self: Array, /, *, api_version: Optional[str] = None ) -> types.ModuleType: if api_version is not None and not api_version.startswith("2021."): raise ValueError(f"Unrecognized array API version: {api_version!r}") return array_api def __bool__(self: Array, /) -> bool: """ Performs the operation __bool__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("bool is only allowed on arrays with 0 dimensions") if self.dtype not in _boolean_dtypes: raise ValueError("bool is only allowed on boolean arrays") res = self._array.__bool__() return res def __dlpack__(self: Array, /, *, stream: None = None) -> PyCapsule: """ Performs the operation __dlpack__. """ return self._array.__dlpack__(stream=stream) def __dlpack_device__(self: Array, /) -> Tuple[IntEnum, int]: """ Performs the operation __dlpack_device__. """ # Note: device support is required for this return self._array.__dlpack_device__() def __eq__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __eq__. """ # Even though "all" dtypes are allowed, we still require them to be # promotable with each other. other = self._check_allowed_dtypes(other, "all", "__eq__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__eq__(other._array) return self.__class__._new(res) def __float__(self: Array, /) -> float: """ Performs the operation __float__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("float is only allowed on arrays with 0 dimensions") if self.dtype not in _floating_dtypes: raise ValueError("float is only allowed on floating-point arrays") res = self._array.__float__() return res def __floordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __floordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__floordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__floordiv__(other._array) return self.__class__._new(res) def __ge__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ge__. """ other = self._check_allowed_dtypes(other, "numeric", "__ge__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ge__(other._array) return self.__class__._new(res) def __getitem__( self: Array, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], /, ) -> Array: """ Performs the operation __getitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array res = self._array.__getitem__(key) return self._new(res) def __gt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __gt__. """ other = self._check_allowed_dtypes(other, "numeric", "__gt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__gt__(other._array) return self.__class__._new(res) def __int__(self: Array, /) -> int: """ Performs the operation __int__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("int is only allowed on arrays with 0 dimensions") if self.dtype not in _integer_dtypes: raise ValueError("int is only allowed on integer arrays") res = self._array.__int__() return res def __index__(self: Array, /) -> int: """ Performs the operation __index__. """ res = self._array.__index__() return res def __invert__(self: Array, /) -> Array: """ Performs the operation __invert__. """ if self.dtype not in _integer_or_boolean_dtypes: raise TypeError("Only integer or boolean dtypes are allowed in __invert__") res = self._array.__invert__() return self.__class__._new(res) def __le__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __le__. """ other = self._check_allowed_dtypes(other, "numeric", "__le__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__le__(other._array) return self.__class__._new(res) def __lshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __lshift__. """ other = self._check_allowed_dtypes(other, "integer", "__lshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lshift__(other._array) return self.__class__._new(res) def __lt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __lt__. """ other = self._check_allowed_dtypes(other, "numeric", "__lt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lt__(other._array) return self.__class__._new(res) def __matmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __matmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__matmul__") if other is NotImplemented: return other res = self._array.__matmul__(other._array) return self.__class__._new(res) def __mod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mod__. """ other = self._check_allowed_dtypes(other, "numeric", "__mod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mod__(other._array) return self.__class__._new(res) def __mul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mul__. """ other = self._check_allowed_dtypes(other, "numeric", "__mul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mul__(other._array) return self.__class__._new(res) def __ne__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __ne__. """ other = self._check_allowed_dtypes(other, "all", "__ne__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ne__(other._array) return self.__class__._new(res) def __neg__(self: Array, /) -> Array: """ Performs the operation __neg__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __neg__") res = self._array.__neg__() return self.__class__._new(res) def __or__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __or__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__or__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__or__(other._array) return self.__class__._new(res) def __pos__(self: Array, /) -> Array: """ Performs the operation __pos__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __pos__") res = self._array.__pos__() return self.__class__._new(res) def __pow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __pow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__pow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow type promotion rules for 0-d # arrays, so we use pow() here instead. return pow(self, other) def __rshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rshift__(other._array) return self.__class__._new(res) def __setitem__( self, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], value: Union[int, float, bool, Array], /, ) -> None: """ Performs the operation __setitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array self._array.__setitem__(key, asarray(value)._array) def __sub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __sub__. """ other = self._check_allowed_dtypes(other, "numeric", "__sub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__sub__(other._array) return self.__class__._new(res) # PEP 484 requires int to be a subtype of float, but __truediv__ should # not accept int. def __truediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __truediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__truediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__truediv__(other._array) return self.__class__._new(res) def __xor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __xor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__xor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__xor__(other._array) return self.__class__._new(res) def __iadd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __iadd__. """ other = self._check_allowed_dtypes(other, "numeric", "__iadd__") if other is NotImplemented: return other self._array.__iadd__(other._array) return self def __radd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __radd__. """ other = self._check_allowed_dtypes(other, "numeric", "__radd__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__radd__(other._array) return self.__class__._new(res) def __iand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __iand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__iand__") if other is NotImplemented: return other self._array.__iand__(other._array) return self def __rand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rand__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rand__(other._array) return self.__class__._new(res) def __ifloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ifloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__ifloordiv__") if other is NotImplemented: return other self._array.__ifloordiv__(other._array) return self def __rfloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rfloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__rfloordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rfloordiv__(other._array) return self.__class__._new(res) def __ilshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __ilshift__. """ other = self._check_allowed_dtypes(other, "integer", "__ilshift__") if other is NotImplemented: return other self._array.__ilshift__(other._array) return self def __rlshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rlshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rlshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rlshift__(other._array) return self.__class__._new(res) def __imatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __imatmul__. """ # Note: NumPy does not implement __imatmul__. # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__imatmul__") if other is NotImplemented: return other # __imatmul__ can only be allowed when it would not change the shape # of self. other_shape = other.shape if self.shape == () or other_shape == (): raise ValueError("@= requires at least one dimension") if len(other_shape) == 1 or other_shape[-1] != other_shape[-2]: raise ValueError("@= cannot change the shape of the input array") self._array[:] = self._array.__matmul__(other._array) return self def __rmatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __rmatmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__rmatmul__") if other is NotImplemented: return other res = self._array.__rmatmul__(other._array) return self.__class__._new(res) def __imod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imod__. """ other = self._check_allowed_dtypes(other, "numeric", "__imod__") if other is NotImplemented: return other self._array.__imod__(other._array) return self def __rmod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmod__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmod__(other._array) return self.__class__._new(res) def __imul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imul__. """ other = self._check_allowed_dtypes(other, "numeric", "__imul__") if other is NotImplemented: return other self._array.__imul__(other._array) return self def __rmul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmul__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmul__(other._array) return self.__class__._new(res) def __ior__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ior__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ior__") if other is NotImplemented: return other self._array.__ior__(other._array) return self def __ror__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ror__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ror__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ror__(other._array) return self.__class__._new(res) def __ipow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ipow__. """ other = self._check_allowed_dtypes(other, "numeric", "__ipow__") if other is NotImplemented: return other self._array.__ipow__(other._array) return self def __rpow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rpow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__rpow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow the spec type promotion rules # for 0-d arrays, so we use pow() here instead. return pow(other, self) def __irshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __irshift__. """ other = self._check_allowed_dtypes(other, "integer", "__irshift__") if other is NotImplemented: return other self._array.__irshift__(other._array) return self def __rrshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rrshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rrshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rrshift__(other._array) return self.__class__._new(res) def __isub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __isub__. """ other = self._check_allowed_dtypes(other, "numeric", "__isub__") if other is NotImplemented: return other self._array.__isub__(other._array) return self def __rsub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rsub__. """ other = self._check_allowed_dtypes(other, "numeric", "__rsub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rsub__(other._array) return self.__class__._new(res) def __itruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __itruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__itruediv__") if other is NotImplemented: return other self._array.__itruediv__(other._array) return self def __rtruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __rtruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__rtruediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rtruediv__(other._array) return self.__class__._new(res) def __ixor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ixor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ixor__") if other is NotImplemented: return other self._array.__ixor__(other._array) return self def __rxor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rxor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rxor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rxor__(other._array) return self.__class__._new(res) def to_device(self: Array, device: Device, /, stream: None = None) -> Array: if stream is not None: raise ValueError("The stream argument to to_device() is not supported") if device == 'cpu': return self raise ValueError(f"Unsupported device {device!r}") def dtype(self) -> Dtype: """ Array API compatible wrapper for :py:meth:`np.ndarray.dtype <numpy.ndarray.dtype>`. See its docstring for more information. """ return self._array.dtype def device(self) -> Device: return "cpu" # Note: mT is new in array API spec (see matrix_transpose) def mT(self) -> Array: from .linalg import matrix_transpose return matrix_transpose(self) def ndim(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.ndim <numpy.ndarray.ndim>`. See its docstring for more information. """ return self._array.ndim def shape(self) -> Tuple[int, ...]: """ Array API compatible wrapper for :py:meth:`np.ndarray.shape <numpy.ndarray.shape>`. See its docstring for more information. """ return self._array.shape def size(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.size <numpy.ndarray.size>`. See its docstring for more information. """ return self._array.size def T(self) -> Array: """ Array API compatible wrapper for :py:meth:`np.ndarray.T <numpy.ndarray.T>`. See its docstring for more information. """ # Note: T only works on 2-dimensional arrays. See the corresponding # note in the specification: # https://data-apis.org/array-api/latest/API_specification/array_object.html#t if self.ndim != 2: raise ValueError("x.T requires x to have 2 dimensions. Use x.mT to transpose stacks of matrices and permute_dims() to permute dimensions.") return self.__class__._new(self._array.T) The provided code snippet includes necessary dependencies for implementing the `asin` function. Write a Python function `def asin(x: Array, /) -> Array` to solve the following problem: Array API compatible wrapper for :py:func:`np.arcsin <numpy.arcsin>`. See its docstring for more information. Here is the function: def asin(x: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.arcsin <numpy.arcsin>`. See its docstring for more information. """ if x.dtype not in _floating_dtypes: raise TypeError("Only floating-point dtypes are allowed in asin") return Array._new(np.arcsin(x._array))
Array API compatible wrapper for :py:func:`np.arcsin <numpy.arcsin>`. See its docstring for more information.
170,024
from __future__ import annotations from ._dtypes import ( _boolean_dtypes, _floating_dtypes, _integer_dtypes, _integer_or_boolean_dtypes, _numeric_dtypes, _result_type, ) from ._array_object import Array import numpy as np _floating_dtypes = (float32, float64) class Array: """ n-d array object for the array API namespace. See the docstring of :py:obj:`np.ndarray <numpy.ndarray>` for more information. This is a wrapper around numpy.ndarray that restricts the usage to only those things that are required by the array API namespace. Note, attributes on this object that start with a single underscore are not part of the API specification and should only be used internally. This object should not be constructed directly. Rather, use one of the creation functions, such as asarray(). """ _array: np.ndarray # Use a custom constructor instead of __init__, as manually initializing # this class is not supported API. def _new(cls, x, /): """ This is a private method for initializing the array API Array object. Functions outside of the array_api submodule should not use this method. Use one of the creation functions instead, such as ``asarray``. """ obj = super().__new__(cls) # Note: The spec does not have array scalars, only 0-D arrays. if isinstance(x, np.generic): # Convert the array scalar to a 0-D array x = np.asarray(x) if x.dtype not in _all_dtypes: raise TypeError( f"The array_api namespace does not support the dtype '{x.dtype}'" ) obj._array = x return obj # Prevent Array() from working def __new__(cls, *args, **kwargs): raise TypeError( "The array_api Array object should not be instantiated directly. Use an array creation function, such as asarray(), instead." ) # These functions are not required by the spec, but are implemented for # the sake of usability. def __str__(self: Array, /) -> str: """ Performs the operation __str__. """ return self._array.__str__().replace("array", "Array") def __repr__(self: Array, /) -> str: """ Performs the operation __repr__. """ suffix = f", dtype={self.dtype.name})" if 0 in self.shape: prefix = "empty(" mid = str(self.shape) else: prefix = "Array(" mid = np.array2string(self._array, separator=', ', prefix=prefix, suffix=suffix) return prefix + mid + suffix # This function is not required by the spec, but we implement it here for # convenience so that np.asarray(np.array_api.Array) will work. def __array__(self, dtype: None | np.dtype[Any] = None) -> npt.NDArray[Any]: """ Warning: this method is NOT part of the array API spec. Implementers of other libraries need not include it, and users should not assume it will be present in other implementations. """ return np.asarray(self._array, dtype=dtype) # These are various helper functions to make the array behavior match the # spec in places where it either deviates from or is more strict than # NumPy behavior def _check_allowed_dtypes(self, other: bool | int | float | Array, dtype_category: str, op: str) -> Array: """ Helper function for operators to only allow specific input dtypes Use like other = self._check_allowed_dtypes(other, 'numeric', '__add__') if other is NotImplemented: return other """ if self.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") if isinstance(other, (int, float, bool)): other = self._promote_scalar(other) elif isinstance(other, Array): if other.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") else: return NotImplemented # This will raise TypeError for type combinations that are not allowed # to promote in the spec (even if the NumPy array operator would # promote them). res_dtype = _result_type(self.dtype, other.dtype) if op.startswith("__i"): # Note: NumPy will allow in-place operators in some cases where # the type promoted operator does not match the left-hand side # operand. For example, # >>> a = np.array(1, dtype=np.int8) # >>> a += np.array(1, dtype=np.int16) # The spec explicitly disallows this. if res_dtype != self.dtype: raise TypeError( f"Cannot perform {op} with dtypes {self.dtype} and {other.dtype}" ) return other # Helper function to match the type promotion rules in the spec def _promote_scalar(self, scalar): """ Returns a promoted version of a Python scalar appropriate for use with operations on self. This may raise an OverflowError in cases where the scalar is an integer that is too large to fit in a NumPy integer dtype, or TypeError when the scalar type is incompatible with the dtype of self. """ # Note: Only Python scalar types that match the array dtype are # allowed. if isinstance(scalar, bool): if self.dtype not in _boolean_dtypes: raise TypeError( "Python bool scalars can only be promoted with bool arrays" ) elif isinstance(scalar, int): if self.dtype in _boolean_dtypes: raise TypeError( "Python int scalars cannot be promoted with bool arrays" ) elif isinstance(scalar, float): if self.dtype not in _floating_dtypes: raise TypeError( "Python float scalars can only be promoted with floating-point arrays." ) else: raise TypeError("'scalar' must be a Python scalar") # Note: scalars are unconditionally cast to the same dtype as the # array. # Note: the spec only specifies integer-dtype/int promotion # behavior for integers within the bounds of the integer dtype. # Outside of those bounds we use the default NumPy behavior (either # cast or raise OverflowError). return Array._new(np.array(scalar, self.dtype)) def _normalize_two_args(x1, x2) -> Tuple[Array, Array]: """ Normalize inputs to two arg functions to fix type promotion rules NumPy deviates from the spec type promotion rules in cases where one argument is 0-dimensional and the other is not. For example: >>> import numpy as np >>> a = np.array([1.0], dtype=np.float32) >>> b = np.array(1.0, dtype=np.float64) >>> np.add(a, b) # The spec says this should be float64 array([2.], dtype=float32) To fix this, we add a dimension to the 0-dimension array before passing it through. This works because a dimension would be added anyway from broadcasting, so the resulting shape is the same, but this prevents NumPy from not promoting the dtype. """ # Another option would be to use signature=(x1.dtype, x2.dtype, None), # but that only works for ufuncs, so we would have to call the ufuncs # directly in the operator methods. One should also note that this # sort of trick wouldn't work for functions like searchsorted, which # don't do normal broadcasting, but there aren't any functions like # that in the array API namespace. if x1.ndim == 0 and x2.ndim != 0: # The _array[None] workaround was chosen because it is relatively # performant. broadcast_to(x1._array, x2.shape) is much slower. We # could also manually type promote x2, but that is more complicated # and about the same performance as this. x1 = Array._new(x1._array[None]) elif x2.ndim == 0 and x1.ndim != 0: x2 = Array._new(x2._array[None]) return (x1, x2) # Note: A large fraction of allowed indices are disallowed here (see the # docstring below) def _validate_index(self, key): """ Validate an index according to the array API. The array API specification only requires a subset of indices that are supported by NumPy. This function will reject any index that is allowed by NumPy but not required by the array API specification. We always raise ``IndexError`` on such indices (the spec does not require any specific behavior on them, but this makes the NumPy array API namespace a minimal implementation of the spec). See https://data-apis.org/array-api/latest/API_specification/indexing.html for the full list of required indexing behavior This function raises IndexError if the index ``key`` is invalid. It only raises ``IndexError`` on indices that are not already rejected by NumPy, as NumPy will already raise the appropriate error on such indices. ``shape`` may be None, in which case, only cases that are independent of the array shape are checked. The following cases are allowed by NumPy, but not specified by the array API specification: - Indices to not include an implicit ellipsis at the end. That is, every axis of an array must be explicitly indexed or an ellipsis included. This behaviour is sometimes referred to as flat indexing. - The start and stop of a slice may not be out of bounds. In particular, for a slice ``i:j:k`` on an axis of size ``n``, only the following are allowed: - ``i`` or ``j`` omitted (``None``). - ``-n <= i <= max(0, n - 1)``. - For ``k > 0`` or ``k`` omitted (``None``), ``-n <= j <= n``. - For ``k < 0``, ``-n - 1 <= j <= max(0, n - 1)``. - Boolean array indices are not allowed as part of a larger tuple index. - Integer array indices are not allowed (with the exception of 0-D arrays, which are treated the same as scalars). Additionally, it should be noted that indices that would return a scalar in NumPy will return a 0-D array. Array scalars are not allowed in the specification, only 0-D arrays. This is done in the ``Array._new`` constructor, not this function. """ _key = key if isinstance(key, tuple) else (key,) for i in _key: if isinstance(i, bool) or not ( isinstance(i, SupportsIndex) # i.e. ints or isinstance(i, slice) or i == Ellipsis or i is None or isinstance(i, Array) or isinstance(i, np.ndarray) ): raise IndexError( f"Single-axes index {i} has {type(i)=}, but only " "integers, slices (:), ellipsis (...), newaxis (None), " "zero-dimensional integer arrays and boolean arrays " "are specified in the Array API." ) nonexpanding_key = [] single_axes = [] n_ellipsis = 0 key_has_mask = False for i in _key: if i is not None: nonexpanding_key.append(i) if isinstance(i, Array) or isinstance(i, np.ndarray): if i.dtype in _boolean_dtypes: key_has_mask = True single_axes.append(i) else: # i must not be an array here, to avoid elementwise equals if i == Ellipsis: n_ellipsis += 1 else: single_axes.append(i) n_single_axes = len(single_axes) if n_ellipsis > 1: return # handled by ndarray elif n_ellipsis == 0: # Note boolean masks must be the sole index, which we check for # later on. if not key_has_mask and n_single_axes < self.ndim: raise IndexError( f"{self.ndim=}, but the multi-axes index only specifies " f"{n_single_axes} dimensions. If this was intentional, " "add a trailing ellipsis (...) which expands into as many " "slices (:) as necessary - this is what np.ndarray arrays " "implicitly do, but such flat indexing behaviour is not " "specified in the Array API." ) if n_ellipsis == 0: indexed_shape = self.shape else: ellipsis_start = None for pos, i in enumerate(nonexpanding_key): if not (isinstance(i, Array) or isinstance(i, np.ndarray)): if i == Ellipsis: ellipsis_start = pos break assert ellipsis_start is not None # sanity check ellipsis_end = self.ndim - (n_single_axes - ellipsis_start) indexed_shape = ( self.shape[:ellipsis_start] + self.shape[ellipsis_end:] ) for i, side in zip(single_axes, indexed_shape): if isinstance(i, slice): if side == 0: f_range = "0 (or None)" else: f_range = f"between -{side} and {side - 1} (or None)" if i.start is not None: try: start = operator.index(i.start) except TypeError: pass # handled by ndarray else: if not (-side <= start <= side): raise IndexError( f"Slice {i} contains {start=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds starts are not specified in " "the Array API)" ) if i.stop is not None: try: stop = operator.index(i.stop) except TypeError: pass # handled by ndarray else: if not (-side <= stop <= side): raise IndexError( f"Slice {i} contains {stop=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds stops are not specified in " "the Array API)" ) elif isinstance(i, Array): if i.dtype in _boolean_dtypes and len(_key) != 1: assert isinstance(key, tuple) # sanity check raise IndexError( f"Single-axes index {i} is a boolean array and " f"{len(key)=}, but masking is only specified in the " "Array API when the array is the sole index." ) elif i.dtype in _integer_dtypes and i.ndim != 0: raise IndexError( f"Single-axes index {i} is a non-zero-dimensional " "integer array, but advanced integer indexing is not " "specified in the Array API." ) elif isinstance(i, tuple): raise IndexError( f"Single-axes index {i} is a tuple, but nested tuple " "indices are not specified in the Array API." ) # Everything below this line is required by the spec. def __abs__(self: Array, /) -> Array: """ Performs the operation __abs__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __abs__") res = self._array.__abs__() return self.__class__._new(res) def __add__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __add__. """ other = self._check_allowed_dtypes(other, "numeric", "__add__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__add__(other._array) return self.__class__._new(res) def __and__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __and__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__and__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__and__(other._array) return self.__class__._new(res) def __array_namespace__( self: Array, /, *, api_version: Optional[str] = None ) -> types.ModuleType: if api_version is not None and not api_version.startswith("2021."): raise ValueError(f"Unrecognized array API version: {api_version!r}") return array_api def __bool__(self: Array, /) -> bool: """ Performs the operation __bool__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("bool is only allowed on arrays with 0 dimensions") if self.dtype not in _boolean_dtypes: raise ValueError("bool is only allowed on boolean arrays") res = self._array.__bool__() return res def __dlpack__(self: Array, /, *, stream: None = None) -> PyCapsule: """ Performs the operation __dlpack__. """ return self._array.__dlpack__(stream=stream) def __dlpack_device__(self: Array, /) -> Tuple[IntEnum, int]: """ Performs the operation __dlpack_device__. """ # Note: device support is required for this return self._array.__dlpack_device__() def __eq__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __eq__. """ # Even though "all" dtypes are allowed, we still require them to be # promotable with each other. other = self._check_allowed_dtypes(other, "all", "__eq__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__eq__(other._array) return self.__class__._new(res) def __float__(self: Array, /) -> float: """ Performs the operation __float__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("float is only allowed on arrays with 0 dimensions") if self.dtype not in _floating_dtypes: raise ValueError("float is only allowed on floating-point arrays") res = self._array.__float__() return res def __floordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __floordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__floordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__floordiv__(other._array) return self.__class__._new(res) def __ge__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ge__. """ other = self._check_allowed_dtypes(other, "numeric", "__ge__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ge__(other._array) return self.__class__._new(res) def __getitem__( self: Array, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], /, ) -> Array: """ Performs the operation __getitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array res = self._array.__getitem__(key) return self._new(res) def __gt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __gt__. """ other = self._check_allowed_dtypes(other, "numeric", "__gt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__gt__(other._array) return self.__class__._new(res) def __int__(self: Array, /) -> int: """ Performs the operation __int__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("int is only allowed on arrays with 0 dimensions") if self.dtype not in _integer_dtypes: raise ValueError("int is only allowed on integer arrays") res = self._array.__int__() return res def __index__(self: Array, /) -> int: """ Performs the operation __index__. """ res = self._array.__index__() return res def __invert__(self: Array, /) -> Array: """ Performs the operation __invert__. """ if self.dtype not in _integer_or_boolean_dtypes: raise TypeError("Only integer or boolean dtypes are allowed in __invert__") res = self._array.__invert__() return self.__class__._new(res) def __le__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __le__. """ other = self._check_allowed_dtypes(other, "numeric", "__le__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__le__(other._array) return self.__class__._new(res) def __lshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __lshift__. """ other = self._check_allowed_dtypes(other, "integer", "__lshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lshift__(other._array) return self.__class__._new(res) def __lt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __lt__. """ other = self._check_allowed_dtypes(other, "numeric", "__lt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lt__(other._array) return self.__class__._new(res) def __matmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __matmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__matmul__") if other is NotImplemented: return other res = self._array.__matmul__(other._array) return self.__class__._new(res) def __mod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mod__. """ other = self._check_allowed_dtypes(other, "numeric", "__mod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mod__(other._array) return self.__class__._new(res) def __mul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mul__. """ other = self._check_allowed_dtypes(other, "numeric", "__mul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mul__(other._array) return self.__class__._new(res) def __ne__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __ne__. """ other = self._check_allowed_dtypes(other, "all", "__ne__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ne__(other._array) return self.__class__._new(res) def __neg__(self: Array, /) -> Array: """ Performs the operation __neg__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __neg__") res = self._array.__neg__() return self.__class__._new(res) def __or__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __or__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__or__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__or__(other._array) return self.__class__._new(res) def __pos__(self: Array, /) -> Array: """ Performs the operation __pos__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __pos__") res = self._array.__pos__() return self.__class__._new(res) def __pow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __pow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__pow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow type promotion rules for 0-d # arrays, so we use pow() here instead. return pow(self, other) def __rshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rshift__(other._array) return self.__class__._new(res) def __setitem__( self, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], value: Union[int, float, bool, Array], /, ) -> None: """ Performs the operation __setitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array self._array.__setitem__(key, asarray(value)._array) def __sub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __sub__. """ other = self._check_allowed_dtypes(other, "numeric", "__sub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__sub__(other._array) return self.__class__._new(res) # PEP 484 requires int to be a subtype of float, but __truediv__ should # not accept int. def __truediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __truediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__truediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__truediv__(other._array) return self.__class__._new(res) def __xor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __xor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__xor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__xor__(other._array) return self.__class__._new(res) def __iadd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __iadd__. """ other = self._check_allowed_dtypes(other, "numeric", "__iadd__") if other is NotImplemented: return other self._array.__iadd__(other._array) return self def __radd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __radd__. """ other = self._check_allowed_dtypes(other, "numeric", "__radd__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__radd__(other._array) return self.__class__._new(res) def __iand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __iand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__iand__") if other is NotImplemented: return other self._array.__iand__(other._array) return self def __rand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rand__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rand__(other._array) return self.__class__._new(res) def __ifloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ifloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__ifloordiv__") if other is NotImplemented: return other self._array.__ifloordiv__(other._array) return self def __rfloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rfloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__rfloordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rfloordiv__(other._array) return self.__class__._new(res) def __ilshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __ilshift__. """ other = self._check_allowed_dtypes(other, "integer", "__ilshift__") if other is NotImplemented: return other self._array.__ilshift__(other._array) return self def __rlshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rlshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rlshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rlshift__(other._array) return self.__class__._new(res) def __imatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __imatmul__. """ # Note: NumPy does not implement __imatmul__. # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__imatmul__") if other is NotImplemented: return other # __imatmul__ can only be allowed when it would not change the shape # of self. other_shape = other.shape if self.shape == () or other_shape == (): raise ValueError("@= requires at least one dimension") if len(other_shape) == 1 or other_shape[-1] != other_shape[-2]: raise ValueError("@= cannot change the shape of the input array") self._array[:] = self._array.__matmul__(other._array) return self def __rmatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __rmatmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__rmatmul__") if other is NotImplemented: return other res = self._array.__rmatmul__(other._array) return self.__class__._new(res) def __imod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imod__. """ other = self._check_allowed_dtypes(other, "numeric", "__imod__") if other is NotImplemented: return other self._array.__imod__(other._array) return self def __rmod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmod__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmod__(other._array) return self.__class__._new(res) def __imul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imul__. """ other = self._check_allowed_dtypes(other, "numeric", "__imul__") if other is NotImplemented: return other self._array.__imul__(other._array) return self def __rmul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmul__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmul__(other._array) return self.__class__._new(res) def __ior__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ior__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ior__") if other is NotImplemented: return other self._array.__ior__(other._array) return self def __ror__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ror__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ror__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ror__(other._array) return self.__class__._new(res) def __ipow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ipow__. """ other = self._check_allowed_dtypes(other, "numeric", "__ipow__") if other is NotImplemented: return other self._array.__ipow__(other._array) return self def __rpow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rpow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__rpow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow the spec type promotion rules # for 0-d arrays, so we use pow() here instead. return pow(other, self) def __irshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __irshift__. """ other = self._check_allowed_dtypes(other, "integer", "__irshift__") if other is NotImplemented: return other self._array.__irshift__(other._array) return self def __rrshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rrshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rrshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rrshift__(other._array) return self.__class__._new(res) def __isub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __isub__. """ other = self._check_allowed_dtypes(other, "numeric", "__isub__") if other is NotImplemented: return other self._array.__isub__(other._array) return self def __rsub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rsub__. """ other = self._check_allowed_dtypes(other, "numeric", "__rsub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rsub__(other._array) return self.__class__._new(res) def __itruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __itruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__itruediv__") if other is NotImplemented: return other self._array.__itruediv__(other._array) return self def __rtruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __rtruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__rtruediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rtruediv__(other._array) return self.__class__._new(res) def __ixor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ixor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ixor__") if other is NotImplemented: return other self._array.__ixor__(other._array) return self def __rxor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rxor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rxor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rxor__(other._array) return self.__class__._new(res) def to_device(self: Array, device: Device, /, stream: None = None) -> Array: if stream is not None: raise ValueError("The stream argument to to_device() is not supported") if device == 'cpu': return self raise ValueError(f"Unsupported device {device!r}") def dtype(self) -> Dtype: """ Array API compatible wrapper for :py:meth:`np.ndarray.dtype <numpy.ndarray.dtype>`. See its docstring for more information. """ return self._array.dtype def device(self) -> Device: return "cpu" # Note: mT is new in array API spec (see matrix_transpose) def mT(self) -> Array: from .linalg import matrix_transpose return matrix_transpose(self) def ndim(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.ndim <numpy.ndarray.ndim>`. See its docstring for more information. """ return self._array.ndim def shape(self) -> Tuple[int, ...]: """ Array API compatible wrapper for :py:meth:`np.ndarray.shape <numpy.ndarray.shape>`. See its docstring for more information. """ return self._array.shape def size(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.size <numpy.ndarray.size>`. See its docstring for more information. """ return self._array.size def T(self) -> Array: """ Array API compatible wrapper for :py:meth:`np.ndarray.T <numpy.ndarray.T>`. See its docstring for more information. """ # Note: T only works on 2-dimensional arrays. See the corresponding # note in the specification: # https://data-apis.org/array-api/latest/API_specification/array_object.html#t if self.ndim != 2: raise ValueError("x.T requires x to have 2 dimensions. Use x.mT to transpose stacks of matrices and permute_dims() to permute dimensions.") return self.__class__._new(self._array.T) The provided code snippet includes necessary dependencies for implementing the `asinh` function. Write a Python function `def asinh(x: Array, /) -> Array` to solve the following problem: Array API compatible wrapper for :py:func:`np.arcsinh <numpy.arcsinh>`. See its docstring for more information. Here is the function: def asinh(x: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.arcsinh <numpy.arcsinh>`. See its docstring for more information. """ if x.dtype not in _floating_dtypes: raise TypeError("Only floating-point dtypes are allowed in asinh") return Array._new(np.arcsinh(x._array))
Array API compatible wrapper for :py:func:`np.arcsinh <numpy.arcsinh>`. See its docstring for more information.
170,025
from __future__ import annotations from ._dtypes import ( _boolean_dtypes, _floating_dtypes, _integer_dtypes, _integer_or_boolean_dtypes, _numeric_dtypes, _result_type, ) from ._array_object import Array import numpy as np _floating_dtypes = (float32, float64) class Array: """ n-d array object for the array API namespace. See the docstring of :py:obj:`np.ndarray <numpy.ndarray>` for more information. This is a wrapper around numpy.ndarray that restricts the usage to only those things that are required by the array API namespace. Note, attributes on this object that start with a single underscore are not part of the API specification and should only be used internally. This object should not be constructed directly. Rather, use one of the creation functions, such as asarray(). """ _array: np.ndarray # Use a custom constructor instead of __init__, as manually initializing # this class is not supported API. def _new(cls, x, /): """ This is a private method for initializing the array API Array object. Functions outside of the array_api submodule should not use this method. Use one of the creation functions instead, such as ``asarray``. """ obj = super().__new__(cls) # Note: The spec does not have array scalars, only 0-D arrays. if isinstance(x, np.generic): # Convert the array scalar to a 0-D array x = np.asarray(x) if x.dtype not in _all_dtypes: raise TypeError( f"The array_api namespace does not support the dtype '{x.dtype}'" ) obj._array = x return obj # Prevent Array() from working def __new__(cls, *args, **kwargs): raise TypeError( "The array_api Array object should not be instantiated directly. Use an array creation function, such as asarray(), instead." ) # These functions are not required by the spec, but are implemented for # the sake of usability. def __str__(self: Array, /) -> str: """ Performs the operation __str__. """ return self._array.__str__().replace("array", "Array") def __repr__(self: Array, /) -> str: """ Performs the operation __repr__. """ suffix = f", dtype={self.dtype.name})" if 0 in self.shape: prefix = "empty(" mid = str(self.shape) else: prefix = "Array(" mid = np.array2string(self._array, separator=', ', prefix=prefix, suffix=suffix) return prefix + mid + suffix # This function is not required by the spec, but we implement it here for # convenience so that np.asarray(np.array_api.Array) will work. def __array__(self, dtype: None | np.dtype[Any] = None) -> npt.NDArray[Any]: """ Warning: this method is NOT part of the array API spec. Implementers of other libraries need not include it, and users should not assume it will be present in other implementations. """ return np.asarray(self._array, dtype=dtype) # These are various helper functions to make the array behavior match the # spec in places where it either deviates from or is more strict than # NumPy behavior def _check_allowed_dtypes(self, other: bool | int | float | Array, dtype_category: str, op: str) -> Array: """ Helper function for operators to only allow specific input dtypes Use like other = self._check_allowed_dtypes(other, 'numeric', '__add__') if other is NotImplemented: return other """ if self.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") if isinstance(other, (int, float, bool)): other = self._promote_scalar(other) elif isinstance(other, Array): if other.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") else: return NotImplemented # This will raise TypeError for type combinations that are not allowed # to promote in the spec (even if the NumPy array operator would # promote them). res_dtype = _result_type(self.dtype, other.dtype) if op.startswith("__i"): # Note: NumPy will allow in-place operators in some cases where # the type promoted operator does not match the left-hand side # operand. For example, # >>> a = np.array(1, dtype=np.int8) # >>> a += np.array(1, dtype=np.int16) # The spec explicitly disallows this. if res_dtype != self.dtype: raise TypeError( f"Cannot perform {op} with dtypes {self.dtype} and {other.dtype}" ) return other # Helper function to match the type promotion rules in the spec def _promote_scalar(self, scalar): """ Returns a promoted version of a Python scalar appropriate for use with operations on self. This may raise an OverflowError in cases where the scalar is an integer that is too large to fit in a NumPy integer dtype, or TypeError when the scalar type is incompatible with the dtype of self. """ # Note: Only Python scalar types that match the array dtype are # allowed. if isinstance(scalar, bool): if self.dtype not in _boolean_dtypes: raise TypeError( "Python bool scalars can only be promoted with bool arrays" ) elif isinstance(scalar, int): if self.dtype in _boolean_dtypes: raise TypeError( "Python int scalars cannot be promoted with bool arrays" ) elif isinstance(scalar, float): if self.dtype not in _floating_dtypes: raise TypeError( "Python float scalars can only be promoted with floating-point arrays." ) else: raise TypeError("'scalar' must be a Python scalar") # Note: scalars are unconditionally cast to the same dtype as the # array. # Note: the spec only specifies integer-dtype/int promotion # behavior for integers within the bounds of the integer dtype. # Outside of those bounds we use the default NumPy behavior (either # cast or raise OverflowError). return Array._new(np.array(scalar, self.dtype)) def _normalize_two_args(x1, x2) -> Tuple[Array, Array]: """ Normalize inputs to two arg functions to fix type promotion rules NumPy deviates from the spec type promotion rules in cases where one argument is 0-dimensional and the other is not. For example: >>> import numpy as np >>> a = np.array([1.0], dtype=np.float32) >>> b = np.array(1.0, dtype=np.float64) >>> np.add(a, b) # The spec says this should be float64 array([2.], dtype=float32) To fix this, we add a dimension to the 0-dimension array before passing it through. This works because a dimension would be added anyway from broadcasting, so the resulting shape is the same, but this prevents NumPy from not promoting the dtype. """ # Another option would be to use signature=(x1.dtype, x2.dtype, None), # but that only works for ufuncs, so we would have to call the ufuncs # directly in the operator methods. One should also note that this # sort of trick wouldn't work for functions like searchsorted, which # don't do normal broadcasting, but there aren't any functions like # that in the array API namespace. if x1.ndim == 0 and x2.ndim != 0: # The _array[None] workaround was chosen because it is relatively # performant. broadcast_to(x1._array, x2.shape) is much slower. We # could also manually type promote x2, but that is more complicated # and about the same performance as this. x1 = Array._new(x1._array[None]) elif x2.ndim == 0 and x1.ndim != 0: x2 = Array._new(x2._array[None]) return (x1, x2) # Note: A large fraction of allowed indices are disallowed here (see the # docstring below) def _validate_index(self, key): """ Validate an index according to the array API. The array API specification only requires a subset of indices that are supported by NumPy. This function will reject any index that is allowed by NumPy but not required by the array API specification. We always raise ``IndexError`` on such indices (the spec does not require any specific behavior on them, but this makes the NumPy array API namespace a minimal implementation of the spec). See https://data-apis.org/array-api/latest/API_specification/indexing.html for the full list of required indexing behavior This function raises IndexError if the index ``key`` is invalid. It only raises ``IndexError`` on indices that are not already rejected by NumPy, as NumPy will already raise the appropriate error on such indices. ``shape`` may be None, in which case, only cases that are independent of the array shape are checked. The following cases are allowed by NumPy, but not specified by the array API specification: - Indices to not include an implicit ellipsis at the end. That is, every axis of an array must be explicitly indexed or an ellipsis included. This behaviour is sometimes referred to as flat indexing. - The start and stop of a slice may not be out of bounds. In particular, for a slice ``i:j:k`` on an axis of size ``n``, only the following are allowed: - ``i`` or ``j`` omitted (``None``). - ``-n <= i <= max(0, n - 1)``. - For ``k > 0`` or ``k`` omitted (``None``), ``-n <= j <= n``. - For ``k < 0``, ``-n - 1 <= j <= max(0, n - 1)``. - Boolean array indices are not allowed as part of a larger tuple index. - Integer array indices are not allowed (with the exception of 0-D arrays, which are treated the same as scalars). Additionally, it should be noted that indices that would return a scalar in NumPy will return a 0-D array. Array scalars are not allowed in the specification, only 0-D arrays. This is done in the ``Array._new`` constructor, not this function. """ _key = key if isinstance(key, tuple) else (key,) for i in _key: if isinstance(i, bool) or not ( isinstance(i, SupportsIndex) # i.e. ints or isinstance(i, slice) or i == Ellipsis or i is None or isinstance(i, Array) or isinstance(i, np.ndarray) ): raise IndexError( f"Single-axes index {i} has {type(i)=}, but only " "integers, slices (:), ellipsis (...), newaxis (None), " "zero-dimensional integer arrays and boolean arrays " "are specified in the Array API." ) nonexpanding_key = [] single_axes = [] n_ellipsis = 0 key_has_mask = False for i in _key: if i is not None: nonexpanding_key.append(i) if isinstance(i, Array) or isinstance(i, np.ndarray): if i.dtype in _boolean_dtypes: key_has_mask = True single_axes.append(i) else: # i must not be an array here, to avoid elementwise equals if i == Ellipsis: n_ellipsis += 1 else: single_axes.append(i) n_single_axes = len(single_axes) if n_ellipsis > 1: return # handled by ndarray elif n_ellipsis == 0: # Note boolean masks must be the sole index, which we check for # later on. if not key_has_mask and n_single_axes < self.ndim: raise IndexError( f"{self.ndim=}, but the multi-axes index only specifies " f"{n_single_axes} dimensions. If this was intentional, " "add a trailing ellipsis (...) which expands into as many " "slices (:) as necessary - this is what np.ndarray arrays " "implicitly do, but such flat indexing behaviour is not " "specified in the Array API." ) if n_ellipsis == 0: indexed_shape = self.shape else: ellipsis_start = None for pos, i in enumerate(nonexpanding_key): if not (isinstance(i, Array) or isinstance(i, np.ndarray)): if i == Ellipsis: ellipsis_start = pos break assert ellipsis_start is not None # sanity check ellipsis_end = self.ndim - (n_single_axes - ellipsis_start) indexed_shape = ( self.shape[:ellipsis_start] + self.shape[ellipsis_end:] ) for i, side in zip(single_axes, indexed_shape): if isinstance(i, slice): if side == 0: f_range = "0 (or None)" else: f_range = f"between -{side} and {side - 1} (or None)" if i.start is not None: try: start = operator.index(i.start) except TypeError: pass # handled by ndarray else: if not (-side <= start <= side): raise IndexError( f"Slice {i} contains {start=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds starts are not specified in " "the Array API)" ) if i.stop is not None: try: stop = operator.index(i.stop) except TypeError: pass # handled by ndarray else: if not (-side <= stop <= side): raise IndexError( f"Slice {i} contains {stop=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds stops are not specified in " "the Array API)" ) elif isinstance(i, Array): if i.dtype in _boolean_dtypes and len(_key) != 1: assert isinstance(key, tuple) # sanity check raise IndexError( f"Single-axes index {i} is a boolean array and " f"{len(key)=}, but masking is only specified in the " "Array API when the array is the sole index." ) elif i.dtype in _integer_dtypes and i.ndim != 0: raise IndexError( f"Single-axes index {i} is a non-zero-dimensional " "integer array, but advanced integer indexing is not " "specified in the Array API." ) elif isinstance(i, tuple): raise IndexError( f"Single-axes index {i} is a tuple, but nested tuple " "indices are not specified in the Array API." ) # Everything below this line is required by the spec. def __abs__(self: Array, /) -> Array: """ Performs the operation __abs__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __abs__") res = self._array.__abs__() return self.__class__._new(res) def __add__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __add__. """ other = self._check_allowed_dtypes(other, "numeric", "__add__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__add__(other._array) return self.__class__._new(res) def __and__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __and__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__and__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__and__(other._array) return self.__class__._new(res) def __array_namespace__( self: Array, /, *, api_version: Optional[str] = None ) -> types.ModuleType: if api_version is not None and not api_version.startswith("2021."): raise ValueError(f"Unrecognized array API version: {api_version!r}") return array_api def __bool__(self: Array, /) -> bool: """ Performs the operation __bool__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("bool is only allowed on arrays with 0 dimensions") if self.dtype not in _boolean_dtypes: raise ValueError("bool is only allowed on boolean arrays") res = self._array.__bool__() return res def __dlpack__(self: Array, /, *, stream: None = None) -> PyCapsule: """ Performs the operation __dlpack__. """ return self._array.__dlpack__(stream=stream) def __dlpack_device__(self: Array, /) -> Tuple[IntEnum, int]: """ Performs the operation __dlpack_device__. """ # Note: device support is required for this return self._array.__dlpack_device__() def __eq__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __eq__. """ # Even though "all" dtypes are allowed, we still require them to be # promotable with each other. other = self._check_allowed_dtypes(other, "all", "__eq__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__eq__(other._array) return self.__class__._new(res) def __float__(self: Array, /) -> float: """ Performs the operation __float__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("float is only allowed on arrays with 0 dimensions") if self.dtype not in _floating_dtypes: raise ValueError("float is only allowed on floating-point arrays") res = self._array.__float__() return res def __floordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __floordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__floordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__floordiv__(other._array) return self.__class__._new(res) def __ge__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ge__. """ other = self._check_allowed_dtypes(other, "numeric", "__ge__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ge__(other._array) return self.__class__._new(res) def __getitem__( self: Array, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], /, ) -> Array: """ Performs the operation __getitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array res = self._array.__getitem__(key) return self._new(res) def __gt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __gt__. """ other = self._check_allowed_dtypes(other, "numeric", "__gt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__gt__(other._array) return self.__class__._new(res) def __int__(self: Array, /) -> int: """ Performs the operation __int__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("int is only allowed on arrays with 0 dimensions") if self.dtype not in _integer_dtypes: raise ValueError("int is only allowed on integer arrays") res = self._array.__int__() return res def __index__(self: Array, /) -> int: """ Performs the operation __index__. """ res = self._array.__index__() return res def __invert__(self: Array, /) -> Array: """ Performs the operation __invert__. """ if self.dtype not in _integer_or_boolean_dtypes: raise TypeError("Only integer or boolean dtypes are allowed in __invert__") res = self._array.__invert__() return self.__class__._new(res) def __le__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __le__. """ other = self._check_allowed_dtypes(other, "numeric", "__le__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__le__(other._array) return self.__class__._new(res) def __lshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __lshift__. """ other = self._check_allowed_dtypes(other, "integer", "__lshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lshift__(other._array) return self.__class__._new(res) def __lt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __lt__. """ other = self._check_allowed_dtypes(other, "numeric", "__lt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lt__(other._array) return self.__class__._new(res) def __matmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __matmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__matmul__") if other is NotImplemented: return other res = self._array.__matmul__(other._array) return self.__class__._new(res) def __mod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mod__. """ other = self._check_allowed_dtypes(other, "numeric", "__mod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mod__(other._array) return self.__class__._new(res) def __mul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mul__. """ other = self._check_allowed_dtypes(other, "numeric", "__mul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mul__(other._array) return self.__class__._new(res) def __ne__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __ne__. """ other = self._check_allowed_dtypes(other, "all", "__ne__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ne__(other._array) return self.__class__._new(res) def __neg__(self: Array, /) -> Array: """ Performs the operation __neg__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __neg__") res = self._array.__neg__() return self.__class__._new(res) def __or__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __or__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__or__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__or__(other._array) return self.__class__._new(res) def __pos__(self: Array, /) -> Array: """ Performs the operation __pos__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __pos__") res = self._array.__pos__() return self.__class__._new(res) def __pow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __pow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__pow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow type promotion rules for 0-d # arrays, so we use pow() here instead. return pow(self, other) def __rshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rshift__(other._array) return self.__class__._new(res) def __setitem__( self, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], value: Union[int, float, bool, Array], /, ) -> None: """ Performs the operation __setitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array self._array.__setitem__(key, asarray(value)._array) def __sub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __sub__. """ other = self._check_allowed_dtypes(other, "numeric", "__sub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__sub__(other._array) return self.__class__._new(res) # PEP 484 requires int to be a subtype of float, but __truediv__ should # not accept int. def __truediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __truediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__truediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__truediv__(other._array) return self.__class__._new(res) def __xor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __xor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__xor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__xor__(other._array) return self.__class__._new(res) def __iadd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __iadd__. """ other = self._check_allowed_dtypes(other, "numeric", "__iadd__") if other is NotImplemented: return other self._array.__iadd__(other._array) return self def __radd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __radd__. """ other = self._check_allowed_dtypes(other, "numeric", "__radd__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__radd__(other._array) return self.__class__._new(res) def __iand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __iand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__iand__") if other is NotImplemented: return other self._array.__iand__(other._array) return self def __rand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rand__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rand__(other._array) return self.__class__._new(res) def __ifloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ifloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__ifloordiv__") if other is NotImplemented: return other self._array.__ifloordiv__(other._array) return self def __rfloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rfloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__rfloordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rfloordiv__(other._array) return self.__class__._new(res) def __ilshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __ilshift__. """ other = self._check_allowed_dtypes(other, "integer", "__ilshift__") if other is NotImplemented: return other self._array.__ilshift__(other._array) return self def __rlshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rlshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rlshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rlshift__(other._array) return self.__class__._new(res) def __imatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __imatmul__. """ # Note: NumPy does not implement __imatmul__. # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__imatmul__") if other is NotImplemented: return other # __imatmul__ can only be allowed when it would not change the shape # of self. other_shape = other.shape if self.shape == () or other_shape == (): raise ValueError("@= requires at least one dimension") if len(other_shape) == 1 or other_shape[-1] != other_shape[-2]: raise ValueError("@= cannot change the shape of the input array") self._array[:] = self._array.__matmul__(other._array) return self def __rmatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __rmatmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__rmatmul__") if other is NotImplemented: return other res = self._array.__rmatmul__(other._array) return self.__class__._new(res) def __imod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imod__. """ other = self._check_allowed_dtypes(other, "numeric", "__imod__") if other is NotImplemented: return other self._array.__imod__(other._array) return self def __rmod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmod__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmod__(other._array) return self.__class__._new(res) def __imul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imul__. """ other = self._check_allowed_dtypes(other, "numeric", "__imul__") if other is NotImplemented: return other self._array.__imul__(other._array) return self def __rmul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmul__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmul__(other._array) return self.__class__._new(res) def __ior__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ior__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ior__") if other is NotImplemented: return other self._array.__ior__(other._array) return self def __ror__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ror__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ror__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ror__(other._array) return self.__class__._new(res) def __ipow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ipow__. """ other = self._check_allowed_dtypes(other, "numeric", "__ipow__") if other is NotImplemented: return other self._array.__ipow__(other._array) return self def __rpow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rpow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__rpow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow the spec type promotion rules # for 0-d arrays, so we use pow() here instead. return pow(other, self) def __irshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __irshift__. """ other = self._check_allowed_dtypes(other, "integer", "__irshift__") if other is NotImplemented: return other self._array.__irshift__(other._array) return self def __rrshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rrshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rrshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rrshift__(other._array) return self.__class__._new(res) def __isub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __isub__. """ other = self._check_allowed_dtypes(other, "numeric", "__isub__") if other is NotImplemented: return other self._array.__isub__(other._array) return self def __rsub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rsub__. """ other = self._check_allowed_dtypes(other, "numeric", "__rsub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rsub__(other._array) return self.__class__._new(res) def __itruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __itruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__itruediv__") if other is NotImplemented: return other self._array.__itruediv__(other._array) return self def __rtruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __rtruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__rtruediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rtruediv__(other._array) return self.__class__._new(res) def __ixor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ixor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ixor__") if other is NotImplemented: return other self._array.__ixor__(other._array) return self def __rxor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rxor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rxor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rxor__(other._array) return self.__class__._new(res) def to_device(self: Array, device: Device, /, stream: None = None) -> Array: if stream is not None: raise ValueError("The stream argument to to_device() is not supported") if device == 'cpu': return self raise ValueError(f"Unsupported device {device!r}") def dtype(self) -> Dtype: """ Array API compatible wrapper for :py:meth:`np.ndarray.dtype <numpy.ndarray.dtype>`. See its docstring for more information. """ return self._array.dtype def device(self) -> Device: return "cpu" # Note: mT is new in array API spec (see matrix_transpose) def mT(self) -> Array: from .linalg import matrix_transpose return matrix_transpose(self) def ndim(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.ndim <numpy.ndarray.ndim>`. See its docstring for more information. """ return self._array.ndim def shape(self) -> Tuple[int, ...]: """ Array API compatible wrapper for :py:meth:`np.ndarray.shape <numpy.ndarray.shape>`. See its docstring for more information. """ return self._array.shape def size(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.size <numpy.ndarray.size>`. See its docstring for more information. """ return self._array.size def T(self) -> Array: """ Array API compatible wrapper for :py:meth:`np.ndarray.T <numpy.ndarray.T>`. See its docstring for more information. """ # Note: T only works on 2-dimensional arrays. See the corresponding # note in the specification: # https://data-apis.org/array-api/latest/API_specification/array_object.html#t if self.ndim != 2: raise ValueError("x.T requires x to have 2 dimensions. Use x.mT to transpose stacks of matrices and permute_dims() to permute dimensions.") return self.__class__._new(self._array.T) The provided code snippet includes necessary dependencies for implementing the `atan` function. Write a Python function `def atan(x: Array, /) -> Array` to solve the following problem: Array API compatible wrapper for :py:func:`np.arctan <numpy.arctan>`. See its docstring for more information. Here is the function: def atan(x: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.arctan <numpy.arctan>`. See its docstring for more information. """ if x.dtype not in _floating_dtypes: raise TypeError("Only floating-point dtypes are allowed in atan") return Array._new(np.arctan(x._array))
Array API compatible wrapper for :py:func:`np.arctan <numpy.arctan>`. See its docstring for more information.
170,026
from __future__ import annotations from ._dtypes import ( _boolean_dtypes, _floating_dtypes, _integer_dtypes, _integer_or_boolean_dtypes, _numeric_dtypes, _result_type, ) from ._array_object import Array import numpy as np _floating_dtypes = (float32, float64) def _result_type(type1, type2): if (type1, type2) in _promotion_table: return _promotion_table[type1, type2] raise TypeError(f"{type1} and {type2} cannot be type promoted together") class Array: """ n-d array object for the array API namespace. See the docstring of :py:obj:`np.ndarray <numpy.ndarray>` for more information. This is a wrapper around numpy.ndarray that restricts the usage to only those things that are required by the array API namespace. Note, attributes on this object that start with a single underscore are not part of the API specification and should only be used internally. This object should not be constructed directly. Rather, use one of the creation functions, such as asarray(). """ _array: np.ndarray # Use a custom constructor instead of __init__, as manually initializing # this class is not supported API. def _new(cls, x, /): """ This is a private method for initializing the array API Array object. Functions outside of the array_api submodule should not use this method. Use one of the creation functions instead, such as ``asarray``. """ obj = super().__new__(cls) # Note: The spec does not have array scalars, only 0-D arrays. if isinstance(x, np.generic): # Convert the array scalar to a 0-D array x = np.asarray(x) if x.dtype not in _all_dtypes: raise TypeError( f"The array_api namespace does not support the dtype '{x.dtype}'" ) obj._array = x return obj # Prevent Array() from working def __new__(cls, *args, **kwargs): raise TypeError( "The array_api Array object should not be instantiated directly. Use an array creation function, such as asarray(), instead." ) # These functions are not required by the spec, but are implemented for # the sake of usability. def __str__(self: Array, /) -> str: """ Performs the operation __str__. """ return self._array.__str__().replace("array", "Array") def __repr__(self: Array, /) -> str: """ Performs the operation __repr__. """ suffix = f", dtype={self.dtype.name})" if 0 in self.shape: prefix = "empty(" mid = str(self.shape) else: prefix = "Array(" mid = np.array2string(self._array, separator=', ', prefix=prefix, suffix=suffix) return prefix + mid + suffix # This function is not required by the spec, but we implement it here for # convenience so that np.asarray(np.array_api.Array) will work. def __array__(self, dtype: None | np.dtype[Any] = None) -> npt.NDArray[Any]: """ Warning: this method is NOT part of the array API spec. Implementers of other libraries need not include it, and users should not assume it will be present in other implementations. """ return np.asarray(self._array, dtype=dtype) # These are various helper functions to make the array behavior match the # spec in places where it either deviates from or is more strict than # NumPy behavior def _check_allowed_dtypes(self, other: bool | int | float | Array, dtype_category: str, op: str) -> Array: """ Helper function for operators to only allow specific input dtypes Use like other = self._check_allowed_dtypes(other, 'numeric', '__add__') if other is NotImplemented: return other """ if self.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") if isinstance(other, (int, float, bool)): other = self._promote_scalar(other) elif isinstance(other, Array): if other.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") else: return NotImplemented # This will raise TypeError for type combinations that are not allowed # to promote in the spec (even if the NumPy array operator would # promote them). res_dtype = _result_type(self.dtype, other.dtype) if op.startswith("__i"): # Note: NumPy will allow in-place operators in some cases where # the type promoted operator does not match the left-hand side # operand. For example, # >>> a = np.array(1, dtype=np.int8) # >>> a += np.array(1, dtype=np.int16) # The spec explicitly disallows this. if res_dtype != self.dtype: raise TypeError( f"Cannot perform {op} with dtypes {self.dtype} and {other.dtype}" ) return other # Helper function to match the type promotion rules in the spec def _promote_scalar(self, scalar): """ Returns a promoted version of a Python scalar appropriate for use with operations on self. This may raise an OverflowError in cases where the scalar is an integer that is too large to fit in a NumPy integer dtype, or TypeError when the scalar type is incompatible with the dtype of self. """ # Note: Only Python scalar types that match the array dtype are # allowed. if isinstance(scalar, bool): if self.dtype not in _boolean_dtypes: raise TypeError( "Python bool scalars can only be promoted with bool arrays" ) elif isinstance(scalar, int): if self.dtype in _boolean_dtypes: raise TypeError( "Python int scalars cannot be promoted with bool arrays" ) elif isinstance(scalar, float): if self.dtype not in _floating_dtypes: raise TypeError( "Python float scalars can only be promoted with floating-point arrays." ) else: raise TypeError("'scalar' must be a Python scalar") # Note: scalars are unconditionally cast to the same dtype as the # array. # Note: the spec only specifies integer-dtype/int promotion # behavior for integers within the bounds of the integer dtype. # Outside of those bounds we use the default NumPy behavior (either # cast or raise OverflowError). return Array._new(np.array(scalar, self.dtype)) def _normalize_two_args(x1, x2) -> Tuple[Array, Array]: """ Normalize inputs to two arg functions to fix type promotion rules NumPy deviates from the spec type promotion rules in cases where one argument is 0-dimensional and the other is not. For example: >>> import numpy as np >>> a = np.array([1.0], dtype=np.float32) >>> b = np.array(1.0, dtype=np.float64) >>> np.add(a, b) # The spec says this should be float64 array([2.], dtype=float32) To fix this, we add a dimension to the 0-dimension array before passing it through. This works because a dimension would be added anyway from broadcasting, so the resulting shape is the same, but this prevents NumPy from not promoting the dtype. """ # Another option would be to use signature=(x1.dtype, x2.dtype, None), # but that only works for ufuncs, so we would have to call the ufuncs # directly in the operator methods. One should also note that this # sort of trick wouldn't work for functions like searchsorted, which # don't do normal broadcasting, but there aren't any functions like # that in the array API namespace. if x1.ndim == 0 and x2.ndim != 0: # The _array[None] workaround was chosen because it is relatively # performant. broadcast_to(x1._array, x2.shape) is much slower. We # could also manually type promote x2, but that is more complicated # and about the same performance as this. x1 = Array._new(x1._array[None]) elif x2.ndim == 0 and x1.ndim != 0: x2 = Array._new(x2._array[None]) return (x1, x2) # Note: A large fraction of allowed indices are disallowed here (see the # docstring below) def _validate_index(self, key): """ Validate an index according to the array API. The array API specification only requires a subset of indices that are supported by NumPy. This function will reject any index that is allowed by NumPy but not required by the array API specification. We always raise ``IndexError`` on such indices (the spec does not require any specific behavior on them, but this makes the NumPy array API namespace a minimal implementation of the spec). See https://data-apis.org/array-api/latest/API_specification/indexing.html for the full list of required indexing behavior This function raises IndexError if the index ``key`` is invalid. It only raises ``IndexError`` on indices that are not already rejected by NumPy, as NumPy will already raise the appropriate error on such indices. ``shape`` may be None, in which case, only cases that are independent of the array shape are checked. The following cases are allowed by NumPy, but not specified by the array API specification: - Indices to not include an implicit ellipsis at the end. That is, every axis of an array must be explicitly indexed or an ellipsis included. This behaviour is sometimes referred to as flat indexing. - The start and stop of a slice may not be out of bounds. In particular, for a slice ``i:j:k`` on an axis of size ``n``, only the following are allowed: - ``i`` or ``j`` omitted (``None``). - ``-n <= i <= max(0, n - 1)``. - For ``k > 0`` or ``k`` omitted (``None``), ``-n <= j <= n``. - For ``k < 0``, ``-n - 1 <= j <= max(0, n - 1)``. - Boolean array indices are not allowed as part of a larger tuple index. - Integer array indices are not allowed (with the exception of 0-D arrays, which are treated the same as scalars). Additionally, it should be noted that indices that would return a scalar in NumPy will return a 0-D array. Array scalars are not allowed in the specification, only 0-D arrays. This is done in the ``Array._new`` constructor, not this function. """ _key = key if isinstance(key, tuple) else (key,) for i in _key: if isinstance(i, bool) or not ( isinstance(i, SupportsIndex) # i.e. ints or isinstance(i, slice) or i == Ellipsis or i is None or isinstance(i, Array) or isinstance(i, np.ndarray) ): raise IndexError( f"Single-axes index {i} has {type(i)=}, but only " "integers, slices (:), ellipsis (...), newaxis (None), " "zero-dimensional integer arrays and boolean arrays " "are specified in the Array API." ) nonexpanding_key = [] single_axes = [] n_ellipsis = 0 key_has_mask = False for i in _key: if i is not None: nonexpanding_key.append(i) if isinstance(i, Array) or isinstance(i, np.ndarray): if i.dtype in _boolean_dtypes: key_has_mask = True single_axes.append(i) else: # i must not be an array here, to avoid elementwise equals if i == Ellipsis: n_ellipsis += 1 else: single_axes.append(i) n_single_axes = len(single_axes) if n_ellipsis > 1: return # handled by ndarray elif n_ellipsis == 0: # Note boolean masks must be the sole index, which we check for # later on. if not key_has_mask and n_single_axes < self.ndim: raise IndexError( f"{self.ndim=}, but the multi-axes index only specifies " f"{n_single_axes} dimensions. If this was intentional, " "add a trailing ellipsis (...) which expands into as many " "slices (:) as necessary - this is what np.ndarray arrays " "implicitly do, but such flat indexing behaviour is not " "specified in the Array API." ) if n_ellipsis == 0: indexed_shape = self.shape else: ellipsis_start = None for pos, i in enumerate(nonexpanding_key): if not (isinstance(i, Array) or isinstance(i, np.ndarray)): if i == Ellipsis: ellipsis_start = pos break assert ellipsis_start is not None # sanity check ellipsis_end = self.ndim - (n_single_axes - ellipsis_start) indexed_shape = ( self.shape[:ellipsis_start] + self.shape[ellipsis_end:] ) for i, side in zip(single_axes, indexed_shape): if isinstance(i, slice): if side == 0: f_range = "0 (or None)" else: f_range = f"between -{side} and {side - 1} (or None)" if i.start is not None: try: start = operator.index(i.start) except TypeError: pass # handled by ndarray else: if not (-side <= start <= side): raise IndexError( f"Slice {i} contains {start=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds starts are not specified in " "the Array API)" ) if i.stop is not None: try: stop = operator.index(i.stop) except TypeError: pass # handled by ndarray else: if not (-side <= stop <= side): raise IndexError( f"Slice {i} contains {stop=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds stops are not specified in " "the Array API)" ) elif isinstance(i, Array): if i.dtype in _boolean_dtypes and len(_key) != 1: assert isinstance(key, tuple) # sanity check raise IndexError( f"Single-axes index {i} is a boolean array and " f"{len(key)=}, but masking is only specified in the " "Array API when the array is the sole index." ) elif i.dtype in _integer_dtypes and i.ndim != 0: raise IndexError( f"Single-axes index {i} is a non-zero-dimensional " "integer array, but advanced integer indexing is not " "specified in the Array API." ) elif isinstance(i, tuple): raise IndexError( f"Single-axes index {i} is a tuple, but nested tuple " "indices are not specified in the Array API." ) # Everything below this line is required by the spec. def __abs__(self: Array, /) -> Array: """ Performs the operation __abs__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __abs__") res = self._array.__abs__() return self.__class__._new(res) def __add__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __add__. """ other = self._check_allowed_dtypes(other, "numeric", "__add__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__add__(other._array) return self.__class__._new(res) def __and__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __and__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__and__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__and__(other._array) return self.__class__._new(res) def __array_namespace__( self: Array, /, *, api_version: Optional[str] = None ) -> types.ModuleType: if api_version is not None and not api_version.startswith("2021."): raise ValueError(f"Unrecognized array API version: {api_version!r}") return array_api def __bool__(self: Array, /) -> bool: """ Performs the operation __bool__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("bool is only allowed on arrays with 0 dimensions") if self.dtype not in _boolean_dtypes: raise ValueError("bool is only allowed on boolean arrays") res = self._array.__bool__() return res def __dlpack__(self: Array, /, *, stream: None = None) -> PyCapsule: """ Performs the operation __dlpack__. """ return self._array.__dlpack__(stream=stream) def __dlpack_device__(self: Array, /) -> Tuple[IntEnum, int]: """ Performs the operation __dlpack_device__. """ # Note: device support is required for this return self._array.__dlpack_device__() def __eq__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __eq__. """ # Even though "all" dtypes are allowed, we still require them to be # promotable with each other. other = self._check_allowed_dtypes(other, "all", "__eq__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__eq__(other._array) return self.__class__._new(res) def __float__(self: Array, /) -> float: """ Performs the operation __float__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("float is only allowed on arrays with 0 dimensions") if self.dtype not in _floating_dtypes: raise ValueError("float is only allowed on floating-point arrays") res = self._array.__float__() return res def __floordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __floordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__floordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__floordiv__(other._array) return self.__class__._new(res) def __ge__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ge__. """ other = self._check_allowed_dtypes(other, "numeric", "__ge__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ge__(other._array) return self.__class__._new(res) def __getitem__( self: Array, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], /, ) -> Array: """ Performs the operation __getitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array res = self._array.__getitem__(key) return self._new(res) def __gt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __gt__. """ other = self._check_allowed_dtypes(other, "numeric", "__gt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__gt__(other._array) return self.__class__._new(res) def __int__(self: Array, /) -> int: """ Performs the operation __int__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("int is only allowed on arrays with 0 dimensions") if self.dtype not in _integer_dtypes: raise ValueError("int is only allowed on integer arrays") res = self._array.__int__() return res def __index__(self: Array, /) -> int: """ Performs the operation __index__. """ res = self._array.__index__() return res def __invert__(self: Array, /) -> Array: """ Performs the operation __invert__. """ if self.dtype not in _integer_or_boolean_dtypes: raise TypeError("Only integer or boolean dtypes are allowed in __invert__") res = self._array.__invert__() return self.__class__._new(res) def __le__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __le__. """ other = self._check_allowed_dtypes(other, "numeric", "__le__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__le__(other._array) return self.__class__._new(res) def __lshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __lshift__. """ other = self._check_allowed_dtypes(other, "integer", "__lshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lshift__(other._array) return self.__class__._new(res) def __lt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __lt__. """ other = self._check_allowed_dtypes(other, "numeric", "__lt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lt__(other._array) return self.__class__._new(res) def __matmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __matmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__matmul__") if other is NotImplemented: return other res = self._array.__matmul__(other._array) return self.__class__._new(res) def __mod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mod__. """ other = self._check_allowed_dtypes(other, "numeric", "__mod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mod__(other._array) return self.__class__._new(res) def __mul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mul__. """ other = self._check_allowed_dtypes(other, "numeric", "__mul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mul__(other._array) return self.__class__._new(res) def __ne__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __ne__. """ other = self._check_allowed_dtypes(other, "all", "__ne__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ne__(other._array) return self.__class__._new(res) def __neg__(self: Array, /) -> Array: """ Performs the operation __neg__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __neg__") res = self._array.__neg__() return self.__class__._new(res) def __or__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __or__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__or__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__or__(other._array) return self.__class__._new(res) def __pos__(self: Array, /) -> Array: """ Performs the operation __pos__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __pos__") res = self._array.__pos__() return self.__class__._new(res) def __pow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __pow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__pow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow type promotion rules for 0-d # arrays, so we use pow() here instead. return pow(self, other) def __rshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rshift__(other._array) return self.__class__._new(res) def __setitem__( self, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], value: Union[int, float, bool, Array], /, ) -> None: """ Performs the operation __setitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array self._array.__setitem__(key, asarray(value)._array) def __sub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __sub__. """ other = self._check_allowed_dtypes(other, "numeric", "__sub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__sub__(other._array) return self.__class__._new(res) # PEP 484 requires int to be a subtype of float, but __truediv__ should # not accept int. def __truediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __truediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__truediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__truediv__(other._array) return self.__class__._new(res) def __xor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __xor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__xor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__xor__(other._array) return self.__class__._new(res) def __iadd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __iadd__. """ other = self._check_allowed_dtypes(other, "numeric", "__iadd__") if other is NotImplemented: return other self._array.__iadd__(other._array) return self def __radd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __radd__. """ other = self._check_allowed_dtypes(other, "numeric", "__radd__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__radd__(other._array) return self.__class__._new(res) def __iand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __iand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__iand__") if other is NotImplemented: return other self._array.__iand__(other._array) return self def __rand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rand__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rand__(other._array) return self.__class__._new(res) def __ifloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ifloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__ifloordiv__") if other is NotImplemented: return other self._array.__ifloordiv__(other._array) return self def __rfloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rfloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__rfloordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rfloordiv__(other._array) return self.__class__._new(res) def __ilshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __ilshift__. """ other = self._check_allowed_dtypes(other, "integer", "__ilshift__") if other is NotImplemented: return other self._array.__ilshift__(other._array) return self def __rlshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rlshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rlshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rlshift__(other._array) return self.__class__._new(res) def __imatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __imatmul__. """ # Note: NumPy does not implement __imatmul__. # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__imatmul__") if other is NotImplemented: return other # __imatmul__ can only be allowed when it would not change the shape # of self. other_shape = other.shape if self.shape == () or other_shape == (): raise ValueError("@= requires at least one dimension") if len(other_shape) == 1 or other_shape[-1] != other_shape[-2]: raise ValueError("@= cannot change the shape of the input array") self._array[:] = self._array.__matmul__(other._array) return self def __rmatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __rmatmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__rmatmul__") if other is NotImplemented: return other res = self._array.__rmatmul__(other._array) return self.__class__._new(res) def __imod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imod__. """ other = self._check_allowed_dtypes(other, "numeric", "__imod__") if other is NotImplemented: return other self._array.__imod__(other._array) return self def __rmod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmod__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmod__(other._array) return self.__class__._new(res) def __imul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imul__. """ other = self._check_allowed_dtypes(other, "numeric", "__imul__") if other is NotImplemented: return other self._array.__imul__(other._array) return self def __rmul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmul__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmul__(other._array) return self.__class__._new(res) def __ior__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ior__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ior__") if other is NotImplemented: return other self._array.__ior__(other._array) return self def __ror__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ror__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ror__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ror__(other._array) return self.__class__._new(res) def __ipow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ipow__. """ other = self._check_allowed_dtypes(other, "numeric", "__ipow__") if other is NotImplemented: return other self._array.__ipow__(other._array) return self def __rpow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rpow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__rpow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow the spec type promotion rules # for 0-d arrays, so we use pow() here instead. return pow(other, self) def __irshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __irshift__. """ other = self._check_allowed_dtypes(other, "integer", "__irshift__") if other is NotImplemented: return other self._array.__irshift__(other._array) return self def __rrshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rrshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rrshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rrshift__(other._array) return self.__class__._new(res) def __isub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __isub__. """ other = self._check_allowed_dtypes(other, "numeric", "__isub__") if other is NotImplemented: return other self._array.__isub__(other._array) return self def __rsub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rsub__. """ other = self._check_allowed_dtypes(other, "numeric", "__rsub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rsub__(other._array) return self.__class__._new(res) def __itruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __itruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__itruediv__") if other is NotImplemented: return other self._array.__itruediv__(other._array) return self def __rtruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __rtruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__rtruediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rtruediv__(other._array) return self.__class__._new(res) def __ixor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ixor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ixor__") if other is NotImplemented: return other self._array.__ixor__(other._array) return self def __rxor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rxor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rxor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rxor__(other._array) return self.__class__._new(res) def to_device(self: Array, device: Device, /, stream: None = None) -> Array: if stream is not None: raise ValueError("The stream argument to to_device() is not supported") if device == 'cpu': return self raise ValueError(f"Unsupported device {device!r}") def dtype(self) -> Dtype: """ Array API compatible wrapper for :py:meth:`np.ndarray.dtype <numpy.ndarray.dtype>`. See its docstring for more information. """ return self._array.dtype def device(self) -> Device: return "cpu" # Note: mT is new in array API spec (see matrix_transpose) def mT(self) -> Array: from .linalg import matrix_transpose return matrix_transpose(self) def ndim(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.ndim <numpy.ndarray.ndim>`. See its docstring for more information. """ return self._array.ndim def shape(self) -> Tuple[int, ...]: """ Array API compatible wrapper for :py:meth:`np.ndarray.shape <numpy.ndarray.shape>`. See its docstring for more information. """ return self._array.shape def size(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.size <numpy.ndarray.size>`. See its docstring for more information. """ return self._array.size def T(self) -> Array: """ Array API compatible wrapper for :py:meth:`np.ndarray.T <numpy.ndarray.T>`. See its docstring for more information. """ # Note: T only works on 2-dimensional arrays. See the corresponding # note in the specification: # https://data-apis.org/array-api/latest/API_specification/array_object.html#t if self.ndim != 2: raise ValueError("x.T requires x to have 2 dimensions. Use x.mT to transpose stacks of matrices and permute_dims() to permute dimensions.") return self.__class__._new(self._array.T) The provided code snippet includes necessary dependencies for implementing the `atan2` function. Write a Python function `def atan2(x1: Array, x2: Array, /) -> Array` to solve the following problem: Array API compatible wrapper for :py:func:`np.arctan2 <numpy.arctan2>`. See its docstring for more information. Here is the function: def atan2(x1: Array, x2: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.arctan2 <numpy.arctan2>`. See its docstring for more information. """ if x1.dtype not in _floating_dtypes or x2.dtype not in _floating_dtypes: raise TypeError("Only floating-point dtypes are allowed in atan2") # Call result type here just to raise on disallowed type combinations _result_type(x1.dtype, x2.dtype) x1, x2 = Array._normalize_two_args(x1, x2) return Array._new(np.arctan2(x1._array, x2._array))
Array API compatible wrapper for :py:func:`np.arctan2 <numpy.arctan2>`. See its docstring for more information.
170,027
from __future__ import annotations from ._dtypes import ( _boolean_dtypes, _floating_dtypes, _integer_dtypes, _integer_or_boolean_dtypes, _numeric_dtypes, _result_type, ) from ._array_object import Array import numpy as np _floating_dtypes = (float32, float64) class Array: """ n-d array object for the array API namespace. See the docstring of :py:obj:`np.ndarray <numpy.ndarray>` for more information. This is a wrapper around numpy.ndarray that restricts the usage to only those things that are required by the array API namespace. Note, attributes on this object that start with a single underscore are not part of the API specification and should only be used internally. This object should not be constructed directly. Rather, use one of the creation functions, such as asarray(). """ _array: np.ndarray # Use a custom constructor instead of __init__, as manually initializing # this class is not supported API. def _new(cls, x, /): """ This is a private method for initializing the array API Array object. Functions outside of the array_api submodule should not use this method. Use one of the creation functions instead, such as ``asarray``. """ obj = super().__new__(cls) # Note: The spec does not have array scalars, only 0-D arrays. if isinstance(x, np.generic): # Convert the array scalar to a 0-D array x = np.asarray(x) if x.dtype not in _all_dtypes: raise TypeError( f"The array_api namespace does not support the dtype '{x.dtype}'" ) obj._array = x return obj # Prevent Array() from working def __new__(cls, *args, **kwargs): raise TypeError( "The array_api Array object should not be instantiated directly. Use an array creation function, such as asarray(), instead." ) # These functions are not required by the spec, but are implemented for # the sake of usability. def __str__(self: Array, /) -> str: """ Performs the operation __str__. """ return self._array.__str__().replace("array", "Array") def __repr__(self: Array, /) -> str: """ Performs the operation __repr__. """ suffix = f", dtype={self.dtype.name})" if 0 in self.shape: prefix = "empty(" mid = str(self.shape) else: prefix = "Array(" mid = np.array2string(self._array, separator=', ', prefix=prefix, suffix=suffix) return prefix + mid + suffix # This function is not required by the spec, but we implement it here for # convenience so that np.asarray(np.array_api.Array) will work. def __array__(self, dtype: None | np.dtype[Any] = None) -> npt.NDArray[Any]: """ Warning: this method is NOT part of the array API spec. Implementers of other libraries need not include it, and users should not assume it will be present in other implementations. """ return np.asarray(self._array, dtype=dtype) # These are various helper functions to make the array behavior match the # spec in places where it either deviates from or is more strict than # NumPy behavior def _check_allowed_dtypes(self, other: bool | int | float | Array, dtype_category: str, op: str) -> Array: """ Helper function for operators to only allow specific input dtypes Use like other = self._check_allowed_dtypes(other, 'numeric', '__add__') if other is NotImplemented: return other """ if self.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") if isinstance(other, (int, float, bool)): other = self._promote_scalar(other) elif isinstance(other, Array): if other.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") else: return NotImplemented # This will raise TypeError for type combinations that are not allowed # to promote in the spec (even if the NumPy array operator would # promote them). res_dtype = _result_type(self.dtype, other.dtype) if op.startswith("__i"): # Note: NumPy will allow in-place operators in some cases where # the type promoted operator does not match the left-hand side # operand. For example, # >>> a = np.array(1, dtype=np.int8) # >>> a += np.array(1, dtype=np.int16) # The spec explicitly disallows this. if res_dtype != self.dtype: raise TypeError( f"Cannot perform {op} with dtypes {self.dtype} and {other.dtype}" ) return other # Helper function to match the type promotion rules in the spec def _promote_scalar(self, scalar): """ Returns a promoted version of a Python scalar appropriate for use with operations on self. This may raise an OverflowError in cases where the scalar is an integer that is too large to fit in a NumPy integer dtype, or TypeError when the scalar type is incompatible with the dtype of self. """ # Note: Only Python scalar types that match the array dtype are # allowed. if isinstance(scalar, bool): if self.dtype not in _boolean_dtypes: raise TypeError( "Python bool scalars can only be promoted with bool arrays" ) elif isinstance(scalar, int): if self.dtype in _boolean_dtypes: raise TypeError( "Python int scalars cannot be promoted with bool arrays" ) elif isinstance(scalar, float): if self.dtype not in _floating_dtypes: raise TypeError( "Python float scalars can only be promoted with floating-point arrays." ) else: raise TypeError("'scalar' must be a Python scalar") # Note: scalars are unconditionally cast to the same dtype as the # array. # Note: the spec only specifies integer-dtype/int promotion # behavior for integers within the bounds of the integer dtype. # Outside of those bounds we use the default NumPy behavior (either # cast or raise OverflowError). return Array._new(np.array(scalar, self.dtype)) def _normalize_two_args(x1, x2) -> Tuple[Array, Array]: """ Normalize inputs to two arg functions to fix type promotion rules NumPy deviates from the spec type promotion rules in cases where one argument is 0-dimensional and the other is not. For example: >>> import numpy as np >>> a = np.array([1.0], dtype=np.float32) >>> b = np.array(1.0, dtype=np.float64) >>> np.add(a, b) # The spec says this should be float64 array([2.], dtype=float32) To fix this, we add a dimension to the 0-dimension array before passing it through. This works because a dimension would be added anyway from broadcasting, so the resulting shape is the same, but this prevents NumPy from not promoting the dtype. """ # Another option would be to use signature=(x1.dtype, x2.dtype, None), # but that only works for ufuncs, so we would have to call the ufuncs # directly in the operator methods. One should also note that this # sort of trick wouldn't work for functions like searchsorted, which # don't do normal broadcasting, but there aren't any functions like # that in the array API namespace. if x1.ndim == 0 and x2.ndim != 0: # The _array[None] workaround was chosen because it is relatively # performant. broadcast_to(x1._array, x2.shape) is much slower. We # could also manually type promote x2, but that is more complicated # and about the same performance as this. x1 = Array._new(x1._array[None]) elif x2.ndim == 0 and x1.ndim != 0: x2 = Array._new(x2._array[None]) return (x1, x2) # Note: A large fraction of allowed indices are disallowed here (see the # docstring below) def _validate_index(self, key): """ Validate an index according to the array API. The array API specification only requires a subset of indices that are supported by NumPy. This function will reject any index that is allowed by NumPy but not required by the array API specification. We always raise ``IndexError`` on such indices (the spec does not require any specific behavior on them, but this makes the NumPy array API namespace a minimal implementation of the spec). See https://data-apis.org/array-api/latest/API_specification/indexing.html for the full list of required indexing behavior This function raises IndexError if the index ``key`` is invalid. It only raises ``IndexError`` on indices that are not already rejected by NumPy, as NumPy will already raise the appropriate error on such indices. ``shape`` may be None, in which case, only cases that are independent of the array shape are checked. The following cases are allowed by NumPy, but not specified by the array API specification: - Indices to not include an implicit ellipsis at the end. That is, every axis of an array must be explicitly indexed or an ellipsis included. This behaviour is sometimes referred to as flat indexing. - The start and stop of a slice may not be out of bounds. In particular, for a slice ``i:j:k`` on an axis of size ``n``, only the following are allowed: - ``i`` or ``j`` omitted (``None``). - ``-n <= i <= max(0, n - 1)``. - For ``k > 0`` or ``k`` omitted (``None``), ``-n <= j <= n``. - For ``k < 0``, ``-n - 1 <= j <= max(0, n - 1)``. - Boolean array indices are not allowed as part of a larger tuple index. - Integer array indices are not allowed (with the exception of 0-D arrays, which are treated the same as scalars). Additionally, it should be noted that indices that would return a scalar in NumPy will return a 0-D array. Array scalars are not allowed in the specification, only 0-D arrays. This is done in the ``Array._new`` constructor, not this function. """ _key = key if isinstance(key, tuple) else (key,) for i in _key: if isinstance(i, bool) or not ( isinstance(i, SupportsIndex) # i.e. ints or isinstance(i, slice) or i == Ellipsis or i is None or isinstance(i, Array) or isinstance(i, np.ndarray) ): raise IndexError( f"Single-axes index {i} has {type(i)=}, but only " "integers, slices (:), ellipsis (...), newaxis (None), " "zero-dimensional integer arrays and boolean arrays " "are specified in the Array API." ) nonexpanding_key = [] single_axes = [] n_ellipsis = 0 key_has_mask = False for i in _key: if i is not None: nonexpanding_key.append(i) if isinstance(i, Array) or isinstance(i, np.ndarray): if i.dtype in _boolean_dtypes: key_has_mask = True single_axes.append(i) else: # i must not be an array here, to avoid elementwise equals if i == Ellipsis: n_ellipsis += 1 else: single_axes.append(i) n_single_axes = len(single_axes) if n_ellipsis > 1: return # handled by ndarray elif n_ellipsis == 0: # Note boolean masks must be the sole index, which we check for # later on. if not key_has_mask and n_single_axes < self.ndim: raise IndexError( f"{self.ndim=}, but the multi-axes index only specifies " f"{n_single_axes} dimensions. If this was intentional, " "add a trailing ellipsis (...) which expands into as many " "slices (:) as necessary - this is what np.ndarray arrays " "implicitly do, but such flat indexing behaviour is not " "specified in the Array API." ) if n_ellipsis == 0: indexed_shape = self.shape else: ellipsis_start = None for pos, i in enumerate(nonexpanding_key): if not (isinstance(i, Array) or isinstance(i, np.ndarray)): if i == Ellipsis: ellipsis_start = pos break assert ellipsis_start is not None # sanity check ellipsis_end = self.ndim - (n_single_axes - ellipsis_start) indexed_shape = ( self.shape[:ellipsis_start] + self.shape[ellipsis_end:] ) for i, side in zip(single_axes, indexed_shape): if isinstance(i, slice): if side == 0: f_range = "0 (or None)" else: f_range = f"between -{side} and {side - 1} (or None)" if i.start is not None: try: start = operator.index(i.start) except TypeError: pass # handled by ndarray else: if not (-side <= start <= side): raise IndexError( f"Slice {i} contains {start=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds starts are not specified in " "the Array API)" ) if i.stop is not None: try: stop = operator.index(i.stop) except TypeError: pass # handled by ndarray else: if not (-side <= stop <= side): raise IndexError( f"Slice {i} contains {stop=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds stops are not specified in " "the Array API)" ) elif isinstance(i, Array): if i.dtype in _boolean_dtypes and len(_key) != 1: assert isinstance(key, tuple) # sanity check raise IndexError( f"Single-axes index {i} is a boolean array and " f"{len(key)=}, but masking is only specified in the " "Array API when the array is the sole index." ) elif i.dtype in _integer_dtypes and i.ndim != 0: raise IndexError( f"Single-axes index {i} is a non-zero-dimensional " "integer array, but advanced integer indexing is not " "specified in the Array API." ) elif isinstance(i, tuple): raise IndexError( f"Single-axes index {i} is a tuple, but nested tuple " "indices are not specified in the Array API." ) # Everything below this line is required by the spec. def __abs__(self: Array, /) -> Array: """ Performs the operation __abs__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __abs__") res = self._array.__abs__() return self.__class__._new(res) def __add__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __add__. """ other = self._check_allowed_dtypes(other, "numeric", "__add__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__add__(other._array) return self.__class__._new(res) def __and__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __and__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__and__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__and__(other._array) return self.__class__._new(res) def __array_namespace__( self: Array, /, *, api_version: Optional[str] = None ) -> types.ModuleType: if api_version is not None and not api_version.startswith("2021."): raise ValueError(f"Unrecognized array API version: {api_version!r}") return array_api def __bool__(self: Array, /) -> bool: """ Performs the operation __bool__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("bool is only allowed on arrays with 0 dimensions") if self.dtype not in _boolean_dtypes: raise ValueError("bool is only allowed on boolean arrays") res = self._array.__bool__() return res def __dlpack__(self: Array, /, *, stream: None = None) -> PyCapsule: """ Performs the operation __dlpack__. """ return self._array.__dlpack__(stream=stream) def __dlpack_device__(self: Array, /) -> Tuple[IntEnum, int]: """ Performs the operation __dlpack_device__. """ # Note: device support is required for this return self._array.__dlpack_device__() def __eq__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __eq__. """ # Even though "all" dtypes are allowed, we still require them to be # promotable with each other. other = self._check_allowed_dtypes(other, "all", "__eq__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__eq__(other._array) return self.__class__._new(res) def __float__(self: Array, /) -> float: """ Performs the operation __float__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("float is only allowed on arrays with 0 dimensions") if self.dtype not in _floating_dtypes: raise ValueError("float is only allowed on floating-point arrays") res = self._array.__float__() return res def __floordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __floordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__floordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__floordiv__(other._array) return self.__class__._new(res) def __ge__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ge__. """ other = self._check_allowed_dtypes(other, "numeric", "__ge__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ge__(other._array) return self.__class__._new(res) def __getitem__( self: Array, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], /, ) -> Array: """ Performs the operation __getitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array res = self._array.__getitem__(key) return self._new(res) def __gt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __gt__. """ other = self._check_allowed_dtypes(other, "numeric", "__gt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__gt__(other._array) return self.__class__._new(res) def __int__(self: Array, /) -> int: """ Performs the operation __int__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("int is only allowed on arrays with 0 dimensions") if self.dtype not in _integer_dtypes: raise ValueError("int is only allowed on integer arrays") res = self._array.__int__() return res def __index__(self: Array, /) -> int: """ Performs the operation __index__. """ res = self._array.__index__() return res def __invert__(self: Array, /) -> Array: """ Performs the operation __invert__. """ if self.dtype not in _integer_or_boolean_dtypes: raise TypeError("Only integer or boolean dtypes are allowed in __invert__") res = self._array.__invert__() return self.__class__._new(res) def __le__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __le__. """ other = self._check_allowed_dtypes(other, "numeric", "__le__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__le__(other._array) return self.__class__._new(res) def __lshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __lshift__. """ other = self._check_allowed_dtypes(other, "integer", "__lshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lshift__(other._array) return self.__class__._new(res) def __lt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __lt__. """ other = self._check_allowed_dtypes(other, "numeric", "__lt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lt__(other._array) return self.__class__._new(res) def __matmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __matmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__matmul__") if other is NotImplemented: return other res = self._array.__matmul__(other._array) return self.__class__._new(res) def __mod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mod__. """ other = self._check_allowed_dtypes(other, "numeric", "__mod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mod__(other._array) return self.__class__._new(res) def __mul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mul__. """ other = self._check_allowed_dtypes(other, "numeric", "__mul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mul__(other._array) return self.__class__._new(res) def __ne__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __ne__. """ other = self._check_allowed_dtypes(other, "all", "__ne__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ne__(other._array) return self.__class__._new(res) def __neg__(self: Array, /) -> Array: """ Performs the operation __neg__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __neg__") res = self._array.__neg__() return self.__class__._new(res) def __or__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __or__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__or__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__or__(other._array) return self.__class__._new(res) def __pos__(self: Array, /) -> Array: """ Performs the operation __pos__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __pos__") res = self._array.__pos__() return self.__class__._new(res) def __pow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __pow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__pow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow type promotion rules for 0-d # arrays, so we use pow() here instead. return pow(self, other) def __rshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rshift__(other._array) return self.__class__._new(res) def __setitem__( self, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], value: Union[int, float, bool, Array], /, ) -> None: """ Performs the operation __setitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array self._array.__setitem__(key, asarray(value)._array) def __sub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __sub__. """ other = self._check_allowed_dtypes(other, "numeric", "__sub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__sub__(other._array) return self.__class__._new(res) # PEP 484 requires int to be a subtype of float, but __truediv__ should # not accept int. def __truediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __truediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__truediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__truediv__(other._array) return self.__class__._new(res) def __xor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __xor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__xor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__xor__(other._array) return self.__class__._new(res) def __iadd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __iadd__. """ other = self._check_allowed_dtypes(other, "numeric", "__iadd__") if other is NotImplemented: return other self._array.__iadd__(other._array) return self def __radd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __radd__. """ other = self._check_allowed_dtypes(other, "numeric", "__radd__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__radd__(other._array) return self.__class__._new(res) def __iand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __iand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__iand__") if other is NotImplemented: return other self._array.__iand__(other._array) return self def __rand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rand__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rand__(other._array) return self.__class__._new(res) def __ifloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ifloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__ifloordiv__") if other is NotImplemented: return other self._array.__ifloordiv__(other._array) return self def __rfloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rfloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__rfloordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rfloordiv__(other._array) return self.__class__._new(res) def __ilshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __ilshift__. """ other = self._check_allowed_dtypes(other, "integer", "__ilshift__") if other is NotImplemented: return other self._array.__ilshift__(other._array) return self def __rlshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rlshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rlshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rlshift__(other._array) return self.__class__._new(res) def __imatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __imatmul__. """ # Note: NumPy does not implement __imatmul__. # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__imatmul__") if other is NotImplemented: return other # __imatmul__ can only be allowed when it would not change the shape # of self. other_shape = other.shape if self.shape == () or other_shape == (): raise ValueError("@= requires at least one dimension") if len(other_shape) == 1 or other_shape[-1] != other_shape[-2]: raise ValueError("@= cannot change the shape of the input array") self._array[:] = self._array.__matmul__(other._array) return self def __rmatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __rmatmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__rmatmul__") if other is NotImplemented: return other res = self._array.__rmatmul__(other._array) return self.__class__._new(res) def __imod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imod__. """ other = self._check_allowed_dtypes(other, "numeric", "__imod__") if other is NotImplemented: return other self._array.__imod__(other._array) return self def __rmod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmod__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmod__(other._array) return self.__class__._new(res) def __imul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imul__. """ other = self._check_allowed_dtypes(other, "numeric", "__imul__") if other is NotImplemented: return other self._array.__imul__(other._array) return self def __rmul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmul__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmul__(other._array) return self.__class__._new(res) def __ior__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ior__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ior__") if other is NotImplemented: return other self._array.__ior__(other._array) return self def __ror__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ror__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ror__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ror__(other._array) return self.__class__._new(res) def __ipow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ipow__. """ other = self._check_allowed_dtypes(other, "numeric", "__ipow__") if other is NotImplemented: return other self._array.__ipow__(other._array) return self def __rpow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rpow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__rpow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow the spec type promotion rules # for 0-d arrays, so we use pow() here instead. return pow(other, self) def __irshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __irshift__. """ other = self._check_allowed_dtypes(other, "integer", "__irshift__") if other is NotImplemented: return other self._array.__irshift__(other._array) return self def __rrshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rrshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rrshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rrshift__(other._array) return self.__class__._new(res) def __isub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __isub__. """ other = self._check_allowed_dtypes(other, "numeric", "__isub__") if other is NotImplemented: return other self._array.__isub__(other._array) return self def __rsub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rsub__. """ other = self._check_allowed_dtypes(other, "numeric", "__rsub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rsub__(other._array) return self.__class__._new(res) def __itruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __itruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__itruediv__") if other is NotImplemented: return other self._array.__itruediv__(other._array) return self def __rtruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __rtruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__rtruediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rtruediv__(other._array) return self.__class__._new(res) def __ixor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ixor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ixor__") if other is NotImplemented: return other self._array.__ixor__(other._array) return self def __rxor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rxor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rxor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rxor__(other._array) return self.__class__._new(res) def to_device(self: Array, device: Device, /, stream: None = None) -> Array: if stream is not None: raise ValueError("The stream argument to to_device() is not supported") if device == 'cpu': return self raise ValueError(f"Unsupported device {device!r}") def dtype(self) -> Dtype: """ Array API compatible wrapper for :py:meth:`np.ndarray.dtype <numpy.ndarray.dtype>`. See its docstring for more information. """ return self._array.dtype def device(self) -> Device: return "cpu" # Note: mT is new in array API spec (see matrix_transpose) def mT(self) -> Array: from .linalg import matrix_transpose return matrix_transpose(self) def ndim(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.ndim <numpy.ndarray.ndim>`. See its docstring for more information. """ return self._array.ndim def shape(self) -> Tuple[int, ...]: """ Array API compatible wrapper for :py:meth:`np.ndarray.shape <numpy.ndarray.shape>`. See its docstring for more information. """ return self._array.shape def size(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.size <numpy.ndarray.size>`. See its docstring for more information. """ return self._array.size def T(self) -> Array: """ Array API compatible wrapper for :py:meth:`np.ndarray.T <numpy.ndarray.T>`. See its docstring for more information. """ # Note: T only works on 2-dimensional arrays. See the corresponding # note in the specification: # https://data-apis.org/array-api/latest/API_specification/array_object.html#t if self.ndim != 2: raise ValueError("x.T requires x to have 2 dimensions. Use x.mT to transpose stacks of matrices and permute_dims() to permute dimensions.") return self.__class__._new(self._array.T) The provided code snippet includes necessary dependencies for implementing the `atanh` function. Write a Python function `def atanh(x: Array, /) -> Array` to solve the following problem: Array API compatible wrapper for :py:func:`np.arctanh <numpy.arctanh>`. See its docstring for more information. Here is the function: def atanh(x: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.arctanh <numpy.arctanh>`. See its docstring for more information. """ if x.dtype not in _floating_dtypes: raise TypeError("Only floating-point dtypes are allowed in atanh") return Array._new(np.arctanh(x._array))
Array API compatible wrapper for :py:func:`np.arctanh <numpy.arctanh>`. See its docstring for more information.
170,028
from __future__ import annotations from ._dtypes import ( _boolean_dtypes, _floating_dtypes, _integer_dtypes, _integer_or_boolean_dtypes, _numeric_dtypes, _result_type, ) from ._array_object import Array import numpy as np _integer_or_boolean_dtypes = ( bool, int8, int16, int32, int64, uint8, uint16, uint32, uint64, ) def _result_type(type1, type2): if (type1, type2) in _promotion_table: return _promotion_table[type1, type2] raise TypeError(f"{type1} and {type2} cannot be type promoted together") class Array: """ n-d array object for the array API namespace. See the docstring of :py:obj:`np.ndarray <numpy.ndarray>` for more information. This is a wrapper around numpy.ndarray that restricts the usage to only those things that are required by the array API namespace. Note, attributes on this object that start with a single underscore are not part of the API specification and should only be used internally. This object should not be constructed directly. Rather, use one of the creation functions, such as asarray(). """ _array: np.ndarray # Use a custom constructor instead of __init__, as manually initializing # this class is not supported API. def _new(cls, x, /): """ This is a private method for initializing the array API Array object. Functions outside of the array_api submodule should not use this method. Use one of the creation functions instead, such as ``asarray``. """ obj = super().__new__(cls) # Note: The spec does not have array scalars, only 0-D arrays. if isinstance(x, np.generic): # Convert the array scalar to a 0-D array x = np.asarray(x) if x.dtype not in _all_dtypes: raise TypeError( f"The array_api namespace does not support the dtype '{x.dtype}'" ) obj._array = x return obj # Prevent Array() from working def __new__(cls, *args, **kwargs): raise TypeError( "The array_api Array object should not be instantiated directly. Use an array creation function, such as asarray(), instead." ) # These functions are not required by the spec, but are implemented for # the sake of usability. def __str__(self: Array, /) -> str: """ Performs the operation __str__. """ return self._array.__str__().replace("array", "Array") def __repr__(self: Array, /) -> str: """ Performs the operation __repr__. """ suffix = f", dtype={self.dtype.name})" if 0 in self.shape: prefix = "empty(" mid = str(self.shape) else: prefix = "Array(" mid = np.array2string(self._array, separator=', ', prefix=prefix, suffix=suffix) return prefix + mid + suffix # This function is not required by the spec, but we implement it here for # convenience so that np.asarray(np.array_api.Array) will work. def __array__(self, dtype: None | np.dtype[Any] = None) -> npt.NDArray[Any]: """ Warning: this method is NOT part of the array API spec. Implementers of other libraries need not include it, and users should not assume it will be present in other implementations. """ return np.asarray(self._array, dtype=dtype) # These are various helper functions to make the array behavior match the # spec in places where it either deviates from or is more strict than # NumPy behavior def _check_allowed_dtypes(self, other: bool | int | float | Array, dtype_category: str, op: str) -> Array: """ Helper function for operators to only allow specific input dtypes Use like other = self._check_allowed_dtypes(other, 'numeric', '__add__') if other is NotImplemented: return other """ if self.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") if isinstance(other, (int, float, bool)): other = self._promote_scalar(other) elif isinstance(other, Array): if other.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") else: return NotImplemented # This will raise TypeError for type combinations that are not allowed # to promote in the spec (even if the NumPy array operator would # promote them). res_dtype = _result_type(self.dtype, other.dtype) if op.startswith("__i"): # Note: NumPy will allow in-place operators in some cases where # the type promoted operator does not match the left-hand side # operand. For example, # >>> a = np.array(1, dtype=np.int8) # >>> a += np.array(1, dtype=np.int16) # The spec explicitly disallows this. if res_dtype != self.dtype: raise TypeError( f"Cannot perform {op} with dtypes {self.dtype} and {other.dtype}" ) return other # Helper function to match the type promotion rules in the spec def _promote_scalar(self, scalar): """ Returns a promoted version of a Python scalar appropriate for use with operations on self. This may raise an OverflowError in cases where the scalar is an integer that is too large to fit in a NumPy integer dtype, or TypeError when the scalar type is incompatible with the dtype of self. """ # Note: Only Python scalar types that match the array dtype are # allowed. if isinstance(scalar, bool): if self.dtype not in _boolean_dtypes: raise TypeError( "Python bool scalars can only be promoted with bool arrays" ) elif isinstance(scalar, int): if self.dtype in _boolean_dtypes: raise TypeError( "Python int scalars cannot be promoted with bool arrays" ) elif isinstance(scalar, float): if self.dtype not in _floating_dtypes: raise TypeError( "Python float scalars can only be promoted with floating-point arrays." ) else: raise TypeError("'scalar' must be a Python scalar") # Note: scalars are unconditionally cast to the same dtype as the # array. # Note: the spec only specifies integer-dtype/int promotion # behavior for integers within the bounds of the integer dtype. # Outside of those bounds we use the default NumPy behavior (either # cast or raise OverflowError). return Array._new(np.array(scalar, self.dtype)) def _normalize_two_args(x1, x2) -> Tuple[Array, Array]: """ Normalize inputs to two arg functions to fix type promotion rules NumPy deviates from the spec type promotion rules in cases where one argument is 0-dimensional and the other is not. For example: >>> import numpy as np >>> a = np.array([1.0], dtype=np.float32) >>> b = np.array(1.0, dtype=np.float64) >>> np.add(a, b) # The spec says this should be float64 array([2.], dtype=float32) To fix this, we add a dimension to the 0-dimension array before passing it through. This works because a dimension would be added anyway from broadcasting, so the resulting shape is the same, but this prevents NumPy from not promoting the dtype. """ # Another option would be to use signature=(x1.dtype, x2.dtype, None), # but that only works for ufuncs, so we would have to call the ufuncs # directly in the operator methods. One should also note that this # sort of trick wouldn't work for functions like searchsorted, which # don't do normal broadcasting, but there aren't any functions like # that in the array API namespace. if x1.ndim == 0 and x2.ndim != 0: # The _array[None] workaround was chosen because it is relatively # performant. broadcast_to(x1._array, x2.shape) is much slower. We # could also manually type promote x2, but that is more complicated # and about the same performance as this. x1 = Array._new(x1._array[None]) elif x2.ndim == 0 and x1.ndim != 0: x2 = Array._new(x2._array[None]) return (x1, x2) # Note: A large fraction of allowed indices are disallowed here (see the # docstring below) def _validate_index(self, key): """ Validate an index according to the array API. The array API specification only requires a subset of indices that are supported by NumPy. This function will reject any index that is allowed by NumPy but not required by the array API specification. We always raise ``IndexError`` on such indices (the spec does not require any specific behavior on them, but this makes the NumPy array API namespace a minimal implementation of the spec). See https://data-apis.org/array-api/latest/API_specification/indexing.html for the full list of required indexing behavior This function raises IndexError if the index ``key`` is invalid. It only raises ``IndexError`` on indices that are not already rejected by NumPy, as NumPy will already raise the appropriate error on such indices. ``shape`` may be None, in which case, only cases that are independent of the array shape are checked. The following cases are allowed by NumPy, but not specified by the array API specification: - Indices to not include an implicit ellipsis at the end. That is, every axis of an array must be explicitly indexed or an ellipsis included. This behaviour is sometimes referred to as flat indexing. - The start and stop of a slice may not be out of bounds. In particular, for a slice ``i:j:k`` on an axis of size ``n``, only the following are allowed: - ``i`` or ``j`` omitted (``None``). - ``-n <= i <= max(0, n - 1)``. - For ``k > 0`` or ``k`` omitted (``None``), ``-n <= j <= n``. - For ``k < 0``, ``-n - 1 <= j <= max(0, n - 1)``. - Boolean array indices are not allowed as part of a larger tuple index. - Integer array indices are not allowed (with the exception of 0-D arrays, which are treated the same as scalars). Additionally, it should be noted that indices that would return a scalar in NumPy will return a 0-D array. Array scalars are not allowed in the specification, only 0-D arrays. This is done in the ``Array._new`` constructor, not this function. """ _key = key if isinstance(key, tuple) else (key,) for i in _key: if isinstance(i, bool) or not ( isinstance(i, SupportsIndex) # i.e. ints or isinstance(i, slice) or i == Ellipsis or i is None or isinstance(i, Array) or isinstance(i, np.ndarray) ): raise IndexError( f"Single-axes index {i} has {type(i)=}, but only " "integers, slices (:), ellipsis (...), newaxis (None), " "zero-dimensional integer arrays and boolean arrays " "are specified in the Array API." ) nonexpanding_key = [] single_axes = [] n_ellipsis = 0 key_has_mask = False for i in _key: if i is not None: nonexpanding_key.append(i) if isinstance(i, Array) or isinstance(i, np.ndarray): if i.dtype in _boolean_dtypes: key_has_mask = True single_axes.append(i) else: # i must not be an array here, to avoid elementwise equals if i == Ellipsis: n_ellipsis += 1 else: single_axes.append(i) n_single_axes = len(single_axes) if n_ellipsis > 1: return # handled by ndarray elif n_ellipsis == 0: # Note boolean masks must be the sole index, which we check for # later on. if not key_has_mask and n_single_axes < self.ndim: raise IndexError( f"{self.ndim=}, but the multi-axes index only specifies " f"{n_single_axes} dimensions. If this was intentional, " "add a trailing ellipsis (...) which expands into as many " "slices (:) as necessary - this is what np.ndarray arrays " "implicitly do, but such flat indexing behaviour is not " "specified in the Array API." ) if n_ellipsis == 0: indexed_shape = self.shape else: ellipsis_start = None for pos, i in enumerate(nonexpanding_key): if not (isinstance(i, Array) or isinstance(i, np.ndarray)): if i == Ellipsis: ellipsis_start = pos break assert ellipsis_start is not None # sanity check ellipsis_end = self.ndim - (n_single_axes - ellipsis_start) indexed_shape = ( self.shape[:ellipsis_start] + self.shape[ellipsis_end:] ) for i, side in zip(single_axes, indexed_shape): if isinstance(i, slice): if side == 0: f_range = "0 (or None)" else: f_range = f"between -{side} and {side - 1} (or None)" if i.start is not None: try: start = operator.index(i.start) except TypeError: pass # handled by ndarray else: if not (-side <= start <= side): raise IndexError( f"Slice {i} contains {start=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds starts are not specified in " "the Array API)" ) if i.stop is not None: try: stop = operator.index(i.stop) except TypeError: pass # handled by ndarray else: if not (-side <= stop <= side): raise IndexError( f"Slice {i} contains {stop=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds stops are not specified in " "the Array API)" ) elif isinstance(i, Array): if i.dtype in _boolean_dtypes and len(_key) != 1: assert isinstance(key, tuple) # sanity check raise IndexError( f"Single-axes index {i} is a boolean array and " f"{len(key)=}, but masking is only specified in the " "Array API when the array is the sole index." ) elif i.dtype in _integer_dtypes and i.ndim != 0: raise IndexError( f"Single-axes index {i} is a non-zero-dimensional " "integer array, but advanced integer indexing is not " "specified in the Array API." ) elif isinstance(i, tuple): raise IndexError( f"Single-axes index {i} is a tuple, but nested tuple " "indices are not specified in the Array API." ) # Everything below this line is required by the spec. def __abs__(self: Array, /) -> Array: """ Performs the operation __abs__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __abs__") res = self._array.__abs__() return self.__class__._new(res) def __add__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __add__. """ other = self._check_allowed_dtypes(other, "numeric", "__add__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__add__(other._array) return self.__class__._new(res) def __and__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __and__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__and__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__and__(other._array) return self.__class__._new(res) def __array_namespace__( self: Array, /, *, api_version: Optional[str] = None ) -> types.ModuleType: if api_version is not None and not api_version.startswith("2021."): raise ValueError(f"Unrecognized array API version: {api_version!r}") return array_api def __bool__(self: Array, /) -> bool: """ Performs the operation __bool__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("bool is only allowed on arrays with 0 dimensions") if self.dtype not in _boolean_dtypes: raise ValueError("bool is only allowed on boolean arrays") res = self._array.__bool__() return res def __dlpack__(self: Array, /, *, stream: None = None) -> PyCapsule: """ Performs the operation __dlpack__. """ return self._array.__dlpack__(stream=stream) def __dlpack_device__(self: Array, /) -> Tuple[IntEnum, int]: """ Performs the operation __dlpack_device__. """ # Note: device support is required for this return self._array.__dlpack_device__() def __eq__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __eq__. """ # Even though "all" dtypes are allowed, we still require them to be # promotable with each other. other = self._check_allowed_dtypes(other, "all", "__eq__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__eq__(other._array) return self.__class__._new(res) def __float__(self: Array, /) -> float: """ Performs the operation __float__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("float is only allowed on arrays with 0 dimensions") if self.dtype not in _floating_dtypes: raise ValueError("float is only allowed on floating-point arrays") res = self._array.__float__() return res def __floordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __floordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__floordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__floordiv__(other._array) return self.__class__._new(res) def __ge__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ge__. """ other = self._check_allowed_dtypes(other, "numeric", "__ge__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ge__(other._array) return self.__class__._new(res) def __getitem__( self: Array, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], /, ) -> Array: """ Performs the operation __getitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array res = self._array.__getitem__(key) return self._new(res) def __gt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __gt__. """ other = self._check_allowed_dtypes(other, "numeric", "__gt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__gt__(other._array) return self.__class__._new(res) def __int__(self: Array, /) -> int: """ Performs the operation __int__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("int is only allowed on arrays with 0 dimensions") if self.dtype not in _integer_dtypes: raise ValueError("int is only allowed on integer arrays") res = self._array.__int__() return res def __index__(self: Array, /) -> int: """ Performs the operation __index__. """ res = self._array.__index__() return res def __invert__(self: Array, /) -> Array: """ Performs the operation __invert__. """ if self.dtype not in _integer_or_boolean_dtypes: raise TypeError("Only integer or boolean dtypes are allowed in __invert__") res = self._array.__invert__() return self.__class__._new(res) def __le__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __le__. """ other = self._check_allowed_dtypes(other, "numeric", "__le__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__le__(other._array) return self.__class__._new(res) def __lshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __lshift__. """ other = self._check_allowed_dtypes(other, "integer", "__lshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lshift__(other._array) return self.__class__._new(res) def __lt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __lt__. """ other = self._check_allowed_dtypes(other, "numeric", "__lt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lt__(other._array) return self.__class__._new(res) def __matmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __matmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__matmul__") if other is NotImplemented: return other res = self._array.__matmul__(other._array) return self.__class__._new(res) def __mod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mod__. """ other = self._check_allowed_dtypes(other, "numeric", "__mod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mod__(other._array) return self.__class__._new(res) def __mul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mul__. """ other = self._check_allowed_dtypes(other, "numeric", "__mul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mul__(other._array) return self.__class__._new(res) def __ne__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __ne__. """ other = self._check_allowed_dtypes(other, "all", "__ne__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ne__(other._array) return self.__class__._new(res) def __neg__(self: Array, /) -> Array: """ Performs the operation __neg__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __neg__") res = self._array.__neg__() return self.__class__._new(res) def __or__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __or__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__or__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__or__(other._array) return self.__class__._new(res) def __pos__(self: Array, /) -> Array: """ Performs the operation __pos__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __pos__") res = self._array.__pos__() return self.__class__._new(res) def __pow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __pow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__pow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow type promotion rules for 0-d # arrays, so we use pow() here instead. return pow(self, other) def __rshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rshift__(other._array) return self.__class__._new(res) def __setitem__( self, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], value: Union[int, float, bool, Array], /, ) -> None: """ Performs the operation __setitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array self._array.__setitem__(key, asarray(value)._array) def __sub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __sub__. """ other = self._check_allowed_dtypes(other, "numeric", "__sub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__sub__(other._array) return self.__class__._new(res) # PEP 484 requires int to be a subtype of float, but __truediv__ should # not accept int. def __truediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __truediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__truediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__truediv__(other._array) return self.__class__._new(res) def __xor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __xor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__xor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__xor__(other._array) return self.__class__._new(res) def __iadd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __iadd__. """ other = self._check_allowed_dtypes(other, "numeric", "__iadd__") if other is NotImplemented: return other self._array.__iadd__(other._array) return self def __radd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __radd__. """ other = self._check_allowed_dtypes(other, "numeric", "__radd__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__radd__(other._array) return self.__class__._new(res) def __iand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __iand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__iand__") if other is NotImplemented: return other self._array.__iand__(other._array) return self def __rand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rand__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rand__(other._array) return self.__class__._new(res) def __ifloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ifloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__ifloordiv__") if other is NotImplemented: return other self._array.__ifloordiv__(other._array) return self def __rfloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rfloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__rfloordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rfloordiv__(other._array) return self.__class__._new(res) def __ilshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __ilshift__. """ other = self._check_allowed_dtypes(other, "integer", "__ilshift__") if other is NotImplemented: return other self._array.__ilshift__(other._array) return self def __rlshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rlshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rlshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rlshift__(other._array) return self.__class__._new(res) def __imatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __imatmul__. """ # Note: NumPy does not implement __imatmul__. # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__imatmul__") if other is NotImplemented: return other # __imatmul__ can only be allowed when it would not change the shape # of self. other_shape = other.shape if self.shape == () or other_shape == (): raise ValueError("@= requires at least one dimension") if len(other_shape) == 1 or other_shape[-1] != other_shape[-2]: raise ValueError("@= cannot change the shape of the input array") self._array[:] = self._array.__matmul__(other._array) return self def __rmatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __rmatmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__rmatmul__") if other is NotImplemented: return other res = self._array.__rmatmul__(other._array) return self.__class__._new(res) def __imod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imod__. """ other = self._check_allowed_dtypes(other, "numeric", "__imod__") if other is NotImplemented: return other self._array.__imod__(other._array) return self def __rmod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmod__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmod__(other._array) return self.__class__._new(res) def __imul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imul__. """ other = self._check_allowed_dtypes(other, "numeric", "__imul__") if other is NotImplemented: return other self._array.__imul__(other._array) return self def __rmul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmul__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmul__(other._array) return self.__class__._new(res) def __ior__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ior__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ior__") if other is NotImplemented: return other self._array.__ior__(other._array) return self def __ror__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ror__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ror__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ror__(other._array) return self.__class__._new(res) def __ipow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ipow__. """ other = self._check_allowed_dtypes(other, "numeric", "__ipow__") if other is NotImplemented: return other self._array.__ipow__(other._array) return self def __rpow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rpow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__rpow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow the spec type promotion rules # for 0-d arrays, so we use pow() here instead. return pow(other, self) def __irshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __irshift__. """ other = self._check_allowed_dtypes(other, "integer", "__irshift__") if other is NotImplemented: return other self._array.__irshift__(other._array) return self def __rrshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rrshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rrshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rrshift__(other._array) return self.__class__._new(res) def __isub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __isub__. """ other = self._check_allowed_dtypes(other, "numeric", "__isub__") if other is NotImplemented: return other self._array.__isub__(other._array) return self def __rsub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rsub__. """ other = self._check_allowed_dtypes(other, "numeric", "__rsub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rsub__(other._array) return self.__class__._new(res) def __itruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __itruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__itruediv__") if other is NotImplemented: return other self._array.__itruediv__(other._array) return self def __rtruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __rtruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__rtruediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rtruediv__(other._array) return self.__class__._new(res) def __ixor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ixor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ixor__") if other is NotImplemented: return other self._array.__ixor__(other._array) return self def __rxor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rxor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rxor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rxor__(other._array) return self.__class__._new(res) def to_device(self: Array, device: Device, /, stream: None = None) -> Array: if stream is not None: raise ValueError("The stream argument to to_device() is not supported") if device == 'cpu': return self raise ValueError(f"Unsupported device {device!r}") def dtype(self) -> Dtype: """ Array API compatible wrapper for :py:meth:`np.ndarray.dtype <numpy.ndarray.dtype>`. See its docstring for more information. """ return self._array.dtype def device(self) -> Device: return "cpu" # Note: mT is new in array API spec (see matrix_transpose) def mT(self) -> Array: from .linalg import matrix_transpose return matrix_transpose(self) def ndim(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.ndim <numpy.ndarray.ndim>`. See its docstring for more information. """ return self._array.ndim def shape(self) -> Tuple[int, ...]: """ Array API compatible wrapper for :py:meth:`np.ndarray.shape <numpy.ndarray.shape>`. See its docstring for more information. """ return self._array.shape def size(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.size <numpy.ndarray.size>`. See its docstring for more information. """ return self._array.size def T(self) -> Array: """ Array API compatible wrapper for :py:meth:`np.ndarray.T <numpy.ndarray.T>`. See its docstring for more information. """ # Note: T only works on 2-dimensional arrays. See the corresponding # note in the specification: # https://data-apis.org/array-api/latest/API_specification/array_object.html#t if self.ndim != 2: raise ValueError("x.T requires x to have 2 dimensions. Use x.mT to transpose stacks of matrices and permute_dims() to permute dimensions.") return self.__class__._new(self._array.T) The provided code snippet includes necessary dependencies for implementing the `bitwise_and` function. Write a Python function `def bitwise_and(x1: Array, x2: Array, /) -> Array` to solve the following problem: Array API compatible wrapper for :py:func:`np.bitwise_and <numpy.bitwise_and>`. See its docstring for more information. Here is the function: def bitwise_and(x1: Array, x2: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.bitwise_and <numpy.bitwise_and>`. See its docstring for more information. """ if ( x1.dtype not in _integer_or_boolean_dtypes or x2.dtype not in _integer_or_boolean_dtypes ): raise TypeError("Only integer or boolean dtypes are allowed in bitwise_and") # Call result type here just to raise on disallowed type combinations _result_type(x1.dtype, x2.dtype) x1, x2 = Array._normalize_two_args(x1, x2) return Array._new(np.bitwise_and(x1._array, x2._array))
Array API compatible wrapper for :py:func:`np.bitwise_and <numpy.bitwise_and>`. See its docstring for more information.
170,029
from __future__ import annotations from ._dtypes import ( _boolean_dtypes, _floating_dtypes, _integer_dtypes, _integer_or_boolean_dtypes, _numeric_dtypes, _result_type, ) from ._array_object import Array import numpy as np _integer_dtypes = (int8, int16, int32, int64, uint8, uint16, uint32, uint64) def _result_type(type1, type2): if (type1, type2) in _promotion_table: return _promotion_table[type1, type2] raise TypeError(f"{type1} and {type2} cannot be type promoted together") class Array: """ n-d array object for the array API namespace. See the docstring of :py:obj:`np.ndarray <numpy.ndarray>` for more information. This is a wrapper around numpy.ndarray that restricts the usage to only those things that are required by the array API namespace. Note, attributes on this object that start with a single underscore are not part of the API specification and should only be used internally. This object should not be constructed directly. Rather, use one of the creation functions, such as asarray(). """ _array: np.ndarray # Use a custom constructor instead of __init__, as manually initializing # this class is not supported API. def _new(cls, x, /): """ This is a private method for initializing the array API Array object. Functions outside of the array_api submodule should not use this method. Use one of the creation functions instead, such as ``asarray``. """ obj = super().__new__(cls) # Note: The spec does not have array scalars, only 0-D arrays. if isinstance(x, np.generic): # Convert the array scalar to a 0-D array x = np.asarray(x) if x.dtype not in _all_dtypes: raise TypeError( f"The array_api namespace does not support the dtype '{x.dtype}'" ) obj._array = x return obj # Prevent Array() from working def __new__(cls, *args, **kwargs): raise TypeError( "The array_api Array object should not be instantiated directly. Use an array creation function, such as asarray(), instead." ) # These functions are not required by the spec, but are implemented for # the sake of usability. def __str__(self: Array, /) -> str: """ Performs the operation __str__. """ return self._array.__str__().replace("array", "Array") def __repr__(self: Array, /) -> str: """ Performs the operation __repr__. """ suffix = f", dtype={self.dtype.name})" if 0 in self.shape: prefix = "empty(" mid = str(self.shape) else: prefix = "Array(" mid = np.array2string(self._array, separator=', ', prefix=prefix, suffix=suffix) return prefix + mid + suffix # This function is not required by the spec, but we implement it here for # convenience so that np.asarray(np.array_api.Array) will work. def __array__(self, dtype: None | np.dtype[Any] = None) -> npt.NDArray[Any]: """ Warning: this method is NOT part of the array API spec. Implementers of other libraries need not include it, and users should not assume it will be present in other implementations. """ return np.asarray(self._array, dtype=dtype) # These are various helper functions to make the array behavior match the # spec in places where it either deviates from or is more strict than # NumPy behavior def _check_allowed_dtypes(self, other: bool | int | float | Array, dtype_category: str, op: str) -> Array: """ Helper function for operators to only allow specific input dtypes Use like other = self._check_allowed_dtypes(other, 'numeric', '__add__') if other is NotImplemented: return other """ if self.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") if isinstance(other, (int, float, bool)): other = self._promote_scalar(other) elif isinstance(other, Array): if other.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") else: return NotImplemented # This will raise TypeError for type combinations that are not allowed # to promote in the spec (even if the NumPy array operator would # promote them). res_dtype = _result_type(self.dtype, other.dtype) if op.startswith("__i"): # Note: NumPy will allow in-place operators in some cases where # the type promoted operator does not match the left-hand side # operand. For example, # >>> a = np.array(1, dtype=np.int8) # >>> a += np.array(1, dtype=np.int16) # The spec explicitly disallows this. if res_dtype != self.dtype: raise TypeError( f"Cannot perform {op} with dtypes {self.dtype} and {other.dtype}" ) return other # Helper function to match the type promotion rules in the spec def _promote_scalar(self, scalar): """ Returns a promoted version of a Python scalar appropriate for use with operations on self. This may raise an OverflowError in cases where the scalar is an integer that is too large to fit in a NumPy integer dtype, or TypeError when the scalar type is incompatible with the dtype of self. """ # Note: Only Python scalar types that match the array dtype are # allowed. if isinstance(scalar, bool): if self.dtype not in _boolean_dtypes: raise TypeError( "Python bool scalars can only be promoted with bool arrays" ) elif isinstance(scalar, int): if self.dtype in _boolean_dtypes: raise TypeError( "Python int scalars cannot be promoted with bool arrays" ) elif isinstance(scalar, float): if self.dtype not in _floating_dtypes: raise TypeError( "Python float scalars can only be promoted with floating-point arrays." ) else: raise TypeError("'scalar' must be a Python scalar") # Note: scalars are unconditionally cast to the same dtype as the # array. # Note: the spec only specifies integer-dtype/int promotion # behavior for integers within the bounds of the integer dtype. # Outside of those bounds we use the default NumPy behavior (either # cast or raise OverflowError). return Array._new(np.array(scalar, self.dtype)) def _normalize_two_args(x1, x2) -> Tuple[Array, Array]: """ Normalize inputs to two arg functions to fix type promotion rules NumPy deviates from the spec type promotion rules in cases where one argument is 0-dimensional and the other is not. For example: >>> import numpy as np >>> a = np.array([1.0], dtype=np.float32) >>> b = np.array(1.0, dtype=np.float64) >>> np.add(a, b) # The spec says this should be float64 array([2.], dtype=float32) To fix this, we add a dimension to the 0-dimension array before passing it through. This works because a dimension would be added anyway from broadcasting, so the resulting shape is the same, but this prevents NumPy from not promoting the dtype. """ # Another option would be to use signature=(x1.dtype, x2.dtype, None), # but that only works for ufuncs, so we would have to call the ufuncs # directly in the operator methods. One should also note that this # sort of trick wouldn't work for functions like searchsorted, which # don't do normal broadcasting, but there aren't any functions like # that in the array API namespace. if x1.ndim == 0 and x2.ndim != 0: # The _array[None] workaround was chosen because it is relatively # performant. broadcast_to(x1._array, x2.shape) is much slower. We # could also manually type promote x2, but that is more complicated # and about the same performance as this. x1 = Array._new(x1._array[None]) elif x2.ndim == 0 and x1.ndim != 0: x2 = Array._new(x2._array[None]) return (x1, x2) # Note: A large fraction of allowed indices are disallowed here (see the # docstring below) def _validate_index(self, key): """ Validate an index according to the array API. The array API specification only requires a subset of indices that are supported by NumPy. This function will reject any index that is allowed by NumPy but not required by the array API specification. We always raise ``IndexError`` on such indices (the spec does not require any specific behavior on them, but this makes the NumPy array API namespace a minimal implementation of the spec). See https://data-apis.org/array-api/latest/API_specification/indexing.html for the full list of required indexing behavior This function raises IndexError if the index ``key`` is invalid. It only raises ``IndexError`` on indices that are not already rejected by NumPy, as NumPy will already raise the appropriate error on such indices. ``shape`` may be None, in which case, only cases that are independent of the array shape are checked. The following cases are allowed by NumPy, but not specified by the array API specification: - Indices to not include an implicit ellipsis at the end. That is, every axis of an array must be explicitly indexed or an ellipsis included. This behaviour is sometimes referred to as flat indexing. - The start and stop of a slice may not be out of bounds. In particular, for a slice ``i:j:k`` on an axis of size ``n``, only the following are allowed: - ``i`` or ``j`` omitted (``None``). - ``-n <= i <= max(0, n - 1)``. - For ``k > 0`` or ``k`` omitted (``None``), ``-n <= j <= n``. - For ``k < 0``, ``-n - 1 <= j <= max(0, n - 1)``. - Boolean array indices are not allowed as part of a larger tuple index. - Integer array indices are not allowed (with the exception of 0-D arrays, which are treated the same as scalars). Additionally, it should be noted that indices that would return a scalar in NumPy will return a 0-D array. Array scalars are not allowed in the specification, only 0-D arrays. This is done in the ``Array._new`` constructor, not this function. """ _key = key if isinstance(key, tuple) else (key,) for i in _key: if isinstance(i, bool) or not ( isinstance(i, SupportsIndex) # i.e. ints or isinstance(i, slice) or i == Ellipsis or i is None or isinstance(i, Array) or isinstance(i, np.ndarray) ): raise IndexError( f"Single-axes index {i} has {type(i)=}, but only " "integers, slices (:), ellipsis (...), newaxis (None), " "zero-dimensional integer arrays and boolean arrays " "are specified in the Array API." ) nonexpanding_key = [] single_axes = [] n_ellipsis = 0 key_has_mask = False for i in _key: if i is not None: nonexpanding_key.append(i) if isinstance(i, Array) or isinstance(i, np.ndarray): if i.dtype in _boolean_dtypes: key_has_mask = True single_axes.append(i) else: # i must not be an array here, to avoid elementwise equals if i == Ellipsis: n_ellipsis += 1 else: single_axes.append(i) n_single_axes = len(single_axes) if n_ellipsis > 1: return # handled by ndarray elif n_ellipsis == 0: # Note boolean masks must be the sole index, which we check for # later on. if not key_has_mask and n_single_axes < self.ndim: raise IndexError( f"{self.ndim=}, but the multi-axes index only specifies " f"{n_single_axes} dimensions. If this was intentional, " "add a trailing ellipsis (...) which expands into as many " "slices (:) as necessary - this is what np.ndarray arrays " "implicitly do, but such flat indexing behaviour is not " "specified in the Array API." ) if n_ellipsis == 0: indexed_shape = self.shape else: ellipsis_start = None for pos, i in enumerate(nonexpanding_key): if not (isinstance(i, Array) or isinstance(i, np.ndarray)): if i == Ellipsis: ellipsis_start = pos break assert ellipsis_start is not None # sanity check ellipsis_end = self.ndim - (n_single_axes - ellipsis_start) indexed_shape = ( self.shape[:ellipsis_start] + self.shape[ellipsis_end:] ) for i, side in zip(single_axes, indexed_shape): if isinstance(i, slice): if side == 0: f_range = "0 (or None)" else: f_range = f"between -{side} and {side - 1} (or None)" if i.start is not None: try: start = operator.index(i.start) except TypeError: pass # handled by ndarray else: if not (-side <= start <= side): raise IndexError( f"Slice {i} contains {start=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds starts are not specified in " "the Array API)" ) if i.stop is not None: try: stop = operator.index(i.stop) except TypeError: pass # handled by ndarray else: if not (-side <= stop <= side): raise IndexError( f"Slice {i} contains {stop=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds stops are not specified in " "the Array API)" ) elif isinstance(i, Array): if i.dtype in _boolean_dtypes and len(_key) != 1: assert isinstance(key, tuple) # sanity check raise IndexError( f"Single-axes index {i} is a boolean array and " f"{len(key)=}, but masking is only specified in the " "Array API when the array is the sole index." ) elif i.dtype in _integer_dtypes and i.ndim != 0: raise IndexError( f"Single-axes index {i} is a non-zero-dimensional " "integer array, but advanced integer indexing is not " "specified in the Array API." ) elif isinstance(i, tuple): raise IndexError( f"Single-axes index {i} is a tuple, but nested tuple " "indices are not specified in the Array API." ) # Everything below this line is required by the spec. def __abs__(self: Array, /) -> Array: """ Performs the operation __abs__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __abs__") res = self._array.__abs__() return self.__class__._new(res) def __add__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __add__. """ other = self._check_allowed_dtypes(other, "numeric", "__add__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__add__(other._array) return self.__class__._new(res) def __and__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __and__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__and__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__and__(other._array) return self.__class__._new(res) def __array_namespace__( self: Array, /, *, api_version: Optional[str] = None ) -> types.ModuleType: if api_version is not None and not api_version.startswith("2021."): raise ValueError(f"Unrecognized array API version: {api_version!r}") return array_api def __bool__(self: Array, /) -> bool: """ Performs the operation __bool__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("bool is only allowed on arrays with 0 dimensions") if self.dtype not in _boolean_dtypes: raise ValueError("bool is only allowed on boolean arrays") res = self._array.__bool__() return res def __dlpack__(self: Array, /, *, stream: None = None) -> PyCapsule: """ Performs the operation __dlpack__. """ return self._array.__dlpack__(stream=stream) def __dlpack_device__(self: Array, /) -> Tuple[IntEnum, int]: """ Performs the operation __dlpack_device__. """ # Note: device support is required for this return self._array.__dlpack_device__() def __eq__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __eq__. """ # Even though "all" dtypes are allowed, we still require them to be # promotable with each other. other = self._check_allowed_dtypes(other, "all", "__eq__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__eq__(other._array) return self.__class__._new(res) def __float__(self: Array, /) -> float: """ Performs the operation __float__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("float is only allowed on arrays with 0 dimensions") if self.dtype not in _floating_dtypes: raise ValueError("float is only allowed on floating-point arrays") res = self._array.__float__() return res def __floordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __floordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__floordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__floordiv__(other._array) return self.__class__._new(res) def __ge__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ge__. """ other = self._check_allowed_dtypes(other, "numeric", "__ge__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ge__(other._array) return self.__class__._new(res) def __getitem__( self: Array, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], /, ) -> Array: """ Performs the operation __getitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array res = self._array.__getitem__(key) return self._new(res) def __gt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __gt__. """ other = self._check_allowed_dtypes(other, "numeric", "__gt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__gt__(other._array) return self.__class__._new(res) def __int__(self: Array, /) -> int: """ Performs the operation __int__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("int is only allowed on arrays with 0 dimensions") if self.dtype not in _integer_dtypes: raise ValueError("int is only allowed on integer arrays") res = self._array.__int__() return res def __index__(self: Array, /) -> int: """ Performs the operation __index__. """ res = self._array.__index__() return res def __invert__(self: Array, /) -> Array: """ Performs the operation __invert__. """ if self.dtype not in _integer_or_boolean_dtypes: raise TypeError("Only integer or boolean dtypes are allowed in __invert__") res = self._array.__invert__() return self.__class__._new(res) def __le__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __le__. """ other = self._check_allowed_dtypes(other, "numeric", "__le__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__le__(other._array) return self.__class__._new(res) def __lshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __lshift__. """ other = self._check_allowed_dtypes(other, "integer", "__lshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lshift__(other._array) return self.__class__._new(res) def __lt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __lt__. """ other = self._check_allowed_dtypes(other, "numeric", "__lt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lt__(other._array) return self.__class__._new(res) def __matmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __matmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__matmul__") if other is NotImplemented: return other res = self._array.__matmul__(other._array) return self.__class__._new(res) def __mod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mod__. """ other = self._check_allowed_dtypes(other, "numeric", "__mod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mod__(other._array) return self.__class__._new(res) def __mul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mul__. """ other = self._check_allowed_dtypes(other, "numeric", "__mul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mul__(other._array) return self.__class__._new(res) def __ne__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __ne__. """ other = self._check_allowed_dtypes(other, "all", "__ne__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ne__(other._array) return self.__class__._new(res) def __neg__(self: Array, /) -> Array: """ Performs the operation __neg__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __neg__") res = self._array.__neg__() return self.__class__._new(res) def __or__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __or__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__or__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__or__(other._array) return self.__class__._new(res) def __pos__(self: Array, /) -> Array: """ Performs the operation __pos__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __pos__") res = self._array.__pos__() return self.__class__._new(res) def __pow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __pow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__pow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow type promotion rules for 0-d # arrays, so we use pow() here instead. return pow(self, other) def __rshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rshift__(other._array) return self.__class__._new(res) def __setitem__( self, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], value: Union[int, float, bool, Array], /, ) -> None: """ Performs the operation __setitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array self._array.__setitem__(key, asarray(value)._array) def __sub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __sub__. """ other = self._check_allowed_dtypes(other, "numeric", "__sub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__sub__(other._array) return self.__class__._new(res) # PEP 484 requires int to be a subtype of float, but __truediv__ should # not accept int. def __truediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __truediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__truediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__truediv__(other._array) return self.__class__._new(res) def __xor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __xor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__xor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__xor__(other._array) return self.__class__._new(res) def __iadd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __iadd__. """ other = self._check_allowed_dtypes(other, "numeric", "__iadd__") if other is NotImplemented: return other self._array.__iadd__(other._array) return self def __radd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __radd__. """ other = self._check_allowed_dtypes(other, "numeric", "__radd__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__radd__(other._array) return self.__class__._new(res) def __iand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __iand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__iand__") if other is NotImplemented: return other self._array.__iand__(other._array) return self def __rand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rand__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rand__(other._array) return self.__class__._new(res) def __ifloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ifloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__ifloordiv__") if other is NotImplemented: return other self._array.__ifloordiv__(other._array) return self def __rfloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rfloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__rfloordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rfloordiv__(other._array) return self.__class__._new(res) def __ilshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __ilshift__. """ other = self._check_allowed_dtypes(other, "integer", "__ilshift__") if other is NotImplemented: return other self._array.__ilshift__(other._array) return self def __rlshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rlshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rlshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rlshift__(other._array) return self.__class__._new(res) def __imatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __imatmul__. """ # Note: NumPy does not implement __imatmul__. # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__imatmul__") if other is NotImplemented: return other # __imatmul__ can only be allowed when it would not change the shape # of self. other_shape = other.shape if self.shape == () or other_shape == (): raise ValueError("@= requires at least one dimension") if len(other_shape) == 1 or other_shape[-1] != other_shape[-2]: raise ValueError("@= cannot change the shape of the input array") self._array[:] = self._array.__matmul__(other._array) return self def __rmatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __rmatmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__rmatmul__") if other is NotImplemented: return other res = self._array.__rmatmul__(other._array) return self.__class__._new(res) def __imod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imod__. """ other = self._check_allowed_dtypes(other, "numeric", "__imod__") if other is NotImplemented: return other self._array.__imod__(other._array) return self def __rmod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmod__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmod__(other._array) return self.__class__._new(res) def __imul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imul__. """ other = self._check_allowed_dtypes(other, "numeric", "__imul__") if other is NotImplemented: return other self._array.__imul__(other._array) return self def __rmul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmul__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmul__(other._array) return self.__class__._new(res) def __ior__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ior__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ior__") if other is NotImplemented: return other self._array.__ior__(other._array) return self def __ror__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ror__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ror__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ror__(other._array) return self.__class__._new(res) def __ipow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ipow__. """ other = self._check_allowed_dtypes(other, "numeric", "__ipow__") if other is NotImplemented: return other self._array.__ipow__(other._array) return self def __rpow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rpow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__rpow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow the spec type promotion rules # for 0-d arrays, so we use pow() here instead. return pow(other, self) def __irshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __irshift__. """ other = self._check_allowed_dtypes(other, "integer", "__irshift__") if other is NotImplemented: return other self._array.__irshift__(other._array) return self def __rrshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rrshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rrshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rrshift__(other._array) return self.__class__._new(res) def __isub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __isub__. """ other = self._check_allowed_dtypes(other, "numeric", "__isub__") if other is NotImplemented: return other self._array.__isub__(other._array) return self def __rsub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rsub__. """ other = self._check_allowed_dtypes(other, "numeric", "__rsub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rsub__(other._array) return self.__class__._new(res) def __itruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __itruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__itruediv__") if other is NotImplemented: return other self._array.__itruediv__(other._array) return self def __rtruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __rtruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__rtruediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rtruediv__(other._array) return self.__class__._new(res) def __ixor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ixor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ixor__") if other is NotImplemented: return other self._array.__ixor__(other._array) return self def __rxor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rxor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rxor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rxor__(other._array) return self.__class__._new(res) def to_device(self: Array, device: Device, /, stream: None = None) -> Array: if stream is not None: raise ValueError("The stream argument to to_device() is not supported") if device == 'cpu': return self raise ValueError(f"Unsupported device {device!r}") def dtype(self) -> Dtype: """ Array API compatible wrapper for :py:meth:`np.ndarray.dtype <numpy.ndarray.dtype>`. See its docstring for more information. """ return self._array.dtype def device(self) -> Device: return "cpu" # Note: mT is new in array API spec (see matrix_transpose) def mT(self) -> Array: from .linalg import matrix_transpose return matrix_transpose(self) def ndim(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.ndim <numpy.ndarray.ndim>`. See its docstring for more information. """ return self._array.ndim def shape(self) -> Tuple[int, ...]: """ Array API compatible wrapper for :py:meth:`np.ndarray.shape <numpy.ndarray.shape>`. See its docstring for more information. """ return self._array.shape def size(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.size <numpy.ndarray.size>`. See its docstring for more information. """ return self._array.size def T(self) -> Array: """ Array API compatible wrapper for :py:meth:`np.ndarray.T <numpy.ndarray.T>`. See its docstring for more information. """ # Note: T only works on 2-dimensional arrays. See the corresponding # note in the specification: # https://data-apis.org/array-api/latest/API_specification/array_object.html#t if self.ndim != 2: raise ValueError("x.T requires x to have 2 dimensions. Use x.mT to transpose stacks of matrices and permute_dims() to permute dimensions.") return self.__class__._new(self._array.T) The provided code snippet includes necessary dependencies for implementing the `bitwise_left_shift` function. Write a Python function `def bitwise_left_shift(x1: Array, x2: Array, /) -> Array` to solve the following problem: Array API compatible wrapper for :py:func:`np.left_shift <numpy.left_shift>`. See its docstring for more information. Here is the function: def bitwise_left_shift(x1: Array, x2: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.left_shift <numpy.left_shift>`. See its docstring for more information. """ if x1.dtype not in _integer_dtypes or x2.dtype not in _integer_dtypes: raise TypeError("Only integer dtypes are allowed in bitwise_left_shift") # Call result type here just to raise on disallowed type combinations _result_type(x1.dtype, x2.dtype) x1, x2 = Array._normalize_two_args(x1, x2) # Note: bitwise_left_shift is only defined for x2 nonnegative. if np.any(x2._array < 0): raise ValueError("bitwise_left_shift(x1, x2) is only defined for x2 >= 0") return Array._new(np.left_shift(x1._array, x2._array))
Array API compatible wrapper for :py:func:`np.left_shift <numpy.left_shift>`. See its docstring for more information.
170,030
from __future__ import annotations from ._dtypes import ( _boolean_dtypes, _floating_dtypes, _integer_dtypes, _integer_or_boolean_dtypes, _numeric_dtypes, _result_type, ) from ._array_object import Array import numpy as np _integer_or_boolean_dtypes = ( bool, int8, int16, int32, int64, uint8, uint16, uint32, uint64, ) class Array: """ n-d array object for the array API namespace. See the docstring of :py:obj:`np.ndarray <numpy.ndarray>` for more information. This is a wrapper around numpy.ndarray that restricts the usage to only those things that are required by the array API namespace. Note, attributes on this object that start with a single underscore are not part of the API specification and should only be used internally. This object should not be constructed directly. Rather, use one of the creation functions, such as asarray(). """ _array: np.ndarray # Use a custom constructor instead of __init__, as manually initializing # this class is not supported API. def _new(cls, x, /): """ This is a private method for initializing the array API Array object. Functions outside of the array_api submodule should not use this method. Use one of the creation functions instead, such as ``asarray``. """ obj = super().__new__(cls) # Note: The spec does not have array scalars, only 0-D arrays. if isinstance(x, np.generic): # Convert the array scalar to a 0-D array x = np.asarray(x) if x.dtype not in _all_dtypes: raise TypeError( f"The array_api namespace does not support the dtype '{x.dtype}'" ) obj._array = x return obj # Prevent Array() from working def __new__(cls, *args, **kwargs): raise TypeError( "The array_api Array object should not be instantiated directly. Use an array creation function, such as asarray(), instead." ) # These functions are not required by the spec, but are implemented for # the sake of usability. def __str__(self: Array, /) -> str: """ Performs the operation __str__. """ return self._array.__str__().replace("array", "Array") def __repr__(self: Array, /) -> str: """ Performs the operation __repr__. """ suffix = f", dtype={self.dtype.name})" if 0 in self.shape: prefix = "empty(" mid = str(self.shape) else: prefix = "Array(" mid = np.array2string(self._array, separator=', ', prefix=prefix, suffix=suffix) return prefix + mid + suffix # This function is not required by the spec, but we implement it here for # convenience so that np.asarray(np.array_api.Array) will work. def __array__(self, dtype: None | np.dtype[Any] = None) -> npt.NDArray[Any]: """ Warning: this method is NOT part of the array API spec. Implementers of other libraries need not include it, and users should not assume it will be present in other implementations. """ return np.asarray(self._array, dtype=dtype) # These are various helper functions to make the array behavior match the # spec in places where it either deviates from or is more strict than # NumPy behavior def _check_allowed_dtypes(self, other: bool | int | float | Array, dtype_category: str, op: str) -> Array: """ Helper function for operators to only allow specific input dtypes Use like other = self._check_allowed_dtypes(other, 'numeric', '__add__') if other is NotImplemented: return other """ if self.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") if isinstance(other, (int, float, bool)): other = self._promote_scalar(other) elif isinstance(other, Array): if other.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") else: return NotImplemented # This will raise TypeError for type combinations that are not allowed # to promote in the spec (even if the NumPy array operator would # promote them). res_dtype = _result_type(self.dtype, other.dtype) if op.startswith("__i"): # Note: NumPy will allow in-place operators in some cases where # the type promoted operator does not match the left-hand side # operand. For example, # >>> a = np.array(1, dtype=np.int8) # >>> a += np.array(1, dtype=np.int16) # The spec explicitly disallows this. if res_dtype != self.dtype: raise TypeError( f"Cannot perform {op} with dtypes {self.dtype} and {other.dtype}" ) return other # Helper function to match the type promotion rules in the spec def _promote_scalar(self, scalar): """ Returns a promoted version of a Python scalar appropriate for use with operations on self. This may raise an OverflowError in cases where the scalar is an integer that is too large to fit in a NumPy integer dtype, or TypeError when the scalar type is incompatible with the dtype of self. """ # Note: Only Python scalar types that match the array dtype are # allowed. if isinstance(scalar, bool): if self.dtype not in _boolean_dtypes: raise TypeError( "Python bool scalars can only be promoted with bool arrays" ) elif isinstance(scalar, int): if self.dtype in _boolean_dtypes: raise TypeError( "Python int scalars cannot be promoted with bool arrays" ) elif isinstance(scalar, float): if self.dtype not in _floating_dtypes: raise TypeError( "Python float scalars can only be promoted with floating-point arrays." ) else: raise TypeError("'scalar' must be a Python scalar") # Note: scalars are unconditionally cast to the same dtype as the # array. # Note: the spec only specifies integer-dtype/int promotion # behavior for integers within the bounds of the integer dtype. # Outside of those bounds we use the default NumPy behavior (either # cast or raise OverflowError). return Array._new(np.array(scalar, self.dtype)) def _normalize_two_args(x1, x2) -> Tuple[Array, Array]: """ Normalize inputs to two arg functions to fix type promotion rules NumPy deviates from the spec type promotion rules in cases where one argument is 0-dimensional and the other is not. For example: >>> import numpy as np >>> a = np.array([1.0], dtype=np.float32) >>> b = np.array(1.0, dtype=np.float64) >>> np.add(a, b) # The spec says this should be float64 array([2.], dtype=float32) To fix this, we add a dimension to the 0-dimension array before passing it through. This works because a dimension would be added anyway from broadcasting, so the resulting shape is the same, but this prevents NumPy from not promoting the dtype. """ # Another option would be to use signature=(x1.dtype, x2.dtype, None), # but that only works for ufuncs, so we would have to call the ufuncs # directly in the operator methods. One should also note that this # sort of trick wouldn't work for functions like searchsorted, which # don't do normal broadcasting, but there aren't any functions like # that in the array API namespace. if x1.ndim == 0 and x2.ndim != 0: # The _array[None] workaround was chosen because it is relatively # performant. broadcast_to(x1._array, x2.shape) is much slower. We # could also manually type promote x2, but that is more complicated # and about the same performance as this. x1 = Array._new(x1._array[None]) elif x2.ndim == 0 and x1.ndim != 0: x2 = Array._new(x2._array[None]) return (x1, x2) # Note: A large fraction of allowed indices are disallowed here (see the # docstring below) def _validate_index(self, key): """ Validate an index according to the array API. The array API specification only requires a subset of indices that are supported by NumPy. This function will reject any index that is allowed by NumPy but not required by the array API specification. We always raise ``IndexError`` on such indices (the spec does not require any specific behavior on them, but this makes the NumPy array API namespace a minimal implementation of the spec). See https://data-apis.org/array-api/latest/API_specification/indexing.html for the full list of required indexing behavior This function raises IndexError if the index ``key`` is invalid. It only raises ``IndexError`` on indices that are not already rejected by NumPy, as NumPy will already raise the appropriate error on such indices. ``shape`` may be None, in which case, only cases that are independent of the array shape are checked. The following cases are allowed by NumPy, but not specified by the array API specification: - Indices to not include an implicit ellipsis at the end. That is, every axis of an array must be explicitly indexed or an ellipsis included. This behaviour is sometimes referred to as flat indexing. - The start and stop of a slice may not be out of bounds. In particular, for a slice ``i:j:k`` on an axis of size ``n``, only the following are allowed: - ``i`` or ``j`` omitted (``None``). - ``-n <= i <= max(0, n - 1)``. - For ``k > 0`` or ``k`` omitted (``None``), ``-n <= j <= n``. - For ``k < 0``, ``-n - 1 <= j <= max(0, n - 1)``. - Boolean array indices are not allowed as part of a larger tuple index. - Integer array indices are not allowed (with the exception of 0-D arrays, which are treated the same as scalars). Additionally, it should be noted that indices that would return a scalar in NumPy will return a 0-D array. Array scalars are not allowed in the specification, only 0-D arrays. This is done in the ``Array._new`` constructor, not this function. """ _key = key if isinstance(key, tuple) else (key,) for i in _key: if isinstance(i, bool) or not ( isinstance(i, SupportsIndex) # i.e. ints or isinstance(i, slice) or i == Ellipsis or i is None or isinstance(i, Array) or isinstance(i, np.ndarray) ): raise IndexError( f"Single-axes index {i} has {type(i)=}, but only " "integers, slices (:), ellipsis (...), newaxis (None), " "zero-dimensional integer arrays and boolean arrays " "are specified in the Array API." ) nonexpanding_key = [] single_axes = [] n_ellipsis = 0 key_has_mask = False for i in _key: if i is not None: nonexpanding_key.append(i) if isinstance(i, Array) or isinstance(i, np.ndarray): if i.dtype in _boolean_dtypes: key_has_mask = True single_axes.append(i) else: # i must not be an array here, to avoid elementwise equals if i == Ellipsis: n_ellipsis += 1 else: single_axes.append(i) n_single_axes = len(single_axes) if n_ellipsis > 1: return # handled by ndarray elif n_ellipsis == 0: # Note boolean masks must be the sole index, which we check for # later on. if not key_has_mask and n_single_axes < self.ndim: raise IndexError( f"{self.ndim=}, but the multi-axes index only specifies " f"{n_single_axes} dimensions. If this was intentional, " "add a trailing ellipsis (...) which expands into as many " "slices (:) as necessary - this is what np.ndarray arrays " "implicitly do, but such flat indexing behaviour is not " "specified in the Array API." ) if n_ellipsis == 0: indexed_shape = self.shape else: ellipsis_start = None for pos, i in enumerate(nonexpanding_key): if not (isinstance(i, Array) or isinstance(i, np.ndarray)): if i == Ellipsis: ellipsis_start = pos break assert ellipsis_start is not None # sanity check ellipsis_end = self.ndim - (n_single_axes - ellipsis_start) indexed_shape = ( self.shape[:ellipsis_start] + self.shape[ellipsis_end:] ) for i, side in zip(single_axes, indexed_shape): if isinstance(i, slice): if side == 0: f_range = "0 (or None)" else: f_range = f"between -{side} and {side - 1} (or None)" if i.start is not None: try: start = operator.index(i.start) except TypeError: pass # handled by ndarray else: if not (-side <= start <= side): raise IndexError( f"Slice {i} contains {start=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds starts are not specified in " "the Array API)" ) if i.stop is not None: try: stop = operator.index(i.stop) except TypeError: pass # handled by ndarray else: if not (-side <= stop <= side): raise IndexError( f"Slice {i} contains {stop=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds stops are not specified in " "the Array API)" ) elif isinstance(i, Array): if i.dtype in _boolean_dtypes and len(_key) != 1: assert isinstance(key, tuple) # sanity check raise IndexError( f"Single-axes index {i} is a boolean array and " f"{len(key)=}, but masking is only specified in the " "Array API when the array is the sole index." ) elif i.dtype in _integer_dtypes and i.ndim != 0: raise IndexError( f"Single-axes index {i} is a non-zero-dimensional " "integer array, but advanced integer indexing is not " "specified in the Array API." ) elif isinstance(i, tuple): raise IndexError( f"Single-axes index {i} is a tuple, but nested tuple " "indices are not specified in the Array API." ) # Everything below this line is required by the spec. def __abs__(self: Array, /) -> Array: """ Performs the operation __abs__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __abs__") res = self._array.__abs__() return self.__class__._new(res) def __add__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __add__. """ other = self._check_allowed_dtypes(other, "numeric", "__add__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__add__(other._array) return self.__class__._new(res) def __and__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __and__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__and__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__and__(other._array) return self.__class__._new(res) def __array_namespace__( self: Array, /, *, api_version: Optional[str] = None ) -> types.ModuleType: if api_version is not None and not api_version.startswith("2021."): raise ValueError(f"Unrecognized array API version: {api_version!r}") return array_api def __bool__(self: Array, /) -> bool: """ Performs the operation __bool__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("bool is only allowed on arrays with 0 dimensions") if self.dtype not in _boolean_dtypes: raise ValueError("bool is only allowed on boolean arrays") res = self._array.__bool__() return res def __dlpack__(self: Array, /, *, stream: None = None) -> PyCapsule: """ Performs the operation __dlpack__. """ return self._array.__dlpack__(stream=stream) def __dlpack_device__(self: Array, /) -> Tuple[IntEnum, int]: """ Performs the operation __dlpack_device__. """ # Note: device support is required for this return self._array.__dlpack_device__() def __eq__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __eq__. """ # Even though "all" dtypes are allowed, we still require them to be # promotable with each other. other = self._check_allowed_dtypes(other, "all", "__eq__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__eq__(other._array) return self.__class__._new(res) def __float__(self: Array, /) -> float: """ Performs the operation __float__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("float is only allowed on arrays with 0 dimensions") if self.dtype not in _floating_dtypes: raise ValueError("float is only allowed on floating-point arrays") res = self._array.__float__() return res def __floordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __floordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__floordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__floordiv__(other._array) return self.__class__._new(res) def __ge__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ge__. """ other = self._check_allowed_dtypes(other, "numeric", "__ge__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ge__(other._array) return self.__class__._new(res) def __getitem__( self: Array, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], /, ) -> Array: """ Performs the operation __getitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array res = self._array.__getitem__(key) return self._new(res) def __gt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __gt__. """ other = self._check_allowed_dtypes(other, "numeric", "__gt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__gt__(other._array) return self.__class__._new(res) def __int__(self: Array, /) -> int: """ Performs the operation __int__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("int is only allowed on arrays with 0 dimensions") if self.dtype not in _integer_dtypes: raise ValueError("int is only allowed on integer arrays") res = self._array.__int__() return res def __index__(self: Array, /) -> int: """ Performs the operation __index__. """ res = self._array.__index__() return res def __invert__(self: Array, /) -> Array: """ Performs the operation __invert__. """ if self.dtype not in _integer_or_boolean_dtypes: raise TypeError("Only integer or boolean dtypes are allowed in __invert__") res = self._array.__invert__() return self.__class__._new(res) def __le__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __le__. """ other = self._check_allowed_dtypes(other, "numeric", "__le__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__le__(other._array) return self.__class__._new(res) def __lshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __lshift__. """ other = self._check_allowed_dtypes(other, "integer", "__lshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lshift__(other._array) return self.__class__._new(res) def __lt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __lt__. """ other = self._check_allowed_dtypes(other, "numeric", "__lt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lt__(other._array) return self.__class__._new(res) def __matmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __matmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__matmul__") if other is NotImplemented: return other res = self._array.__matmul__(other._array) return self.__class__._new(res) def __mod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mod__. """ other = self._check_allowed_dtypes(other, "numeric", "__mod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mod__(other._array) return self.__class__._new(res) def __mul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mul__. """ other = self._check_allowed_dtypes(other, "numeric", "__mul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mul__(other._array) return self.__class__._new(res) def __ne__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __ne__. """ other = self._check_allowed_dtypes(other, "all", "__ne__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ne__(other._array) return self.__class__._new(res) def __neg__(self: Array, /) -> Array: """ Performs the operation __neg__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __neg__") res = self._array.__neg__() return self.__class__._new(res) def __or__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __or__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__or__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__or__(other._array) return self.__class__._new(res) def __pos__(self: Array, /) -> Array: """ Performs the operation __pos__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __pos__") res = self._array.__pos__() return self.__class__._new(res) def __pow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __pow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__pow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow type promotion rules for 0-d # arrays, so we use pow() here instead. return pow(self, other) def __rshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rshift__(other._array) return self.__class__._new(res) def __setitem__( self, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], value: Union[int, float, bool, Array], /, ) -> None: """ Performs the operation __setitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array self._array.__setitem__(key, asarray(value)._array) def __sub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __sub__. """ other = self._check_allowed_dtypes(other, "numeric", "__sub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__sub__(other._array) return self.__class__._new(res) # PEP 484 requires int to be a subtype of float, but __truediv__ should # not accept int. def __truediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __truediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__truediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__truediv__(other._array) return self.__class__._new(res) def __xor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __xor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__xor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__xor__(other._array) return self.__class__._new(res) def __iadd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __iadd__. """ other = self._check_allowed_dtypes(other, "numeric", "__iadd__") if other is NotImplemented: return other self._array.__iadd__(other._array) return self def __radd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __radd__. """ other = self._check_allowed_dtypes(other, "numeric", "__radd__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__radd__(other._array) return self.__class__._new(res) def __iand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __iand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__iand__") if other is NotImplemented: return other self._array.__iand__(other._array) return self def __rand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rand__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rand__(other._array) return self.__class__._new(res) def __ifloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ifloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__ifloordiv__") if other is NotImplemented: return other self._array.__ifloordiv__(other._array) return self def __rfloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rfloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__rfloordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rfloordiv__(other._array) return self.__class__._new(res) def __ilshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __ilshift__. """ other = self._check_allowed_dtypes(other, "integer", "__ilshift__") if other is NotImplemented: return other self._array.__ilshift__(other._array) return self def __rlshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rlshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rlshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rlshift__(other._array) return self.__class__._new(res) def __imatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __imatmul__. """ # Note: NumPy does not implement __imatmul__. # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__imatmul__") if other is NotImplemented: return other # __imatmul__ can only be allowed when it would not change the shape # of self. other_shape = other.shape if self.shape == () or other_shape == (): raise ValueError("@= requires at least one dimension") if len(other_shape) == 1 or other_shape[-1] != other_shape[-2]: raise ValueError("@= cannot change the shape of the input array") self._array[:] = self._array.__matmul__(other._array) return self def __rmatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __rmatmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__rmatmul__") if other is NotImplemented: return other res = self._array.__rmatmul__(other._array) return self.__class__._new(res) def __imod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imod__. """ other = self._check_allowed_dtypes(other, "numeric", "__imod__") if other is NotImplemented: return other self._array.__imod__(other._array) return self def __rmod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmod__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmod__(other._array) return self.__class__._new(res) def __imul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imul__. """ other = self._check_allowed_dtypes(other, "numeric", "__imul__") if other is NotImplemented: return other self._array.__imul__(other._array) return self def __rmul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmul__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmul__(other._array) return self.__class__._new(res) def __ior__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ior__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ior__") if other is NotImplemented: return other self._array.__ior__(other._array) return self def __ror__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ror__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ror__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ror__(other._array) return self.__class__._new(res) def __ipow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ipow__. """ other = self._check_allowed_dtypes(other, "numeric", "__ipow__") if other is NotImplemented: return other self._array.__ipow__(other._array) return self def __rpow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rpow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__rpow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow the spec type promotion rules # for 0-d arrays, so we use pow() here instead. return pow(other, self) def __irshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __irshift__. """ other = self._check_allowed_dtypes(other, "integer", "__irshift__") if other is NotImplemented: return other self._array.__irshift__(other._array) return self def __rrshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rrshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rrshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rrshift__(other._array) return self.__class__._new(res) def __isub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __isub__. """ other = self._check_allowed_dtypes(other, "numeric", "__isub__") if other is NotImplemented: return other self._array.__isub__(other._array) return self def __rsub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rsub__. """ other = self._check_allowed_dtypes(other, "numeric", "__rsub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rsub__(other._array) return self.__class__._new(res) def __itruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __itruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__itruediv__") if other is NotImplemented: return other self._array.__itruediv__(other._array) return self def __rtruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __rtruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__rtruediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rtruediv__(other._array) return self.__class__._new(res) def __ixor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ixor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ixor__") if other is NotImplemented: return other self._array.__ixor__(other._array) return self def __rxor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rxor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rxor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rxor__(other._array) return self.__class__._new(res) def to_device(self: Array, device: Device, /, stream: None = None) -> Array: if stream is not None: raise ValueError("The stream argument to to_device() is not supported") if device == 'cpu': return self raise ValueError(f"Unsupported device {device!r}") def dtype(self) -> Dtype: """ Array API compatible wrapper for :py:meth:`np.ndarray.dtype <numpy.ndarray.dtype>`. See its docstring for more information. """ return self._array.dtype def device(self) -> Device: return "cpu" # Note: mT is new in array API spec (see matrix_transpose) def mT(self) -> Array: from .linalg import matrix_transpose return matrix_transpose(self) def ndim(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.ndim <numpy.ndarray.ndim>`. See its docstring for more information. """ return self._array.ndim def shape(self) -> Tuple[int, ...]: """ Array API compatible wrapper for :py:meth:`np.ndarray.shape <numpy.ndarray.shape>`. See its docstring for more information. """ return self._array.shape def size(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.size <numpy.ndarray.size>`. See its docstring for more information. """ return self._array.size def T(self) -> Array: """ Array API compatible wrapper for :py:meth:`np.ndarray.T <numpy.ndarray.T>`. See its docstring for more information. """ # Note: T only works on 2-dimensional arrays. See the corresponding # note in the specification: # https://data-apis.org/array-api/latest/API_specification/array_object.html#t if self.ndim != 2: raise ValueError("x.T requires x to have 2 dimensions. Use x.mT to transpose stacks of matrices and permute_dims() to permute dimensions.") return self.__class__._new(self._array.T) The provided code snippet includes necessary dependencies for implementing the `bitwise_invert` function. Write a Python function `def bitwise_invert(x: Array, /) -> Array` to solve the following problem: Array API compatible wrapper for :py:func:`np.invert <numpy.invert>`. See its docstring for more information. Here is the function: def bitwise_invert(x: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.invert <numpy.invert>`. See its docstring for more information. """ if x.dtype not in _integer_or_boolean_dtypes: raise TypeError("Only integer or boolean dtypes are allowed in bitwise_invert") return Array._new(np.invert(x._array))
Array API compatible wrapper for :py:func:`np.invert <numpy.invert>`. See its docstring for more information.
170,031
from __future__ import annotations from ._dtypes import ( _boolean_dtypes, _floating_dtypes, _integer_dtypes, _integer_or_boolean_dtypes, _numeric_dtypes, _result_type, ) from ._array_object import Array import numpy as np _integer_or_boolean_dtypes = ( bool, int8, int16, int32, int64, uint8, uint16, uint32, uint64, ) def _result_type(type1, type2): if (type1, type2) in _promotion_table: return _promotion_table[type1, type2] raise TypeError(f"{type1} and {type2} cannot be type promoted together") class Array: """ n-d array object for the array API namespace. See the docstring of :py:obj:`np.ndarray <numpy.ndarray>` for more information. This is a wrapper around numpy.ndarray that restricts the usage to only those things that are required by the array API namespace. Note, attributes on this object that start with a single underscore are not part of the API specification and should only be used internally. This object should not be constructed directly. Rather, use one of the creation functions, such as asarray(). """ _array: np.ndarray # Use a custom constructor instead of __init__, as manually initializing # this class is not supported API. def _new(cls, x, /): """ This is a private method for initializing the array API Array object. Functions outside of the array_api submodule should not use this method. Use one of the creation functions instead, such as ``asarray``. """ obj = super().__new__(cls) # Note: The spec does not have array scalars, only 0-D arrays. if isinstance(x, np.generic): # Convert the array scalar to a 0-D array x = np.asarray(x) if x.dtype not in _all_dtypes: raise TypeError( f"The array_api namespace does not support the dtype '{x.dtype}'" ) obj._array = x return obj # Prevent Array() from working def __new__(cls, *args, **kwargs): raise TypeError( "The array_api Array object should not be instantiated directly. Use an array creation function, such as asarray(), instead." ) # These functions are not required by the spec, but are implemented for # the sake of usability. def __str__(self: Array, /) -> str: """ Performs the operation __str__. """ return self._array.__str__().replace("array", "Array") def __repr__(self: Array, /) -> str: """ Performs the operation __repr__. """ suffix = f", dtype={self.dtype.name})" if 0 in self.shape: prefix = "empty(" mid = str(self.shape) else: prefix = "Array(" mid = np.array2string(self._array, separator=', ', prefix=prefix, suffix=suffix) return prefix + mid + suffix # This function is not required by the spec, but we implement it here for # convenience so that np.asarray(np.array_api.Array) will work. def __array__(self, dtype: None | np.dtype[Any] = None) -> npt.NDArray[Any]: """ Warning: this method is NOT part of the array API spec. Implementers of other libraries need not include it, and users should not assume it will be present in other implementations. """ return np.asarray(self._array, dtype=dtype) # These are various helper functions to make the array behavior match the # spec in places where it either deviates from or is more strict than # NumPy behavior def _check_allowed_dtypes(self, other: bool | int | float | Array, dtype_category: str, op: str) -> Array: """ Helper function for operators to only allow specific input dtypes Use like other = self._check_allowed_dtypes(other, 'numeric', '__add__') if other is NotImplemented: return other """ if self.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") if isinstance(other, (int, float, bool)): other = self._promote_scalar(other) elif isinstance(other, Array): if other.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") else: return NotImplemented # This will raise TypeError for type combinations that are not allowed # to promote in the spec (even if the NumPy array operator would # promote them). res_dtype = _result_type(self.dtype, other.dtype) if op.startswith("__i"): # Note: NumPy will allow in-place operators in some cases where # the type promoted operator does not match the left-hand side # operand. For example, # >>> a = np.array(1, dtype=np.int8) # >>> a += np.array(1, dtype=np.int16) # The spec explicitly disallows this. if res_dtype != self.dtype: raise TypeError( f"Cannot perform {op} with dtypes {self.dtype} and {other.dtype}" ) return other # Helper function to match the type promotion rules in the spec def _promote_scalar(self, scalar): """ Returns a promoted version of a Python scalar appropriate for use with operations on self. This may raise an OverflowError in cases where the scalar is an integer that is too large to fit in a NumPy integer dtype, or TypeError when the scalar type is incompatible with the dtype of self. """ # Note: Only Python scalar types that match the array dtype are # allowed. if isinstance(scalar, bool): if self.dtype not in _boolean_dtypes: raise TypeError( "Python bool scalars can only be promoted with bool arrays" ) elif isinstance(scalar, int): if self.dtype in _boolean_dtypes: raise TypeError( "Python int scalars cannot be promoted with bool arrays" ) elif isinstance(scalar, float): if self.dtype not in _floating_dtypes: raise TypeError( "Python float scalars can only be promoted with floating-point arrays." ) else: raise TypeError("'scalar' must be a Python scalar") # Note: scalars are unconditionally cast to the same dtype as the # array. # Note: the spec only specifies integer-dtype/int promotion # behavior for integers within the bounds of the integer dtype. # Outside of those bounds we use the default NumPy behavior (either # cast or raise OverflowError). return Array._new(np.array(scalar, self.dtype)) def _normalize_two_args(x1, x2) -> Tuple[Array, Array]: """ Normalize inputs to two arg functions to fix type promotion rules NumPy deviates from the spec type promotion rules in cases where one argument is 0-dimensional and the other is not. For example: >>> import numpy as np >>> a = np.array([1.0], dtype=np.float32) >>> b = np.array(1.0, dtype=np.float64) >>> np.add(a, b) # The spec says this should be float64 array([2.], dtype=float32) To fix this, we add a dimension to the 0-dimension array before passing it through. This works because a dimension would be added anyway from broadcasting, so the resulting shape is the same, but this prevents NumPy from not promoting the dtype. """ # Another option would be to use signature=(x1.dtype, x2.dtype, None), # but that only works for ufuncs, so we would have to call the ufuncs # directly in the operator methods. One should also note that this # sort of trick wouldn't work for functions like searchsorted, which # don't do normal broadcasting, but there aren't any functions like # that in the array API namespace. if x1.ndim == 0 and x2.ndim != 0: # The _array[None] workaround was chosen because it is relatively # performant. broadcast_to(x1._array, x2.shape) is much slower. We # could also manually type promote x2, but that is more complicated # and about the same performance as this. x1 = Array._new(x1._array[None]) elif x2.ndim == 0 and x1.ndim != 0: x2 = Array._new(x2._array[None]) return (x1, x2) # Note: A large fraction of allowed indices are disallowed here (see the # docstring below) def _validate_index(self, key): """ Validate an index according to the array API. The array API specification only requires a subset of indices that are supported by NumPy. This function will reject any index that is allowed by NumPy but not required by the array API specification. We always raise ``IndexError`` on such indices (the spec does not require any specific behavior on them, but this makes the NumPy array API namespace a minimal implementation of the spec). See https://data-apis.org/array-api/latest/API_specification/indexing.html for the full list of required indexing behavior This function raises IndexError if the index ``key`` is invalid. It only raises ``IndexError`` on indices that are not already rejected by NumPy, as NumPy will already raise the appropriate error on such indices. ``shape`` may be None, in which case, only cases that are independent of the array shape are checked. The following cases are allowed by NumPy, but not specified by the array API specification: - Indices to not include an implicit ellipsis at the end. That is, every axis of an array must be explicitly indexed or an ellipsis included. This behaviour is sometimes referred to as flat indexing. - The start and stop of a slice may not be out of bounds. In particular, for a slice ``i:j:k`` on an axis of size ``n``, only the following are allowed: - ``i`` or ``j`` omitted (``None``). - ``-n <= i <= max(0, n - 1)``. - For ``k > 0`` or ``k`` omitted (``None``), ``-n <= j <= n``. - For ``k < 0``, ``-n - 1 <= j <= max(0, n - 1)``. - Boolean array indices are not allowed as part of a larger tuple index. - Integer array indices are not allowed (with the exception of 0-D arrays, which are treated the same as scalars). Additionally, it should be noted that indices that would return a scalar in NumPy will return a 0-D array. Array scalars are not allowed in the specification, only 0-D arrays. This is done in the ``Array._new`` constructor, not this function. """ _key = key if isinstance(key, tuple) else (key,) for i in _key: if isinstance(i, bool) or not ( isinstance(i, SupportsIndex) # i.e. ints or isinstance(i, slice) or i == Ellipsis or i is None or isinstance(i, Array) or isinstance(i, np.ndarray) ): raise IndexError( f"Single-axes index {i} has {type(i)=}, but only " "integers, slices (:), ellipsis (...), newaxis (None), " "zero-dimensional integer arrays and boolean arrays " "are specified in the Array API." ) nonexpanding_key = [] single_axes = [] n_ellipsis = 0 key_has_mask = False for i in _key: if i is not None: nonexpanding_key.append(i) if isinstance(i, Array) or isinstance(i, np.ndarray): if i.dtype in _boolean_dtypes: key_has_mask = True single_axes.append(i) else: # i must not be an array here, to avoid elementwise equals if i == Ellipsis: n_ellipsis += 1 else: single_axes.append(i) n_single_axes = len(single_axes) if n_ellipsis > 1: return # handled by ndarray elif n_ellipsis == 0: # Note boolean masks must be the sole index, which we check for # later on. if not key_has_mask and n_single_axes < self.ndim: raise IndexError( f"{self.ndim=}, but the multi-axes index only specifies " f"{n_single_axes} dimensions. If this was intentional, " "add a trailing ellipsis (...) which expands into as many " "slices (:) as necessary - this is what np.ndarray arrays " "implicitly do, but such flat indexing behaviour is not " "specified in the Array API." ) if n_ellipsis == 0: indexed_shape = self.shape else: ellipsis_start = None for pos, i in enumerate(nonexpanding_key): if not (isinstance(i, Array) or isinstance(i, np.ndarray)): if i == Ellipsis: ellipsis_start = pos break assert ellipsis_start is not None # sanity check ellipsis_end = self.ndim - (n_single_axes - ellipsis_start) indexed_shape = ( self.shape[:ellipsis_start] + self.shape[ellipsis_end:] ) for i, side in zip(single_axes, indexed_shape): if isinstance(i, slice): if side == 0: f_range = "0 (or None)" else: f_range = f"between -{side} and {side - 1} (or None)" if i.start is not None: try: start = operator.index(i.start) except TypeError: pass # handled by ndarray else: if not (-side <= start <= side): raise IndexError( f"Slice {i} contains {start=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds starts are not specified in " "the Array API)" ) if i.stop is not None: try: stop = operator.index(i.stop) except TypeError: pass # handled by ndarray else: if not (-side <= stop <= side): raise IndexError( f"Slice {i} contains {stop=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds stops are not specified in " "the Array API)" ) elif isinstance(i, Array): if i.dtype in _boolean_dtypes and len(_key) != 1: assert isinstance(key, tuple) # sanity check raise IndexError( f"Single-axes index {i} is a boolean array and " f"{len(key)=}, but masking is only specified in the " "Array API when the array is the sole index." ) elif i.dtype in _integer_dtypes and i.ndim != 0: raise IndexError( f"Single-axes index {i} is a non-zero-dimensional " "integer array, but advanced integer indexing is not " "specified in the Array API." ) elif isinstance(i, tuple): raise IndexError( f"Single-axes index {i} is a tuple, but nested tuple " "indices are not specified in the Array API." ) # Everything below this line is required by the spec. def __abs__(self: Array, /) -> Array: """ Performs the operation __abs__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __abs__") res = self._array.__abs__() return self.__class__._new(res) def __add__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __add__. """ other = self._check_allowed_dtypes(other, "numeric", "__add__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__add__(other._array) return self.__class__._new(res) def __and__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __and__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__and__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__and__(other._array) return self.__class__._new(res) def __array_namespace__( self: Array, /, *, api_version: Optional[str] = None ) -> types.ModuleType: if api_version is not None and not api_version.startswith("2021."): raise ValueError(f"Unrecognized array API version: {api_version!r}") return array_api def __bool__(self: Array, /) -> bool: """ Performs the operation __bool__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("bool is only allowed on arrays with 0 dimensions") if self.dtype not in _boolean_dtypes: raise ValueError("bool is only allowed on boolean arrays") res = self._array.__bool__() return res def __dlpack__(self: Array, /, *, stream: None = None) -> PyCapsule: """ Performs the operation __dlpack__. """ return self._array.__dlpack__(stream=stream) def __dlpack_device__(self: Array, /) -> Tuple[IntEnum, int]: """ Performs the operation __dlpack_device__. """ # Note: device support is required for this return self._array.__dlpack_device__() def __eq__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __eq__. """ # Even though "all" dtypes are allowed, we still require them to be # promotable with each other. other = self._check_allowed_dtypes(other, "all", "__eq__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__eq__(other._array) return self.__class__._new(res) def __float__(self: Array, /) -> float: """ Performs the operation __float__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("float is only allowed on arrays with 0 dimensions") if self.dtype not in _floating_dtypes: raise ValueError("float is only allowed on floating-point arrays") res = self._array.__float__() return res def __floordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __floordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__floordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__floordiv__(other._array) return self.__class__._new(res) def __ge__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ge__. """ other = self._check_allowed_dtypes(other, "numeric", "__ge__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ge__(other._array) return self.__class__._new(res) def __getitem__( self: Array, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], /, ) -> Array: """ Performs the operation __getitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array res = self._array.__getitem__(key) return self._new(res) def __gt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __gt__. """ other = self._check_allowed_dtypes(other, "numeric", "__gt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__gt__(other._array) return self.__class__._new(res) def __int__(self: Array, /) -> int: """ Performs the operation __int__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("int is only allowed on arrays with 0 dimensions") if self.dtype not in _integer_dtypes: raise ValueError("int is only allowed on integer arrays") res = self._array.__int__() return res def __index__(self: Array, /) -> int: """ Performs the operation __index__. """ res = self._array.__index__() return res def __invert__(self: Array, /) -> Array: """ Performs the operation __invert__. """ if self.dtype not in _integer_or_boolean_dtypes: raise TypeError("Only integer or boolean dtypes are allowed in __invert__") res = self._array.__invert__() return self.__class__._new(res) def __le__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __le__. """ other = self._check_allowed_dtypes(other, "numeric", "__le__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__le__(other._array) return self.__class__._new(res) def __lshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __lshift__. """ other = self._check_allowed_dtypes(other, "integer", "__lshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lshift__(other._array) return self.__class__._new(res) def __lt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __lt__. """ other = self._check_allowed_dtypes(other, "numeric", "__lt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lt__(other._array) return self.__class__._new(res) def __matmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __matmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__matmul__") if other is NotImplemented: return other res = self._array.__matmul__(other._array) return self.__class__._new(res) def __mod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mod__. """ other = self._check_allowed_dtypes(other, "numeric", "__mod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mod__(other._array) return self.__class__._new(res) def __mul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mul__. """ other = self._check_allowed_dtypes(other, "numeric", "__mul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mul__(other._array) return self.__class__._new(res) def __ne__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __ne__. """ other = self._check_allowed_dtypes(other, "all", "__ne__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ne__(other._array) return self.__class__._new(res) def __neg__(self: Array, /) -> Array: """ Performs the operation __neg__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __neg__") res = self._array.__neg__() return self.__class__._new(res) def __or__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __or__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__or__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__or__(other._array) return self.__class__._new(res) def __pos__(self: Array, /) -> Array: """ Performs the operation __pos__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __pos__") res = self._array.__pos__() return self.__class__._new(res) def __pow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __pow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__pow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow type promotion rules for 0-d # arrays, so we use pow() here instead. return pow(self, other) def __rshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rshift__(other._array) return self.__class__._new(res) def __setitem__( self, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], value: Union[int, float, bool, Array], /, ) -> None: """ Performs the operation __setitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array self._array.__setitem__(key, asarray(value)._array) def __sub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __sub__. """ other = self._check_allowed_dtypes(other, "numeric", "__sub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__sub__(other._array) return self.__class__._new(res) # PEP 484 requires int to be a subtype of float, but __truediv__ should # not accept int. def __truediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __truediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__truediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__truediv__(other._array) return self.__class__._new(res) def __xor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __xor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__xor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__xor__(other._array) return self.__class__._new(res) def __iadd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __iadd__. """ other = self._check_allowed_dtypes(other, "numeric", "__iadd__") if other is NotImplemented: return other self._array.__iadd__(other._array) return self def __radd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __radd__. """ other = self._check_allowed_dtypes(other, "numeric", "__radd__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__radd__(other._array) return self.__class__._new(res) def __iand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __iand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__iand__") if other is NotImplemented: return other self._array.__iand__(other._array) return self def __rand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rand__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rand__(other._array) return self.__class__._new(res) def __ifloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ifloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__ifloordiv__") if other is NotImplemented: return other self._array.__ifloordiv__(other._array) return self def __rfloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rfloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__rfloordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rfloordiv__(other._array) return self.__class__._new(res) def __ilshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __ilshift__. """ other = self._check_allowed_dtypes(other, "integer", "__ilshift__") if other is NotImplemented: return other self._array.__ilshift__(other._array) return self def __rlshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rlshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rlshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rlshift__(other._array) return self.__class__._new(res) def __imatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __imatmul__. """ # Note: NumPy does not implement __imatmul__. # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__imatmul__") if other is NotImplemented: return other # __imatmul__ can only be allowed when it would not change the shape # of self. other_shape = other.shape if self.shape == () or other_shape == (): raise ValueError("@= requires at least one dimension") if len(other_shape) == 1 or other_shape[-1] != other_shape[-2]: raise ValueError("@= cannot change the shape of the input array") self._array[:] = self._array.__matmul__(other._array) return self def __rmatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __rmatmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__rmatmul__") if other is NotImplemented: return other res = self._array.__rmatmul__(other._array) return self.__class__._new(res) def __imod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imod__. """ other = self._check_allowed_dtypes(other, "numeric", "__imod__") if other is NotImplemented: return other self._array.__imod__(other._array) return self def __rmod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmod__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmod__(other._array) return self.__class__._new(res) def __imul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imul__. """ other = self._check_allowed_dtypes(other, "numeric", "__imul__") if other is NotImplemented: return other self._array.__imul__(other._array) return self def __rmul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmul__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmul__(other._array) return self.__class__._new(res) def __ior__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ior__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ior__") if other is NotImplemented: return other self._array.__ior__(other._array) return self def __ror__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ror__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ror__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ror__(other._array) return self.__class__._new(res) def __ipow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ipow__. """ other = self._check_allowed_dtypes(other, "numeric", "__ipow__") if other is NotImplemented: return other self._array.__ipow__(other._array) return self def __rpow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rpow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__rpow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow the spec type promotion rules # for 0-d arrays, so we use pow() here instead. return pow(other, self) def __irshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __irshift__. """ other = self._check_allowed_dtypes(other, "integer", "__irshift__") if other is NotImplemented: return other self._array.__irshift__(other._array) return self def __rrshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rrshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rrshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rrshift__(other._array) return self.__class__._new(res) def __isub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __isub__. """ other = self._check_allowed_dtypes(other, "numeric", "__isub__") if other is NotImplemented: return other self._array.__isub__(other._array) return self def __rsub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rsub__. """ other = self._check_allowed_dtypes(other, "numeric", "__rsub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rsub__(other._array) return self.__class__._new(res) def __itruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __itruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__itruediv__") if other is NotImplemented: return other self._array.__itruediv__(other._array) return self def __rtruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __rtruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__rtruediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rtruediv__(other._array) return self.__class__._new(res) def __ixor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ixor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ixor__") if other is NotImplemented: return other self._array.__ixor__(other._array) return self def __rxor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rxor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rxor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rxor__(other._array) return self.__class__._new(res) def to_device(self: Array, device: Device, /, stream: None = None) -> Array: if stream is not None: raise ValueError("The stream argument to to_device() is not supported") if device == 'cpu': return self raise ValueError(f"Unsupported device {device!r}") def dtype(self) -> Dtype: """ Array API compatible wrapper for :py:meth:`np.ndarray.dtype <numpy.ndarray.dtype>`. See its docstring for more information. """ return self._array.dtype def device(self) -> Device: return "cpu" # Note: mT is new in array API spec (see matrix_transpose) def mT(self) -> Array: from .linalg import matrix_transpose return matrix_transpose(self) def ndim(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.ndim <numpy.ndarray.ndim>`. See its docstring for more information. """ return self._array.ndim def shape(self) -> Tuple[int, ...]: """ Array API compatible wrapper for :py:meth:`np.ndarray.shape <numpy.ndarray.shape>`. See its docstring for more information. """ return self._array.shape def size(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.size <numpy.ndarray.size>`. See its docstring for more information. """ return self._array.size def T(self) -> Array: """ Array API compatible wrapper for :py:meth:`np.ndarray.T <numpy.ndarray.T>`. See its docstring for more information. """ # Note: T only works on 2-dimensional arrays. See the corresponding # note in the specification: # https://data-apis.org/array-api/latest/API_specification/array_object.html#t if self.ndim != 2: raise ValueError("x.T requires x to have 2 dimensions. Use x.mT to transpose stacks of matrices and permute_dims() to permute dimensions.") return self.__class__._new(self._array.T) The provided code snippet includes necessary dependencies for implementing the `bitwise_or` function. Write a Python function `def bitwise_or(x1: Array, x2: Array, /) -> Array` to solve the following problem: Array API compatible wrapper for :py:func:`np.bitwise_or <numpy.bitwise_or>`. See its docstring for more information. Here is the function: def bitwise_or(x1: Array, x2: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.bitwise_or <numpy.bitwise_or>`. See its docstring for more information. """ if ( x1.dtype not in _integer_or_boolean_dtypes or x2.dtype not in _integer_or_boolean_dtypes ): raise TypeError("Only integer or boolean dtypes are allowed in bitwise_or") # Call result type here just to raise on disallowed type combinations _result_type(x1.dtype, x2.dtype) x1, x2 = Array._normalize_two_args(x1, x2) return Array._new(np.bitwise_or(x1._array, x2._array))
Array API compatible wrapper for :py:func:`np.bitwise_or <numpy.bitwise_or>`. See its docstring for more information.
170,032
from __future__ import annotations from ._dtypes import ( _boolean_dtypes, _floating_dtypes, _integer_dtypes, _integer_or_boolean_dtypes, _numeric_dtypes, _result_type, ) from ._array_object import Array import numpy as np _integer_dtypes = (int8, int16, int32, int64, uint8, uint16, uint32, uint64) def _result_type(type1, type2): if (type1, type2) in _promotion_table: return _promotion_table[type1, type2] raise TypeError(f"{type1} and {type2} cannot be type promoted together") class Array: """ n-d array object for the array API namespace. See the docstring of :py:obj:`np.ndarray <numpy.ndarray>` for more information. This is a wrapper around numpy.ndarray that restricts the usage to only those things that are required by the array API namespace. Note, attributes on this object that start with a single underscore are not part of the API specification and should only be used internally. This object should not be constructed directly. Rather, use one of the creation functions, such as asarray(). """ _array: np.ndarray # Use a custom constructor instead of __init__, as manually initializing # this class is not supported API. def _new(cls, x, /): """ This is a private method for initializing the array API Array object. Functions outside of the array_api submodule should not use this method. Use one of the creation functions instead, such as ``asarray``. """ obj = super().__new__(cls) # Note: The spec does not have array scalars, only 0-D arrays. if isinstance(x, np.generic): # Convert the array scalar to a 0-D array x = np.asarray(x) if x.dtype not in _all_dtypes: raise TypeError( f"The array_api namespace does not support the dtype '{x.dtype}'" ) obj._array = x return obj # Prevent Array() from working def __new__(cls, *args, **kwargs): raise TypeError( "The array_api Array object should not be instantiated directly. Use an array creation function, such as asarray(), instead." ) # These functions are not required by the spec, but are implemented for # the sake of usability. def __str__(self: Array, /) -> str: """ Performs the operation __str__. """ return self._array.__str__().replace("array", "Array") def __repr__(self: Array, /) -> str: """ Performs the operation __repr__. """ suffix = f", dtype={self.dtype.name})" if 0 in self.shape: prefix = "empty(" mid = str(self.shape) else: prefix = "Array(" mid = np.array2string(self._array, separator=', ', prefix=prefix, suffix=suffix) return prefix + mid + suffix # This function is not required by the spec, but we implement it here for # convenience so that np.asarray(np.array_api.Array) will work. def __array__(self, dtype: None | np.dtype[Any] = None) -> npt.NDArray[Any]: """ Warning: this method is NOT part of the array API spec. Implementers of other libraries need not include it, and users should not assume it will be present in other implementations. """ return np.asarray(self._array, dtype=dtype) # These are various helper functions to make the array behavior match the # spec in places where it either deviates from or is more strict than # NumPy behavior def _check_allowed_dtypes(self, other: bool | int | float | Array, dtype_category: str, op: str) -> Array: """ Helper function for operators to only allow specific input dtypes Use like other = self._check_allowed_dtypes(other, 'numeric', '__add__') if other is NotImplemented: return other """ if self.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") if isinstance(other, (int, float, bool)): other = self._promote_scalar(other) elif isinstance(other, Array): if other.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") else: return NotImplemented # This will raise TypeError for type combinations that are not allowed # to promote in the spec (even if the NumPy array operator would # promote them). res_dtype = _result_type(self.dtype, other.dtype) if op.startswith("__i"): # Note: NumPy will allow in-place operators in some cases where # the type promoted operator does not match the left-hand side # operand. For example, # >>> a = np.array(1, dtype=np.int8) # >>> a += np.array(1, dtype=np.int16) # The spec explicitly disallows this. if res_dtype != self.dtype: raise TypeError( f"Cannot perform {op} with dtypes {self.dtype} and {other.dtype}" ) return other # Helper function to match the type promotion rules in the spec def _promote_scalar(self, scalar): """ Returns a promoted version of a Python scalar appropriate for use with operations on self. This may raise an OverflowError in cases where the scalar is an integer that is too large to fit in a NumPy integer dtype, or TypeError when the scalar type is incompatible with the dtype of self. """ # Note: Only Python scalar types that match the array dtype are # allowed. if isinstance(scalar, bool): if self.dtype not in _boolean_dtypes: raise TypeError( "Python bool scalars can only be promoted with bool arrays" ) elif isinstance(scalar, int): if self.dtype in _boolean_dtypes: raise TypeError( "Python int scalars cannot be promoted with bool arrays" ) elif isinstance(scalar, float): if self.dtype not in _floating_dtypes: raise TypeError( "Python float scalars can only be promoted with floating-point arrays." ) else: raise TypeError("'scalar' must be a Python scalar") # Note: scalars are unconditionally cast to the same dtype as the # array. # Note: the spec only specifies integer-dtype/int promotion # behavior for integers within the bounds of the integer dtype. # Outside of those bounds we use the default NumPy behavior (either # cast or raise OverflowError). return Array._new(np.array(scalar, self.dtype)) def _normalize_two_args(x1, x2) -> Tuple[Array, Array]: """ Normalize inputs to two arg functions to fix type promotion rules NumPy deviates from the spec type promotion rules in cases where one argument is 0-dimensional and the other is not. For example: >>> import numpy as np >>> a = np.array([1.0], dtype=np.float32) >>> b = np.array(1.0, dtype=np.float64) >>> np.add(a, b) # The spec says this should be float64 array([2.], dtype=float32) To fix this, we add a dimension to the 0-dimension array before passing it through. This works because a dimension would be added anyway from broadcasting, so the resulting shape is the same, but this prevents NumPy from not promoting the dtype. """ # Another option would be to use signature=(x1.dtype, x2.dtype, None), # but that only works for ufuncs, so we would have to call the ufuncs # directly in the operator methods. One should also note that this # sort of trick wouldn't work for functions like searchsorted, which # don't do normal broadcasting, but there aren't any functions like # that in the array API namespace. if x1.ndim == 0 and x2.ndim != 0: # The _array[None] workaround was chosen because it is relatively # performant. broadcast_to(x1._array, x2.shape) is much slower. We # could also manually type promote x2, but that is more complicated # and about the same performance as this. x1 = Array._new(x1._array[None]) elif x2.ndim == 0 and x1.ndim != 0: x2 = Array._new(x2._array[None]) return (x1, x2) # Note: A large fraction of allowed indices are disallowed here (see the # docstring below) def _validate_index(self, key): """ Validate an index according to the array API. The array API specification only requires a subset of indices that are supported by NumPy. This function will reject any index that is allowed by NumPy but not required by the array API specification. We always raise ``IndexError`` on such indices (the spec does not require any specific behavior on them, but this makes the NumPy array API namespace a minimal implementation of the spec). See https://data-apis.org/array-api/latest/API_specification/indexing.html for the full list of required indexing behavior This function raises IndexError if the index ``key`` is invalid. It only raises ``IndexError`` on indices that are not already rejected by NumPy, as NumPy will already raise the appropriate error on such indices. ``shape`` may be None, in which case, only cases that are independent of the array shape are checked. The following cases are allowed by NumPy, but not specified by the array API specification: - Indices to not include an implicit ellipsis at the end. That is, every axis of an array must be explicitly indexed or an ellipsis included. This behaviour is sometimes referred to as flat indexing. - The start and stop of a slice may not be out of bounds. In particular, for a slice ``i:j:k`` on an axis of size ``n``, only the following are allowed: - ``i`` or ``j`` omitted (``None``). - ``-n <= i <= max(0, n - 1)``. - For ``k > 0`` or ``k`` omitted (``None``), ``-n <= j <= n``. - For ``k < 0``, ``-n - 1 <= j <= max(0, n - 1)``. - Boolean array indices are not allowed as part of a larger tuple index. - Integer array indices are not allowed (with the exception of 0-D arrays, which are treated the same as scalars). Additionally, it should be noted that indices that would return a scalar in NumPy will return a 0-D array. Array scalars are not allowed in the specification, only 0-D arrays. This is done in the ``Array._new`` constructor, not this function. """ _key = key if isinstance(key, tuple) else (key,) for i in _key: if isinstance(i, bool) or not ( isinstance(i, SupportsIndex) # i.e. ints or isinstance(i, slice) or i == Ellipsis or i is None or isinstance(i, Array) or isinstance(i, np.ndarray) ): raise IndexError( f"Single-axes index {i} has {type(i)=}, but only " "integers, slices (:), ellipsis (...), newaxis (None), " "zero-dimensional integer arrays and boolean arrays " "are specified in the Array API." ) nonexpanding_key = [] single_axes = [] n_ellipsis = 0 key_has_mask = False for i in _key: if i is not None: nonexpanding_key.append(i) if isinstance(i, Array) or isinstance(i, np.ndarray): if i.dtype in _boolean_dtypes: key_has_mask = True single_axes.append(i) else: # i must not be an array here, to avoid elementwise equals if i == Ellipsis: n_ellipsis += 1 else: single_axes.append(i) n_single_axes = len(single_axes) if n_ellipsis > 1: return # handled by ndarray elif n_ellipsis == 0: # Note boolean masks must be the sole index, which we check for # later on. if not key_has_mask and n_single_axes < self.ndim: raise IndexError( f"{self.ndim=}, but the multi-axes index only specifies " f"{n_single_axes} dimensions. If this was intentional, " "add a trailing ellipsis (...) which expands into as many " "slices (:) as necessary - this is what np.ndarray arrays " "implicitly do, but such flat indexing behaviour is not " "specified in the Array API." ) if n_ellipsis == 0: indexed_shape = self.shape else: ellipsis_start = None for pos, i in enumerate(nonexpanding_key): if not (isinstance(i, Array) or isinstance(i, np.ndarray)): if i == Ellipsis: ellipsis_start = pos break assert ellipsis_start is not None # sanity check ellipsis_end = self.ndim - (n_single_axes - ellipsis_start) indexed_shape = ( self.shape[:ellipsis_start] + self.shape[ellipsis_end:] ) for i, side in zip(single_axes, indexed_shape): if isinstance(i, slice): if side == 0: f_range = "0 (or None)" else: f_range = f"between -{side} and {side - 1} (or None)" if i.start is not None: try: start = operator.index(i.start) except TypeError: pass # handled by ndarray else: if not (-side <= start <= side): raise IndexError( f"Slice {i} contains {start=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds starts are not specified in " "the Array API)" ) if i.stop is not None: try: stop = operator.index(i.stop) except TypeError: pass # handled by ndarray else: if not (-side <= stop <= side): raise IndexError( f"Slice {i} contains {stop=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds stops are not specified in " "the Array API)" ) elif isinstance(i, Array): if i.dtype in _boolean_dtypes and len(_key) != 1: assert isinstance(key, tuple) # sanity check raise IndexError( f"Single-axes index {i} is a boolean array and " f"{len(key)=}, but masking is only specified in the " "Array API when the array is the sole index." ) elif i.dtype in _integer_dtypes and i.ndim != 0: raise IndexError( f"Single-axes index {i} is a non-zero-dimensional " "integer array, but advanced integer indexing is not " "specified in the Array API." ) elif isinstance(i, tuple): raise IndexError( f"Single-axes index {i} is a tuple, but nested tuple " "indices are not specified in the Array API." ) # Everything below this line is required by the spec. def __abs__(self: Array, /) -> Array: """ Performs the operation __abs__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __abs__") res = self._array.__abs__() return self.__class__._new(res) def __add__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __add__. """ other = self._check_allowed_dtypes(other, "numeric", "__add__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__add__(other._array) return self.__class__._new(res) def __and__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __and__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__and__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__and__(other._array) return self.__class__._new(res) def __array_namespace__( self: Array, /, *, api_version: Optional[str] = None ) -> types.ModuleType: if api_version is not None and not api_version.startswith("2021."): raise ValueError(f"Unrecognized array API version: {api_version!r}") return array_api def __bool__(self: Array, /) -> bool: """ Performs the operation __bool__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("bool is only allowed on arrays with 0 dimensions") if self.dtype not in _boolean_dtypes: raise ValueError("bool is only allowed on boolean arrays") res = self._array.__bool__() return res def __dlpack__(self: Array, /, *, stream: None = None) -> PyCapsule: """ Performs the operation __dlpack__. """ return self._array.__dlpack__(stream=stream) def __dlpack_device__(self: Array, /) -> Tuple[IntEnum, int]: """ Performs the operation __dlpack_device__. """ # Note: device support is required for this return self._array.__dlpack_device__() def __eq__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __eq__. """ # Even though "all" dtypes are allowed, we still require them to be # promotable with each other. other = self._check_allowed_dtypes(other, "all", "__eq__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__eq__(other._array) return self.__class__._new(res) def __float__(self: Array, /) -> float: """ Performs the operation __float__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("float is only allowed on arrays with 0 dimensions") if self.dtype not in _floating_dtypes: raise ValueError("float is only allowed on floating-point arrays") res = self._array.__float__() return res def __floordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __floordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__floordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__floordiv__(other._array) return self.__class__._new(res) def __ge__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ge__. """ other = self._check_allowed_dtypes(other, "numeric", "__ge__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ge__(other._array) return self.__class__._new(res) def __getitem__( self: Array, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], /, ) -> Array: """ Performs the operation __getitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array res = self._array.__getitem__(key) return self._new(res) def __gt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __gt__. """ other = self._check_allowed_dtypes(other, "numeric", "__gt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__gt__(other._array) return self.__class__._new(res) def __int__(self: Array, /) -> int: """ Performs the operation __int__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("int is only allowed on arrays with 0 dimensions") if self.dtype not in _integer_dtypes: raise ValueError("int is only allowed on integer arrays") res = self._array.__int__() return res def __index__(self: Array, /) -> int: """ Performs the operation __index__. """ res = self._array.__index__() return res def __invert__(self: Array, /) -> Array: """ Performs the operation __invert__. """ if self.dtype not in _integer_or_boolean_dtypes: raise TypeError("Only integer or boolean dtypes are allowed in __invert__") res = self._array.__invert__() return self.__class__._new(res) def __le__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __le__. """ other = self._check_allowed_dtypes(other, "numeric", "__le__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__le__(other._array) return self.__class__._new(res) def __lshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __lshift__. """ other = self._check_allowed_dtypes(other, "integer", "__lshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lshift__(other._array) return self.__class__._new(res) def __lt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __lt__. """ other = self._check_allowed_dtypes(other, "numeric", "__lt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lt__(other._array) return self.__class__._new(res) def __matmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __matmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__matmul__") if other is NotImplemented: return other res = self._array.__matmul__(other._array) return self.__class__._new(res) def __mod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mod__. """ other = self._check_allowed_dtypes(other, "numeric", "__mod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mod__(other._array) return self.__class__._new(res) def __mul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mul__. """ other = self._check_allowed_dtypes(other, "numeric", "__mul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mul__(other._array) return self.__class__._new(res) def __ne__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __ne__. """ other = self._check_allowed_dtypes(other, "all", "__ne__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ne__(other._array) return self.__class__._new(res) def __neg__(self: Array, /) -> Array: """ Performs the operation __neg__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __neg__") res = self._array.__neg__() return self.__class__._new(res) def __or__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __or__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__or__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__or__(other._array) return self.__class__._new(res) def __pos__(self: Array, /) -> Array: """ Performs the operation __pos__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __pos__") res = self._array.__pos__() return self.__class__._new(res) def __pow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __pow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__pow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow type promotion rules for 0-d # arrays, so we use pow() here instead. return pow(self, other) def __rshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rshift__(other._array) return self.__class__._new(res) def __setitem__( self, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], value: Union[int, float, bool, Array], /, ) -> None: """ Performs the operation __setitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array self._array.__setitem__(key, asarray(value)._array) def __sub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __sub__. """ other = self._check_allowed_dtypes(other, "numeric", "__sub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__sub__(other._array) return self.__class__._new(res) # PEP 484 requires int to be a subtype of float, but __truediv__ should # not accept int. def __truediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __truediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__truediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__truediv__(other._array) return self.__class__._new(res) def __xor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __xor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__xor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__xor__(other._array) return self.__class__._new(res) def __iadd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __iadd__. """ other = self._check_allowed_dtypes(other, "numeric", "__iadd__") if other is NotImplemented: return other self._array.__iadd__(other._array) return self def __radd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __radd__. """ other = self._check_allowed_dtypes(other, "numeric", "__radd__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__radd__(other._array) return self.__class__._new(res) def __iand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __iand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__iand__") if other is NotImplemented: return other self._array.__iand__(other._array) return self def __rand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rand__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rand__(other._array) return self.__class__._new(res) def __ifloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ifloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__ifloordiv__") if other is NotImplemented: return other self._array.__ifloordiv__(other._array) return self def __rfloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rfloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__rfloordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rfloordiv__(other._array) return self.__class__._new(res) def __ilshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __ilshift__. """ other = self._check_allowed_dtypes(other, "integer", "__ilshift__") if other is NotImplemented: return other self._array.__ilshift__(other._array) return self def __rlshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rlshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rlshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rlshift__(other._array) return self.__class__._new(res) def __imatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __imatmul__. """ # Note: NumPy does not implement __imatmul__. # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__imatmul__") if other is NotImplemented: return other # __imatmul__ can only be allowed when it would not change the shape # of self. other_shape = other.shape if self.shape == () or other_shape == (): raise ValueError("@= requires at least one dimension") if len(other_shape) == 1 or other_shape[-1] != other_shape[-2]: raise ValueError("@= cannot change the shape of the input array") self._array[:] = self._array.__matmul__(other._array) return self def __rmatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __rmatmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__rmatmul__") if other is NotImplemented: return other res = self._array.__rmatmul__(other._array) return self.__class__._new(res) def __imod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imod__. """ other = self._check_allowed_dtypes(other, "numeric", "__imod__") if other is NotImplemented: return other self._array.__imod__(other._array) return self def __rmod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmod__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmod__(other._array) return self.__class__._new(res) def __imul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imul__. """ other = self._check_allowed_dtypes(other, "numeric", "__imul__") if other is NotImplemented: return other self._array.__imul__(other._array) return self def __rmul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmul__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmul__(other._array) return self.__class__._new(res) def __ior__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ior__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ior__") if other is NotImplemented: return other self._array.__ior__(other._array) return self def __ror__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ror__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ror__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ror__(other._array) return self.__class__._new(res) def __ipow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ipow__. """ other = self._check_allowed_dtypes(other, "numeric", "__ipow__") if other is NotImplemented: return other self._array.__ipow__(other._array) return self def __rpow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rpow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__rpow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow the spec type promotion rules # for 0-d arrays, so we use pow() here instead. return pow(other, self) def __irshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __irshift__. """ other = self._check_allowed_dtypes(other, "integer", "__irshift__") if other is NotImplemented: return other self._array.__irshift__(other._array) return self def __rrshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rrshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rrshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rrshift__(other._array) return self.__class__._new(res) def __isub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __isub__. """ other = self._check_allowed_dtypes(other, "numeric", "__isub__") if other is NotImplemented: return other self._array.__isub__(other._array) return self def __rsub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rsub__. """ other = self._check_allowed_dtypes(other, "numeric", "__rsub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rsub__(other._array) return self.__class__._new(res) def __itruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __itruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__itruediv__") if other is NotImplemented: return other self._array.__itruediv__(other._array) return self def __rtruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __rtruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__rtruediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rtruediv__(other._array) return self.__class__._new(res) def __ixor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ixor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ixor__") if other is NotImplemented: return other self._array.__ixor__(other._array) return self def __rxor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rxor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rxor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rxor__(other._array) return self.__class__._new(res) def to_device(self: Array, device: Device, /, stream: None = None) -> Array: if stream is not None: raise ValueError("The stream argument to to_device() is not supported") if device == 'cpu': return self raise ValueError(f"Unsupported device {device!r}") def dtype(self) -> Dtype: """ Array API compatible wrapper for :py:meth:`np.ndarray.dtype <numpy.ndarray.dtype>`. See its docstring for more information. """ return self._array.dtype def device(self) -> Device: return "cpu" # Note: mT is new in array API spec (see matrix_transpose) def mT(self) -> Array: from .linalg import matrix_transpose return matrix_transpose(self) def ndim(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.ndim <numpy.ndarray.ndim>`. See its docstring for more information. """ return self._array.ndim def shape(self) -> Tuple[int, ...]: """ Array API compatible wrapper for :py:meth:`np.ndarray.shape <numpy.ndarray.shape>`. See its docstring for more information. """ return self._array.shape def size(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.size <numpy.ndarray.size>`. See its docstring for more information. """ return self._array.size def T(self) -> Array: """ Array API compatible wrapper for :py:meth:`np.ndarray.T <numpy.ndarray.T>`. See its docstring for more information. """ # Note: T only works on 2-dimensional arrays. See the corresponding # note in the specification: # https://data-apis.org/array-api/latest/API_specification/array_object.html#t if self.ndim != 2: raise ValueError("x.T requires x to have 2 dimensions. Use x.mT to transpose stacks of matrices and permute_dims() to permute dimensions.") return self.__class__._new(self._array.T) The provided code snippet includes necessary dependencies for implementing the `bitwise_right_shift` function. Write a Python function `def bitwise_right_shift(x1: Array, x2: Array, /) -> Array` to solve the following problem: Array API compatible wrapper for :py:func:`np.right_shift <numpy.right_shift>`. See its docstring for more information. Here is the function: def bitwise_right_shift(x1: Array, x2: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.right_shift <numpy.right_shift>`. See its docstring for more information. """ if x1.dtype not in _integer_dtypes or x2.dtype not in _integer_dtypes: raise TypeError("Only integer dtypes are allowed in bitwise_right_shift") # Call result type here just to raise on disallowed type combinations _result_type(x1.dtype, x2.dtype) x1, x2 = Array._normalize_two_args(x1, x2) # Note: bitwise_right_shift is only defined for x2 nonnegative. if np.any(x2._array < 0): raise ValueError("bitwise_right_shift(x1, x2) is only defined for x2 >= 0") return Array._new(np.right_shift(x1._array, x2._array))
Array API compatible wrapper for :py:func:`np.right_shift <numpy.right_shift>`. See its docstring for more information.
170,033
from __future__ import annotations from ._dtypes import ( _boolean_dtypes, _floating_dtypes, _integer_dtypes, _integer_or_boolean_dtypes, _numeric_dtypes, _result_type, ) from ._array_object import Array import numpy as np _integer_or_boolean_dtypes = ( bool, int8, int16, int32, int64, uint8, uint16, uint32, uint64, ) def _result_type(type1, type2): if (type1, type2) in _promotion_table: return _promotion_table[type1, type2] raise TypeError(f"{type1} and {type2} cannot be type promoted together") class Array: """ n-d array object for the array API namespace. See the docstring of :py:obj:`np.ndarray <numpy.ndarray>` for more information. This is a wrapper around numpy.ndarray that restricts the usage to only those things that are required by the array API namespace. Note, attributes on this object that start with a single underscore are not part of the API specification and should only be used internally. This object should not be constructed directly. Rather, use one of the creation functions, such as asarray(). """ _array: np.ndarray # Use a custom constructor instead of __init__, as manually initializing # this class is not supported API. def _new(cls, x, /): """ This is a private method for initializing the array API Array object. Functions outside of the array_api submodule should not use this method. Use one of the creation functions instead, such as ``asarray``. """ obj = super().__new__(cls) # Note: The spec does not have array scalars, only 0-D arrays. if isinstance(x, np.generic): # Convert the array scalar to a 0-D array x = np.asarray(x) if x.dtype not in _all_dtypes: raise TypeError( f"The array_api namespace does not support the dtype '{x.dtype}'" ) obj._array = x return obj # Prevent Array() from working def __new__(cls, *args, **kwargs): raise TypeError( "The array_api Array object should not be instantiated directly. Use an array creation function, such as asarray(), instead." ) # These functions are not required by the spec, but are implemented for # the sake of usability. def __str__(self: Array, /) -> str: """ Performs the operation __str__. """ return self._array.__str__().replace("array", "Array") def __repr__(self: Array, /) -> str: """ Performs the operation __repr__. """ suffix = f", dtype={self.dtype.name})" if 0 in self.shape: prefix = "empty(" mid = str(self.shape) else: prefix = "Array(" mid = np.array2string(self._array, separator=', ', prefix=prefix, suffix=suffix) return prefix + mid + suffix # This function is not required by the spec, but we implement it here for # convenience so that np.asarray(np.array_api.Array) will work. def __array__(self, dtype: None | np.dtype[Any] = None) -> npt.NDArray[Any]: """ Warning: this method is NOT part of the array API spec. Implementers of other libraries need not include it, and users should not assume it will be present in other implementations. """ return np.asarray(self._array, dtype=dtype) # These are various helper functions to make the array behavior match the # spec in places where it either deviates from or is more strict than # NumPy behavior def _check_allowed_dtypes(self, other: bool | int | float | Array, dtype_category: str, op: str) -> Array: """ Helper function for operators to only allow specific input dtypes Use like other = self._check_allowed_dtypes(other, 'numeric', '__add__') if other is NotImplemented: return other """ if self.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") if isinstance(other, (int, float, bool)): other = self._promote_scalar(other) elif isinstance(other, Array): if other.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") else: return NotImplemented # This will raise TypeError for type combinations that are not allowed # to promote in the spec (even if the NumPy array operator would # promote them). res_dtype = _result_type(self.dtype, other.dtype) if op.startswith("__i"): # Note: NumPy will allow in-place operators in some cases where # the type promoted operator does not match the left-hand side # operand. For example, # >>> a = np.array(1, dtype=np.int8) # >>> a += np.array(1, dtype=np.int16) # The spec explicitly disallows this. if res_dtype != self.dtype: raise TypeError( f"Cannot perform {op} with dtypes {self.dtype} and {other.dtype}" ) return other # Helper function to match the type promotion rules in the spec def _promote_scalar(self, scalar): """ Returns a promoted version of a Python scalar appropriate for use with operations on self. This may raise an OverflowError in cases where the scalar is an integer that is too large to fit in a NumPy integer dtype, or TypeError when the scalar type is incompatible with the dtype of self. """ # Note: Only Python scalar types that match the array dtype are # allowed. if isinstance(scalar, bool): if self.dtype not in _boolean_dtypes: raise TypeError( "Python bool scalars can only be promoted with bool arrays" ) elif isinstance(scalar, int): if self.dtype in _boolean_dtypes: raise TypeError( "Python int scalars cannot be promoted with bool arrays" ) elif isinstance(scalar, float): if self.dtype not in _floating_dtypes: raise TypeError( "Python float scalars can only be promoted with floating-point arrays." ) else: raise TypeError("'scalar' must be a Python scalar") # Note: scalars are unconditionally cast to the same dtype as the # array. # Note: the spec only specifies integer-dtype/int promotion # behavior for integers within the bounds of the integer dtype. # Outside of those bounds we use the default NumPy behavior (either # cast or raise OverflowError). return Array._new(np.array(scalar, self.dtype)) def _normalize_two_args(x1, x2) -> Tuple[Array, Array]: """ Normalize inputs to two arg functions to fix type promotion rules NumPy deviates from the spec type promotion rules in cases where one argument is 0-dimensional and the other is not. For example: >>> import numpy as np >>> a = np.array([1.0], dtype=np.float32) >>> b = np.array(1.0, dtype=np.float64) >>> np.add(a, b) # The spec says this should be float64 array([2.], dtype=float32) To fix this, we add a dimension to the 0-dimension array before passing it through. This works because a dimension would be added anyway from broadcasting, so the resulting shape is the same, but this prevents NumPy from not promoting the dtype. """ # Another option would be to use signature=(x1.dtype, x2.dtype, None), # but that only works for ufuncs, so we would have to call the ufuncs # directly in the operator methods. One should also note that this # sort of trick wouldn't work for functions like searchsorted, which # don't do normal broadcasting, but there aren't any functions like # that in the array API namespace. if x1.ndim == 0 and x2.ndim != 0: # The _array[None] workaround was chosen because it is relatively # performant. broadcast_to(x1._array, x2.shape) is much slower. We # could also manually type promote x2, but that is more complicated # and about the same performance as this. x1 = Array._new(x1._array[None]) elif x2.ndim == 0 and x1.ndim != 0: x2 = Array._new(x2._array[None]) return (x1, x2) # Note: A large fraction of allowed indices are disallowed here (see the # docstring below) def _validate_index(self, key): """ Validate an index according to the array API. The array API specification only requires a subset of indices that are supported by NumPy. This function will reject any index that is allowed by NumPy but not required by the array API specification. We always raise ``IndexError`` on such indices (the spec does not require any specific behavior on them, but this makes the NumPy array API namespace a minimal implementation of the spec). See https://data-apis.org/array-api/latest/API_specification/indexing.html for the full list of required indexing behavior This function raises IndexError if the index ``key`` is invalid. It only raises ``IndexError`` on indices that are not already rejected by NumPy, as NumPy will already raise the appropriate error on such indices. ``shape`` may be None, in which case, only cases that are independent of the array shape are checked. The following cases are allowed by NumPy, but not specified by the array API specification: - Indices to not include an implicit ellipsis at the end. That is, every axis of an array must be explicitly indexed or an ellipsis included. This behaviour is sometimes referred to as flat indexing. - The start and stop of a slice may not be out of bounds. In particular, for a slice ``i:j:k`` on an axis of size ``n``, only the following are allowed: - ``i`` or ``j`` omitted (``None``). - ``-n <= i <= max(0, n - 1)``. - For ``k > 0`` or ``k`` omitted (``None``), ``-n <= j <= n``. - For ``k < 0``, ``-n - 1 <= j <= max(0, n - 1)``. - Boolean array indices are not allowed as part of a larger tuple index. - Integer array indices are not allowed (with the exception of 0-D arrays, which are treated the same as scalars). Additionally, it should be noted that indices that would return a scalar in NumPy will return a 0-D array. Array scalars are not allowed in the specification, only 0-D arrays. This is done in the ``Array._new`` constructor, not this function. """ _key = key if isinstance(key, tuple) else (key,) for i in _key: if isinstance(i, bool) or not ( isinstance(i, SupportsIndex) # i.e. ints or isinstance(i, slice) or i == Ellipsis or i is None or isinstance(i, Array) or isinstance(i, np.ndarray) ): raise IndexError( f"Single-axes index {i} has {type(i)=}, but only " "integers, slices (:), ellipsis (...), newaxis (None), " "zero-dimensional integer arrays and boolean arrays " "are specified in the Array API." ) nonexpanding_key = [] single_axes = [] n_ellipsis = 0 key_has_mask = False for i in _key: if i is not None: nonexpanding_key.append(i) if isinstance(i, Array) or isinstance(i, np.ndarray): if i.dtype in _boolean_dtypes: key_has_mask = True single_axes.append(i) else: # i must not be an array here, to avoid elementwise equals if i == Ellipsis: n_ellipsis += 1 else: single_axes.append(i) n_single_axes = len(single_axes) if n_ellipsis > 1: return # handled by ndarray elif n_ellipsis == 0: # Note boolean masks must be the sole index, which we check for # later on. if not key_has_mask and n_single_axes < self.ndim: raise IndexError( f"{self.ndim=}, but the multi-axes index only specifies " f"{n_single_axes} dimensions. If this was intentional, " "add a trailing ellipsis (...) which expands into as many " "slices (:) as necessary - this is what np.ndarray arrays " "implicitly do, but such flat indexing behaviour is not " "specified in the Array API." ) if n_ellipsis == 0: indexed_shape = self.shape else: ellipsis_start = None for pos, i in enumerate(nonexpanding_key): if not (isinstance(i, Array) or isinstance(i, np.ndarray)): if i == Ellipsis: ellipsis_start = pos break assert ellipsis_start is not None # sanity check ellipsis_end = self.ndim - (n_single_axes - ellipsis_start) indexed_shape = ( self.shape[:ellipsis_start] + self.shape[ellipsis_end:] ) for i, side in zip(single_axes, indexed_shape): if isinstance(i, slice): if side == 0: f_range = "0 (or None)" else: f_range = f"between -{side} and {side - 1} (or None)" if i.start is not None: try: start = operator.index(i.start) except TypeError: pass # handled by ndarray else: if not (-side <= start <= side): raise IndexError( f"Slice {i} contains {start=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds starts are not specified in " "the Array API)" ) if i.stop is not None: try: stop = operator.index(i.stop) except TypeError: pass # handled by ndarray else: if not (-side <= stop <= side): raise IndexError( f"Slice {i} contains {stop=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds stops are not specified in " "the Array API)" ) elif isinstance(i, Array): if i.dtype in _boolean_dtypes and len(_key) != 1: assert isinstance(key, tuple) # sanity check raise IndexError( f"Single-axes index {i} is a boolean array and " f"{len(key)=}, but masking is only specified in the " "Array API when the array is the sole index." ) elif i.dtype in _integer_dtypes and i.ndim != 0: raise IndexError( f"Single-axes index {i} is a non-zero-dimensional " "integer array, but advanced integer indexing is not " "specified in the Array API." ) elif isinstance(i, tuple): raise IndexError( f"Single-axes index {i} is a tuple, but nested tuple " "indices are not specified in the Array API." ) # Everything below this line is required by the spec. def __abs__(self: Array, /) -> Array: """ Performs the operation __abs__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __abs__") res = self._array.__abs__() return self.__class__._new(res) def __add__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __add__. """ other = self._check_allowed_dtypes(other, "numeric", "__add__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__add__(other._array) return self.__class__._new(res) def __and__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __and__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__and__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__and__(other._array) return self.__class__._new(res) def __array_namespace__( self: Array, /, *, api_version: Optional[str] = None ) -> types.ModuleType: if api_version is not None and not api_version.startswith("2021."): raise ValueError(f"Unrecognized array API version: {api_version!r}") return array_api def __bool__(self: Array, /) -> bool: """ Performs the operation __bool__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("bool is only allowed on arrays with 0 dimensions") if self.dtype not in _boolean_dtypes: raise ValueError("bool is only allowed on boolean arrays") res = self._array.__bool__() return res def __dlpack__(self: Array, /, *, stream: None = None) -> PyCapsule: """ Performs the operation __dlpack__. """ return self._array.__dlpack__(stream=stream) def __dlpack_device__(self: Array, /) -> Tuple[IntEnum, int]: """ Performs the operation __dlpack_device__. """ # Note: device support is required for this return self._array.__dlpack_device__() def __eq__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __eq__. """ # Even though "all" dtypes are allowed, we still require them to be # promotable with each other. other = self._check_allowed_dtypes(other, "all", "__eq__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__eq__(other._array) return self.__class__._new(res) def __float__(self: Array, /) -> float: """ Performs the operation __float__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("float is only allowed on arrays with 0 dimensions") if self.dtype not in _floating_dtypes: raise ValueError("float is only allowed on floating-point arrays") res = self._array.__float__() return res def __floordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __floordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__floordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__floordiv__(other._array) return self.__class__._new(res) def __ge__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ge__. """ other = self._check_allowed_dtypes(other, "numeric", "__ge__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ge__(other._array) return self.__class__._new(res) def __getitem__( self: Array, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], /, ) -> Array: """ Performs the operation __getitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array res = self._array.__getitem__(key) return self._new(res) def __gt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __gt__. """ other = self._check_allowed_dtypes(other, "numeric", "__gt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__gt__(other._array) return self.__class__._new(res) def __int__(self: Array, /) -> int: """ Performs the operation __int__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("int is only allowed on arrays with 0 dimensions") if self.dtype not in _integer_dtypes: raise ValueError("int is only allowed on integer arrays") res = self._array.__int__() return res def __index__(self: Array, /) -> int: """ Performs the operation __index__. """ res = self._array.__index__() return res def __invert__(self: Array, /) -> Array: """ Performs the operation __invert__. """ if self.dtype not in _integer_or_boolean_dtypes: raise TypeError("Only integer or boolean dtypes are allowed in __invert__") res = self._array.__invert__() return self.__class__._new(res) def __le__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __le__. """ other = self._check_allowed_dtypes(other, "numeric", "__le__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__le__(other._array) return self.__class__._new(res) def __lshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __lshift__. """ other = self._check_allowed_dtypes(other, "integer", "__lshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lshift__(other._array) return self.__class__._new(res) def __lt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __lt__. """ other = self._check_allowed_dtypes(other, "numeric", "__lt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lt__(other._array) return self.__class__._new(res) def __matmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __matmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__matmul__") if other is NotImplemented: return other res = self._array.__matmul__(other._array) return self.__class__._new(res) def __mod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mod__. """ other = self._check_allowed_dtypes(other, "numeric", "__mod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mod__(other._array) return self.__class__._new(res) def __mul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mul__. """ other = self._check_allowed_dtypes(other, "numeric", "__mul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mul__(other._array) return self.__class__._new(res) def __ne__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __ne__. """ other = self._check_allowed_dtypes(other, "all", "__ne__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ne__(other._array) return self.__class__._new(res) def __neg__(self: Array, /) -> Array: """ Performs the operation __neg__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __neg__") res = self._array.__neg__() return self.__class__._new(res) def __or__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __or__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__or__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__or__(other._array) return self.__class__._new(res) def __pos__(self: Array, /) -> Array: """ Performs the operation __pos__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __pos__") res = self._array.__pos__() return self.__class__._new(res) def __pow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __pow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__pow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow type promotion rules for 0-d # arrays, so we use pow() here instead. return pow(self, other) def __rshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rshift__(other._array) return self.__class__._new(res) def __setitem__( self, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], value: Union[int, float, bool, Array], /, ) -> None: """ Performs the operation __setitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array self._array.__setitem__(key, asarray(value)._array) def __sub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __sub__. """ other = self._check_allowed_dtypes(other, "numeric", "__sub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__sub__(other._array) return self.__class__._new(res) # PEP 484 requires int to be a subtype of float, but __truediv__ should # not accept int. def __truediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __truediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__truediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__truediv__(other._array) return self.__class__._new(res) def __xor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __xor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__xor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__xor__(other._array) return self.__class__._new(res) def __iadd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __iadd__. """ other = self._check_allowed_dtypes(other, "numeric", "__iadd__") if other is NotImplemented: return other self._array.__iadd__(other._array) return self def __radd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __radd__. """ other = self._check_allowed_dtypes(other, "numeric", "__radd__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__radd__(other._array) return self.__class__._new(res) def __iand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __iand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__iand__") if other is NotImplemented: return other self._array.__iand__(other._array) return self def __rand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rand__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rand__(other._array) return self.__class__._new(res) def __ifloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ifloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__ifloordiv__") if other is NotImplemented: return other self._array.__ifloordiv__(other._array) return self def __rfloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rfloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__rfloordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rfloordiv__(other._array) return self.__class__._new(res) def __ilshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __ilshift__. """ other = self._check_allowed_dtypes(other, "integer", "__ilshift__") if other is NotImplemented: return other self._array.__ilshift__(other._array) return self def __rlshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rlshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rlshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rlshift__(other._array) return self.__class__._new(res) def __imatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __imatmul__. """ # Note: NumPy does not implement __imatmul__. # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__imatmul__") if other is NotImplemented: return other # __imatmul__ can only be allowed when it would not change the shape # of self. other_shape = other.shape if self.shape == () or other_shape == (): raise ValueError("@= requires at least one dimension") if len(other_shape) == 1 or other_shape[-1] != other_shape[-2]: raise ValueError("@= cannot change the shape of the input array") self._array[:] = self._array.__matmul__(other._array) return self def __rmatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __rmatmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__rmatmul__") if other is NotImplemented: return other res = self._array.__rmatmul__(other._array) return self.__class__._new(res) def __imod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imod__. """ other = self._check_allowed_dtypes(other, "numeric", "__imod__") if other is NotImplemented: return other self._array.__imod__(other._array) return self def __rmod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmod__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmod__(other._array) return self.__class__._new(res) def __imul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imul__. """ other = self._check_allowed_dtypes(other, "numeric", "__imul__") if other is NotImplemented: return other self._array.__imul__(other._array) return self def __rmul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmul__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmul__(other._array) return self.__class__._new(res) def __ior__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ior__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ior__") if other is NotImplemented: return other self._array.__ior__(other._array) return self def __ror__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ror__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ror__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ror__(other._array) return self.__class__._new(res) def __ipow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ipow__. """ other = self._check_allowed_dtypes(other, "numeric", "__ipow__") if other is NotImplemented: return other self._array.__ipow__(other._array) return self def __rpow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rpow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__rpow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow the spec type promotion rules # for 0-d arrays, so we use pow() here instead. return pow(other, self) def __irshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __irshift__. """ other = self._check_allowed_dtypes(other, "integer", "__irshift__") if other is NotImplemented: return other self._array.__irshift__(other._array) return self def __rrshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rrshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rrshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rrshift__(other._array) return self.__class__._new(res) def __isub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __isub__. """ other = self._check_allowed_dtypes(other, "numeric", "__isub__") if other is NotImplemented: return other self._array.__isub__(other._array) return self def __rsub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rsub__. """ other = self._check_allowed_dtypes(other, "numeric", "__rsub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rsub__(other._array) return self.__class__._new(res) def __itruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __itruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__itruediv__") if other is NotImplemented: return other self._array.__itruediv__(other._array) return self def __rtruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __rtruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__rtruediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rtruediv__(other._array) return self.__class__._new(res) def __ixor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ixor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ixor__") if other is NotImplemented: return other self._array.__ixor__(other._array) return self def __rxor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rxor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rxor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rxor__(other._array) return self.__class__._new(res) def to_device(self: Array, device: Device, /, stream: None = None) -> Array: if stream is not None: raise ValueError("The stream argument to to_device() is not supported") if device == 'cpu': return self raise ValueError(f"Unsupported device {device!r}") def dtype(self) -> Dtype: """ Array API compatible wrapper for :py:meth:`np.ndarray.dtype <numpy.ndarray.dtype>`. See its docstring for more information. """ return self._array.dtype def device(self) -> Device: return "cpu" # Note: mT is new in array API spec (see matrix_transpose) def mT(self) -> Array: from .linalg import matrix_transpose return matrix_transpose(self) def ndim(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.ndim <numpy.ndarray.ndim>`. See its docstring for more information. """ return self._array.ndim def shape(self) -> Tuple[int, ...]: """ Array API compatible wrapper for :py:meth:`np.ndarray.shape <numpy.ndarray.shape>`. See its docstring for more information. """ return self._array.shape def size(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.size <numpy.ndarray.size>`. See its docstring for more information. """ return self._array.size def T(self) -> Array: """ Array API compatible wrapper for :py:meth:`np.ndarray.T <numpy.ndarray.T>`. See its docstring for more information. """ # Note: T only works on 2-dimensional arrays. See the corresponding # note in the specification: # https://data-apis.org/array-api/latest/API_specification/array_object.html#t if self.ndim != 2: raise ValueError("x.T requires x to have 2 dimensions. Use x.mT to transpose stacks of matrices and permute_dims() to permute dimensions.") return self.__class__._new(self._array.T) The provided code snippet includes necessary dependencies for implementing the `bitwise_xor` function. Write a Python function `def bitwise_xor(x1: Array, x2: Array, /) -> Array` to solve the following problem: Array API compatible wrapper for :py:func:`np.bitwise_xor <numpy.bitwise_xor>`. See its docstring for more information. Here is the function: def bitwise_xor(x1: Array, x2: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.bitwise_xor <numpy.bitwise_xor>`. See its docstring for more information. """ if ( x1.dtype not in _integer_or_boolean_dtypes or x2.dtype not in _integer_or_boolean_dtypes ): raise TypeError("Only integer or boolean dtypes are allowed in bitwise_xor") # Call result type here just to raise on disallowed type combinations _result_type(x1.dtype, x2.dtype) x1, x2 = Array._normalize_two_args(x1, x2) return Array._new(np.bitwise_xor(x1._array, x2._array))
Array API compatible wrapper for :py:func:`np.bitwise_xor <numpy.bitwise_xor>`. See its docstring for more information.
170,034
from __future__ import annotations from ._dtypes import ( _boolean_dtypes, _floating_dtypes, _integer_dtypes, _integer_or_boolean_dtypes, _numeric_dtypes, _result_type, ) from ._array_object import Array import numpy as np _integer_dtypes = (int8, int16, int32, int64, uint8, uint16, uint32, uint64) _numeric_dtypes = ( float32, float64, int8, int16, int32, int64, uint8, uint16, uint32, uint64, ) class Array: """ n-d array object for the array API namespace. See the docstring of :py:obj:`np.ndarray <numpy.ndarray>` for more information. This is a wrapper around numpy.ndarray that restricts the usage to only those things that are required by the array API namespace. Note, attributes on this object that start with a single underscore are not part of the API specification and should only be used internally. This object should not be constructed directly. Rather, use one of the creation functions, such as asarray(). """ _array: np.ndarray # Use a custom constructor instead of __init__, as manually initializing # this class is not supported API. def _new(cls, x, /): """ This is a private method for initializing the array API Array object. Functions outside of the array_api submodule should not use this method. Use one of the creation functions instead, such as ``asarray``. """ obj = super().__new__(cls) # Note: The spec does not have array scalars, only 0-D arrays. if isinstance(x, np.generic): # Convert the array scalar to a 0-D array x = np.asarray(x) if x.dtype not in _all_dtypes: raise TypeError( f"The array_api namespace does not support the dtype '{x.dtype}'" ) obj._array = x return obj # Prevent Array() from working def __new__(cls, *args, **kwargs): raise TypeError( "The array_api Array object should not be instantiated directly. Use an array creation function, such as asarray(), instead." ) # These functions are not required by the spec, but are implemented for # the sake of usability. def __str__(self: Array, /) -> str: """ Performs the operation __str__. """ return self._array.__str__().replace("array", "Array") def __repr__(self: Array, /) -> str: """ Performs the operation __repr__. """ suffix = f", dtype={self.dtype.name})" if 0 in self.shape: prefix = "empty(" mid = str(self.shape) else: prefix = "Array(" mid = np.array2string(self._array, separator=', ', prefix=prefix, suffix=suffix) return prefix + mid + suffix # This function is not required by the spec, but we implement it here for # convenience so that np.asarray(np.array_api.Array) will work. def __array__(self, dtype: None | np.dtype[Any] = None) -> npt.NDArray[Any]: """ Warning: this method is NOT part of the array API spec. Implementers of other libraries need not include it, and users should not assume it will be present in other implementations. """ return np.asarray(self._array, dtype=dtype) # These are various helper functions to make the array behavior match the # spec in places where it either deviates from or is more strict than # NumPy behavior def _check_allowed_dtypes(self, other: bool | int | float | Array, dtype_category: str, op: str) -> Array: """ Helper function for operators to only allow specific input dtypes Use like other = self._check_allowed_dtypes(other, 'numeric', '__add__') if other is NotImplemented: return other """ if self.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") if isinstance(other, (int, float, bool)): other = self._promote_scalar(other) elif isinstance(other, Array): if other.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") else: return NotImplemented # This will raise TypeError for type combinations that are not allowed # to promote in the spec (even if the NumPy array operator would # promote them). res_dtype = _result_type(self.dtype, other.dtype) if op.startswith("__i"): # Note: NumPy will allow in-place operators in some cases where # the type promoted operator does not match the left-hand side # operand. For example, # >>> a = np.array(1, dtype=np.int8) # >>> a += np.array(1, dtype=np.int16) # The spec explicitly disallows this. if res_dtype != self.dtype: raise TypeError( f"Cannot perform {op} with dtypes {self.dtype} and {other.dtype}" ) return other # Helper function to match the type promotion rules in the spec def _promote_scalar(self, scalar): """ Returns a promoted version of a Python scalar appropriate for use with operations on self. This may raise an OverflowError in cases where the scalar is an integer that is too large to fit in a NumPy integer dtype, or TypeError when the scalar type is incompatible with the dtype of self. """ # Note: Only Python scalar types that match the array dtype are # allowed. if isinstance(scalar, bool): if self.dtype not in _boolean_dtypes: raise TypeError( "Python bool scalars can only be promoted with bool arrays" ) elif isinstance(scalar, int): if self.dtype in _boolean_dtypes: raise TypeError( "Python int scalars cannot be promoted with bool arrays" ) elif isinstance(scalar, float): if self.dtype not in _floating_dtypes: raise TypeError( "Python float scalars can only be promoted with floating-point arrays." ) else: raise TypeError("'scalar' must be a Python scalar") # Note: scalars are unconditionally cast to the same dtype as the # array. # Note: the spec only specifies integer-dtype/int promotion # behavior for integers within the bounds of the integer dtype. # Outside of those bounds we use the default NumPy behavior (either # cast or raise OverflowError). return Array._new(np.array(scalar, self.dtype)) def _normalize_two_args(x1, x2) -> Tuple[Array, Array]: """ Normalize inputs to two arg functions to fix type promotion rules NumPy deviates from the spec type promotion rules in cases where one argument is 0-dimensional and the other is not. For example: >>> import numpy as np >>> a = np.array([1.0], dtype=np.float32) >>> b = np.array(1.0, dtype=np.float64) >>> np.add(a, b) # The spec says this should be float64 array([2.], dtype=float32) To fix this, we add a dimension to the 0-dimension array before passing it through. This works because a dimension would be added anyway from broadcasting, so the resulting shape is the same, but this prevents NumPy from not promoting the dtype. """ # Another option would be to use signature=(x1.dtype, x2.dtype, None), # but that only works for ufuncs, so we would have to call the ufuncs # directly in the operator methods. One should also note that this # sort of trick wouldn't work for functions like searchsorted, which # don't do normal broadcasting, but there aren't any functions like # that in the array API namespace. if x1.ndim == 0 and x2.ndim != 0: # The _array[None] workaround was chosen because it is relatively # performant. broadcast_to(x1._array, x2.shape) is much slower. We # could also manually type promote x2, but that is more complicated # and about the same performance as this. x1 = Array._new(x1._array[None]) elif x2.ndim == 0 and x1.ndim != 0: x2 = Array._new(x2._array[None]) return (x1, x2) # Note: A large fraction of allowed indices are disallowed here (see the # docstring below) def _validate_index(self, key): """ Validate an index according to the array API. The array API specification only requires a subset of indices that are supported by NumPy. This function will reject any index that is allowed by NumPy but not required by the array API specification. We always raise ``IndexError`` on such indices (the spec does not require any specific behavior on them, but this makes the NumPy array API namespace a minimal implementation of the spec). See https://data-apis.org/array-api/latest/API_specification/indexing.html for the full list of required indexing behavior This function raises IndexError if the index ``key`` is invalid. It only raises ``IndexError`` on indices that are not already rejected by NumPy, as NumPy will already raise the appropriate error on such indices. ``shape`` may be None, in which case, only cases that are independent of the array shape are checked. The following cases are allowed by NumPy, but not specified by the array API specification: - Indices to not include an implicit ellipsis at the end. That is, every axis of an array must be explicitly indexed or an ellipsis included. This behaviour is sometimes referred to as flat indexing. - The start and stop of a slice may not be out of bounds. In particular, for a slice ``i:j:k`` on an axis of size ``n``, only the following are allowed: - ``i`` or ``j`` omitted (``None``). - ``-n <= i <= max(0, n - 1)``. - For ``k > 0`` or ``k`` omitted (``None``), ``-n <= j <= n``. - For ``k < 0``, ``-n - 1 <= j <= max(0, n - 1)``. - Boolean array indices are not allowed as part of a larger tuple index. - Integer array indices are not allowed (with the exception of 0-D arrays, which are treated the same as scalars). Additionally, it should be noted that indices that would return a scalar in NumPy will return a 0-D array. Array scalars are not allowed in the specification, only 0-D arrays. This is done in the ``Array._new`` constructor, not this function. """ _key = key if isinstance(key, tuple) else (key,) for i in _key: if isinstance(i, bool) or not ( isinstance(i, SupportsIndex) # i.e. ints or isinstance(i, slice) or i == Ellipsis or i is None or isinstance(i, Array) or isinstance(i, np.ndarray) ): raise IndexError( f"Single-axes index {i} has {type(i)=}, but only " "integers, slices (:), ellipsis (...), newaxis (None), " "zero-dimensional integer arrays and boolean arrays " "are specified in the Array API." ) nonexpanding_key = [] single_axes = [] n_ellipsis = 0 key_has_mask = False for i in _key: if i is not None: nonexpanding_key.append(i) if isinstance(i, Array) or isinstance(i, np.ndarray): if i.dtype in _boolean_dtypes: key_has_mask = True single_axes.append(i) else: # i must not be an array here, to avoid elementwise equals if i == Ellipsis: n_ellipsis += 1 else: single_axes.append(i) n_single_axes = len(single_axes) if n_ellipsis > 1: return # handled by ndarray elif n_ellipsis == 0: # Note boolean masks must be the sole index, which we check for # later on. if not key_has_mask and n_single_axes < self.ndim: raise IndexError( f"{self.ndim=}, but the multi-axes index only specifies " f"{n_single_axes} dimensions. If this was intentional, " "add a trailing ellipsis (...) which expands into as many " "slices (:) as necessary - this is what np.ndarray arrays " "implicitly do, but such flat indexing behaviour is not " "specified in the Array API." ) if n_ellipsis == 0: indexed_shape = self.shape else: ellipsis_start = None for pos, i in enumerate(nonexpanding_key): if not (isinstance(i, Array) or isinstance(i, np.ndarray)): if i == Ellipsis: ellipsis_start = pos break assert ellipsis_start is not None # sanity check ellipsis_end = self.ndim - (n_single_axes - ellipsis_start) indexed_shape = ( self.shape[:ellipsis_start] + self.shape[ellipsis_end:] ) for i, side in zip(single_axes, indexed_shape): if isinstance(i, slice): if side == 0: f_range = "0 (or None)" else: f_range = f"between -{side} and {side - 1} (or None)" if i.start is not None: try: start = operator.index(i.start) except TypeError: pass # handled by ndarray else: if not (-side <= start <= side): raise IndexError( f"Slice {i} contains {start=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds starts are not specified in " "the Array API)" ) if i.stop is not None: try: stop = operator.index(i.stop) except TypeError: pass # handled by ndarray else: if not (-side <= stop <= side): raise IndexError( f"Slice {i} contains {stop=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds stops are not specified in " "the Array API)" ) elif isinstance(i, Array): if i.dtype in _boolean_dtypes and len(_key) != 1: assert isinstance(key, tuple) # sanity check raise IndexError( f"Single-axes index {i} is a boolean array and " f"{len(key)=}, but masking is only specified in the " "Array API when the array is the sole index." ) elif i.dtype in _integer_dtypes and i.ndim != 0: raise IndexError( f"Single-axes index {i} is a non-zero-dimensional " "integer array, but advanced integer indexing is not " "specified in the Array API." ) elif isinstance(i, tuple): raise IndexError( f"Single-axes index {i} is a tuple, but nested tuple " "indices are not specified in the Array API." ) # Everything below this line is required by the spec. def __abs__(self: Array, /) -> Array: """ Performs the operation __abs__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __abs__") res = self._array.__abs__() return self.__class__._new(res) def __add__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __add__. """ other = self._check_allowed_dtypes(other, "numeric", "__add__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__add__(other._array) return self.__class__._new(res) def __and__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __and__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__and__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__and__(other._array) return self.__class__._new(res) def __array_namespace__( self: Array, /, *, api_version: Optional[str] = None ) -> types.ModuleType: if api_version is not None and not api_version.startswith("2021."): raise ValueError(f"Unrecognized array API version: {api_version!r}") return array_api def __bool__(self: Array, /) -> bool: """ Performs the operation __bool__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("bool is only allowed on arrays with 0 dimensions") if self.dtype not in _boolean_dtypes: raise ValueError("bool is only allowed on boolean arrays") res = self._array.__bool__() return res def __dlpack__(self: Array, /, *, stream: None = None) -> PyCapsule: """ Performs the operation __dlpack__. """ return self._array.__dlpack__(stream=stream) def __dlpack_device__(self: Array, /) -> Tuple[IntEnum, int]: """ Performs the operation __dlpack_device__. """ # Note: device support is required for this return self._array.__dlpack_device__() def __eq__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __eq__. """ # Even though "all" dtypes are allowed, we still require them to be # promotable with each other. other = self._check_allowed_dtypes(other, "all", "__eq__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__eq__(other._array) return self.__class__._new(res) def __float__(self: Array, /) -> float: """ Performs the operation __float__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("float is only allowed on arrays with 0 dimensions") if self.dtype not in _floating_dtypes: raise ValueError("float is only allowed on floating-point arrays") res = self._array.__float__() return res def __floordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __floordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__floordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__floordiv__(other._array) return self.__class__._new(res) def __ge__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ge__. """ other = self._check_allowed_dtypes(other, "numeric", "__ge__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ge__(other._array) return self.__class__._new(res) def __getitem__( self: Array, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], /, ) -> Array: """ Performs the operation __getitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array res = self._array.__getitem__(key) return self._new(res) def __gt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __gt__. """ other = self._check_allowed_dtypes(other, "numeric", "__gt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__gt__(other._array) return self.__class__._new(res) def __int__(self: Array, /) -> int: """ Performs the operation __int__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("int is only allowed on arrays with 0 dimensions") if self.dtype not in _integer_dtypes: raise ValueError("int is only allowed on integer arrays") res = self._array.__int__() return res def __index__(self: Array, /) -> int: """ Performs the operation __index__. """ res = self._array.__index__() return res def __invert__(self: Array, /) -> Array: """ Performs the operation __invert__. """ if self.dtype not in _integer_or_boolean_dtypes: raise TypeError("Only integer or boolean dtypes are allowed in __invert__") res = self._array.__invert__() return self.__class__._new(res) def __le__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __le__. """ other = self._check_allowed_dtypes(other, "numeric", "__le__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__le__(other._array) return self.__class__._new(res) def __lshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __lshift__. """ other = self._check_allowed_dtypes(other, "integer", "__lshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lshift__(other._array) return self.__class__._new(res) def __lt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __lt__. """ other = self._check_allowed_dtypes(other, "numeric", "__lt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lt__(other._array) return self.__class__._new(res) def __matmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __matmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__matmul__") if other is NotImplemented: return other res = self._array.__matmul__(other._array) return self.__class__._new(res) def __mod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mod__. """ other = self._check_allowed_dtypes(other, "numeric", "__mod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mod__(other._array) return self.__class__._new(res) def __mul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mul__. """ other = self._check_allowed_dtypes(other, "numeric", "__mul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mul__(other._array) return self.__class__._new(res) def __ne__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __ne__. """ other = self._check_allowed_dtypes(other, "all", "__ne__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ne__(other._array) return self.__class__._new(res) def __neg__(self: Array, /) -> Array: """ Performs the operation __neg__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __neg__") res = self._array.__neg__() return self.__class__._new(res) def __or__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __or__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__or__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__or__(other._array) return self.__class__._new(res) def __pos__(self: Array, /) -> Array: """ Performs the operation __pos__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __pos__") res = self._array.__pos__() return self.__class__._new(res) def __pow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __pow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__pow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow type promotion rules for 0-d # arrays, so we use pow() here instead. return pow(self, other) def __rshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rshift__(other._array) return self.__class__._new(res) def __setitem__( self, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], value: Union[int, float, bool, Array], /, ) -> None: """ Performs the operation __setitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array self._array.__setitem__(key, asarray(value)._array) def __sub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __sub__. """ other = self._check_allowed_dtypes(other, "numeric", "__sub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__sub__(other._array) return self.__class__._new(res) # PEP 484 requires int to be a subtype of float, but __truediv__ should # not accept int. def __truediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __truediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__truediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__truediv__(other._array) return self.__class__._new(res) def __xor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __xor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__xor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__xor__(other._array) return self.__class__._new(res) def __iadd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __iadd__. """ other = self._check_allowed_dtypes(other, "numeric", "__iadd__") if other is NotImplemented: return other self._array.__iadd__(other._array) return self def __radd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __radd__. """ other = self._check_allowed_dtypes(other, "numeric", "__radd__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__radd__(other._array) return self.__class__._new(res) def __iand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __iand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__iand__") if other is NotImplemented: return other self._array.__iand__(other._array) return self def __rand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rand__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rand__(other._array) return self.__class__._new(res) def __ifloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ifloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__ifloordiv__") if other is NotImplemented: return other self._array.__ifloordiv__(other._array) return self def __rfloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rfloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__rfloordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rfloordiv__(other._array) return self.__class__._new(res) def __ilshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __ilshift__. """ other = self._check_allowed_dtypes(other, "integer", "__ilshift__") if other is NotImplemented: return other self._array.__ilshift__(other._array) return self def __rlshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rlshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rlshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rlshift__(other._array) return self.__class__._new(res) def __imatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __imatmul__. """ # Note: NumPy does not implement __imatmul__. # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__imatmul__") if other is NotImplemented: return other # __imatmul__ can only be allowed when it would not change the shape # of self. other_shape = other.shape if self.shape == () or other_shape == (): raise ValueError("@= requires at least one dimension") if len(other_shape) == 1 or other_shape[-1] != other_shape[-2]: raise ValueError("@= cannot change the shape of the input array") self._array[:] = self._array.__matmul__(other._array) return self def __rmatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __rmatmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__rmatmul__") if other is NotImplemented: return other res = self._array.__rmatmul__(other._array) return self.__class__._new(res) def __imod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imod__. """ other = self._check_allowed_dtypes(other, "numeric", "__imod__") if other is NotImplemented: return other self._array.__imod__(other._array) return self def __rmod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmod__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmod__(other._array) return self.__class__._new(res) def __imul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imul__. """ other = self._check_allowed_dtypes(other, "numeric", "__imul__") if other is NotImplemented: return other self._array.__imul__(other._array) return self def __rmul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmul__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmul__(other._array) return self.__class__._new(res) def __ior__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ior__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ior__") if other is NotImplemented: return other self._array.__ior__(other._array) return self def __ror__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ror__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ror__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ror__(other._array) return self.__class__._new(res) def __ipow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ipow__. """ other = self._check_allowed_dtypes(other, "numeric", "__ipow__") if other is NotImplemented: return other self._array.__ipow__(other._array) return self def __rpow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rpow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__rpow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow the spec type promotion rules # for 0-d arrays, so we use pow() here instead. return pow(other, self) def __irshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __irshift__. """ other = self._check_allowed_dtypes(other, "integer", "__irshift__") if other is NotImplemented: return other self._array.__irshift__(other._array) return self def __rrshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rrshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rrshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rrshift__(other._array) return self.__class__._new(res) def __isub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __isub__. """ other = self._check_allowed_dtypes(other, "numeric", "__isub__") if other is NotImplemented: return other self._array.__isub__(other._array) return self def __rsub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rsub__. """ other = self._check_allowed_dtypes(other, "numeric", "__rsub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rsub__(other._array) return self.__class__._new(res) def __itruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __itruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__itruediv__") if other is NotImplemented: return other self._array.__itruediv__(other._array) return self def __rtruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __rtruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__rtruediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rtruediv__(other._array) return self.__class__._new(res) def __ixor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ixor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ixor__") if other is NotImplemented: return other self._array.__ixor__(other._array) return self def __rxor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rxor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rxor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rxor__(other._array) return self.__class__._new(res) def to_device(self: Array, device: Device, /, stream: None = None) -> Array: if stream is not None: raise ValueError("The stream argument to to_device() is not supported") if device == 'cpu': return self raise ValueError(f"Unsupported device {device!r}") def dtype(self) -> Dtype: """ Array API compatible wrapper for :py:meth:`np.ndarray.dtype <numpy.ndarray.dtype>`. See its docstring for more information. """ return self._array.dtype def device(self) -> Device: return "cpu" # Note: mT is new in array API spec (see matrix_transpose) def mT(self) -> Array: from .linalg import matrix_transpose return matrix_transpose(self) def ndim(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.ndim <numpy.ndarray.ndim>`. See its docstring for more information. """ return self._array.ndim def shape(self) -> Tuple[int, ...]: """ Array API compatible wrapper for :py:meth:`np.ndarray.shape <numpy.ndarray.shape>`. See its docstring for more information. """ return self._array.shape def size(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.size <numpy.ndarray.size>`. See its docstring for more information. """ return self._array.size def T(self) -> Array: """ Array API compatible wrapper for :py:meth:`np.ndarray.T <numpy.ndarray.T>`. See its docstring for more information. """ # Note: T only works on 2-dimensional arrays. See the corresponding # note in the specification: # https://data-apis.org/array-api/latest/API_specification/array_object.html#t if self.ndim != 2: raise ValueError("x.T requires x to have 2 dimensions. Use x.mT to transpose stacks of matrices and permute_dims() to permute dimensions.") return self.__class__._new(self._array.T) The provided code snippet includes necessary dependencies for implementing the `ceil` function. Write a Python function `def ceil(x: Array, /) -> Array` to solve the following problem: Array API compatible wrapper for :py:func:`np.ceil <numpy.ceil>`. See its docstring for more information. Here is the function: def ceil(x: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.ceil <numpy.ceil>`. See its docstring for more information. """ if x.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in ceil") if x.dtype in _integer_dtypes: # Note: The return dtype of ceil is the same as the input return x return Array._new(np.ceil(x._array))
Array API compatible wrapper for :py:func:`np.ceil <numpy.ceil>`. See its docstring for more information.
170,035
from __future__ import annotations from ._dtypes import ( _boolean_dtypes, _floating_dtypes, _integer_dtypes, _integer_or_boolean_dtypes, _numeric_dtypes, _result_type, ) from ._array_object import Array import numpy as np _floating_dtypes = (float32, float64) class Array: """ n-d array object for the array API namespace. See the docstring of :py:obj:`np.ndarray <numpy.ndarray>` for more information. This is a wrapper around numpy.ndarray that restricts the usage to only those things that are required by the array API namespace. Note, attributes on this object that start with a single underscore are not part of the API specification and should only be used internally. This object should not be constructed directly. Rather, use one of the creation functions, such as asarray(). """ _array: np.ndarray # Use a custom constructor instead of __init__, as manually initializing # this class is not supported API. def _new(cls, x, /): """ This is a private method for initializing the array API Array object. Functions outside of the array_api submodule should not use this method. Use one of the creation functions instead, such as ``asarray``. """ obj = super().__new__(cls) # Note: The spec does not have array scalars, only 0-D arrays. if isinstance(x, np.generic): # Convert the array scalar to a 0-D array x = np.asarray(x) if x.dtype not in _all_dtypes: raise TypeError( f"The array_api namespace does not support the dtype '{x.dtype}'" ) obj._array = x return obj # Prevent Array() from working def __new__(cls, *args, **kwargs): raise TypeError( "The array_api Array object should not be instantiated directly. Use an array creation function, such as asarray(), instead." ) # These functions are not required by the spec, but are implemented for # the sake of usability. def __str__(self: Array, /) -> str: """ Performs the operation __str__. """ return self._array.__str__().replace("array", "Array") def __repr__(self: Array, /) -> str: """ Performs the operation __repr__. """ suffix = f", dtype={self.dtype.name})" if 0 in self.shape: prefix = "empty(" mid = str(self.shape) else: prefix = "Array(" mid = np.array2string(self._array, separator=', ', prefix=prefix, suffix=suffix) return prefix + mid + suffix # This function is not required by the spec, but we implement it here for # convenience so that np.asarray(np.array_api.Array) will work. def __array__(self, dtype: None | np.dtype[Any] = None) -> npt.NDArray[Any]: """ Warning: this method is NOT part of the array API spec. Implementers of other libraries need not include it, and users should not assume it will be present in other implementations. """ return np.asarray(self._array, dtype=dtype) # These are various helper functions to make the array behavior match the # spec in places where it either deviates from or is more strict than # NumPy behavior def _check_allowed_dtypes(self, other: bool | int | float | Array, dtype_category: str, op: str) -> Array: """ Helper function for operators to only allow specific input dtypes Use like other = self._check_allowed_dtypes(other, 'numeric', '__add__') if other is NotImplemented: return other """ if self.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") if isinstance(other, (int, float, bool)): other = self._promote_scalar(other) elif isinstance(other, Array): if other.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") else: return NotImplemented # This will raise TypeError for type combinations that are not allowed # to promote in the spec (even if the NumPy array operator would # promote them). res_dtype = _result_type(self.dtype, other.dtype) if op.startswith("__i"): # Note: NumPy will allow in-place operators in some cases where # the type promoted operator does not match the left-hand side # operand. For example, # >>> a = np.array(1, dtype=np.int8) # >>> a += np.array(1, dtype=np.int16) # The spec explicitly disallows this. if res_dtype != self.dtype: raise TypeError( f"Cannot perform {op} with dtypes {self.dtype} and {other.dtype}" ) return other # Helper function to match the type promotion rules in the spec def _promote_scalar(self, scalar): """ Returns a promoted version of a Python scalar appropriate for use with operations on self. This may raise an OverflowError in cases where the scalar is an integer that is too large to fit in a NumPy integer dtype, or TypeError when the scalar type is incompatible with the dtype of self. """ # Note: Only Python scalar types that match the array dtype are # allowed. if isinstance(scalar, bool): if self.dtype not in _boolean_dtypes: raise TypeError( "Python bool scalars can only be promoted with bool arrays" ) elif isinstance(scalar, int): if self.dtype in _boolean_dtypes: raise TypeError( "Python int scalars cannot be promoted with bool arrays" ) elif isinstance(scalar, float): if self.dtype not in _floating_dtypes: raise TypeError( "Python float scalars can only be promoted with floating-point arrays." ) else: raise TypeError("'scalar' must be a Python scalar") # Note: scalars are unconditionally cast to the same dtype as the # array. # Note: the spec only specifies integer-dtype/int promotion # behavior for integers within the bounds of the integer dtype. # Outside of those bounds we use the default NumPy behavior (either # cast or raise OverflowError). return Array._new(np.array(scalar, self.dtype)) def _normalize_two_args(x1, x2) -> Tuple[Array, Array]: """ Normalize inputs to two arg functions to fix type promotion rules NumPy deviates from the spec type promotion rules in cases where one argument is 0-dimensional and the other is not. For example: >>> import numpy as np >>> a = np.array([1.0], dtype=np.float32) >>> b = np.array(1.0, dtype=np.float64) >>> np.add(a, b) # The spec says this should be float64 array([2.], dtype=float32) To fix this, we add a dimension to the 0-dimension array before passing it through. This works because a dimension would be added anyway from broadcasting, so the resulting shape is the same, but this prevents NumPy from not promoting the dtype. """ # Another option would be to use signature=(x1.dtype, x2.dtype, None), # but that only works for ufuncs, so we would have to call the ufuncs # directly in the operator methods. One should also note that this # sort of trick wouldn't work for functions like searchsorted, which # don't do normal broadcasting, but there aren't any functions like # that in the array API namespace. if x1.ndim == 0 and x2.ndim != 0: # The _array[None] workaround was chosen because it is relatively # performant. broadcast_to(x1._array, x2.shape) is much slower. We # could also manually type promote x2, but that is more complicated # and about the same performance as this. x1 = Array._new(x1._array[None]) elif x2.ndim == 0 and x1.ndim != 0: x2 = Array._new(x2._array[None]) return (x1, x2) # Note: A large fraction of allowed indices are disallowed here (see the # docstring below) def _validate_index(self, key): """ Validate an index according to the array API. The array API specification only requires a subset of indices that are supported by NumPy. This function will reject any index that is allowed by NumPy but not required by the array API specification. We always raise ``IndexError`` on such indices (the spec does not require any specific behavior on them, but this makes the NumPy array API namespace a minimal implementation of the spec). See https://data-apis.org/array-api/latest/API_specification/indexing.html for the full list of required indexing behavior This function raises IndexError if the index ``key`` is invalid. It only raises ``IndexError`` on indices that are not already rejected by NumPy, as NumPy will already raise the appropriate error on such indices. ``shape`` may be None, in which case, only cases that are independent of the array shape are checked. The following cases are allowed by NumPy, but not specified by the array API specification: - Indices to not include an implicit ellipsis at the end. That is, every axis of an array must be explicitly indexed or an ellipsis included. This behaviour is sometimes referred to as flat indexing. - The start and stop of a slice may not be out of bounds. In particular, for a slice ``i:j:k`` on an axis of size ``n``, only the following are allowed: - ``i`` or ``j`` omitted (``None``). - ``-n <= i <= max(0, n - 1)``. - For ``k > 0`` or ``k`` omitted (``None``), ``-n <= j <= n``. - For ``k < 0``, ``-n - 1 <= j <= max(0, n - 1)``. - Boolean array indices are not allowed as part of a larger tuple index. - Integer array indices are not allowed (with the exception of 0-D arrays, which are treated the same as scalars). Additionally, it should be noted that indices that would return a scalar in NumPy will return a 0-D array. Array scalars are not allowed in the specification, only 0-D arrays. This is done in the ``Array._new`` constructor, not this function. """ _key = key if isinstance(key, tuple) else (key,) for i in _key: if isinstance(i, bool) or not ( isinstance(i, SupportsIndex) # i.e. ints or isinstance(i, slice) or i == Ellipsis or i is None or isinstance(i, Array) or isinstance(i, np.ndarray) ): raise IndexError( f"Single-axes index {i} has {type(i)=}, but only " "integers, slices (:), ellipsis (...), newaxis (None), " "zero-dimensional integer arrays and boolean arrays " "are specified in the Array API." ) nonexpanding_key = [] single_axes = [] n_ellipsis = 0 key_has_mask = False for i in _key: if i is not None: nonexpanding_key.append(i) if isinstance(i, Array) or isinstance(i, np.ndarray): if i.dtype in _boolean_dtypes: key_has_mask = True single_axes.append(i) else: # i must not be an array here, to avoid elementwise equals if i == Ellipsis: n_ellipsis += 1 else: single_axes.append(i) n_single_axes = len(single_axes) if n_ellipsis > 1: return # handled by ndarray elif n_ellipsis == 0: # Note boolean masks must be the sole index, which we check for # later on. if not key_has_mask and n_single_axes < self.ndim: raise IndexError( f"{self.ndim=}, but the multi-axes index only specifies " f"{n_single_axes} dimensions. If this was intentional, " "add a trailing ellipsis (...) which expands into as many " "slices (:) as necessary - this is what np.ndarray arrays " "implicitly do, but such flat indexing behaviour is not " "specified in the Array API." ) if n_ellipsis == 0: indexed_shape = self.shape else: ellipsis_start = None for pos, i in enumerate(nonexpanding_key): if not (isinstance(i, Array) or isinstance(i, np.ndarray)): if i == Ellipsis: ellipsis_start = pos break assert ellipsis_start is not None # sanity check ellipsis_end = self.ndim - (n_single_axes - ellipsis_start) indexed_shape = ( self.shape[:ellipsis_start] + self.shape[ellipsis_end:] ) for i, side in zip(single_axes, indexed_shape): if isinstance(i, slice): if side == 0: f_range = "0 (or None)" else: f_range = f"between -{side} and {side - 1} (or None)" if i.start is not None: try: start = operator.index(i.start) except TypeError: pass # handled by ndarray else: if not (-side <= start <= side): raise IndexError( f"Slice {i} contains {start=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds starts are not specified in " "the Array API)" ) if i.stop is not None: try: stop = operator.index(i.stop) except TypeError: pass # handled by ndarray else: if not (-side <= stop <= side): raise IndexError( f"Slice {i} contains {stop=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds stops are not specified in " "the Array API)" ) elif isinstance(i, Array): if i.dtype in _boolean_dtypes and len(_key) != 1: assert isinstance(key, tuple) # sanity check raise IndexError( f"Single-axes index {i} is a boolean array and " f"{len(key)=}, but masking is only specified in the " "Array API when the array is the sole index." ) elif i.dtype in _integer_dtypes and i.ndim != 0: raise IndexError( f"Single-axes index {i} is a non-zero-dimensional " "integer array, but advanced integer indexing is not " "specified in the Array API." ) elif isinstance(i, tuple): raise IndexError( f"Single-axes index {i} is a tuple, but nested tuple " "indices are not specified in the Array API." ) # Everything below this line is required by the spec. def __abs__(self: Array, /) -> Array: """ Performs the operation __abs__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __abs__") res = self._array.__abs__() return self.__class__._new(res) def __add__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __add__. """ other = self._check_allowed_dtypes(other, "numeric", "__add__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__add__(other._array) return self.__class__._new(res) def __and__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __and__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__and__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__and__(other._array) return self.__class__._new(res) def __array_namespace__( self: Array, /, *, api_version: Optional[str] = None ) -> types.ModuleType: if api_version is not None and not api_version.startswith("2021."): raise ValueError(f"Unrecognized array API version: {api_version!r}") return array_api def __bool__(self: Array, /) -> bool: """ Performs the operation __bool__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("bool is only allowed on arrays with 0 dimensions") if self.dtype not in _boolean_dtypes: raise ValueError("bool is only allowed on boolean arrays") res = self._array.__bool__() return res def __dlpack__(self: Array, /, *, stream: None = None) -> PyCapsule: """ Performs the operation __dlpack__. """ return self._array.__dlpack__(stream=stream) def __dlpack_device__(self: Array, /) -> Tuple[IntEnum, int]: """ Performs the operation __dlpack_device__. """ # Note: device support is required for this return self._array.__dlpack_device__() def __eq__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __eq__. """ # Even though "all" dtypes are allowed, we still require them to be # promotable with each other. other = self._check_allowed_dtypes(other, "all", "__eq__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__eq__(other._array) return self.__class__._new(res) def __float__(self: Array, /) -> float: """ Performs the operation __float__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("float is only allowed on arrays with 0 dimensions") if self.dtype not in _floating_dtypes: raise ValueError("float is only allowed on floating-point arrays") res = self._array.__float__() return res def __floordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __floordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__floordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__floordiv__(other._array) return self.__class__._new(res) def __ge__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ge__. """ other = self._check_allowed_dtypes(other, "numeric", "__ge__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ge__(other._array) return self.__class__._new(res) def __getitem__( self: Array, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], /, ) -> Array: """ Performs the operation __getitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array res = self._array.__getitem__(key) return self._new(res) def __gt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __gt__. """ other = self._check_allowed_dtypes(other, "numeric", "__gt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__gt__(other._array) return self.__class__._new(res) def __int__(self: Array, /) -> int: """ Performs the operation __int__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("int is only allowed on arrays with 0 dimensions") if self.dtype not in _integer_dtypes: raise ValueError("int is only allowed on integer arrays") res = self._array.__int__() return res def __index__(self: Array, /) -> int: """ Performs the operation __index__. """ res = self._array.__index__() return res def __invert__(self: Array, /) -> Array: """ Performs the operation __invert__. """ if self.dtype not in _integer_or_boolean_dtypes: raise TypeError("Only integer or boolean dtypes are allowed in __invert__") res = self._array.__invert__() return self.__class__._new(res) def __le__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __le__. """ other = self._check_allowed_dtypes(other, "numeric", "__le__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__le__(other._array) return self.__class__._new(res) def __lshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __lshift__. """ other = self._check_allowed_dtypes(other, "integer", "__lshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lshift__(other._array) return self.__class__._new(res) def __lt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __lt__. """ other = self._check_allowed_dtypes(other, "numeric", "__lt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lt__(other._array) return self.__class__._new(res) def __matmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __matmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__matmul__") if other is NotImplemented: return other res = self._array.__matmul__(other._array) return self.__class__._new(res) def __mod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mod__. """ other = self._check_allowed_dtypes(other, "numeric", "__mod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mod__(other._array) return self.__class__._new(res) def __mul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mul__. """ other = self._check_allowed_dtypes(other, "numeric", "__mul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mul__(other._array) return self.__class__._new(res) def __ne__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __ne__. """ other = self._check_allowed_dtypes(other, "all", "__ne__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ne__(other._array) return self.__class__._new(res) def __neg__(self: Array, /) -> Array: """ Performs the operation __neg__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __neg__") res = self._array.__neg__() return self.__class__._new(res) def __or__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __or__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__or__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__or__(other._array) return self.__class__._new(res) def __pos__(self: Array, /) -> Array: """ Performs the operation __pos__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __pos__") res = self._array.__pos__() return self.__class__._new(res) def __pow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __pow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__pow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow type promotion rules for 0-d # arrays, so we use pow() here instead. return pow(self, other) def __rshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rshift__(other._array) return self.__class__._new(res) def __setitem__( self, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], value: Union[int, float, bool, Array], /, ) -> None: """ Performs the operation __setitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array self._array.__setitem__(key, asarray(value)._array) def __sub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __sub__. """ other = self._check_allowed_dtypes(other, "numeric", "__sub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__sub__(other._array) return self.__class__._new(res) # PEP 484 requires int to be a subtype of float, but __truediv__ should # not accept int. def __truediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __truediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__truediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__truediv__(other._array) return self.__class__._new(res) def __xor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __xor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__xor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__xor__(other._array) return self.__class__._new(res) def __iadd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __iadd__. """ other = self._check_allowed_dtypes(other, "numeric", "__iadd__") if other is NotImplemented: return other self._array.__iadd__(other._array) return self def __radd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __radd__. """ other = self._check_allowed_dtypes(other, "numeric", "__radd__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__radd__(other._array) return self.__class__._new(res) def __iand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __iand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__iand__") if other is NotImplemented: return other self._array.__iand__(other._array) return self def __rand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rand__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rand__(other._array) return self.__class__._new(res) def __ifloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ifloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__ifloordiv__") if other is NotImplemented: return other self._array.__ifloordiv__(other._array) return self def __rfloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rfloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__rfloordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rfloordiv__(other._array) return self.__class__._new(res) def __ilshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __ilshift__. """ other = self._check_allowed_dtypes(other, "integer", "__ilshift__") if other is NotImplemented: return other self._array.__ilshift__(other._array) return self def __rlshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rlshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rlshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rlshift__(other._array) return self.__class__._new(res) def __imatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __imatmul__. """ # Note: NumPy does not implement __imatmul__. # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__imatmul__") if other is NotImplemented: return other # __imatmul__ can only be allowed when it would not change the shape # of self. other_shape = other.shape if self.shape == () or other_shape == (): raise ValueError("@= requires at least one dimension") if len(other_shape) == 1 or other_shape[-1] != other_shape[-2]: raise ValueError("@= cannot change the shape of the input array") self._array[:] = self._array.__matmul__(other._array) return self def __rmatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __rmatmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__rmatmul__") if other is NotImplemented: return other res = self._array.__rmatmul__(other._array) return self.__class__._new(res) def __imod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imod__. """ other = self._check_allowed_dtypes(other, "numeric", "__imod__") if other is NotImplemented: return other self._array.__imod__(other._array) return self def __rmod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmod__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmod__(other._array) return self.__class__._new(res) def __imul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imul__. """ other = self._check_allowed_dtypes(other, "numeric", "__imul__") if other is NotImplemented: return other self._array.__imul__(other._array) return self def __rmul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmul__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmul__(other._array) return self.__class__._new(res) def __ior__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ior__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ior__") if other is NotImplemented: return other self._array.__ior__(other._array) return self def __ror__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ror__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ror__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ror__(other._array) return self.__class__._new(res) def __ipow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ipow__. """ other = self._check_allowed_dtypes(other, "numeric", "__ipow__") if other is NotImplemented: return other self._array.__ipow__(other._array) return self def __rpow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rpow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__rpow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow the spec type promotion rules # for 0-d arrays, so we use pow() here instead. return pow(other, self) def __irshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __irshift__. """ other = self._check_allowed_dtypes(other, "integer", "__irshift__") if other is NotImplemented: return other self._array.__irshift__(other._array) return self def __rrshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rrshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rrshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rrshift__(other._array) return self.__class__._new(res) def __isub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __isub__. """ other = self._check_allowed_dtypes(other, "numeric", "__isub__") if other is NotImplemented: return other self._array.__isub__(other._array) return self def __rsub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rsub__. """ other = self._check_allowed_dtypes(other, "numeric", "__rsub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rsub__(other._array) return self.__class__._new(res) def __itruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __itruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__itruediv__") if other is NotImplemented: return other self._array.__itruediv__(other._array) return self def __rtruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __rtruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__rtruediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rtruediv__(other._array) return self.__class__._new(res) def __ixor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ixor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ixor__") if other is NotImplemented: return other self._array.__ixor__(other._array) return self def __rxor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rxor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rxor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rxor__(other._array) return self.__class__._new(res) def to_device(self: Array, device: Device, /, stream: None = None) -> Array: if stream is not None: raise ValueError("The stream argument to to_device() is not supported") if device == 'cpu': return self raise ValueError(f"Unsupported device {device!r}") def dtype(self) -> Dtype: """ Array API compatible wrapper for :py:meth:`np.ndarray.dtype <numpy.ndarray.dtype>`. See its docstring for more information. """ return self._array.dtype def device(self) -> Device: return "cpu" # Note: mT is new in array API spec (see matrix_transpose) def mT(self) -> Array: from .linalg import matrix_transpose return matrix_transpose(self) def ndim(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.ndim <numpy.ndarray.ndim>`. See its docstring for more information. """ return self._array.ndim def shape(self) -> Tuple[int, ...]: """ Array API compatible wrapper for :py:meth:`np.ndarray.shape <numpy.ndarray.shape>`. See its docstring for more information. """ return self._array.shape def size(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.size <numpy.ndarray.size>`. See its docstring for more information. """ return self._array.size def T(self) -> Array: """ Array API compatible wrapper for :py:meth:`np.ndarray.T <numpy.ndarray.T>`. See its docstring for more information. """ # Note: T only works on 2-dimensional arrays. See the corresponding # note in the specification: # https://data-apis.org/array-api/latest/API_specification/array_object.html#t if self.ndim != 2: raise ValueError("x.T requires x to have 2 dimensions. Use x.mT to transpose stacks of matrices and permute_dims() to permute dimensions.") return self.__class__._new(self._array.T) The provided code snippet includes necessary dependencies for implementing the `cos` function. Write a Python function `def cos(x: Array, /) -> Array` to solve the following problem: Array API compatible wrapper for :py:func:`np.cos <numpy.cos>`. See its docstring for more information. Here is the function: def cos(x: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.cos <numpy.cos>`. See its docstring for more information. """ if x.dtype not in _floating_dtypes: raise TypeError("Only floating-point dtypes are allowed in cos") return Array._new(np.cos(x._array))
Array API compatible wrapper for :py:func:`np.cos <numpy.cos>`. See its docstring for more information.
170,036
from __future__ import annotations from ._dtypes import ( _boolean_dtypes, _floating_dtypes, _integer_dtypes, _integer_or_boolean_dtypes, _numeric_dtypes, _result_type, ) from ._array_object import Array import numpy as np _floating_dtypes = (float32, float64) class Array: """ n-d array object for the array API namespace. See the docstring of :py:obj:`np.ndarray <numpy.ndarray>` for more information. This is a wrapper around numpy.ndarray that restricts the usage to only those things that are required by the array API namespace. Note, attributes on this object that start with a single underscore are not part of the API specification and should only be used internally. This object should not be constructed directly. Rather, use one of the creation functions, such as asarray(). """ _array: np.ndarray # Use a custom constructor instead of __init__, as manually initializing # this class is not supported API. def _new(cls, x, /): """ This is a private method for initializing the array API Array object. Functions outside of the array_api submodule should not use this method. Use one of the creation functions instead, such as ``asarray``. """ obj = super().__new__(cls) # Note: The spec does not have array scalars, only 0-D arrays. if isinstance(x, np.generic): # Convert the array scalar to a 0-D array x = np.asarray(x) if x.dtype not in _all_dtypes: raise TypeError( f"The array_api namespace does not support the dtype '{x.dtype}'" ) obj._array = x return obj # Prevent Array() from working def __new__(cls, *args, **kwargs): raise TypeError( "The array_api Array object should not be instantiated directly. Use an array creation function, such as asarray(), instead." ) # These functions are not required by the spec, but are implemented for # the sake of usability. def __str__(self: Array, /) -> str: """ Performs the operation __str__. """ return self._array.__str__().replace("array", "Array") def __repr__(self: Array, /) -> str: """ Performs the operation __repr__. """ suffix = f", dtype={self.dtype.name})" if 0 in self.shape: prefix = "empty(" mid = str(self.shape) else: prefix = "Array(" mid = np.array2string(self._array, separator=', ', prefix=prefix, suffix=suffix) return prefix + mid + suffix # This function is not required by the spec, but we implement it here for # convenience so that np.asarray(np.array_api.Array) will work. def __array__(self, dtype: None | np.dtype[Any] = None) -> npt.NDArray[Any]: """ Warning: this method is NOT part of the array API spec. Implementers of other libraries need not include it, and users should not assume it will be present in other implementations. """ return np.asarray(self._array, dtype=dtype) # These are various helper functions to make the array behavior match the # spec in places where it either deviates from or is more strict than # NumPy behavior def _check_allowed_dtypes(self, other: bool | int | float | Array, dtype_category: str, op: str) -> Array: """ Helper function for operators to only allow specific input dtypes Use like other = self._check_allowed_dtypes(other, 'numeric', '__add__') if other is NotImplemented: return other """ if self.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") if isinstance(other, (int, float, bool)): other = self._promote_scalar(other) elif isinstance(other, Array): if other.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") else: return NotImplemented # This will raise TypeError for type combinations that are not allowed # to promote in the spec (even if the NumPy array operator would # promote them). res_dtype = _result_type(self.dtype, other.dtype) if op.startswith("__i"): # Note: NumPy will allow in-place operators in some cases where # the type promoted operator does not match the left-hand side # operand. For example, # >>> a = np.array(1, dtype=np.int8) # >>> a += np.array(1, dtype=np.int16) # The spec explicitly disallows this. if res_dtype != self.dtype: raise TypeError( f"Cannot perform {op} with dtypes {self.dtype} and {other.dtype}" ) return other # Helper function to match the type promotion rules in the spec def _promote_scalar(self, scalar): """ Returns a promoted version of a Python scalar appropriate for use with operations on self. This may raise an OverflowError in cases where the scalar is an integer that is too large to fit in a NumPy integer dtype, or TypeError when the scalar type is incompatible with the dtype of self. """ # Note: Only Python scalar types that match the array dtype are # allowed. if isinstance(scalar, bool): if self.dtype not in _boolean_dtypes: raise TypeError( "Python bool scalars can only be promoted with bool arrays" ) elif isinstance(scalar, int): if self.dtype in _boolean_dtypes: raise TypeError( "Python int scalars cannot be promoted with bool arrays" ) elif isinstance(scalar, float): if self.dtype not in _floating_dtypes: raise TypeError( "Python float scalars can only be promoted with floating-point arrays." ) else: raise TypeError("'scalar' must be a Python scalar") # Note: scalars are unconditionally cast to the same dtype as the # array. # Note: the spec only specifies integer-dtype/int promotion # behavior for integers within the bounds of the integer dtype. # Outside of those bounds we use the default NumPy behavior (either # cast or raise OverflowError). return Array._new(np.array(scalar, self.dtype)) def _normalize_two_args(x1, x2) -> Tuple[Array, Array]: """ Normalize inputs to two arg functions to fix type promotion rules NumPy deviates from the spec type promotion rules in cases where one argument is 0-dimensional and the other is not. For example: >>> import numpy as np >>> a = np.array([1.0], dtype=np.float32) >>> b = np.array(1.0, dtype=np.float64) >>> np.add(a, b) # The spec says this should be float64 array([2.], dtype=float32) To fix this, we add a dimension to the 0-dimension array before passing it through. This works because a dimension would be added anyway from broadcasting, so the resulting shape is the same, but this prevents NumPy from not promoting the dtype. """ # Another option would be to use signature=(x1.dtype, x2.dtype, None), # but that only works for ufuncs, so we would have to call the ufuncs # directly in the operator methods. One should also note that this # sort of trick wouldn't work for functions like searchsorted, which # don't do normal broadcasting, but there aren't any functions like # that in the array API namespace. if x1.ndim == 0 and x2.ndim != 0: # The _array[None] workaround was chosen because it is relatively # performant. broadcast_to(x1._array, x2.shape) is much slower. We # could also manually type promote x2, but that is more complicated # and about the same performance as this. x1 = Array._new(x1._array[None]) elif x2.ndim == 0 and x1.ndim != 0: x2 = Array._new(x2._array[None]) return (x1, x2) # Note: A large fraction of allowed indices are disallowed here (see the # docstring below) def _validate_index(self, key): """ Validate an index according to the array API. The array API specification only requires a subset of indices that are supported by NumPy. This function will reject any index that is allowed by NumPy but not required by the array API specification. We always raise ``IndexError`` on such indices (the spec does not require any specific behavior on them, but this makes the NumPy array API namespace a minimal implementation of the spec). See https://data-apis.org/array-api/latest/API_specification/indexing.html for the full list of required indexing behavior This function raises IndexError if the index ``key`` is invalid. It only raises ``IndexError`` on indices that are not already rejected by NumPy, as NumPy will already raise the appropriate error on such indices. ``shape`` may be None, in which case, only cases that are independent of the array shape are checked. The following cases are allowed by NumPy, but not specified by the array API specification: - Indices to not include an implicit ellipsis at the end. That is, every axis of an array must be explicitly indexed or an ellipsis included. This behaviour is sometimes referred to as flat indexing. - The start and stop of a slice may not be out of bounds. In particular, for a slice ``i:j:k`` on an axis of size ``n``, only the following are allowed: - ``i`` or ``j`` omitted (``None``). - ``-n <= i <= max(0, n - 1)``. - For ``k > 0`` or ``k`` omitted (``None``), ``-n <= j <= n``. - For ``k < 0``, ``-n - 1 <= j <= max(0, n - 1)``. - Boolean array indices are not allowed as part of a larger tuple index. - Integer array indices are not allowed (with the exception of 0-D arrays, which are treated the same as scalars). Additionally, it should be noted that indices that would return a scalar in NumPy will return a 0-D array. Array scalars are not allowed in the specification, only 0-D arrays. This is done in the ``Array._new`` constructor, not this function. """ _key = key if isinstance(key, tuple) else (key,) for i in _key: if isinstance(i, bool) or not ( isinstance(i, SupportsIndex) # i.e. ints or isinstance(i, slice) or i == Ellipsis or i is None or isinstance(i, Array) or isinstance(i, np.ndarray) ): raise IndexError( f"Single-axes index {i} has {type(i)=}, but only " "integers, slices (:), ellipsis (...), newaxis (None), " "zero-dimensional integer arrays and boolean arrays " "are specified in the Array API." ) nonexpanding_key = [] single_axes = [] n_ellipsis = 0 key_has_mask = False for i in _key: if i is not None: nonexpanding_key.append(i) if isinstance(i, Array) or isinstance(i, np.ndarray): if i.dtype in _boolean_dtypes: key_has_mask = True single_axes.append(i) else: # i must not be an array here, to avoid elementwise equals if i == Ellipsis: n_ellipsis += 1 else: single_axes.append(i) n_single_axes = len(single_axes) if n_ellipsis > 1: return # handled by ndarray elif n_ellipsis == 0: # Note boolean masks must be the sole index, which we check for # later on. if not key_has_mask and n_single_axes < self.ndim: raise IndexError( f"{self.ndim=}, but the multi-axes index only specifies " f"{n_single_axes} dimensions. If this was intentional, " "add a trailing ellipsis (...) which expands into as many " "slices (:) as necessary - this is what np.ndarray arrays " "implicitly do, but such flat indexing behaviour is not " "specified in the Array API." ) if n_ellipsis == 0: indexed_shape = self.shape else: ellipsis_start = None for pos, i in enumerate(nonexpanding_key): if not (isinstance(i, Array) or isinstance(i, np.ndarray)): if i == Ellipsis: ellipsis_start = pos break assert ellipsis_start is not None # sanity check ellipsis_end = self.ndim - (n_single_axes - ellipsis_start) indexed_shape = ( self.shape[:ellipsis_start] + self.shape[ellipsis_end:] ) for i, side in zip(single_axes, indexed_shape): if isinstance(i, slice): if side == 0: f_range = "0 (or None)" else: f_range = f"between -{side} and {side - 1} (or None)" if i.start is not None: try: start = operator.index(i.start) except TypeError: pass # handled by ndarray else: if not (-side <= start <= side): raise IndexError( f"Slice {i} contains {start=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds starts are not specified in " "the Array API)" ) if i.stop is not None: try: stop = operator.index(i.stop) except TypeError: pass # handled by ndarray else: if not (-side <= stop <= side): raise IndexError( f"Slice {i} contains {stop=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds stops are not specified in " "the Array API)" ) elif isinstance(i, Array): if i.dtype in _boolean_dtypes and len(_key) != 1: assert isinstance(key, tuple) # sanity check raise IndexError( f"Single-axes index {i} is a boolean array and " f"{len(key)=}, but masking is only specified in the " "Array API when the array is the sole index." ) elif i.dtype in _integer_dtypes and i.ndim != 0: raise IndexError( f"Single-axes index {i} is a non-zero-dimensional " "integer array, but advanced integer indexing is not " "specified in the Array API." ) elif isinstance(i, tuple): raise IndexError( f"Single-axes index {i} is a tuple, but nested tuple " "indices are not specified in the Array API." ) # Everything below this line is required by the spec. def __abs__(self: Array, /) -> Array: """ Performs the operation __abs__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __abs__") res = self._array.__abs__() return self.__class__._new(res) def __add__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __add__. """ other = self._check_allowed_dtypes(other, "numeric", "__add__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__add__(other._array) return self.__class__._new(res) def __and__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __and__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__and__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__and__(other._array) return self.__class__._new(res) def __array_namespace__( self: Array, /, *, api_version: Optional[str] = None ) -> types.ModuleType: if api_version is not None and not api_version.startswith("2021."): raise ValueError(f"Unrecognized array API version: {api_version!r}") return array_api def __bool__(self: Array, /) -> bool: """ Performs the operation __bool__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("bool is only allowed on arrays with 0 dimensions") if self.dtype not in _boolean_dtypes: raise ValueError("bool is only allowed on boolean arrays") res = self._array.__bool__() return res def __dlpack__(self: Array, /, *, stream: None = None) -> PyCapsule: """ Performs the operation __dlpack__. """ return self._array.__dlpack__(stream=stream) def __dlpack_device__(self: Array, /) -> Tuple[IntEnum, int]: """ Performs the operation __dlpack_device__. """ # Note: device support is required for this return self._array.__dlpack_device__() def __eq__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __eq__. """ # Even though "all" dtypes are allowed, we still require them to be # promotable with each other. other = self._check_allowed_dtypes(other, "all", "__eq__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__eq__(other._array) return self.__class__._new(res) def __float__(self: Array, /) -> float: """ Performs the operation __float__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("float is only allowed on arrays with 0 dimensions") if self.dtype not in _floating_dtypes: raise ValueError("float is only allowed on floating-point arrays") res = self._array.__float__() return res def __floordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __floordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__floordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__floordiv__(other._array) return self.__class__._new(res) def __ge__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ge__. """ other = self._check_allowed_dtypes(other, "numeric", "__ge__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ge__(other._array) return self.__class__._new(res) def __getitem__( self: Array, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], /, ) -> Array: """ Performs the operation __getitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array res = self._array.__getitem__(key) return self._new(res) def __gt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __gt__. """ other = self._check_allowed_dtypes(other, "numeric", "__gt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__gt__(other._array) return self.__class__._new(res) def __int__(self: Array, /) -> int: """ Performs the operation __int__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("int is only allowed on arrays with 0 dimensions") if self.dtype not in _integer_dtypes: raise ValueError("int is only allowed on integer arrays") res = self._array.__int__() return res def __index__(self: Array, /) -> int: """ Performs the operation __index__. """ res = self._array.__index__() return res def __invert__(self: Array, /) -> Array: """ Performs the operation __invert__. """ if self.dtype not in _integer_or_boolean_dtypes: raise TypeError("Only integer or boolean dtypes are allowed in __invert__") res = self._array.__invert__() return self.__class__._new(res) def __le__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __le__. """ other = self._check_allowed_dtypes(other, "numeric", "__le__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__le__(other._array) return self.__class__._new(res) def __lshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __lshift__. """ other = self._check_allowed_dtypes(other, "integer", "__lshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lshift__(other._array) return self.__class__._new(res) def __lt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __lt__. """ other = self._check_allowed_dtypes(other, "numeric", "__lt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lt__(other._array) return self.__class__._new(res) def __matmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __matmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__matmul__") if other is NotImplemented: return other res = self._array.__matmul__(other._array) return self.__class__._new(res) def __mod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mod__. """ other = self._check_allowed_dtypes(other, "numeric", "__mod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mod__(other._array) return self.__class__._new(res) def __mul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mul__. """ other = self._check_allowed_dtypes(other, "numeric", "__mul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mul__(other._array) return self.__class__._new(res) def __ne__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __ne__. """ other = self._check_allowed_dtypes(other, "all", "__ne__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ne__(other._array) return self.__class__._new(res) def __neg__(self: Array, /) -> Array: """ Performs the operation __neg__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __neg__") res = self._array.__neg__() return self.__class__._new(res) def __or__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __or__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__or__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__or__(other._array) return self.__class__._new(res) def __pos__(self: Array, /) -> Array: """ Performs the operation __pos__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __pos__") res = self._array.__pos__() return self.__class__._new(res) def __pow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __pow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__pow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow type promotion rules for 0-d # arrays, so we use pow() here instead. return pow(self, other) def __rshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rshift__(other._array) return self.__class__._new(res) def __setitem__( self, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], value: Union[int, float, bool, Array], /, ) -> None: """ Performs the operation __setitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array self._array.__setitem__(key, asarray(value)._array) def __sub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __sub__. """ other = self._check_allowed_dtypes(other, "numeric", "__sub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__sub__(other._array) return self.__class__._new(res) # PEP 484 requires int to be a subtype of float, but __truediv__ should # not accept int. def __truediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __truediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__truediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__truediv__(other._array) return self.__class__._new(res) def __xor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __xor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__xor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__xor__(other._array) return self.__class__._new(res) def __iadd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __iadd__. """ other = self._check_allowed_dtypes(other, "numeric", "__iadd__") if other is NotImplemented: return other self._array.__iadd__(other._array) return self def __radd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __radd__. """ other = self._check_allowed_dtypes(other, "numeric", "__radd__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__radd__(other._array) return self.__class__._new(res) def __iand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __iand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__iand__") if other is NotImplemented: return other self._array.__iand__(other._array) return self def __rand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rand__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rand__(other._array) return self.__class__._new(res) def __ifloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ifloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__ifloordiv__") if other is NotImplemented: return other self._array.__ifloordiv__(other._array) return self def __rfloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rfloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__rfloordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rfloordiv__(other._array) return self.__class__._new(res) def __ilshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __ilshift__. """ other = self._check_allowed_dtypes(other, "integer", "__ilshift__") if other is NotImplemented: return other self._array.__ilshift__(other._array) return self def __rlshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rlshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rlshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rlshift__(other._array) return self.__class__._new(res) def __imatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __imatmul__. """ # Note: NumPy does not implement __imatmul__. # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__imatmul__") if other is NotImplemented: return other # __imatmul__ can only be allowed when it would not change the shape # of self. other_shape = other.shape if self.shape == () or other_shape == (): raise ValueError("@= requires at least one dimension") if len(other_shape) == 1 or other_shape[-1] != other_shape[-2]: raise ValueError("@= cannot change the shape of the input array") self._array[:] = self._array.__matmul__(other._array) return self def __rmatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __rmatmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__rmatmul__") if other is NotImplemented: return other res = self._array.__rmatmul__(other._array) return self.__class__._new(res) def __imod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imod__. """ other = self._check_allowed_dtypes(other, "numeric", "__imod__") if other is NotImplemented: return other self._array.__imod__(other._array) return self def __rmod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmod__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmod__(other._array) return self.__class__._new(res) def __imul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imul__. """ other = self._check_allowed_dtypes(other, "numeric", "__imul__") if other is NotImplemented: return other self._array.__imul__(other._array) return self def __rmul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmul__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmul__(other._array) return self.__class__._new(res) def __ior__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ior__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ior__") if other is NotImplemented: return other self._array.__ior__(other._array) return self def __ror__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ror__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ror__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ror__(other._array) return self.__class__._new(res) def __ipow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ipow__. """ other = self._check_allowed_dtypes(other, "numeric", "__ipow__") if other is NotImplemented: return other self._array.__ipow__(other._array) return self def __rpow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rpow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__rpow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow the spec type promotion rules # for 0-d arrays, so we use pow() here instead. return pow(other, self) def __irshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __irshift__. """ other = self._check_allowed_dtypes(other, "integer", "__irshift__") if other is NotImplemented: return other self._array.__irshift__(other._array) return self def __rrshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rrshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rrshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rrshift__(other._array) return self.__class__._new(res) def __isub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __isub__. """ other = self._check_allowed_dtypes(other, "numeric", "__isub__") if other is NotImplemented: return other self._array.__isub__(other._array) return self def __rsub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rsub__. """ other = self._check_allowed_dtypes(other, "numeric", "__rsub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rsub__(other._array) return self.__class__._new(res) def __itruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __itruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__itruediv__") if other is NotImplemented: return other self._array.__itruediv__(other._array) return self def __rtruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __rtruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__rtruediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rtruediv__(other._array) return self.__class__._new(res) def __ixor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ixor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ixor__") if other is NotImplemented: return other self._array.__ixor__(other._array) return self def __rxor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rxor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rxor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rxor__(other._array) return self.__class__._new(res) def to_device(self: Array, device: Device, /, stream: None = None) -> Array: if stream is not None: raise ValueError("The stream argument to to_device() is not supported") if device == 'cpu': return self raise ValueError(f"Unsupported device {device!r}") def dtype(self) -> Dtype: """ Array API compatible wrapper for :py:meth:`np.ndarray.dtype <numpy.ndarray.dtype>`. See its docstring for more information. """ return self._array.dtype def device(self) -> Device: return "cpu" # Note: mT is new in array API spec (see matrix_transpose) def mT(self) -> Array: from .linalg import matrix_transpose return matrix_transpose(self) def ndim(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.ndim <numpy.ndarray.ndim>`. See its docstring for more information. """ return self._array.ndim def shape(self) -> Tuple[int, ...]: """ Array API compatible wrapper for :py:meth:`np.ndarray.shape <numpy.ndarray.shape>`. See its docstring for more information. """ return self._array.shape def size(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.size <numpy.ndarray.size>`. See its docstring for more information. """ return self._array.size def T(self) -> Array: """ Array API compatible wrapper for :py:meth:`np.ndarray.T <numpy.ndarray.T>`. See its docstring for more information. """ # Note: T only works on 2-dimensional arrays. See the corresponding # note in the specification: # https://data-apis.org/array-api/latest/API_specification/array_object.html#t if self.ndim != 2: raise ValueError("x.T requires x to have 2 dimensions. Use x.mT to transpose stacks of matrices and permute_dims() to permute dimensions.") return self.__class__._new(self._array.T) The provided code snippet includes necessary dependencies for implementing the `cosh` function. Write a Python function `def cosh(x: Array, /) -> Array` to solve the following problem: Array API compatible wrapper for :py:func:`np.cosh <numpy.cosh>`. See its docstring for more information. Here is the function: def cosh(x: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.cosh <numpy.cosh>`. See its docstring for more information. """ if x.dtype not in _floating_dtypes: raise TypeError("Only floating-point dtypes are allowed in cosh") return Array._new(np.cosh(x._array))
Array API compatible wrapper for :py:func:`np.cosh <numpy.cosh>`. See its docstring for more information.
170,037
from __future__ import annotations from ._dtypes import ( _boolean_dtypes, _floating_dtypes, _integer_dtypes, _integer_or_boolean_dtypes, _numeric_dtypes, _result_type, ) from ._array_object import Array import numpy as np _floating_dtypes = (float32, float64) def _result_type(type1, type2): if (type1, type2) in _promotion_table: return _promotion_table[type1, type2] raise TypeError(f"{type1} and {type2} cannot be type promoted together") class Array: """ n-d array object for the array API namespace. See the docstring of :py:obj:`np.ndarray <numpy.ndarray>` for more information. This is a wrapper around numpy.ndarray that restricts the usage to only those things that are required by the array API namespace. Note, attributes on this object that start with a single underscore are not part of the API specification and should only be used internally. This object should not be constructed directly. Rather, use one of the creation functions, such as asarray(). """ _array: np.ndarray # Use a custom constructor instead of __init__, as manually initializing # this class is not supported API. def _new(cls, x, /): """ This is a private method for initializing the array API Array object. Functions outside of the array_api submodule should not use this method. Use one of the creation functions instead, such as ``asarray``. """ obj = super().__new__(cls) # Note: The spec does not have array scalars, only 0-D arrays. if isinstance(x, np.generic): # Convert the array scalar to a 0-D array x = np.asarray(x) if x.dtype not in _all_dtypes: raise TypeError( f"The array_api namespace does not support the dtype '{x.dtype}'" ) obj._array = x return obj # Prevent Array() from working def __new__(cls, *args, **kwargs): raise TypeError( "The array_api Array object should not be instantiated directly. Use an array creation function, such as asarray(), instead." ) # These functions are not required by the spec, but are implemented for # the sake of usability. def __str__(self: Array, /) -> str: """ Performs the operation __str__. """ return self._array.__str__().replace("array", "Array") def __repr__(self: Array, /) -> str: """ Performs the operation __repr__. """ suffix = f", dtype={self.dtype.name})" if 0 in self.shape: prefix = "empty(" mid = str(self.shape) else: prefix = "Array(" mid = np.array2string(self._array, separator=', ', prefix=prefix, suffix=suffix) return prefix + mid + suffix # This function is not required by the spec, but we implement it here for # convenience so that np.asarray(np.array_api.Array) will work. def __array__(self, dtype: None | np.dtype[Any] = None) -> npt.NDArray[Any]: """ Warning: this method is NOT part of the array API spec. Implementers of other libraries need not include it, and users should not assume it will be present in other implementations. """ return np.asarray(self._array, dtype=dtype) # These are various helper functions to make the array behavior match the # spec in places where it either deviates from or is more strict than # NumPy behavior def _check_allowed_dtypes(self, other: bool | int | float | Array, dtype_category: str, op: str) -> Array: """ Helper function for operators to only allow specific input dtypes Use like other = self._check_allowed_dtypes(other, 'numeric', '__add__') if other is NotImplemented: return other """ if self.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") if isinstance(other, (int, float, bool)): other = self._promote_scalar(other) elif isinstance(other, Array): if other.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") else: return NotImplemented # This will raise TypeError for type combinations that are not allowed # to promote in the spec (even if the NumPy array operator would # promote them). res_dtype = _result_type(self.dtype, other.dtype) if op.startswith("__i"): # Note: NumPy will allow in-place operators in some cases where # the type promoted operator does not match the left-hand side # operand. For example, # >>> a = np.array(1, dtype=np.int8) # >>> a += np.array(1, dtype=np.int16) # The spec explicitly disallows this. if res_dtype != self.dtype: raise TypeError( f"Cannot perform {op} with dtypes {self.dtype} and {other.dtype}" ) return other # Helper function to match the type promotion rules in the spec def _promote_scalar(self, scalar): """ Returns a promoted version of a Python scalar appropriate for use with operations on self. This may raise an OverflowError in cases where the scalar is an integer that is too large to fit in a NumPy integer dtype, or TypeError when the scalar type is incompatible with the dtype of self. """ # Note: Only Python scalar types that match the array dtype are # allowed. if isinstance(scalar, bool): if self.dtype not in _boolean_dtypes: raise TypeError( "Python bool scalars can only be promoted with bool arrays" ) elif isinstance(scalar, int): if self.dtype in _boolean_dtypes: raise TypeError( "Python int scalars cannot be promoted with bool arrays" ) elif isinstance(scalar, float): if self.dtype not in _floating_dtypes: raise TypeError( "Python float scalars can only be promoted with floating-point arrays." ) else: raise TypeError("'scalar' must be a Python scalar") # Note: scalars are unconditionally cast to the same dtype as the # array. # Note: the spec only specifies integer-dtype/int promotion # behavior for integers within the bounds of the integer dtype. # Outside of those bounds we use the default NumPy behavior (either # cast or raise OverflowError). return Array._new(np.array(scalar, self.dtype)) def _normalize_two_args(x1, x2) -> Tuple[Array, Array]: """ Normalize inputs to two arg functions to fix type promotion rules NumPy deviates from the spec type promotion rules in cases where one argument is 0-dimensional and the other is not. For example: >>> import numpy as np >>> a = np.array([1.0], dtype=np.float32) >>> b = np.array(1.0, dtype=np.float64) >>> np.add(a, b) # The spec says this should be float64 array([2.], dtype=float32) To fix this, we add a dimension to the 0-dimension array before passing it through. This works because a dimension would be added anyway from broadcasting, so the resulting shape is the same, but this prevents NumPy from not promoting the dtype. """ # Another option would be to use signature=(x1.dtype, x2.dtype, None), # but that only works for ufuncs, so we would have to call the ufuncs # directly in the operator methods. One should also note that this # sort of trick wouldn't work for functions like searchsorted, which # don't do normal broadcasting, but there aren't any functions like # that in the array API namespace. if x1.ndim == 0 and x2.ndim != 0: # The _array[None] workaround was chosen because it is relatively # performant. broadcast_to(x1._array, x2.shape) is much slower. We # could also manually type promote x2, but that is more complicated # and about the same performance as this. x1 = Array._new(x1._array[None]) elif x2.ndim == 0 and x1.ndim != 0: x2 = Array._new(x2._array[None]) return (x1, x2) # Note: A large fraction of allowed indices are disallowed here (see the # docstring below) def _validate_index(self, key): """ Validate an index according to the array API. The array API specification only requires a subset of indices that are supported by NumPy. This function will reject any index that is allowed by NumPy but not required by the array API specification. We always raise ``IndexError`` on such indices (the spec does not require any specific behavior on them, but this makes the NumPy array API namespace a minimal implementation of the spec). See https://data-apis.org/array-api/latest/API_specification/indexing.html for the full list of required indexing behavior This function raises IndexError if the index ``key`` is invalid. It only raises ``IndexError`` on indices that are not already rejected by NumPy, as NumPy will already raise the appropriate error on such indices. ``shape`` may be None, in which case, only cases that are independent of the array shape are checked. The following cases are allowed by NumPy, but not specified by the array API specification: - Indices to not include an implicit ellipsis at the end. That is, every axis of an array must be explicitly indexed or an ellipsis included. This behaviour is sometimes referred to as flat indexing. - The start and stop of a slice may not be out of bounds. In particular, for a slice ``i:j:k`` on an axis of size ``n``, only the following are allowed: - ``i`` or ``j`` omitted (``None``). - ``-n <= i <= max(0, n - 1)``. - For ``k > 0`` or ``k`` omitted (``None``), ``-n <= j <= n``. - For ``k < 0``, ``-n - 1 <= j <= max(0, n - 1)``. - Boolean array indices are not allowed as part of a larger tuple index. - Integer array indices are not allowed (with the exception of 0-D arrays, which are treated the same as scalars). Additionally, it should be noted that indices that would return a scalar in NumPy will return a 0-D array. Array scalars are not allowed in the specification, only 0-D arrays. This is done in the ``Array._new`` constructor, not this function. """ _key = key if isinstance(key, tuple) else (key,) for i in _key: if isinstance(i, bool) or not ( isinstance(i, SupportsIndex) # i.e. ints or isinstance(i, slice) or i == Ellipsis or i is None or isinstance(i, Array) or isinstance(i, np.ndarray) ): raise IndexError( f"Single-axes index {i} has {type(i)=}, but only " "integers, slices (:), ellipsis (...), newaxis (None), " "zero-dimensional integer arrays and boolean arrays " "are specified in the Array API." ) nonexpanding_key = [] single_axes = [] n_ellipsis = 0 key_has_mask = False for i in _key: if i is not None: nonexpanding_key.append(i) if isinstance(i, Array) or isinstance(i, np.ndarray): if i.dtype in _boolean_dtypes: key_has_mask = True single_axes.append(i) else: # i must not be an array here, to avoid elementwise equals if i == Ellipsis: n_ellipsis += 1 else: single_axes.append(i) n_single_axes = len(single_axes) if n_ellipsis > 1: return # handled by ndarray elif n_ellipsis == 0: # Note boolean masks must be the sole index, which we check for # later on. if not key_has_mask and n_single_axes < self.ndim: raise IndexError( f"{self.ndim=}, but the multi-axes index only specifies " f"{n_single_axes} dimensions. If this was intentional, " "add a trailing ellipsis (...) which expands into as many " "slices (:) as necessary - this is what np.ndarray arrays " "implicitly do, but such flat indexing behaviour is not " "specified in the Array API." ) if n_ellipsis == 0: indexed_shape = self.shape else: ellipsis_start = None for pos, i in enumerate(nonexpanding_key): if not (isinstance(i, Array) or isinstance(i, np.ndarray)): if i == Ellipsis: ellipsis_start = pos break assert ellipsis_start is not None # sanity check ellipsis_end = self.ndim - (n_single_axes - ellipsis_start) indexed_shape = ( self.shape[:ellipsis_start] + self.shape[ellipsis_end:] ) for i, side in zip(single_axes, indexed_shape): if isinstance(i, slice): if side == 0: f_range = "0 (or None)" else: f_range = f"between -{side} and {side - 1} (or None)" if i.start is not None: try: start = operator.index(i.start) except TypeError: pass # handled by ndarray else: if not (-side <= start <= side): raise IndexError( f"Slice {i} contains {start=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds starts are not specified in " "the Array API)" ) if i.stop is not None: try: stop = operator.index(i.stop) except TypeError: pass # handled by ndarray else: if not (-side <= stop <= side): raise IndexError( f"Slice {i} contains {stop=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds stops are not specified in " "the Array API)" ) elif isinstance(i, Array): if i.dtype in _boolean_dtypes and len(_key) != 1: assert isinstance(key, tuple) # sanity check raise IndexError( f"Single-axes index {i} is a boolean array and " f"{len(key)=}, but masking is only specified in the " "Array API when the array is the sole index." ) elif i.dtype in _integer_dtypes and i.ndim != 0: raise IndexError( f"Single-axes index {i} is a non-zero-dimensional " "integer array, but advanced integer indexing is not " "specified in the Array API." ) elif isinstance(i, tuple): raise IndexError( f"Single-axes index {i} is a tuple, but nested tuple " "indices are not specified in the Array API." ) # Everything below this line is required by the spec. def __abs__(self: Array, /) -> Array: """ Performs the operation __abs__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __abs__") res = self._array.__abs__() return self.__class__._new(res) def __add__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __add__. """ other = self._check_allowed_dtypes(other, "numeric", "__add__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__add__(other._array) return self.__class__._new(res) def __and__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __and__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__and__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__and__(other._array) return self.__class__._new(res) def __array_namespace__( self: Array, /, *, api_version: Optional[str] = None ) -> types.ModuleType: if api_version is not None and not api_version.startswith("2021."): raise ValueError(f"Unrecognized array API version: {api_version!r}") return array_api def __bool__(self: Array, /) -> bool: """ Performs the operation __bool__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("bool is only allowed on arrays with 0 dimensions") if self.dtype not in _boolean_dtypes: raise ValueError("bool is only allowed on boolean arrays") res = self._array.__bool__() return res def __dlpack__(self: Array, /, *, stream: None = None) -> PyCapsule: """ Performs the operation __dlpack__. """ return self._array.__dlpack__(stream=stream) def __dlpack_device__(self: Array, /) -> Tuple[IntEnum, int]: """ Performs the operation __dlpack_device__. """ # Note: device support is required for this return self._array.__dlpack_device__() def __eq__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __eq__. """ # Even though "all" dtypes are allowed, we still require them to be # promotable with each other. other = self._check_allowed_dtypes(other, "all", "__eq__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__eq__(other._array) return self.__class__._new(res) def __float__(self: Array, /) -> float: """ Performs the operation __float__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("float is only allowed on arrays with 0 dimensions") if self.dtype not in _floating_dtypes: raise ValueError("float is only allowed on floating-point arrays") res = self._array.__float__() return res def __floordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __floordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__floordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__floordiv__(other._array) return self.__class__._new(res) def __ge__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ge__. """ other = self._check_allowed_dtypes(other, "numeric", "__ge__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ge__(other._array) return self.__class__._new(res) def __getitem__( self: Array, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], /, ) -> Array: """ Performs the operation __getitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array res = self._array.__getitem__(key) return self._new(res) def __gt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __gt__. """ other = self._check_allowed_dtypes(other, "numeric", "__gt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__gt__(other._array) return self.__class__._new(res) def __int__(self: Array, /) -> int: """ Performs the operation __int__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("int is only allowed on arrays with 0 dimensions") if self.dtype not in _integer_dtypes: raise ValueError("int is only allowed on integer arrays") res = self._array.__int__() return res def __index__(self: Array, /) -> int: """ Performs the operation __index__. """ res = self._array.__index__() return res def __invert__(self: Array, /) -> Array: """ Performs the operation __invert__. """ if self.dtype not in _integer_or_boolean_dtypes: raise TypeError("Only integer or boolean dtypes are allowed in __invert__") res = self._array.__invert__() return self.__class__._new(res) def __le__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __le__. """ other = self._check_allowed_dtypes(other, "numeric", "__le__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__le__(other._array) return self.__class__._new(res) def __lshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __lshift__. """ other = self._check_allowed_dtypes(other, "integer", "__lshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lshift__(other._array) return self.__class__._new(res) def __lt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __lt__. """ other = self._check_allowed_dtypes(other, "numeric", "__lt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lt__(other._array) return self.__class__._new(res) def __matmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __matmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__matmul__") if other is NotImplemented: return other res = self._array.__matmul__(other._array) return self.__class__._new(res) def __mod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mod__. """ other = self._check_allowed_dtypes(other, "numeric", "__mod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mod__(other._array) return self.__class__._new(res) def __mul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mul__. """ other = self._check_allowed_dtypes(other, "numeric", "__mul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mul__(other._array) return self.__class__._new(res) def __ne__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __ne__. """ other = self._check_allowed_dtypes(other, "all", "__ne__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ne__(other._array) return self.__class__._new(res) def __neg__(self: Array, /) -> Array: """ Performs the operation __neg__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __neg__") res = self._array.__neg__() return self.__class__._new(res) def __or__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __or__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__or__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__or__(other._array) return self.__class__._new(res) def __pos__(self: Array, /) -> Array: """ Performs the operation __pos__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __pos__") res = self._array.__pos__() return self.__class__._new(res) def __pow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __pow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__pow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow type promotion rules for 0-d # arrays, so we use pow() here instead. return pow(self, other) def __rshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rshift__(other._array) return self.__class__._new(res) def __setitem__( self, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], value: Union[int, float, bool, Array], /, ) -> None: """ Performs the operation __setitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array self._array.__setitem__(key, asarray(value)._array) def __sub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __sub__. """ other = self._check_allowed_dtypes(other, "numeric", "__sub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__sub__(other._array) return self.__class__._new(res) # PEP 484 requires int to be a subtype of float, but __truediv__ should # not accept int. def __truediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __truediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__truediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__truediv__(other._array) return self.__class__._new(res) def __xor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __xor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__xor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__xor__(other._array) return self.__class__._new(res) def __iadd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __iadd__. """ other = self._check_allowed_dtypes(other, "numeric", "__iadd__") if other is NotImplemented: return other self._array.__iadd__(other._array) return self def __radd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __radd__. """ other = self._check_allowed_dtypes(other, "numeric", "__radd__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__radd__(other._array) return self.__class__._new(res) def __iand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __iand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__iand__") if other is NotImplemented: return other self._array.__iand__(other._array) return self def __rand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rand__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rand__(other._array) return self.__class__._new(res) def __ifloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ifloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__ifloordiv__") if other is NotImplemented: return other self._array.__ifloordiv__(other._array) return self def __rfloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rfloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__rfloordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rfloordiv__(other._array) return self.__class__._new(res) def __ilshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __ilshift__. """ other = self._check_allowed_dtypes(other, "integer", "__ilshift__") if other is NotImplemented: return other self._array.__ilshift__(other._array) return self def __rlshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rlshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rlshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rlshift__(other._array) return self.__class__._new(res) def __imatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __imatmul__. """ # Note: NumPy does not implement __imatmul__. # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__imatmul__") if other is NotImplemented: return other # __imatmul__ can only be allowed when it would not change the shape # of self. other_shape = other.shape if self.shape == () or other_shape == (): raise ValueError("@= requires at least one dimension") if len(other_shape) == 1 or other_shape[-1] != other_shape[-2]: raise ValueError("@= cannot change the shape of the input array") self._array[:] = self._array.__matmul__(other._array) return self def __rmatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __rmatmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__rmatmul__") if other is NotImplemented: return other res = self._array.__rmatmul__(other._array) return self.__class__._new(res) def __imod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imod__. """ other = self._check_allowed_dtypes(other, "numeric", "__imod__") if other is NotImplemented: return other self._array.__imod__(other._array) return self def __rmod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmod__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmod__(other._array) return self.__class__._new(res) def __imul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imul__. """ other = self._check_allowed_dtypes(other, "numeric", "__imul__") if other is NotImplemented: return other self._array.__imul__(other._array) return self def __rmul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmul__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmul__(other._array) return self.__class__._new(res) def __ior__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ior__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ior__") if other is NotImplemented: return other self._array.__ior__(other._array) return self def __ror__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ror__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ror__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ror__(other._array) return self.__class__._new(res) def __ipow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ipow__. """ other = self._check_allowed_dtypes(other, "numeric", "__ipow__") if other is NotImplemented: return other self._array.__ipow__(other._array) return self def __rpow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rpow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__rpow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow the spec type promotion rules # for 0-d arrays, so we use pow() here instead. return pow(other, self) def __irshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __irshift__. """ other = self._check_allowed_dtypes(other, "integer", "__irshift__") if other is NotImplemented: return other self._array.__irshift__(other._array) return self def __rrshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rrshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rrshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rrshift__(other._array) return self.__class__._new(res) def __isub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __isub__. """ other = self._check_allowed_dtypes(other, "numeric", "__isub__") if other is NotImplemented: return other self._array.__isub__(other._array) return self def __rsub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rsub__. """ other = self._check_allowed_dtypes(other, "numeric", "__rsub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rsub__(other._array) return self.__class__._new(res) def __itruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __itruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__itruediv__") if other is NotImplemented: return other self._array.__itruediv__(other._array) return self def __rtruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __rtruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__rtruediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rtruediv__(other._array) return self.__class__._new(res) def __ixor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ixor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ixor__") if other is NotImplemented: return other self._array.__ixor__(other._array) return self def __rxor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rxor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rxor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rxor__(other._array) return self.__class__._new(res) def to_device(self: Array, device: Device, /, stream: None = None) -> Array: if stream is not None: raise ValueError("The stream argument to to_device() is not supported") if device == 'cpu': return self raise ValueError(f"Unsupported device {device!r}") def dtype(self) -> Dtype: """ Array API compatible wrapper for :py:meth:`np.ndarray.dtype <numpy.ndarray.dtype>`. See its docstring for more information. """ return self._array.dtype def device(self) -> Device: return "cpu" # Note: mT is new in array API spec (see matrix_transpose) def mT(self) -> Array: from .linalg import matrix_transpose return matrix_transpose(self) def ndim(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.ndim <numpy.ndarray.ndim>`. See its docstring for more information. """ return self._array.ndim def shape(self) -> Tuple[int, ...]: """ Array API compatible wrapper for :py:meth:`np.ndarray.shape <numpy.ndarray.shape>`. See its docstring for more information. """ return self._array.shape def size(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.size <numpy.ndarray.size>`. See its docstring for more information. """ return self._array.size def T(self) -> Array: """ Array API compatible wrapper for :py:meth:`np.ndarray.T <numpy.ndarray.T>`. See its docstring for more information. """ # Note: T only works on 2-dimensional arrays. See the corresponding # note in the specification: # https://data-apis.org/array-api/latest/API_specification/array_object.html#t if self.ndim != 2: raise ValueError("x.T requires x to have 2 dimensions. Use x.mT to transpose stacks of matrices and permute_dims() to permute dimensions.") return self.__class__._new(self._array.T) The provided code snippet includes necessary dependencies for implementing the `divide` function. Write a Python function `def divide(x1: Array, x2: Array, /) -> Array` to solve the following problem: Array API compatible wrapper for :py:func:`np.divide <numpy.divide>`. See its docstring for more information. Here is the function: def divide(x1: Array, x2: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.divide <numpy.divide>`. See its docstring for more information. """ if x1.dtype not in _floating_dtypes or x2.dtype not in _floating_dtypes: raise TypeError("Only floating-point dtypes are allowed in divide") # Call result type here just to raise on disallowed type combinations _result_type(x1.dtype, x2.dtype) x1, x2 = Array._normalize_two_args(x1, x2) return Array._new(np.divide(x1._array, x2._array))
Array API compatible wrapper for :py:func:`np.divide <numpy.divide>`. See its docstring for more information.
170,038
from __future__ import annotations from ._dtypes import ( _boolean_dtypes, _floating_dtypes, _integer_dtypes, _integer_or_boolean_dtypes, _numeric_dtypes, _result_type, ) from ._array_object import Array import numpy as np def _result_type(type1, type2): if (type1, type2) in _promotion_table: return _promotion_table[type1, type2] raise TypeError(f"{type1} and {type2} cannot be type promoted together") class Array: """ n-d array object for the array API namespace. See the docstring of :py:obj:`np.ndarray <numpy.ndarray>` for more information. This is a wrapper around numpy.ndarray that restricts the usage to only those things that are required by the array API namespace. Note, attributes on this object that start with a single underscore are not part of the API specification and should only be used internally. This object should not be constructed directly. Rather, use one of the creation functions, such as asarray(). """ _array: np.ndarray # Use a custom constructor instead of __init__, as manually initializing # this class is not supported API. def _new(cls, x, /): """ This is a private method for initializing the array API Array object. Functions outside of the array_api submodule should not use this method. Use one of the creation functions instead, such as ``asarray``. """ obj = super().__new__(cls) # Note: The spec does not have array scalars, only 0-D arrays. if isinstance(x, np.generic): # Convert the array scalar to a 0-D array x = np.asarray(x) if x.dtype not in _all_dtypes: raise TypeError( f"The array_api namespace does not support the dtype '{x.dtype}'" ) obj._array = x return obj # Prevent Array() from working def __new__(cls, *args, **kwargs): raise TypeError( "The array_api Array object should not be instantiated directly. Use an array creation function, such as asarray(), instead." ) # These functions are not required by the spec, but are implemented for # the sake of usability. def __str__(self: Array, /) -> str: """ Performs the operation __str__. """ return self._array.__str__().replace("array", "Array") def __repr__(self: Array, /) -> str: """ Performs the operation __repr__. """ suffix = f", dtype={self.dtype.name})" if 0 in self.shape: prefix = "empty(" mid = str(self.shape) else: prefix = "Array(" mid = np.array2string(self._array, separator=', ', prefix=prefix, suffix=suffix) return prefix + mid + suffix # This function is not required by the spec, but we implement it here for # convenience so that np.asarray(np.array_api.Array) will work. def __array__(self, dtype: None | np.dtype[Any] = None) -> npt.NDArray[Any]: """ Warning: this method is NOT part of the array API spec. Implementers of other libraries need not include it, and users should not assume it will be present in other implementations. """ return np.asarray(self._array, dtype=dtype) # These are various helper functions to make the array behavior match the # spec in places where it either deviates from or is more strict than # NumPy behavior def _check_allowed_dtypes(self, other: bool | int | float | Array, dtype_category: str, op: str) -> Array: """ Helper function for operators to only allow specific input dtypes Use like other = self._check_allowed_dtypes(other, 'numeric', '__add__') if other is NotImplemented: return other """ if self.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") if isinstance(other, (int, float, bool)): other = self._promote_scalar(other) elif isinstance(other, Array): if other.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") else: return NotImplemented # This will raise TypeError for type combinations that are not allowed # to promote in the spec (even if the NumPy array operator would # promote them). res_dtype = _result_type(self.dtype, other.dtype) if op.startswith("__i"): # Note: NumPy will allow in-place operators in some cases where # the type promoted operator does not match the left-hand side # operand. For example, # >>> a = np.array(1, dtype=np.int8) # >>> a += np.array(1, dtype=np.int16) # The spec explicitly disallows this. if res_dtype != self.dtype: raise TypeError( f"Cannot perform {op} with dtypes {self.dtype} and {other.dtype}" ) return other # Helper function to match the type promotion rules in the spec def _promote_scalar(self, scalar): """ Returns a promoted version of a Python scalar appropriate for use with operations on self. This may raise an OverflowError in cases where the scalar is an integer that is too large to fit in a NumPy integer dtype, or TypeError when the scalar type is incompatible with the dtype of self. """ # Note: Only Python scalar types that match the array dtype are # allowed. if isinstance(scalar, bool): if self.dtype not in _boolean_dtypes: raise TypeError( "Python bool scalars can only be promoted with bool arrays" ) elif isinstance(scalar, int): if self.dtype in _boolean_dtypes: raise TypeError( "Python int scalars cannot be promoted with bool arrays" ) elif isinstance(scalar, float): if self.dtype not in _floating_dtypes: raise TypeError( "Python float scalars can only be promoted with floating-point arrays." ) else: raise TypeError("'scalar' must be a Python scalar") # Note: scalars are unconditionally cast to the same dtype as the # array. # Note: the spec only specifies integer-dtype/int promotion # behavior for integers within the bounds of the integer dtype. # Outside of those bounds we use the default NumPy behavior (either # cast or raise OverflowError). return Array._new(np.array(scalar, self.dtype)) def _normalize_two_args(x1, x2) -> Tuple[Array, Array]: """ Normalize inputs to two arg functions to fix type promotion rules NumPy deviates from the spec type promotion rules in cases where one argument is 0-dimensional and the other is not. For example: >>> import numpy as np >>> a = np.array([1.0], dtype=np.float32) >>> b = np.array(1.0, dtype=np.float64) >>> np.add(a, b) # The spec says this should be float64 array([2.], dtype=float32) To fix this, we add a dimension to the 0-dimension array before passing it through. This works because a dimension would be added anyway from broadcasting, so the resulting shape is the same, but this prevents NumPy from not promoting the dtype. """ # Another option would be to use signature=(x1.dtype, x2.dtype, None), # but that only works for ufuncs, so we would have to call the ufuncs # directly in the operator methods. One should also note that this # sort of trick wouldn't work for functions like searchsorted, which # don't do normal broadcasting, but there aren't any functions like # that in the array API namespace. if x1.ndim == 0 and x2.ndim != 0: # The _array[None] workaround was chosen because it is relatively # performant. broadcast_to(x1._array, x2.shape) is much slower. We # could also manually type promote x2, but that is more complicated # and about the same performance as this. x1 = Array._new(x1._array[None]) elif x2.ndim == 0 and x1.ndim != 0: x2 = Array._new(x2._array[None]) return (x1, x2) # Note: A large fraction of allowed indices are disallowed here (see the # docstring below) def _validate_index(self, key): """ Validate an index according to the array API. The array API specification only requires a subset of indices that are supported by NumPy. This function will reject any index that is allowed by NumPy but not required by the array API specification. We always raise ``IndexError`` on such indices (the spec does not require any specific behavior on them, but this makes the NumPy array API namespace a minimal implementation of the spec). See https://data-apis.org/array-api/latest/API_specification/indexing.html for the full list of required indexing behavior This function raises IndexError if the index ``key`` is invalid. It only raises ``IndexError`` on indices that are not already rejected by NumPy, as NumPy will already raise the appropriate error on such indices. ``shape`` may be None, in which case, only cases that are independent of the array shape are checked. The following cases are allowed by NumPy, but not specified by the array API specification: - Indices to not include an implicit ellipsis at the end. That is, every axis of an array must be explicitly indexed or an ellipsis included. This behaviour is sometimes referred to as flat indexing. - The start and stop of a slice may not be out of bounds. In particular, for a slice ``i:j:k`` on an axis of size ``n``, only the following are allowed: - ``i`` or ``j`` omitted (``None``). - ``-n <= i <= max(0, n - 1)``. - For ``k > 0`` or ``k`` omitted (``None``), ``-n <= j <= n``. - For ``k < 0``, ``-n - 1 <= j <= max(0, n - 1)``. - Boolean array indices are not allowed as part of a larger tuple index. - Integer array indices are not allowed (with the exception of 0-D arrays, which are treated the same as scalars). Additionally, it should be noted that indices that would return a scalar in NumPy will return a 0-D array. Array scalars are not allowed in the specification, only 0-D arrays. This is done in the ``Array._new`` constructor, not this function. """ _key = key if isinstance(key, tuple) else (key,) for i in _key: if isinstance(i, bool) or not ( isinstance(i, SupportsIndex) # i.e. ints or isinstance(i, slice) or i == Ellipsis or i is None or isinstance(i, Array) or isinstance(i, np.ndarray) ): raise IndexError( f"Single-axes index {i} has {type(i)=}, but only " "integers, slices (:), ellipsis (...), newaxis (None), " "zero-dimensional integer arrays and boolean arrays " "are specified in the Array API." ) nonexpanding_key = [] single_axes = [] n_ellipsis = 0 key_has_mask = False for i in _key: if i is not None: nonexpanding_key.append(i) if isinstance(i, Array) or isinstance(i, np.ndarray): if i.dtype in _boolean_dtypes: key_has_mask = True single_axes.append(i) else: # i must not be an array here, to avoid elementwise equals if i == Ellipsis: n_ellipsis += 1 else: single_axes.append(i) n_single_axes = len(single_axes) if n_ellipsis > 1: return # handled by ndarray elif n_ellipsis == 0: # Note boolean masks must be the sole index, which we check for # later on. if not key_has_mask and n_single_axes < self.ndim: raise IndexError( f"{self.ndim=}, but the multi-axes index only specifies " f"{n_single_axes} dimensions. If this was intentional, " "add a trailing ellipsis (...) which expands into as many " "slices (:) as necessary - this is what np.ndarray arrays " "implicitly do, but such flat indexing behaviour is not " "specified in the Array API." ) if n_ellipsis == 0: indexed_shape = self.shape else: ellipsis_start = None for pos, i in enumerate(nonexpanding_key): if not (isinstance(i, Array) or isinstance(i, np.ndarray)): if i == Ellipsis: ellipsis_start = pos break assert ellipsis_start is not None # sanity check ellipsis_end = self.ndim - (n_single_axes - ellipsis_start) indexed_shape = ( self.shape[:ellipsis_start] + self.shape[ellipsis_end:] ) for i, side in zip(single_axes, indexed_shape): if isinstance(i, slice): if side == 0: f_range = "0 (or None)" else: f_range = f"between -{side} and {side - 1} (or None)" if i.start is not None: try: start = operator.index(i.start) except TypeError: pass # handled by ndarray else: if not (-side <= start <= side): raise IndexError( f"Slice {i} contains {start=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds starts are not specified in " "the Array API)" ) if i.stop is not None: try: stop = operator.index(i.stop) except TypeError: pass # handled by ndarray else: if not (-side <= stop <= side): raise IndexError( f"Slice {i} contains {stop=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds stops are not specified in " "the Array API)" ) elif isinstance(i, Array): if i.dtype in _boolean_dtypes and len(_key) != 1: assert isinstance(key, tuple) # sanity check raise IndexError( f"Single-axes index {i} is a boolean array and " f"{len(key)=}, but masking is only specified in the " "Array API when the array is the sole index." ) elif i.dtype in _integer_dtypes and i.ndim != 0: raise IndexError( f"Single-axes index {i} is a non-zero-dimensional " "integer array, but advanced integer indexing is not " "specified in the Array API." ) elif isinstance(i, tuple): raise IndexError( f"Single-axes index {i} is a tuple, but nested tuple " "indices are not specified in the Array API." ) # Everything below this line is required by the spec. def __abs__(self: Array, /) -> Array: """ Performs the operation __abs__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __abs__") res = self._array.__abs__() return self.__class__._new(res) def __add__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __add__. """ other = self._check_allowed_dtypes(other, "numeric", "__add__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__add__(other._array) return self.__class__._new(res) def __and__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __and__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__and__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__and__(other._array) return self.__class__._new(res) def __array_namespace__( self: Array, /, *, api_version: Optional[str] = None ) -> types.ModuleType: if api_version is not None and not api_version.startswith("2021."): raise ValueError(f"Unrecognized array API version: {api_version!r}") return array_api def __bool__(self: Array, /) -> bool: """ Performs the operation __bool__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("bool is only allowed on arrays with 0 dimensions") if self.dtype not in _boolean_dtypes: raise ValueError("bool is only allowed on boolean arrays") res = self._array.__bool__() return res def __dlpack__(self: Array, /, *, stream: None = None) -> PyCapsule: """ Performs the operation __dlpack__. """ return self._array.__dlpack__(stream=stream) def __dlpack_device__(self: Array, /) -> Tuple[IntEnum, int]: """ Performs the operation __dlpack_device__. """ # Note: device support is required for this return self._array.__dlpack_device__() def __eq__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __eq__. """ # Even though "all" dtypes are allowed, we still require them to be # promotable with each other. other = self._check_allowed_dtypes(other, "all", "__eq__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__eq__(other._array) return self.__class__._new(res) def __float__(self: Array, /) -> float: """ Performs the operation __float__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("float is only allowed on arrays with 0 dimensions") if self.dtype not in _floating_dtypes: raise ValueError("float is only allowed on floating-point arrays") res = self._array.__float__() return res def __floordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __floordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__floordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__floordiv__(other._array) return self.__class__._new(res) def __ge__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ge__. """ other = self._check_allowed_dtypes(other, "numeric", "__ge__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ge__(other._array) return self.__class__._new(res) def __getitem__( self: Array, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], /, ) -> Array: """ Performs the operation __getitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array res = self._array.__getitem__(key) return self._new(res) def __gt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __gt__. """ other = self._check_allowed_dtypes(other, "numeric", "__gt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__gt__(other._array) return self.__class__._new(res) def __int__(self: Array, /) -> int: """ Performs the operation __int__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("int is only allowed on arrays with 0 dimensions") if self.dtype not in _integer_dtypes: raise ValueError("int is only allowed on integer arrays") res = self._array.__int__() return res def __index__(self: Array, /) -> int: """ Performs the operation __index__. """ res = self._array.__index__() return res def __invert__(self: Array, /) -> Array: """ Performs the operation __invert__. """ if self.dtype not in _integer_or_boolean_dtypes: raise TypeError("Only integer or boolean dtypes are allowed in __invert__") res = self._array.__invert__() return self.__class__._new(res) def __le__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __le__. """ other = self._check_allowed_dtypes(other, "numeric", "__le__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__le__(other._array) return self.__class__._new(res) def __lshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __lshift__. """ other = self._check_allowed_dtypes(other, "integer", "__lshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lshift__(other._array) return self.__class__._new(res) def __lt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __lt__. """ other = self._check_allowed_dtypes(other, "numeric", "__lt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lt__(other._array) return self.__class__._new(res) def __matmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __matmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__matmul__") if other is NotImplemented: return other res = self._array.__matmul__(other._array) return self.__class__._new(res) def __mod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mod__. """ other = self._check_allowed_dtypes(other, "numeric", "__mod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mod__(other._array) return self.__class__._new(res) def __mul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mul__. """ other = self._check_allowed_dtypes(other, "numeric", "__mul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mul__(other._array) return self.__class__._new(res) def __ne__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __ne__. """ other = self._check_allowed_dtypes(other, "all", "__ne__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ne__(other._array) return self.__class__._new(res) def __neg__(self: Array, /) -> Array: """ Performs the operation __neg__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __neg__") res = self._array.__neg__() return self.__class__._new(res) def __or__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __or__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__or__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__or__(other._array) return self.__class__._new(res) def __pos__(self: Array, /) -> Array: """ Performs the operation __pos__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __pos__") res = self._array.__pos__() return self.__class__._new(res) def __pow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __pow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__pow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow type promotion rules for 0-d # arrays, so we use pow() here instead. return pow(self, other) def __rshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rshift__(other._array) return self.__class__._new(res) def __setitem__( self, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], value: Union[int, float, bool, Array], /, ) -> None: """ Performs the operation __setitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array self._array.__setitem__(key, asarray(value)._array) def __sub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __sub__. """ other = self._check_allowed_dtypes(other, "numeric", "__sub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__sub__(other._array) return self.__class__._new(res) # PEP 484 requires int to be a subtype of float, but __truediv__ should # not accept int. def __truediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __truediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__truediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__truediv__(other._array) return self.__class__._new(res) def __xor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __xor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__xor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__xor__(other._array) return self.__class__._new(res) def __iadd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __iadd__. """ other = self._check_allowed_dtypes(other, "numeric", "__iadd__") if other is NotImplemented: return other self._array.__iadd__(other._array) return self def __radd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __radd__. """ other = self._check_allowed_dtypes(other, "numeric", "__radd__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__radd__(other._array) return self.__class__._new(res) def __iand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __iand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__iand__") if other is NotImplemented: return other self._array.__iand__(other._array) return self def __rand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rand__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rand__(other._array) return self.__class__._new(res) def __ifloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ifloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__ifloordiv__") if other is NotImplemented: return other self._array.__ifloordiv__(other._array) return self def __rfloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rfloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__rfloordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rfloordiv__(other._array) return self.__class__._new(res) def __ilshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __ilshift__. """ other = self._check_allowed_dtypes(other, "integer", "__ilshift__") if other is NotImplemented: return other self._array.__ilshift__(other._array) return self def __rlshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rlshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rlshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rlshift__(other._array) return self.__class__._new(res) def __imatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __imatmul__. """ # Note: NumPy does not implement __imatmul__. # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__imatmul__") if other is NotImplemented: return other # __imatmul__ can only be allowed when it would not change the shape # of self. other_shape = other.shape if self.shape == () or other_shape == (): raise ValueError("@= requires at least one dimension") if len(other_shape) == 1 or other_shape[-1] != other_shape[-2]: raise ValueError("@= cannot change the shape of the input array") self._array[:] = self._array.__matmul__(other._array) return self def __rmatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __rmatmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__rmatmul__") if other is NotImplemented: return other res = self._array.__rmatmul__(other._array) return self.__class__._new(res) def __imod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imod__. """ other = self._check_allowed_dtypes(other, "numeric", "__imod__") if other is NotImplemented: return other self._array.__imod__(other._array) return self def __rmod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmod__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmod__(other._array) return self.__class__._new(res) def __imul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imul__. """ other = self._check_allowed_dtypes(other, "numeric", "__imul__") if other is NotImplemented: return other self._array.__imul__(other._array) return self def __rmul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmul__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmul__(other._array) return self.__class__._new(res) def __ior__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ior__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ior__") if other is NotImplemented: return other self._array.__ior__(other._array) return self def __ror__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ror__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ror__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ror__(other._array) return self.__class__._new(res) def __ipow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ipow__. """ other = self._check_allowed_dtypes(other, "numeric", "__ipow__") if other is NotImplemented: return other self._array.__ipow__(other._array) return self def __rpow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rpow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__rpow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow the spec type promotion rules # for 0-d arrays, so we use pow() here instead. return pow(other, self) def __irshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __irshift__. """ other = self._check_allowed_dtypes(other, "integer", "__irshift__") if other is NotImplemented: return other self._array.__irshift__(other._array) return self def __rrshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rrshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rrshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rrshift__(other._array) return self.__class__._new(res) def __isub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __isub__. """ other = self._check_allowed_dtypes(other, "numeric", "__isub__") if other is NotImplemented: return other self._array.__isub__(other._array) return self def __rsub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rsub__. """ other = self._check_allowed_dtypes(other, "numeric", "__rsub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rsub__(other._array) return self.__class__._new(res) def __itruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __itruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__itruediv__") if other is NotImplemented: return other self._array.__itruediv__(other._array) return self def __rtruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __rtruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__rtruediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rtruediv__(other._array) return self.__class__._new(res) def __ixor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ixor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ixor__") if other is NotImplemented: return other self._array.__ixor__(other._array) return self def __rxor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rxor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rxor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rxor__(other._array) return self.__class__._new(res) def to_device(self: Array, device: Device, /, stream: None = None) -> Array: if stream is not None: raise ValueError("The stream argument to to_device() is not supported") if device == 'cpu': return self raise ValueError(f"Unsupported device {device!r}") def dtype(self) -> Dtype: """ Array API compatible wrapper for :py:meth:`np.ndarray.dtype <numpy.ndarray.dtype>`. See its docstring for more information. """ return self._array.dtype def device(self) -> Device: return "cpu" # Note: mT is new in array API spec (see matrix_transpose) def mT(self) -> Array: from .linalg import matrix_transpose return matrix_transpose(self) def ndim(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.ndim <numpy.ndarray.ndim>`. See its docstring for more information. """ return self._array.ndim def shape(self) -> Tuple[int, ...]: """ Array API compatible wrapper for :py:meth:`np.ndarray.shape <numpy.ndarray.shape>`. See its docstring for more information. """ return self._array.shape def size(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.size <numpy.ndarray.size>`. See its docstring for more information. """ return self._array.size def T(self) -> Array: """ Array API compatible wrapper for :py:meth:`np.ndarray.T <numpy.ndarray.T>`. See its docstring for more information. """ # Note: T only works on 2-dimensional arrays. See the corresponding # note in the specification: # https://data-apis.org/array-api/latest/API_specification/array_object.html#t if self.ndim != 2: raise ValueError("x.T requires x to have 2 dimensions. Use x.mT to transpose stacks of matrices and permute_dims() to permute dimensions.") return self.__class__._new(self._array.T) The provided code snippet includes necessary dependencies for implementing the `equal` function. Write a Python function `def equal(x1: Array, x2: Array, /) -> Array` to solve the following problem: Array API compatible wrapper for :py:func:`np.equal <numpy.equal>`. See its docstring for more information. Here is the function: def equal(x1: Array, x2: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.equal <numpy.equal>`. See its docstring for more information. """ # Call result type here just to raise on disallowed type combinations _result_type(x1.dtype, x2.dtype) x1, x2 = Array._normalize_two_args(x1, x2) return Array._new(np.equal(x1._array, x2._array))
Array API compatible wrapper for :py:func:`np.equal <numpy.equal>`. See its docstring for more information.
170,039
from __future__ import annotations from ._dtypes import ( _boolean_dtypes, _floating_dtypes, _integer_dtypes, _integer_or_boolean_dtypes, _numeric_dtypes, _result_type, ) from ._array_object import Array import numpy as np _floating_dtypes = (float32, float64) class Array: """ n-d array object for the array API namespace. See the docstring of :py:obj:`np.ndarray <numpy.ndarray>` for more information. This is a wrapper around numpy.ndarray that restricts the usage to only those things that are required by the array API namespace. Note, attributes on this object that start with a single underscore are not part of the API specification and should only be used internally. This object should not be constructed directly. Rather, use one of the creation functions, such as asarray(). """ _array: np.ndarray # Use a custom constructor instead of __init__, as manually initializing # this class is not supported API. def _new(cls, x, /): """ This is a private method for initializing the array API Array object. Functions outside of the array_api submodule should not use this method. Use one of the creation functions instead, such as ``asarray``. """ obj = super().__new__(cls) # Note: The spec does not have array scalars, only 0-D arrays. if isinstance(x, np.generic): # Convert the array scalar to a 0-D array x = np.asarray(x) if x.dtype not in _all_dtypes: raise TypeError( f"The array_api namespace does not support the dtype '{x.dtype}'" ) obj._array = x return obj # Prevent Array() from working def __new__(cls, *args, **kwargs): raise TypeError( "The array_api Array object should not be instantiated directly. Use an array creation function, such as asarray(), instead." ) # These functions are not required by the spec, but are implemented for # the sake of usability. def __str__(self: Array, /) -> str: """ Performs the operation __str__. """ return self._array.__str__().replace("array", "Array") def __repr__(self: Array, /) -> str: """ Performs the operation __repr__. """ suffix = f", dtype={self.dtype.name})" if 0 in self.shape: prefix = "empty(" mid = str(self.shape) else: prefix = "Array(" mid = np.array2string(self._array, separator=', ', prefix=prefix, suffix=suffix) return prefix + mid + suffix # This function is not required by the spec, but we implement it here for # convenience so that np.asarray(np.array_api.Array) will work. def __array__(self, dtype: None | np.dtype[Any] = None) -> npt.NDArray[Any]: """ Warning: this method is NOT part of the array API spec. Implementers of other libraries need not include it, and users should not assume it will be present in other implementations. """ return np.asarray(self._array, dtype=dtype) # These are various helper functions to make the array behavior match the # spec in places where it either deviates from or is more strict than # NumPy behavior def _check_allowed_dtypes(self, other: bool | int | float | Array, dtype_category: str, op: str) -> Array: """ Helper function for operators to only allow specific input dtypes Use like other = self._check_allowed_dtypes(other, 'numeric', '__add__') if other is NotImplemented: return other """ if self.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") if isinstance(other, (int, float, bool)): other = self._promote_scalar(other) elif isinstance(other, Array): if other.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") else: return NotImplemented # This will raise TypeError for type combinations that are not allowed # to promote in the spec (even if the NumPy array operator would # promote them). res_dtype = _result_type(self.dtype, other.dtype) if op.startswith("__i"): # Note: NumPy will allow in-place operators in some cases where # the type promoted operator does not match the left-hand side # operand. For example, # >>> a = np.array(1, dtype=np.int8) # >>> a += np.array(1, dtype=np.int16) # The spec explicitly disallows this. if res_dtype != self.dtype: raise TypeError( f"Cannot perform {op} with dtypes {self.dtype} and {other.dtype}" ) return other # Helper function to match the type promotion rules in the spec def _promote_scalar(self, scalar): """ Returns a promoted version of a Python scalar appropriate for use with operations on self. This may raise an OverflowError in cases where the scalar is an integer that is too large to fit in a NumPy integer dtype, or TypeError when the scalar type is incompatible with the dtype of self. """ # Note: Only Python scalar types that match the array dtype are # allowed. if isinstance(scalar, bool): if self.dtype not in _boolean_dtypes: raise TypeError( "Python bool scalars can only be promoted with bool arrays" ) elif isinstance(scalar, int): if self.dtype in _boolean_dtypes: raise TypeError( "Python int scalars cannot be promoted with bool arrays" ) elif isinstance(scalar, float): if self.dtype not in _floating_dtypes: raise TypeError( "Python float scalars can only be promoted with floating-point arrays." ) else: raise TypeError("'scalar' must be a Python scalar") # Note: scalars are unconditionally cast to the same dtype as the # array. # Note: the spec only specifies integer-dtype/int promotion # behavior for integers within the bounds of the integer dtype. # Outside of those bounds we use the default NumPy behavior (either # cast or raise OverflowError). return Array._new(np.array(scalar, self.dtype)) def _normalize_two_args(x1, x2) -> Tuple[Array, Array]: """ Normalize inputs to two arg functions to fix type promotion rules NumPy deviates from the spec type promotion rules in cases where one argument is 0-dimensional and the other is not. For example: >>> import numpy as np >>> a = np.array([1.0], dtype=np.float32) >>> b = np.array(1.0, dtype=np.float64) >>> np.add(a, b) # The spec says this should be float64 array([2.], dtype=float32) To fix this, we add a dimension to the 0-dimension array before passing it through. This works because a dimension would be added anyway from broadcasting, so the resulting shape is the same, but this prevents NumPy from not promoting the dtype. """ # Another option would be to use signature=(x1.dtype, x2.dtype, None), # but that only works for ufuncs, so we would have to call the ufuncs # directly in the operator methods. One should also note that this # sort of trick wouldn't work for functions like searchsorted, which # don't do normal broadcasting, but there aren't any functions like # that in the array API namespace. if x1.ndim == 0 and x2.ndim != 0: # The _array[None] workaround was chosen because it is relatively # performant. broadcast_to(x1._array, x2.shape) is much slower. We # could also manually type promote x2, but that is more complicated # and about the same performance as this. x1 = Array._new(x1._array[None]) elif x2.ndim == 0 and x1.ndim != 0: x2 = Array._new(x2._array[None]) return (x1, x2) # Note: A large fraction of allowed indices are disallowed here (see the # docstring below) def _validate_index(self, key): """ Validate an index according to the array API. The array API specification only requires a subset of indices that are supported by NumPy. This function will reject any index that is allowed by NumPy but not required by the array API specification. We always raise ``IndexError`` on such indices (the spec does not require any specific behavior on them, but this makes the NumPy array API namespace a minimal implementation of the spec). See https://data-apis.org/array-api/latest/API_specification/indexing.html for the full list of required indexing behavior This function raises IndexError if the index ``key`` is invalid. It only raises ``IndexError`` on indices that are not already rejected by NumPy, as NumPy will already raise the appropriate error on such indices. ``shape`` may be None, in which case, only cases that are independent of the array shape are checked. The following cases are allowed by NumPy, but not specified by the array API specification: - Indices to not include an implicit ellipsis at the end. That is, every axis of an array must be explicitly indexed or an ellipsis included. This behaviour is sometimes referred to as flat indexing. - The start and stop of a slice may not be out of bounds. In particular, for a slice ``i:j:k`` on an axis of size ``n``, only the following are allowed: - ``i`` or ``j`` omitted (``None``). - ``-n <= i <= max(0, n - 1)``. - For ``k > 0`` or ``k`` omitted (``None``), ``-n <= j <= n``. - For ``k < 0``, ``-n - 1 <= j <= max(0, n - 1)``. - Boolean array indices are not allowed as part of a larger tuple index. - Integer array indices are not allowed (with the exception of 0-D arrays, which are treated the same as scalars). Additionally, it should be noted that indices that would return a scalar in NumPy will return a 0-D array. Array scalars are not allowed in the specification, only 0-D arrays. This is done in the ``Array._new`` constructor, not this function. """ _key = key if isinstance(key, tuple) else (key,) for i in _key: if isinstance(i, bool) or not ( isinstance(i, SupportsIndex) # i.e. ints or isinstance(i, slice) or i == Ellipsis or i is None or isinstance(i, Array) or isinstance(i, np.ndarray) ): raise IndexError( f"Single-axes index {i} has {type(i)=}, but only " "integers, slices (:), ellipsis (...), newaxis (None), " "zero-dimensional integer arrays and boolean arrays " "are specified in the Array API." ) nonexpanding_key = [] single_axes = [] n_ellipsis = 0 key_has_mask = False for i in _key: if i is not None: nonexpanding_key.append(i) if isinstance(i, Array) or isinstance(i, np.ndarray): if i.dtype in _boolean_dtypes: key_has_mask = True single_axes.append(i) else: # i must not be an array here, to avoid elementwise equals if i == Ellipsis: n_ellipsis += 1 else: single_axes.append(i) n_single_axes = len(single_axes) if n_ellipsis > 1: return # handled by ndarray elif n_ellipsis == 0: # Note boolean masks must be the sole index, which we check for # later on. if not key_has_mask and n_single_axes < self.ndim: raise IndexError( f"{self.ndim=}, but the multi-axes index only specifies " f"{n_single_axes} dimensions. If this was intentional, " "add a trailing ellipsis (...) which expands into as many " "slices (:) as necessary - this is what np.ndarray arrays " "implicitly do, but such flat indexing behaviour is not " "specified in the Array API." ) if n_ellipsis == 0: indexed_shape = self.shape else: ellipsis_start = None for pos, i in enumerate(nonexpanding_key): if not (isinstance(i, Array) or isinstance(i, np.ndarray)): if i == Ellipsis: ellipsis_start = pos break assert ellipsis_start is not None # sanity check ellipsis_end = self.ndim - (n_single_axes - ellipsis_start) indexed_shape = ( self.shape[:ellipsis_start] + self.shape[ellipsis_end:] ) for i, side in zip(single_axes, indexed_shape): if isinstance(i, slice): if side == 0: f_range = "0 (or None)" else: f_range = f"between -{side} and {side - 1} (or None)" if i.start is not None: try: start = operator.index(i.start) except TypeError: pass # handled by ndarray else: if not (-side <= start <= side): raise IndexError( f"Slice {i} contains {start=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds starts are not specified in " "the Array API)" ) if i.stop is not None: try: stop = operator.index(i.stop) except TypeError: pass # handled by ndarray else: if not (-side <= stop <= side): raise IndexError( f"Slice {i} contains {stop=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds stops are not specified in " "the Array API)" ) elif isinstance(i, Array): if i.dtype in _boolean_dtypes and len(_key) != 1: assert isinstance(key, tuple) # sanity check raise IndexError( f"Single-axes index {i} is a boolean array and " f"{len(key)=}, but masking is only specified in the " "Array API when the array is the sole index." ) elif i.dtype in _integer_dtypes and i.ndim != 0: raise IndexError( f"Single-axes index {i} is a non-zero-dimensional " "integer array, but advanced integer indexing is not " "specified in the Array API." ) elif isinstance(i, tuple): raise IndexError( f"Single-axes index {i} is a tuple, but nested tuple " "indices are not specified in the Array API." ) # Everything below this line is required by the spec. def __abs__(self: Array, /) -> Array: """ Performs the operation __abs__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __abs__") res = self._array.__abs__() return self.__class__._new(res) def __add__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __add__. """ other = self._check_allowed_dtypes(other, "numeric", "__add__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__add__(other._array) return self.__class__._new(res) def __and__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __and__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__and__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__and__(other._array) return self.__class__._new(res) def __array_namespace__( self: Array, /, *, api_version: Optional[str] = None ) -> types.ModuleType: if api_version is not None and not api_version.startswith("2021."): raise ValueError(f"Unrecognized array API version: {api_version!r}") return array_api def __bool__(self: Array, /) -> bool: """ Performs the operation __bool__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("bool is only allowed on arrays with 0 dimensions") if self.dtype not in _boolean_dtypes: raise ValueError("bool is only allowed on boolean arrays") res = self._array.__bool__() return res def __dlpack__(self: Array, /, *, stream: None = None) -> PyCapsule: """ Performs the operation __dlpack__. """ return self._array.__dlpack__(stream=stream) def __dlpack_device__(self: Array, /) -> Tuple[IntEnum, int]: """ Performs the operation __dlpack_device__. """ # Note: device support is required for this return self._array.__dlpack_device__() def __eq__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __eq__. """ # Even though "all" dtypes are allowed, we still require them to be # promotable with each other. other = self._check_allowed_dtypes(other, "all", "__eq__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__eq__(other._array) return self.__class__._new(res) def __float__(self: Array, /) -> float: """ Performs the operation __float__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("float is only allowed on arrays with 0 dimensions") if self.dtype not in _floating_dtypes: raise ValueError("float is only allowed on floating-point arrays") res = self._array.__float__() return res def __floordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __floordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__floordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__floordiv__(other._array) return self.__class__._new(res) def __ge__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ge__. """ other = self._check_allowed_dtypes(other, "numeric", "__ge__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ge__(other._array) return self.__class__._new(res) def __getitem__( self: Array, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], /, ) -> Array: """ Performs the operation __getitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array res = self._array.__getitem__(key) return self._new(res) def __gt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __gt__. """ other = self._check_allowed_dtypes(other, "numeric", "__gt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__gt__(other._array) return self.__class__._new(res) def __int__(self: Array, /) -> int: """ Performs the operation __int__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("int is only allowed on arrays with 0 dimensions") if self.dtype not in _integer_dtypes: raise ValueError("int is only allowed on integer arrays") res = self._array.__int__() return res def __index__(self: Array, /) -> int: """ Performs the operation __index__. """ res = self._array.__index__() return res def __invert__(self: Array, /) -> Array: """ Performs the operation __invert__. """ if self.dtype not in _integer_or_boolean_dtypes: raise TypeError("Only integer or boolean dtypes are allowed in __invert__") res = self._array.__invert__() return self.__class__._new(res) def __le__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __le__. """ other = self._check_allowed_dtypes(other, "numeric", "__le__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__le__(other._array) return self.__class__._new(res) def __lshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __lshift__. """ other = self._check_allowed_dtypes(other, "integer", "__lshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lshift__(other._array) return self.__class__._new(res) def __lt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __lt__. """ other = self._check_allowed_dtypes(other, "numeric", "__lt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lt__(other._array) return self.__class__._new(res) def __matmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __matmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__matmul__") if other is NotImplemented: return other res = self._array.__matmul__(other._array) return self.__class__._new(res) def __mod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mod__. """ other = self._check_allowed_dtypes(other, "numeric", "__mod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mod__(other._array) return self.__class__._new(res) def __mul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mul__. """ other = self._check_allowed_dtypes(other, "numeric", "__mul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mul__(other._array) return self.__class__._new(res) def __ne__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __ne__. """ other = self._check_allowed_dtypes(other, "all", "__ne__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ne__(other._array) return self.__class__._new(res) def __neg__(self: Array, /) -> Array: """ Performs the operation __neg__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __neg__") res = self._array.__neg__() return self.__class__._new(res) def __or__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __or__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__or__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__or__(other._array) return self.__class__._new(res) def __pos__(self: Array, /) -> Array: """ Performs the operation __pos__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __pos__") res = self._array.__pos__() return self.__class__._new(res) def __pow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __pow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__pow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow type promotion rules for 0-d # arrays, so we use pow() here instead. return pow(self, other) def __rshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rshift__(other._array) return self.__class__._new(res) def __setitem__( self, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], value: Union[int, float, bool, Array], /, ) -> None: """ Performs the operation __setitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array self._array.__setitem__(key, asarray(value)._array) def __sub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __sub__. """ other = self._check_allowed_dtypes(other, "numeric", "__sub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__sub__(other._array) return self.__class__._new(res) # PEP 484 requires int to be a subtype of float, but __truediv__ should # not accept int. def __truediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __truediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__truediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__truediv__(other._array) return self.__class__._new(res) def __xor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __xor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__xor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__xor__(other._array) return self.__class__._new(res) def __iadd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __iadd__. """ other = self._check_allowed_dtypes(other, "numeric", "__iadd__") if other is NotImplemented: return other self._array.__iadd__(other._array) return self def __radd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __radd__. """ other = self._check_allowed_dtypes(other, "numeric", "__radd__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__radd__(other._array) return self.__class__._new(res) def __iand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __iand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__iand__") if other is NotImplemented: return other self._array.__iand__(other._array) return self def __rand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rand__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rand__(other._array) return self.__class__._new(res) def __ifloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ifloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__ifloordiv__") if other is NotImplemented: return other self._array.__ifloordiv__(other._array) return self def __rfloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rfloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__rfloordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rfloordiv__(other._array) return self.__class__._new(res) def __ilshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __ilshift__. """ other = self._check_allowed_dtypes(other, "integer", "__ilshift__") if other is NotImplemented: return other self._array.__ilshift__(other._array) return self def __rlshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rlshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rlshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rlshift__(other._array) return self.__class__._new(res) def __imatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __imatmul__. """ # Note: NumPy does not implement __imatmul__. # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__imatmul__") if other is NotImplemented: return other # __imatmul__ can only be allowed when it would not change the shape # of self. other_shape = other.shape if self.shape == () or other_shape == (): raise ValueError("@= requires at least one dimension") if len(other_shape) == 1 or other_shape[-1] != other_shape[-2]: raise ValueError("@= cannot change the shape of the input array") self._array[:] = self._array.__matmul__(other._array) return self def __rmatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __rmatmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__rmatmul__") if other is NotImplemented: return other res = self._array.__rmatmul__(other._array) return self.__class__._new(res) def __imod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imod__. """ other = self._check_allowed_dtypes(other, "numeric", "__imod__") if other is NotImplemented: return other self._array.__imod__(other._array) return self def __rmod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmod__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmod__(other._array) return self.__class__._new(res) def __imul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imul__. """ other = self._check_allowed_dtypes(other, "numeric", "__imul__") if other is NotImplemented: return other self._array.__imul__(other._array) return self def __rmul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmul__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmul__(other._array) return self.__class__._new(res) def __ior__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ior__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ior__") if other is NotImplemented: return other self._array.__ior__(other._array) return self def __ror__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ror__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ror__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ror__(other._array) return self.__class__._new(res) def __ipow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ipow__. """ other = self._check_allowed_dtypes(other, "numeric", "__ipow__") if other is NotImplemented: return other self._array.__ipow__(other._array) return self def __rpow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rpow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__rpow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow the spec type promotion rules # for 0-d arrays, so we use pow() here instead. return pow(other, self) def __irshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __irshift__. """ other = self._check_allowed_dtypes(other, "integer", "__irshift__") if other is NotImplemented: return other self._array.__irshift__(other._array) return self def __rrshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rrshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rrshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rrshift__(other._array) return self.__class__._new(res) def __isub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __isub__. """ other = self._check_allowed_dtypes(other, "numeric", "__isub__") if other is NotImplemented: return other self._array.__isub__(other._array) return self def __rsub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rsub__. """ other = self._check_allowed_dtypes(other, "numeric", "__rsub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rsub__(other._array) return self.__class__._new(res) def __itruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __itruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__itruediv__") if other is NotImplemented: return other self._array.__itruediv__(other._array) return self def __rtruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __rtruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__rtruediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rtruediv__(other._array) return self.__class__._new(res) def __ixor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ixor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ixor__") if other is NotImplemented: return other self._array.__ixor__(other._array) return self def __rxor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rxor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rxor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rxor__(other._array) return self.__class__._new(res) def to_device(self: Array, device: Device, /, stream: None = None) -> Array: if stream is not None: raise ValueError("The stream argument to to_device() is not supported") if device == 'cpu': return self raise ValueError(f"Unsupported device {device!r}") def dtype(self) -> Dtype: """ Array API compatible wrapper for :py:meth:`np.ndarray.dtype <numpy.ndarray.dtype>`. See its docstring for more information. """ return self._array.dtype def device(self) -> Device: return "cpu" # Note: mT is new in array API spec (see matrix_transpose) def mT(self) -> Array: from .linalg import matrix_transpose return matrix_transpose(self) def ndim(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.ndim <numpy.ndarray.ndim>`. See its docstring for more information. """ return self._array.ndim def shape(self) -> Tuple[int, ...]: """ Array API compatible wrapper for :py:meth:`np.ndarray.shape <numpy.ndarray.shape>`. See its docstring for more information. """ return self._array.shape def size(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.size <numpy.ndarray.size>`. See its docstring for more information. """ return self._array.size def T(self) -> Array: """ Array API compatible wrapper for :py:meth:`np.ndarray.T <numpy.ndarray.T>`. See its docstring for more information. """ # Note: T only works on 2-dimensional arrays. See the corresponding # note in the specification: # https://data-apis.org/array-api/latest/API_specification/array_object.html#t if self.ndim != 2: raise ValueError("x.T requires x to have 2 dimensions. Use x.mT to transpose stacks of matrices and permute_dims() to permute dimensions.") return self.__class__._new(self._array.T) The provided code snippet includes necessary dependencies for implementing the `exp` function. Write a Python function `def exp(x: Array, /) -> Array` to solve the following problem: Array API compatible wrapper for :py:func:`np.exp <numpy.exp>`. See its docstring for more information. Here is the function: def exp(x: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.exp <numpy.exp>`. See its docstring for more information. """ if x.dtype not in _floating_dtypes: raise TypeError("Only floating-point dtypes are allowed in exp") return Array._new(np.exp(x._array))
Array API compatible wrapper for :py:func:`np.exp <numpy.exp>`. See its docstring for more information.
170,040
from __future__ import annotations from ._dtypes import ( _boolean_dtypes, _floating_dtypes, _integer_dtypes, _integer_or_boolean_dtypes, _numeric_dtypes, _result_type, ) from ._array_object import Array import numpy as np _floating_dtypes = (float32, float64) class Array: """ n-d array object for the array API namespace. See the docstring of :py:obj:`np.ndarray <numpy.ndarray>` for more information. This is a wrapper around numpy.ndarray that restricts the usage to only those things that are required by the array API namespace. Note, attributes on this object that start with a single underscore are not part of the API specification and should only be used internally. This object should not be constructed directly. Rather, use one of the creation functions, such as asarray(). """ _array: np.ndarray # Use a custom constructor instead of __init__, as manually initializing # this class is not supported API. def _new(cls, x, /): """ This is a private method for initializing the array API Array object. Functions outside of the array_api submodule should not use this method. Use one of the creation functions instead, such as ``asarray``. """ obj = super().__new__(cls) # Note: The spec does not have array scalars, only 0-D arrays. if isinstance(x, np.generic): # Convert the array scalar to a 0-D array x = np.asarray(x) if x.dtype not in _all_dtypes: raise TypeError( f"The array_api namespace does not support the dtype '{x.dtype}'" ) obj._array = x return obj # Prevent Array() from working def __new__(cls, *args, **kwargs): raise TypeError( "The array_api Array object should not be instantiated directly. Use an array creation function, such as asarray(), instead." ) # These functions are not required by the spec, but are implemented for # the sake of usability. def __str__(self: Array, /) -> str: """ Performs the operation __str__. """ return self._array.__str__().replace("array", "Array") def __repr__(self: Array, /) -> str: """ Performs the operation __repr__. """ suffix = f", dtype={self.dtype.name})" if 0 in self.shape: prefix = "empty(" mid = str(self.shape) else: prefix = "Array(" mid = np.array2string(self._array, separator=', ', prefix=prefix, suffix=suffix) return prefix + mid + suffix # This function is not required by the spec, but we implement it here for # convenience so that np.asarray(np.array_api.Array) will work. def __array__(self, dtype: None | np.dtype[Any] = None) -> npt.NDArray[Any]: """ Warning: this method is NOT part of the array API spec. Implementers of other libraries need not include it, and users should not assume it will be present in other implementations. """ return np.asarray(self._array, dtype=dtype) # These are various helper functions to make the array behavior match the # spec in places where it either deviates from or is more strict than # NumPy behavior def _check_allowed_dtypes(self, other: bool | int | float | Array, dtype_category: str, op: str) -> Array: """ Helper function for operators to only allow specific input dtypes Use like other = self._check_allowed_dtypes(other, 'numeric', '__add__') if other is NotImplemented: return other """ if self.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") if isinstance(other, (int, float, bool)): other = self._promote_scalar(other) elif isinstance(other, Array): if other.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") else: return NotImplemented # This will raise TypeError for type combinations that are not allowed # to promote in the spec (even if the NumPy array operator would # promote them). res_dtype = _result_type(self.dtype, other.dtype) if op.startswith("__i"): # Note: NumPy will allow in-place operators in some cases where # the type promoted operator does not match the left-hand side # operand. For example, # >>> a = np.array(1, dtype=np.int8) # >>> a += np.array(1, dtype=np.int16) # The spec explicitly disallows this. if res_dtype != self.dtype: raise TypeError( f"Cannot perform {op} with dtypes {self.dtype} and {other.dtype}" ) return other # Helper function to match the type promotion rules in the spec def _promote_scalar(self, scalar): """ Returns a promoted version of a Python scalar appropriate for use with operations on self. This may raise an OverflowError in cases where the scalar is an integer that is too large to fit in a NumPy integer dtype, or TypeError when the scalar type is incompatible with the dtype of self. """ # Note: Only Python scalar types that match the array dtype are # allowed. if isinstance(scalar, bool): if self.dtype not in _boolean_dtypes: raise TypeError( "Python bool scalars can only be promoted with bool arrays" ) elif isinstance(scalar, int): if self.dtype in _boolean_dtypes: raise TypeError( "Python int scalars cannot be promoted with bool arrays" ) elif isinstance(scalar, float): if self.dtype not in _floating_dtypes: raise TypeError( "Python float scalars can only be promoted with floating-point arrays." ) else: raise TypeError("'scalar' must be a Python scalar") # Note: scalars are unconditionally cast to the same dtype as the # array. # Note: the spec only specifies integer-dtype/int promotion # behavior for integers within the bounds of the integer dtype. # Outside of those bounds we use the default NumPy behavior (either # cast or raise OverflowError). return Array._new(np.array(scalar, self.dtype)) def _normalize_two_args(x1, x2) -> Tuple[Array, Array]: """ Normalize inputs to two arg functions to fix type promotion rules NumPy deviates from the spec type promotion rules in cases where one argument is 0-dimensional and the other is not. For example: >>> import numpy as np >>> a = np.array([1.0], dtype=np.float32) >>> b = np.array(1.0, dtype=np.float64) >>> np.add(a, b) # The spec says this should be float64 array([2.], dtype=float32) To fix this, we add a dimension to the 0-dimension array before passing it through. This works because a dimension would be added anyway from broadcasting, so the resulting shape is the same, but this prevents NumPy from not promoting the dtype. """ # Another option would be to use signature=(x1.dtype, x2.dtype, None), # but that only works for ufuncs, so we would have to call the ufuncs # directly in the operator methods. One should also note that this # sort of trick wouldn't work for functions like searchsorted, which # don't do normal broadcasting, but there aren't any functions like # that in the array API namespace. if x1.ndim == 0 and x2.ndim != 0: # The _array[None] workaround was chosen because it is relatively # performant. broadcast_to(x1._array, x2.shape) is much slower. We # could also manually type promote x2, but that is more complicated # and about the same performance as this. x1 = Array._new(x1._array[None]) elif x2.ndim == 0 and x1.ndim != 0: x2 = Array._new(x2._array[None]) return (x1, x2) # Note: A large fraction of allowed indices are disallowed here (see the # docstring below) def _validate_index(self, key): """ Validate an index according to the array API. The array API specification only requires a subset of indices that are supported by NumPy. This function will reject any index that is allowed by NumPy but not required by the array API specification. We always raise ``IndexError`` on such indices (the spec does not require any specific behavior on them, but this makes the NumPy array API namespace a minimal implementation of the spec). See https://data-apis.org/array-api/latest/API_specification/indexing.html for the full list of required indexing behavior This function raises IndexError if the index ``key`` is invalid. It only raises ``IndexError`` on indices that are not already rejected by NumPy, as NumPy will already raise the appropriate error on such indices. ``shape`` may be None, in which case, only cases that are independent of the array shape are checked. The following cases are allowed by NumPy, but not specified by the array API specification: - Indices to not include an implicit ellipsis at the end. That is, every axis of an array must be explicitly indexed or an ellipsis included. This behaviour is sometimes referred to as flat indexing. - The start and stop of a slice may not be out of bounds. In particular, for a slice ``i:j:k`` on an axis of size ``n``, only the following are allowed: - ``i`` or ``j`` omitted (``None``). - ``-n <= i <= max(0, n - 1)``. - For ``k > 0`` or ``k`` omitted (``None``), ``-n <= j <= n``. - For ``k < 0``, ``-n - 1 <= j <= max(0, n - 1)``. - Boolean array indices are not allowed as part of a larger tuple index. - Integer array indices are not allowed (with the exception of 0-D arrays, which are treated the same as scalars). Additionally, it should be noted that indices that would return a scalar in NumPy will return a 0-D array. Array scalars are not allowed in the specification, only 0-D arrays. This is done in the ``Array._new`` constructor, not this function. """ _key = key if isinstance(key, tuple) else (key,) for i in _key: if isinstance(i, bool) or not ( isinstance(i, SupportsIndex) # i.e. ints or isinstance(i, slice) or i == Ellipsis or i is None or isinstance(i, Array) or isinstance(i, np.ndarray) ): raise IndexError( f"Single-axes index {i} has {type(i)=}, but only " "integers, slices (:), ellipsis (...), newaxis (None), " "zero-dimensional integer arrays and boolean arrays " "are specified in the Array API." ) nonexpanding_key = [] single_axes = [] n_ellipsis = 0 key_has_mask = False for i in _key: if i is not None: nonexpanding_key.append(i) if isinstance(i, Array) or isinstance(i, np.ndarray): if i.dtype in _boolean_dtypes: key_has_mask = True single_axes.append(i) else: # i must not be an array here, to avoid elementwise equals if i == Ellipsis: n_ellipsis += 1 else: single_axes.append(i) n_single_axes = len(single_axes) if n_ellipsis > 1: return # handled by ndarray elif n_ellipsis == 0: # Note boolean masks must be the sole index, which we check for # later on. if not key_has_mask and n_single_axes < self.ndim: raise IndexError( f"{self.ndim=}, but the multi-axes index only specifies " f"{n_single_axes} dimensions. If this was intentional, " "add a trailing ellipsis (...) which expands into as many " "slices (:) as necessary - this is what np.ndarray arrays " "implicitly do, but such flat indexing behaviour is not " "specified in the Array API." ) if n_ellipsis == 0: indexed_shape = self.shape else: ellipsis_start = None for pos, i in enumerate(nonexpanding_key): if not (isinstance(i, Array) or isinstance(i, np.ndarray)): if i == Ellipsis: ellipsis_start = pos break assert ellipsis_start is not None # sanity check ellipsis_end = self.ndim - (n_single_axes - ellipsis_start) indexed_shape = ( self.shape[:ellipsis_start] + self.shape[ellipsis_end:] ) for i, side in zip(single_axes, indexed_shape): if isinstance(i, slice): if side == 0: f_range = "0 (or None)" else: f_range = f"between -{side} and {side - 1} (or None)" if i.start is not None: try: start = operator.index(i.start) except TypeError: pass # handled by ndarray else: if not (-side <= start <= side): raise IndexError( f"Slice {i} contains {start=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds starts are not specified in " "the Array API)" ) if i.stop is not None: try: stop = operator.index(i.stop) except TypeError: pass # handled by ndarray else: if not (-side <= stop <= side): raise IndexError( f"Slice {i} contains {stop=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds stops are not specified in " "the Array API)" ) elif isinstance(i, Array): if i.dtype in _boolean_dtypes and len(_key) != 1: assert isinstance(key, tuple) # sanity check raise IndexError( f"Single-axes index {i} is a boolean array and " f"{len(key)=}, but masking is only specified in the " "Array API when the array is the sole index." ) elif i.dtype in _integer_dtypes and i.ndim != 0: raise IndexError( f"Single-axes index {i} is a non-zero-dimensional " "integer array, but advanced integer indexing is not " "specified in the Array API." ) elif isinstance(i, tuple): raise IndexError( f"Single-axes index {i} is a tuple, but nested tuple " "indices are not specified in the Array API." ) # Everything below this line is required by the spec. def __abs__(self: Array, /) -> Array: """ Performs the operation __abs__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __abs__") res = self._array.__abs__() return self.__class__._new(res) def __add__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __add__. """ other = self._check_allowed_dtypes(other, "numeric", "__add__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__add__(other._array) return self.__class__._new(res) def __and__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __and__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__and__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__and__(other._array) return self.__class__._new(res) def __array_namespace__( self: Array, /, *, api_version: Optional[str] = None ) -> types.ModuleType: if api_version is not None and not api_version.startswith("2021."): raise ValueError(f"Unrecognized array API version: {api_version!r}") return array_api def __bool__(self: Array, /) -> bool: """ Performs the operation __bool__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("bool is only allowed on arrays with 0 dimensions") if self.dtype not in _boolean_dtypes: raise ValueError("bool is only allowed on boolean arrays") res = self._array.__bool__() return res def __dlpack__(self: Array, /, *, stream: None = None) -> PyCapsule: """ Performs the operation __dlpack__. """ return self._array.__dlpack__(stream=stream) def __dlpack_device__(self: Array, /) -> Tuple[IntEnum, int]: """ Performs the operation __dlpack_device__. """ # Note: device support is required for this return self._array.__dlpack_device__() def __eq__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __eq__. """ # Even though "all" dtypes are allowed, we still require them to be # promotable with each other. other = self._check_allowed_dtypes(other, "all", "__eq__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__eq__(other._array) return self.__class__._new(res) def __float__(self: Array, /) -> float: """ Performs the operation __float__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("float is only allowed on arrays with 0 dimensions") if self.dtype not in _floating_dtypes: raise ValueError("float is only allowed on floating-point arrays") res = self._array.__float__() return res def __floordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __floordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__floordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__floordiv__(other._array) return self.__class__._new(res) def __ge__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ge__. """ other = self._check_allowed_dtypes(other, "numeric", "__ge__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ge__(other._array) return self.__class__._new(res) def __getitem__( self: Array, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], /, ) -> Array: """ Performs the operation __getitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array res = self._array.__getitem__(key) return self._new(res) def __gt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __gt__. """ other = self._check_allowed_dtypes(other, "numeric", "__gt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__gt__(other._array) return self.__class__._new(res) def __int__(self: Array, /) -> int: """ Performs the operation __int__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("int is only allowed on arrays with 0 dimensions") if self.dtype not in _integer_dtypes: raise ValueError("int is only allowed on integer arrays") res = self._array.__int__() return res def __index__(self: Array, /) -> int: """ Performs the operation __index__. """ res = self._array.__index__() return res def __invert__(self: Array, /) -> Array: """ Performs the operation __invert__. """ if self.dtype not in _integer_or_boolean_dtypes: raise TypeError("Only integer or boolean dtypes are allowed in __invert__") res = self._array.__invert__() return self.__class__._new(res) def __le__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __le__. """ other = self._check_allowed_dtypes(other, "numeric", "__le__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__le__(other._array) return self.__class__._new(res) def __lshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __lshift__. """ other = self._check_allowed_dtypes(other, "integer", "__lshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lshift__(other._array) return self.__class__._new(res) def __lt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __lt__. """ other = self._check_allowed_dtypes(other, "numeric", "__lt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lt__(other._array) return self.__class__._new(res) def __matmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __matmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__matmul__") if other is NotImplemented: return other res = self._array.__matmul__(other._array) return self.__class__._new(res) def __mod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mod__. """ other = self._check_allowed_dtypes(other, "numeric", "__mod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mod__(other._array) return self.__class__._new(res) def __mul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mul__. """ other = self._check_allowed_dtypes(other, "numeric", "__mul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mul__(other._array) return self.__class__._new(res) def __ne__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __ne__. """ other = self._check_allowed_dtypes(other, "all", "__ne__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ne__(other._array) return self.__class__._new(res) def __neg__(self: Array, /) -> Array: """ Performs the operation __neg__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __neg__") res = self._array.__neg__() return self.__class__._new(res) def __or__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __or__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__or__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__or__(other._array) return self.__class__._new(res) def __pos__(self: Array, /) -> Array: """ Performs the operation __pos__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __pos__") res = self._array.__pos__() return self.__class__._new(res) def __pow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __pow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__pow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow type promotion rules for 0-d # arrays, so we use pow() here instead. return pow(self, other) def __rshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rshift__(other._array) return self.__class__._new(res) def __setitem__( self, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], value: Union[int, float, bool, Array], /, ) -> None: """ Performs the operation __setitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array self._array.__setitem__(key, asarray(value)._array) def __sub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __sub__. """ other = self._check_allowed_dtypes(other, "numeric", "__sub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__sub__(other._array) return self.__class__._new(res) # PEP 484 requires int to be a subtype of float, but __truediv__ should # not accept int. def __truediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __truediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__truediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__truediv__(other._array) return self.__class__._new(res) def __xor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __xor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__xor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__xor__(other._array) return self.__class__._new(res) def __iadd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __iadd__. """ other = self._check_allowed_dtypes(other, "numeric", "__iadd__") if other is NotImplemented: return other self._array.__iadd__(other._array) return self def __radd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __radd__. """ other = self._check_allowed_dtypes(other, "numeric", "__radd__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__radd__(other._array) return self.__class__._new(res) def __iand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __iand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__iand__") if other is NotImplemented: return other self._array.__iand__(other._array) return self def __rand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rand__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rand__(other._array) return self.__class__._new(res) def __ifloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ifloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__ifloordiv__") if other is NotImplemented: return other self._array.__ifloordiv__(other._array) return self def __rfloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rfloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__rfloordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rfloordiv__(other._array) return self.__class__._new(res) def __ilshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __ilshift__. """ other = self._check_allowed_dtypes(other, "integer", "__ilshift__") if other is NotImplemented: return other self._array.__ilshift__(other._array) return self def __rlshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rlshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rlshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rlshift__(other._array) return self.__class__._new(res) def __imatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __imatmul__. """ # Note: NumPy does not implement __imatmul__. # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__imatmul__") if other is NotImplemented: return other # __imatmul__ can only be allowed when it would not change the shape # of self. other_shape = other.shape if self.shape == () or other_shape == (): raise ValueError("@= requires at least one dimension") if len(other_shape) == 1 or other_shape[-1] != other_shape[-2]: raise ValueError("@= cannot change the shape of the input array") self._array[:] = self._array.__matmul__(other._array) return self def __rmatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __rmatmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__rmatmul__") if other is NotImplemented: return other res = self._array.__rmatmul__(other._array) return self.__class__._new(res) def __imod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imod__. """ other = self._check_allowed_dtypes(other, "numeric", "__imod__") if other is NotImplemented: return other self._array.__imod__(other._array) return self def __rmod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmod__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmod__(other._array) return self.__class__._new(res) def __imul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imul__. """ other = self._check_allowed_dtypes(other, "numeric", "__imul__") if other is NotImplemented: return other self._array.__imul__(other._array) return self def __rmul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmul__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmul__(other._array) return self.__class__._new(res) def __ior__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ior__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ior__") if other is NotImplemented: return other self._array.__ior__(other._array) return self def __ror__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ror__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ror__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ror__(other._array) return self.__class__._new(res) def __ipow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ipow__. """ other = self._check_allowed_dtypes(other, "numeric", "__ipow__") if other is NotImplemented: return other self._array.__ipow__(other._array) return self def __rpow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rpow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__rpow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow the spec type promotion rules # for 0-d arrays, so we use pow() here instead. return pow(other, self) def __irshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __irshift__. """ other = self._check_allowed_dtypes(other, "integer", "__irshift__") if other is NotImplemented: return other self._array.__irshift__(other._array) return self def __rrshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rrshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rrshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rrshift__(other._array) return self.__class__._new(res) def __isub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __isub__. """ other = self._check_allowed_dtypes(other, "numeric", "__isub__") if other is NotImplemented: return other self._array.__isub__(other._array) return self def __rsub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rsub__. """ other = self._check_allowed_dtypes(other, "numeric", "__rsub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rsub__(other._array) return self.__class__._new(res) def __itruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __itruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__itruediv__") if other is NotImplemented: return other self._array.__itruediv__(other._array) return self def __rtruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __rtruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__rtruediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rtruediv__(other._array) return self.__class__._new(res) def __ixor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ixor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ixor__") if other is NotImplemented: return other self._array.__ixor__(other._array) return self def __rxor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rxor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rxor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rxor__(other._array) return self.__class__._new(res) def to_device(self: Array, device: Device, /, stream: None = None) -> Array: if stream is not None: raise ValueError("The stream argument to to_device() is not supported") if device == 'cpu': return self raise ValueError(f"Unsupported device {device!r}") def dtype(self) -> Dtype: """ Array API compatible wrapper for :py:meth:`np.ndarray.dtype <numpy.ndarray.dtype>`. See its docstring for more information. """ return self._array.dtype def device(self) -> Device: return "cpu" # Note: mT is new in array API spec (see matrix_transpose) def mT(self) -> Array: from .linalg import matrix_transpose return matrix_transpose(self) def ndim(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.ndim <numpy.ndarray.ndim>`. See its docstring for more information. """ return self._array.ndim def shape(self) -> Tuple[int, ...]: """ Array API compatible wrapper for :py:meth:`np.ndarray.shape <numpy.ndarray.shape>`. See its docstring for more information. """ return self._array.shape def size(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.size <numpy.ndarray.size>`. See its docstring for more information. """ return self._array.size def T(self) -> Array: """ Array API compatible wrapper for :py:meth:`np.ndarray.T <numpy.ndarray.T>`. See its docstring for more information. """ # Note: T only works on 2-dimensional arrays. See the corresponding # note in the specification: # https://data-apis.org/array-api/latest/API_specification/array_object.html#t if self.ndim != 2: raise ValueError("x.T requires x to have 2 dimensions. Use x.mT to transpose stacks of matrices and permute_dims() to permute dimensions.") return self.__class__._new(self._array.T) The provided code snippet includes necessary dependencies for implementing the `expm1` function. Write a Python function `def expm1(x: Array, /) -> Array` to solve the following problem: Array API compatible wrapper for :py:func:`np.expm1 <numpy.expm1>`. See its docstring for more information. Here is the function: def expm1(x: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.expm1 <numpy.expm1>`. See its docstring for more information. """ if x.dtype not in _floating_dtypes: raise TypeError("Only floating-point dtypes are allowed in expm1") return Array._new(np.expm1(x._array))
Array API compatible wrapper for :py:func:`np.expm1 <numpy.expm1>`. See its docstring for more information.
170,041
from __future__ import annotations from ._dtypes import ( _boolean_dtypes, _floating_dtypes, _integer_dtypes, _integer_or_boolean_dtypes, _numeric_dtypes, _result_type, ) from ._array_object import Array import numpy as np _integer_dtypes = (int8, int16, int32, int64, uint8, uint16, uint32, uint64) _numeric_dtypes = ( float32, float64, int8, int16, int32, int64, uint8, uint16, uint32, uint64, ) class Array: """ n-d array object for the array API namespace. See the docstring of :py:obj:`np.ndarray <numpy.ndarray>` for more information. This is a wrapper around numpy.ndarray that restricts the usage to only those things that are required by the array API namespace. Note, attributes on this object that start with a single underscore are not part of the API specification and should only be used internally. This object should not be constructed directly. Rather, use one of the creation functions, such as asarray(). """ _array: np.ndarray # Use a custom constructor instead of __init__, as manually initializing # this class is not supported API. def _new(cls, x, /): """ This is a private method for initializing the array API Array object. Functions outside of the array_api submodule should not use this method. Use one of the creation functions instead, such as ``asarray``. """ obj = super().__new__(cls) # Note: The spec does not have array scalars, only 0-D arrays. if isinstance(x, np.generic): # Convert the array scalar to a 0-D array x = np.asarray(x) if x.dtype not in _all_dtypes: raise TypeError( f"The array_api namespace does not support the dtype '{x.dtype}'" ) obj._array = x return obj # Prevent Array() from working def __new__(cls, *args, **kwargs): raise TypeError( "The array_api Array object should not be instantiated directly. Use an array creation function, such as asarray(), instead." ) # These functions are not required by the spec, but are implemented for # the sake of usability. def __str__(self: Array, /) -> str: """ Performs the operation __str__. """ return self._array.__str__().replace("array", "Array") def __repr__(self: Array, /) -> str: """ Performs the operation __repr__. """ suffix = f", dtype={self.dtype.name})" if 0 in self.shape: prefix = "empty(" mid = str(self.shape) else: prefix = "Array(" mid = np.array2string(self._array, separator=', ', prefix=prefix, suffix=suffix) return prefix + mid + suffix # This function is not required by the spec, but we implement it here for # convenience so that np.asarray(np.array_api.Array) will work. def __array__(self, dtype: None | np.dtype[Any] = None) -> npt.NDArray[Any]: """ Warning: this method is NOT part of the array API spec. Implementers of other libraries need not include it, and users should not assume it will be present in other implementations. """ return np.asarray(self._array, dtype=dtype) # These are various helper functions to make the array behavior match the # spec in places where it either deviates from or is more strict than # NumPy behavior def _check_allowed_dtypes(self, other: bool | int | float | Array, dtype_category: str, op: str) -> Array: """ Helper function for operators to only allow specific input dtypes Use like other = self._check_allowed_dtypes(other, 'numeric', '__add__') if other is NotImplemented: return other """ if self.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") if isinstance(other, (int, float, bool)): other = self._promote_scalar(other) elif isinstance(other, Array): if other.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") else: return NotImplemented # This will raise TypeError for type combinations that are not allowed # to promote in the spec (even if the NumPy array operator would # promote them). res_dtype = _result_type(self.dtype, other.dtype) if op.startswith("__i"): # Note: NumPy will allow in-place operators in some cases where # the type promoted operator does not match the left-hand side # operand. For example, # >>> a = np.array(1, dtype=np.int8) # >>> a += np.array(1, dtype=np.int16) # The spec explicitly disallows this. if res_dtype != self.dtype: raise TypeError( f"Cannot perform {op} with dtypes {self.dtype} and {other.dtype}" ) return other # Helper function to match the type promotion rules in the spec def _promote_scalar(self, scalar): """ Returns a promoted version of a Python scalar appropriate for use with operations on self. This may raise an OverflowError in cases where the scalar is an integer that is too large to fit in a NumPy integer dtype, or TypeError when the scalar type is incompatible with the dtype of self. """ # Note: Only Python scalar types that match the array dtype are # allowed. if isinstance(scalar, bool): if self.dtype not in _boolean_dtypes: raise TypeError( "Python bool scalars can only be promoted with bool arrays" ) elif isinstance(scalar, int): if self.dtype in _boolean_dtypes: raise TypeError( "Python int scalars cannot be promoted with bool arrays" ) elif isinstance(scalar, float): if self.dtype not in _floating_dtypes: raise TypeError( "Python float scalars can only be promoted with floating-point arrays." ) else: raise TypeError("'scalar' must be a Python scalar") # Note: scalars are unconditionally cast to the same dtype as the # array. # Note: the spec only specifies integer-dtype/int promotion # behavior for integers within the bounds of the integer dtype. # Outside of those bounds we use the default NumPy behavior (either # cast or raise OverflowError). return Array._new(np.array(scalar, self.dtype)) def _normalize_two_args(x1, x2) -> Tuple[Array, Array]: """ Normalize inputs to two arg functions to fix type promotion rules NumPy deviates from the spec type promotion rules in cases where one argument is 0-dimensional and the other is not. For example: >>> import numpy as np >>> a = np.array([1.0], dtype=np.float32) >>> b = np.array(1.0, dtype=np.float64) >>> np.add(a, b) # The spec says this should be float64 array([2.], dtype=float32) To fix this, we add a dimension to the 0-dimension array before passing it through. This works because a dimension would be added anyway from broadcasting, so the resulting shape is the same, but this prevents NumPy from not promoting the dtype. """ # Another option would be to use signature=(x1.dtype, x2.dtype, None), # but that only works for ufuncs, so we would have to call the ufuncs # directly in the operator methods. One should also note that this # sort of trick wouldn't work for functions like searchsorted, which # don't do normal broadcasting, but there aren't any functions like # that in the array API namespace. if x1.ndim == 0 and x2.ndim != 0: # The _array[None] workaround was chosen because it is relatively # performant. broadcast_to(x1._array, x2.shape) is much slower. We # could also manually type promote x2, but that is more complicated # and about the same performance as this. x1 = Array._new(x1._array[None]) elif x2.ndim == 0 and x1.ndim != 0: x2 = Array._new(x2._array[None]) return (x1, x2) # Note: A large fraction of allowed indices are disallowed here (see the # docstring below) def _validate_index(self, key): """ Validate an index according to the array API. The array API specification only requires a subset of indices that are supported by NumPy. This function will reject any index that is allowed by NumPy but not required by the array API specification. We always raise ``IndexError`` on such indices (the spec does not require any specific behavior on them, but this makes the NumPy array API namespace a minimal implementation of the spec). See https://data-apis.org/array-api/latest/API_specification/indexing.html for the full list of required indexing behavior This function raises IndexError if the index ``key`` is invalid. It only raises ``IndexError`` on indices that are not already rejected by NumPy, as NumPy will already raise the appropriate error on such indices. ``shape`` may be None, in which case, only cases that are independent of the array shape are checked. The following cases are allowed by NumPy, but not specified by the array API specification: - Indices to not include an implicit ellipsis at the end. That is, every axis of an array must be explicitly indexed or an ellipsis included. This behaviour is sometimes referred to as flat indexing. - The start and stop of a slice may not be out of bounds. In particular, for a slice ``i:j:k`` on an axis of size ``n``, only the following are allowed: - ``i`` or ``j`` omitted (``None``). - ``-n <= i <= max(0, n - 1)``. - For ``k > 0`` or ``k`` omitted (``None``), ``-n <= j <= n``. - For ``k < 0``, ``-n - 1 <= j <= max(0, n - 1)``. - Boolean array indices are not allowed as part of a larger tuple index. - Integer array indices are not allowed (with the exception of 0-D arrays, which are treated the same as scalars). Additionally, it should be noted that indices that would return a scalar in NumPy will return a 0-D array. Array scalars are not allowed in the specification, only 0-D arrays. This is done in the ``Array._new`` constructor, not this function. """ _key = key if isinstance(key, tuple) else (key,) for i in _key: if isinstance(i, bool) or not ( isinstance(i, SupportsIndex) # i.e. ints or isinstance(i, slice) or i == Ellipsis or i is None or isinstance(i, Array) or isinstance(i, np.ndarray) ): raise IndexError( f"Single-axes index {i} has {type(i)=}, but only " "integers, slices (:), ellipsis (...), newaxis (None), " "zero-dimensional integer arrays and boolean arrays " "are specified in the Array API." ) nonexpanding_key = [] single_axes = [] n_ellipsis = 0 key_has_mask = False for i in _key: if i is not None: nonexpanding_key.append(i) if isinstance(i, Array) or isinstance(i, np.ndarray): if i.dtype in _boolean_dtypes: key_has_mask = True single_axes.append(i) else: # i must not be an array here, to avoid elementwise equals if i == Ellipsis: n_ellipsis += 1 else: single_axes.append(i) n_single_axes = len(single_axes) if n_ellipsis > 1: return # handled by ndarray elif n_ellipsis == 0: # Note boolean masks must be the sole index, which we check for # later on. if not key_has_mask and n_single_axes < self.ndim: raise IndexError( f"{self.ndim=}, but the multi-axes index only specifies " f"{n_single_axes} dimensions. If this was intentional, " "add a trailing ellipsis (...) which expands into as many " "slices (:) as necessary - this is what np.ndarray arrays " "implicitly do, but such flat indexing behaviour is not " "specified in the Array API." ) if n_ellipsis == 0: indexed_shape = self.shape else: ellipsis_start = None for pos, i in enumerate(nonexpanding_key): if not (isinstance(i, Array) or isinstance(i, np.ndarray)): if i == Ellipsis: ellipsis_start = pos break assert ellipsis_start is not None # sanity check ellipsis_end = self.ndim - (n_single_axes - ellipsis_start) indexed_shape = ( self.shape[:ellipsis_start] + self.shape[ellipsis_end:] ) for i, side in zip(single_axes, indexed_shape): if isinstance(i, slice): if side == 0: f_range = "0 (or None)" else: f_range = f"between -{side} and {side - 1} (or None)" if i.start is not None: try: start = operator.index(i.start) except TypeError: pass # handled by ndarray else: if not (-side <= start <= side): raise IndexError( f"Slice {i} contains {start=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds starts are not specified in " "the Array API)" ) if i.stop is not None: try: stop = operator.index(i.stop) except TypeError: pass # handled by ndarray else: if not (-side <= stop <= side): raise IndexError( f"Slice {i} contains {stop=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds stops are not specified in " "the Array API)" ) elif isinstance(i, Array): if i.dtype in _boolean_dtypes and len(_key) != 1: assert isinstance(key, tuple) # sanity check raise IndexError( f"Single-axes index {i} is a boolean array and " f"{len(key)=}, but masking is only specified in the " "Array API when the array is the sole index." ) elif i.dtype in _integer_dtypes and i.ndim != 0: raise IndexError( f"Single-axes index {i} is a non-zero-dimensional " "integer array, but advanced integer indexing is not " "specified in the Array API." ) elif isinstance(i, tuple): raise IndexError( f"Single-axes index {i} is a tuple, but nested tuple " "indices are not specified in the Array API." ) # Everything below this line is required by the spec. def __abs__(self: Array, /) -> Array: """ Performs the operation __abs__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __abs__") res = self._array.__abs__() return self.__class__._new(res) def __add__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __add__. """ other = self._check_allowed_dtypes(other, "numeric", "__add__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__add__(other._array) return self.__class__._new(res) def __and__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __and__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__and__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__and__(other._array) return self.__class__._new(res) def __array_namespace__( self: Array, /, *, api_version: Optional[str] = None ) -> types.ModuleType: if api_version is not None and not api_version.startswith("2021."): raise ValueError(f"Unrecognized array API version: {api_version!r}") return array_api def __bool__(self: Array, /) -> bool: """ Performs the operation __bool__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("bool is only allowed on arrays with 0 dimensions") if self.dtype not in _boolean_dtypes: raise ValueError("bool is only allowed on boolean arrays") res = self._array.__bool__() return res def __dlpack__(self: Array, /, *, stream: None = None) -> PyCapsule: """ Performs the operation __dlpack__. """ return self._array.__dlpack__(stream=stream) def __dlpack_device__(self: Array, /) -> Tuple[IntEnum, int]: """ Performs the operation __dlpack_device__. """ # Note: device support is required for this return self._array.__dlpack_device__() def __eq__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __eq__. """ # Even though "all" dtypes are allowed, we still require them to be # promotable with each other. other = self._check_allowed_dtypes(other, "all", "__eq__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__eq__(other._array) return self.__class__._new(res) def __float__(self: Array, /) -> float: """ Performs the operation __float__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("float is only allowed on arrays with 0 dimensions") if self.dtype not in _floating_dtypes: raise ValueError("float is only allowed on floating-point arrays") res = self._array.__float__() return res def __floordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __floordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__floordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__floordiv__(other._array) return self.__class__._new(res) def __ge__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ge__. """ other = self._check_allowed_dtypes(other, "numeric", "__ge__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ge__(other._array) return self.__class__._new(res) def __getitem__( self: Array, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], /, ) -> Array: """ Performs the operation __getitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array res = self._array.__getitem__(key) return self._new(res) def __gt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __gt__. """ other = self._check_allowed_dtypes(other, "numeric", "__gt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__gt__(other._array) return self.__class__._new(res) def __int__(self: Array, /) -> int: """ Performs the operation __int__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("int is only allowed on arrays with 0 dimensions") if self.dtype not in _integer_dtypes: raise ValueError("int is only allowed on integer arrays") res = self._array.__int__() return res def __index__(self: Array, /) -> int: """ Performs the operation __index__. """ res = self._array.__index__() return res def __invert__(self: Array, /) -> Array: """ Performs the operation __invert__. """ if self.dtype not in _integer_or_boolean_dtypes: raise TypeError("Only integer or boolean dtypes are allowed in __invert__") res = self._array.__invert__() return self.__class__._new(res) def __le__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __le__. """ other = self._check_allowed_dtypes(other, "numeric", "__le__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__le__(other._array) return self.__class__._new(res) def __lshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __lshift__. """ other = self._check_allowed_dtypes(other, "integer", "__lshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lshift__(other._array) return self.__class__._new(res) def __lt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __lt__. """ other = self._check_allowed_dtypes(other, "numeric", "__lt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lt__(other._array) return self.__class__._new(res) def __matmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __matmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__matmul__") if other is NotImplemented: return other res = self._array.__matmul__(other._array) return self.__class__._new(res) def __mod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mod__. """ other = self._check_allowed_dtypes(other, "numeric", "__mod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mod__(other._array) return self.__class__._new(res) def __mul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mul__. """ other = self._check_allowed_dtypes(other, "numeric", "__mul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mul__(other._array) return self.__class__._new(res) def __ne__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __ne__. """ other = self._check_allowed_dtypes(other, "all", "__ne__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ne__(other._array) return self.__class__._new(res) def __neg__(self: Array, /) -> Array: """ Performs the operation __neg__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __neg__") res = self._array.__neg__() return self.__class__._new(res) def __or__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __or__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__or__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__or__(other._array) return self.__class__._new(res) def __pos__(self: Array, /) -> Array: """ Performs the operation __pos__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __pos__") res = self._array.__pos__() return self.__class__._new(res) def __pow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __pow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__pow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow type promotion rules for 0-d # arrays, so we use pow() here instead. return pow(self, other) def __rshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rshift__(other._array) return self.__class__._new(res) def __setitem__( self, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], value: Union[int, float, bool, Array], /, ) -> None: """ Performs the operation __setitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array self._array.__setitem__(key, asarray(value)._array) def __sub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __sub__. """ other = self._check_allowed_dtypes(other, "numeric", "__sub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__sub__(other._array) return self.__class__._new(res) # PEP 484 requires int to be a subtype of float, but __truediv__ should # not accept int. def __truediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __truediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__truediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__truediv__(other._array) return self.__class__._new(res) def __xor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __xor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__xor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__xor__(other._array) return self.__class__._new(res) def __iadd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __iadd__. """ other = self._check_allowed_dtypes(other, "numeric", "__iadd__") if other is NotImplemented: return other self._array.__iadd__(other._array) return self def __radd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __radd__. """ other = self._check_allowed_dtypes(other, "numeric", "__radd__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__radd__(other._array) return self.__class__._new(res) def __iand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __iand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__iand__") if other is NotImplemented: return other self._array.__iand__(other._array) return self def __rand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rand__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rand__(other._array) return self.__class__._new(res) def __ifloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ifloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__ifloordiv__") if other is NotImplemented: return other self._array.__ifloordiv__(other._array) return self def __rfloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rfloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__rfloordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rfloordiv__(other._array) return self.__class__._new(res) def __ilshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __ilshift__. """ other = self._check_allowed_dtypes(other, "integer", "__ilshift__") if other is NotImplemented: return other self._array.__ilshift__(other._array) return self def __rlshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rlshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rlshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rlshift__(other._array) return self.__class__._new(res) def __imatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __imatmul__. """ # Note: NumPy does not implement __imatmul__. # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__imatmul__") if other is NotImplemented: return other # __imatmul__ can only be allowed when it would not change the shape # of self. other_shape = other.shape if self.shape == () or other_shape == (): raise ValueError("@= requires at least one dimension") if len(other_shape) == 1 or other_shape[-1] != other_shape[-2]: raise ValueError("@= cannot change the shape of the input array") self._array[:] = self._array.__matmul__(other._array) return self def __rmatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __rmatmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__rmatmul__") if other is NotImplemented: return other res = self._array.__rmatmul__(other._array) return self.__class__._new(res) def __imod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imod__. """ other = self._check_allowed_dtypes(other, "numeric", "__imod__") if other is NotImplemented: return other self._array.__imod__(other._array) return self def __rmod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmod__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmod__(other._array) return self.__class__._new(res) def __imul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imul__. """ other = self._check_allowed_dtypes(other, "numeric", "__imul__") if other is NotImplemented: return other self._array.__imul__(other._array) return self def __rmul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmul__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmul__(other._array) return self.__class__._new(res) def __ior__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ior__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ior__") if other is NotImplemented: return other self._array.__ior__(other._array) return self def __ror__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ror__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ror__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ror__(other._array) return self.__class__._new(res) def __ipow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ipow__. """ other = self._check_allowed_dtypes(other, "numeric", "__ipow__") if other is NotImplemented: return other self._array.__ipow__(other._array) return self def __rpow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rpow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__rpow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow the spec type promotion rules # for 0-d arrays, so we use pow() here instead. return pow(other, self) def __irshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __irshift__. """ other = self._check_allowed_dtypes(other, "integer", "__irshift__") if other is NotImplemented: return other self._array.__irshift__(other._array) return self def __rrshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rrshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rrshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rrshift__(other._array) return self.__class__._new(res) def __isub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __isub__. """ other = self._check_allowed_dtypes(other, "numeric", "__isub__") if other is NotImplemented: return other self._array.__isub__(other._array) return self def __rsub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rsub__. """ other = self._check_allowed_dtypes(other, "numeric", "__rsub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rsub__(other._array) return self.__class__._new(res) def __itruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __itruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__itruediv__") if other is NotImplemented: return other self._array.__itruediv__(other._array) return self def __rtruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __rtruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__rtruediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rtruediv__(other._array) return self.__class__._new(res) def __ixor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ixor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ixor__") if other is NotImplemented: return other self._array.__ixor__(other._array) return self def __rxor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rxor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rxor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rxor__(other._array) return self.__class__._new(res) def to_device(self: Array, device: Device, /, stream: None = None) -> Array: if stream is not None: raise ValueError("The stream argument to to_device() is not supported") if device == 'cpu': return self raise ValueError(f"Unsupported device {device!r}") def dtype(self) -> Dtype: """ Array API compatible wrapper for :py:meth:`np.ndarray.dtype <numpy.ndarray.dtype>`. See its docstring for more information. """ return self._array.dtype def device(self) -> Device: return "cpu" # Note: mT is new in array API spec (see matrix_transpose) def mT(self) -> Array: from .linalg import matrix_transpose return matrix_transpose(self) def ndim(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.ndim <numpy.ndarray.ndim>`. See its docstring for more information. """ return self._array.ndim def shape(self) -> Tuple[int, ...]: """ Array API compatible wrapper for :py:meth:`np.ndarray.shape <numpy.ndarray.shape>`. See its docstring for more information. """ return self._array.shape def size(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.size <numpy.ndarray.size>`. See its docstring for more information. """ return self._array.size def T(self) -> Array: """ Array API compatible wrapper for :py:meth:`np.ndarray.T <numpy.ndarray.T>`. See its docstring for more information. """ # Note: T only works on 2-dimensional arrays. See the corresponding # note in the specification: # https://data-apis.org/array-api/latest/API_specification/array_object.html#t if self.ndim != 2: raise ValueError("x.T requires x to have 2 dimensions. Use x.mT to transpose stacks of matrices and permute_dims() to permute dimensions.") return self.__class__._new(self._array.T) The provided code snippet includes necessary dependencies for implementing the `floor` function. Write a Python function `def floor(x: Array, /) -> Array` to solve the following problem: Array API compatible wrapper for :py:func:`np.floor <numpy.floor>`. See its docstring for more information. Here is the function: def floor(x: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.floor <numpy.floor>`. See its docstring for more information. """ if x.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in floor") if x.dtype in _integer_dtypes: # Note: The return dtype of floor is the same as the input return x return Array._new(np.floor(x._array))
Array API compatible wrapper for :py:func:`np.floor <numpy.floor>`. See its docstring for more information.
170,042
from __future__ import annotations from ._dtypes import ( _boolean_dtypes, _floating_dtypes, _integer_dtypes, _integer_or_boolean_dtypes, _numeric_dtypes, _result_type, ) from ._array_object import Array import numpy as np _numeric_dtypes = ( float32, float64, int8, int16, int32, int64, uint8, uint16, uint32, uint64, ) def _result_type(type1, type2): if (type1, type2) in _promotion_table: return _promotion_table[type1, type2] raise TypeError(f"{type1} and {type2} cannot be type promoted together") class Array: """ n-d array object for the array API namespace. See the docstring of :py:obj:`np.ndarray <numpy.ndarray>` for more information. This is a wrapper around numpy.ndarray that restricts the usage to only those things that are required by the array API namespace. Note, attributes on this object that start with a single underscore are not part of the API specification and should only be used internally. This object should not be constructed directly. Rather, use one of the creation functions, such as asarray(). """ _array: np.ndarray # Use a custom constructor instead of __init__, as manually initializing # this class is not supported API. def _new(cls, x, /): """ This is a private method for initializing the array API Array object. Functions outside of the array_api submodule should not use this method. Use one of the creation functions instead, such as ``asarray``. """ obj = super().__new__(cls) # Note: The spec does not have array scalars, only 0-D arrays. if isinstance(x, np.generic): # Convert the array scalar to a 0-D array x = np.asarray(x) if x.dtype not in _all_dtypes: raise TypeError( f"The array_api namespace does not support the dtype '{x.dtype}'" ) obj._array = x return obj # Prevent Array() from working def __new__(cls, *args, **kwargs): raise TypeError( "The array_api Array object should not be instantiated directly. Use an array creation function, such as asarray(), instead." ) # These functions are not required by the spec, but are implemented for # the sake of usability. def __str__(self: Array, /) -> str: """ Performs the operation __str__. """ return self._array.__str__().replace("array", "Array") def __repr__(self: Array, /) -> str: """ Performs the operation __repr__. """ suffix = f", dtype={self.dtype.name})" if 0 in self.shape: prefix = "empty(" mid = str(self.shape) else: prefix = "Array(" mid = np.array2string(self._array, separator=', ', prefix=prefix, suffix=suffix) return prefix + mid + suffix # This function is not required by the spec, but we implement it here for # convenience so that np.asarray(np.array_api.Array) will work. def __array__(self, dtype: None | np.dtype[Any] = None) -> npt.NDArray[Any]: """ Warning: this method is NOT part of the array API spec. Implementers of other libraries need not include it, and users should not assume it will be present in other implementations. """ return np.asarray(self._array, dtype=dtype) # These are various helper functions to make the array behavior match the # spec in places where it either deviates from or is more strict than # NumPy behavior def _check_allowed_dtypes(self, other: bool | int | float | Array, dtype_category: str, op: str) -> Array: """ Helper function for operators to only allow specific input dtypes Use like other = self._check_allowed_dtypes(other, 'numeric', '__add__') if other is NotImplemented: return other """ if self.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") if isinstance(other, (int, float, bool)): other = self._promote_scalar(other) elif isinstance(other, Array): if other.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") else: return NotImplemented # This will raise TypeError for type combinations that are not allowed # to promote in the spec (even if the NumPy array operator would # promote them). res_dtype = _result_type(self.dtype, other.dtype) if op.startswith("__i"): # Note: NumPy will allow in-place operators in some cases where # the type promoted operator does not match the left-hand side # operand. For example, # >>> a = np.array(1, dtype=np.int8) # >>> a += np.array(1, dtype=np.int16) # The spec explicitly disallows this. if res_dtype != self.dtype: raise TypeError( f"Cannot perform {op} with dtypes {self.dtype} and {other.dtype}" ) return other # Helper function to match the type promotion rules in the spec def _promote_scalar(self, scalar): """ Returns a promoted version of a Python scalar appropriate for use with operations on self. This may raise an OverflowError in cases where the scalar is an integer that is too large to fit in a NumPy integer dtype, or TypeError when the scalar type is incompatible with the dtype of self. """ # Note: Only Python scalar types that match the array dtype are # allowed. if isinstance(scalar, bool): if self.dtype not in _boolean_dtypes: raise TypeError( "Python bool scalars can only be promoted with bool arrays" ) elif isinstance(scalar, int): if self.dtype in _boolean_dtypes: raise TypeError( "Python int scalars cannot be promoted with bool arrays" ) elif isinstance(scalar, float): if self.dtype not in _floating_dtypes: raise TypeError( "Python float scalars can only be promoted with floating-point arrays." ) else: raise TypeError("'scalar' must be a Python scalar") # Note: scalars are unconditionally cast to the same dtype as the # array. # Note: the spec only specifies integer-dtype/int promotion # behavior for integers within the bounds of the integer dtype. # Outside of those bounds we use the default NumPy behavior (either # cast or raise OverflowError). return Array._new(np.array(scalar, self.dtype)) def _normalize_two_args(x1, x2) -> Tuple[Array, Array]: """ Normalize inputs to two arg functions to fix type promotion rules NumPy deviates from the spec type promotion rules in cases where one argument is 0-dimensional and the other is not. For example: >>> import numpy as np >>> a = np.array([1.0], dtype=np.float32) >>> b = np.array(1.0, dtype=np.float64) >>> np.add(a, b) # The spec says this should be float64 array([2.], dtype=float32) To fix this, we add a dimension to the 0-dimension array before passing it through. This works because a dimension would be added anyway from broadcasting, so the resulting shape is the same, but this prevents NumPy from not promoting the dtype. """ # Another option would be to use signature=(x1.dtype, x2.dtype, None), # but that only works for ufuncs, so we would have to call the ufuncs # directly in the operator methods. One should also note that this # sort of trick wouldn't work for functions like searchsorted, which # don't do normal broadcasting, but there aren't any functions like # that in the array API namespace. if x1.ndim == 0 and x2.ndim != 0: # The _array[None] workaround was chosen because it is relatively # performant. broadcast_to(x1._array, x2.shape) is much slower. We # could also manually type promote x2, but that is more complicated # and about the same performance as this. x1 = Array._new(x1._array[None]) elif x2.ndim == 0 and x1.ndim != 0: x2 = Array._new(x2._array[None]) return (x1, x2) # Note: A large fraction of allowed indices are disallowed here (see the # docstring below) def _validate_index(self, key): """ Validate an index according to the array API. The array API specification only requires a subset of indices that are supported by NumPy. This function will reject any index that is allowed by NumPy but not required by the array API specification. We always raise ``IndexError`` on such indices (the spec does not require any specific behavior on them, but this makes the NumPy array API namespace a minimal implementation of the spec). See https://data-apis.org/array-api/latest/API_specification/indexing.html for the full list of required indexing behavior This function raises IndexError if the index ``key`` is invalid. It only raises ``IndexError`` on indices that are not already rejected by NumPy, as NumPy will already raise the appropriate error on such indices. ``shape`` may be None, in which case, only cases that are independent of the array shape are checked. The following cases are allowed by NumPy, but not specified by the array API specification: - Indices to not include an implicit ellipsis at the end. That is, every axis of an array must be explicitly indexed or an ellipsis included. This behaviour is sometimes referred to as flat indexing. - The start and stop of a slice may not be out of bounds. In particular, for a slice ``i:j:k`` on an axis of size ``n``, only the following are allowed: - ``i`` or ``j`` omitted (``None``). - ``-n <= i <= max(0, n - 1)``. - For ``k > 0`` or ``k`` omitted (``None``), ``-n <= j <= n``. - For ``k < 0``, ``-n - 1 <= j <= max(0, n - 1)``. - Boolean array indices are not allowed as part of a larger tuple index. - Integer array indices are not allowed (with the exception of 0-D arrays, which are treated the same as scalars). Additionally, it should be noted that indices that would return a scalar in NumPy will return a 0-D array. Array scalars are not allowed in the specification, only 0-D arrays. This is done in the ``Array._new`` constructor, not this function. """ _key = key if isinstance(key, tuple) else (key,) for i in _key: if isinstance(i, bool) or not ( isinstance(i, SupportsIndex) # i.e. ints or isinstance(i, slice) or i == Ellipsis or i is None or isinstance(i, Array) or isinstance(i, np.ndarray) ): raise IndexError( f"Single-axes index {i} has {type(i)=}, but only " "integers, slices (:), ellipsis (...), newaxis (None), " "zero-dimensional integer arrays and boolean arrays " "are specified in the Array API." ) nonexpanding_key = [] single_axes = [] n_ellipsis = 0 key_has_mask = False for i in _key: if i is not None: nonexpanding_key.append(i) if isinstance(i, Array) or isinstance(i, np.ndarray): if i.dtype in _boolean_dtypes: key_has_mask = True single_axes.append(i) else: # i must not be an array here, to avoid elementwise equals if i == Ellipsis: n_ellipsis += 1 else: single_axes.append(i) n_single_axes = len(single_axes) if n_ellipsis > 1: return # handled by ndarray elif n_ellipsis == 0: # Note boolean masks must be the sole index, which we check for # later on. if not key_has_mask and n_single_axes < self.ndim: raise IndexError( f"{self.ndim=}, but the multi-axes index only specifies " f"{n_single_axes} dimensions. If this was intentional, " "add a trailing ellipsis (...) which expands into as many " "slices (:) as necessary - this is what np.ndarray arrays " "implicitly do, but such flat indexing behaviour is not " "specified in the Array API." ) if n_ellipsis == 0: indexed_shape = self.shape else: ellipsis_start = None for pos, i in enumerate(nonexpanding_key): if not (isinstance(i, Array) or isinstance(i, np.ndarray)): if i == Ellipsis: ellipsis_start = pos break assert ellipsis_start is not None # sanity check ellipsis_end = self.ndim - (n_single_axes - ellipsis_start) indexed_shape = ( self.shape[:ellipsis_start] + self.shape[ellipsis_end:] ) for i, side in zip(single_axes, indexed_shape): if isinstance(i, slice): if side == 0: f_range = "0 (or None)" else: f_range = f"between -{side} and {side - 1} (or None)" if i.start is not None: try: start = operator.index(i.start) except TypeError: pass # handled by ndarray else: if not (-side <= start <= side): raise IndexError( f"Slice {i} contains {start=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds starts are not specified in " "the Array API)" ) if i.stop is not None: try: stop = operator.index(i.stop) except TypeError: pass # handled by ndarray else: if not (-side <= stop <= side): raise IndexError( f"Slice {i} contains {stop=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds stops are not specified in " "the Array API)" ) elif isinstance(i, Array): if i.dtype in _boolean_dtypes and len(_key) != 1: assert isinstance(key, tuple) # sanity check raise IndexError( f"Single-axes index {i} is a boolean array and " f"{len(key)=}, but masking is only specified in the " "Array API when the array is the sole index." ) elif i.dtype in _integer_dtypes and i.ndim != 0: raise IndexError( f"Single-axes index {i} is a non-zero-dimensional " "integer array, but advanced integer indexing is not " "specified in the Array API." ) elif isinstance(i, tuple): raise IndexError( f"Single-axes index {i} is a tuple, but nested tuple " "indices are not specified in the Array API." ) # Everything below this line is required by the spec. def __abs__(self: Array, /) -> Array: """ Performs the operation __abs__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __abs__") res = self._array.__abs__() return self.__class__._new(res) def __add__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __add__. """ other = self._check_allowed_dtypes(other, "numeric", "__add__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__add__(other._array) return self.__class__._new(res) def __and__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __and__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__and__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__and__(other._array) return self.__class__._new(res) def __array_namespace__( self: Array, /, *, api_version: Optional[str] = None ) -> types.ModuleType: if api_version is not None and not api_version.startswith("2021."): raise ValueError(f"Unrecognized array API version: {api_version!r}") return array_api def __bool__(self: Array, /) -> bool: """ Performs the operation __bool__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("bool is only allowed on arrays with 0 dimensions") if self.dtype not in _boolean_dtypes: raise ValueError("bool is only allowed on boolean arrays") res = self._array.__bool__() return res def __dlpack__(self: Array, /, *, stream: None = None) -> PyCapsule: """ Performs the operation __dlpack__. """ return self._array.__dlpack__(stream=stream) def __dlpack_device__(self: Array, /) -> Tuple[IntEnum, int]: """ Performs the operation __dlpack_device__. """ # Note: device support is required for this return self._array.__dlpack_device__() def __eq__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __eq__. """ # Even though "all" dtypes are allowed, we still require them to be # promotable with each other. other = self._check_allowed_dtypes(other, "all", "__eq__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__eq__(other._array) return self.__class__._new(res) def __float__(self: Array, /) -> float: """ Performs the operation __float__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("float is only allowed on arrays with 0 dimensions") if self.dtype not in _floating_dtypes: raise ValueError("float is only allowed on floating-point arrays") res = self._array.__float__() return res def __floordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __floordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__floordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__floordiv__(other._array) return self.__class__._new(res) def __ge__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ge__. """ other = self._check_allowed_dtypes(other, "numeric", "__ge__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ge__(other._array) return self.__class__._new(res) def __getitem__( self: Array, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], /, ) -> Array: """ Performs the operation __getitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array res = self._array.__getitem__(key) return self._new(res) def __gt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __gt__. """ other = self._check_allowed_dtypes(other, "numeric", "__gt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__gt__(other._array) return self.__class__._new(res) def __int__(self: Array, /) -> int: """ Performs the operation __int__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("int is only allowed on arrays with 0 dimensions") if self.dtype not in _integer_dtypes: raise ValueError("int is only allowed on integer arrays") res = self._array.__int__() return res def __index__(self: Array, /) -> int: """ Performs the operation __index__. """ res = self._array.__index__() return res def __invert__(self: Array, /) -> Array: """ Performs the operation __invert__. """ if self.dtype not in _integer_or_boolean_dtypes: raise TypeError("Only integer or boolean dtypes are allowed in __invert__") res = self._array.__invert__() return self.__class__._new(res) def __le__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __le__. """ other = self._check_allowed_dtypes(other, "numeric", "__le__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__le__(other._array) return self.__class__._new(res) def __lshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __lshift__. """ other = self._check_allowed_dtypes(other, "integer", "__lshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lshift__(other._array) return self.__class__._new(res) def __lt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __lt__. """ other = self._check_allowed_dtypes(other, "numeric", "__lt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lt__(other._array) return self.__class__._new(res) def __matmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __matmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__matmul__") if other is NotImplemented: return other res = self._array.__matmul__(other._array) return self.__class__._new(res) def __mod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mod__. """ other = self._check_allowed_dtypes(other, "numeric", "__mod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mod__(other._array) return self.__class__._new(res) def __mul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mul__. """ other = self._check_allowed_dtypes(other, "numeric", "__mul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mul__(other._array) return self.__class__._new(res) def __ne__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __ne__. """ other = self._check_allowed_dtypes(other, "all", "__ne__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ne__(other._array) return self.__class__._new(res) def __neg__(self: Array, /) -> Array: """ Performs the operation __neg__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __neg__") res = self._array.__neg__() return self.__class__._new(res) def __or__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __or__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__or__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__or__(other._array) return self.__class__._new(res) def __pos__(self: Array, /) -> Array: """ Performs the operation __pos__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __pos__") res = self._array.__pos__() return self.__class__._new(res) def __pow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __pow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__pow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow type promotion rules for 0-d # arrays, so we use pow() here instead. return pow(self, other) def __rshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rshift__(other._array) return self.__class__._new(res) def __setitem__( self, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], value: Union[int, float, bool, Array], /, ) -> None: """ Performs the operation __setitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array self._array.__setitem__(key, asarray(value)._array) def __sub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __sub__. """ other = self._check_allowed_dtypes(other, "numeric", "__sub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__sub__(other._array) return self.__class__._new(res) # PEP 484 requires int to be a subtype of float, but __truediv__ should # not accept int. def __truediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __truediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__truediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__truediv__(other._array) return self.__class__._new(res) def __xor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __xor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__xor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__xor__(other._array) return self.__class__._new(res) def __iadd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __iadd__. """ other = self._check_allowed_dtypes(other, "numeric", "__iadd__") if other is NotImplemented: return other self._array.__iadd__(other._array) return self def __radd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __radd__. """ other = self._check_allowed_dtypes(other, "numeric", "__radd__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__radd__(other._array) return self.__class__._new(res) def __iand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __iand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__iand__") if other is NotImplemented: return other self._array.__iand__(other._array) return self def __rand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rand__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rand__(other._array) return self.__class__._new(res) def __ifloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ifloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__ifloordiv__") if other is NotImplemented: return other self._array.__ifloordiv__(other._array) return self def __rfloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rfloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__rfloordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rfloordiv__(other._array) return self.__class__._new(res) def __ilshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __ilshift__. """ other = self._check_allowed_dtypes(other, "integer", "__ilshift__") if other is NotImplemented: return other self._array.__ilshift__(other._array) return self def __rlshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rlshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rlshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rlshift__(other._array) return self.__class__._new(res) def __imatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __imatmul__. """ # Note: NumPy does not implement __imatmul__. # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__imatmul__") if other is NotImplemented: return other # __imatmul__ can only be allowed when it would not change the shape # of self. other_shape = other.shape if self.shape == () or other_shape == (): raise ValueError("@= requires at least one dimension") if len(other_shape) == 1 or other_shape[-1] != other_shape[-2]: raise ValueError("@= cannot change the shape of the input array") self._array[:] = self._array.__matmul__(other._array) return self def __rmatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __rmatmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__rmatmul__") if other is NotImplemented: return other res = self._array.__rmatmul__(other._array) return self.__class__._new(res) def __imod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imod__. """ other = self._check_allowed_dtypes(other, "numeric", "__imod__") if other is NotImplemented: return other self._array.__imod__(other._array) return self def __rmod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmod__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmod__(other._array) return self.__class__._new(res) def __imul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imul__. """ other = self._check_allowed_dtypes(other, "numeric", "__imul__") if other is NotImplemented: return other self._array.__imul__(other._array) return self def __rmul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmul__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmul__(other._array) return self.__class__._new(res) def __ior__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ior__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ior__") if other is NotImplemented: return other self._array.__ior__(other._array) return self def __ror__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ror__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ror__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ror__(other._array) return self.__class__._new(res) def __ipow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ipow__. """ other = self._check_allowed_dtypes(other, "numeric", "__ipow__") if other is NotImplemented: return other self._array.__ipow__(other._array) return self def __rpow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rpow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__rpow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow the spec type promotion rules # for 0-d arrays, so we use pow() here instead. return pow(other, self) def __irshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __irshift__. """ other = self._check_allowed_dtypes(other, "integer", "__irshift__") if other is NotImplemented: return other self._array.__irshift__(other._array) return self def __rrshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rrshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rrshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rrshift__(other._array) return self.__class__._new(res) def __isub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __isub__. """ other = self._check_allowed_dtypes(other, "numeric", "__isub__") if other is NotImplemented: return other self._array.__isub__(other._array) return self def __rsub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rsub__. """ other = self._check_allowed_dtypes(other, "numeric", "__rsub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rsub__(other._array) return self.__class__._new(res) def __itruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __itruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__itruediv__") if other is NotImplemented: return other self._array.__itruediv__(other._array) return self def __rtruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __rtruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__rtruediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rtruediv__(other._array) return self.__class__._new(res) def __ixor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ixor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ixor__") if other is NotImplemented: return other self._array.__ixor__(other._array) return self def __rxor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rxor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rxor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rxor__(other._array) return self.__class__._new(res) def to_device(self: Array, device: Device, /, stream: None = None) -> Array: if stream is not None: raise ValueError("The stream argument to to_device() is not supported") if device == 'cpu': return self raise ValueError(f"Unsupported device {device!r}") def dtype(self) -> Dtype: """ Array API compatible wrapper for :py:meth:`np.ndarray.dtype <numpy.ndarray.dtype>`. See its docstring for more information. """ return self._array.dtype def device(self) -> Device: return "cpu" # Note: mT is new in array API spec (see matrix_transpose) def mT(self) -> Array: from .linalg import matrix_transpose return matrix_transpose(self) def ndim(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.ndim <numpy.ndarray.ndim>`. See its docstring for more information. """ return self._array.ndim def shape(self) -> Tuple[int, ...]: """ Array API compatible wrapper for :py:meth:`np.ndarray.shape <numpy.ndarray.shape>`. See its docstring for more information. """ return self._array.shape def size(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.size <numpy.ndarray.size>`. See its docstring for more information. """ return self._array.size def T(self) -> Array: """ Array API compatible wrapper for :py:meth:`np.ndarray.T <numpy.ndarray.T>`. See its docstring for more information. """ # Note: T only works on 2-dimensional arrays. See the corresponding # note in the specification: # https://data-apis.org/array-api/latest/API_specification/array_object.html#t if self.ndim != 2: raise ValueError("x.T requires x to have 2 dimensions. Use x.mT to transpose stacks of matrices and permute_dims() to permute dimensions.") return self.__class__._new(self._array.T) The provided code snippet includes necessary dependencies for implementing the `floor_divide` function. Write a Python function `def floor_divide(x1: Array, x2: Array, /) -> Array` to solve the following problem: Array API compatible wrapper for :py:func:`np.floor_divide <numpy.floor_divide>`. See its docstring for more information. Here is the function: def floor_divide(x1: Array, x2: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.floor_divide <numpy.floor_divide>`. See its docstring for more information. """ if x1.dtype not in _numeric_dtypes or x2.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in floor_divide") # Call result type here just to raise on disallowed type combinations _result_type(x1.dtype, x2.dtype) x1, x2 = Array._normalize_two_args(x1, x2) return Array._new(np.floor_divide(x1._array, x2._array))
Array API compatible wrapper for :py:func:`np.floor_divide <numpy.floor_divide>`. See its docstring for more information.
170,043
from __future__ import annotations from ._dtypes import ( _boolean_dtypes, _floating_dtypes, _integer_dtypes, _integer_or_boolean_dtypes, _numeric_dtypes, _result_type, ) from ._array_object import Array import numpy as np _numeric_dtypes = ( float32, float64, int8, int16, int32, int64, uint8, uint16, uint32, uint64, ) def _result_type(type1, type2): if (type1, type2) in _promotion_table: return _promotion_table[type1, type2] raise TypeError(f"{type1} and {type2} cannot be type promoted together") class Array: """ n-d array object for the array API namespace. See the docstring of :py:obj:`np.ndarray <numpy.ndarray>` for more information. This is a wrapper around numpy.ndarray that restricts the usage to only those things that are required by the array API namespace. Note, attributes on this object that start with a single underscore are not part of the API specification and should only be used internally. This object should not be constructed directly. Rather, use one of the creation functions, such as asarray(). """ _array: np.ndarray # Use a custom constructor instead of __init__, as manually initializing # this class is not supported API. def _new(cls, x, /): """ This is a private method for initializing the array API Array object. Functions outside of the array_api submodule should not use this method. Use one of the creation functions instead, such as ``asarray``. """ obj = super().__new__(cls) # Note: The spec does not have array scalars, only 0-D arrays. if isinstance(x, np.generic): # Convert the array scalar to a 0-D array x = np.asarray(x) if x.dtype not in _all_dtypes: raise TypeError( f"The array_api namespace does not support the dtype '{x.dtype}'" ) obj._array = x return obj # Prevent Array() from working def __new__(cls, *args, **kwargs): raise TypeError( "The array_api Array object should not be instantiated directly. Use an array creation function, such as asarray(), instead." ) # These functions are not required by the spec, but are implemented for # the sake of usability. def __str__(self: Array, /) -> str: """ Performs the operation __str__. """ return self._array.__str__().replace("array", "Array") def __repr__(self: Array, /) -> str: """ Performs the operation __repr__. """ suffix = f", dtype={self.dtype.name})" if 0 in self.shape: prefix = "empty(" mid = str(self.shape) else: prefix = "Array(" mid = np.array2string(self._array, separator=', ', prefix=prefix, suffix=suffix) return prefix + mid + suffix # This function is not required by the spec, but we implement it here for # convenience so that np.asarray(np.array_api.Array) will work. def __array__(self, dtype: None | np.dtype[Any] = None) -> npt.NDArray[Any]: """ Warning: this method is NOT part of the array API spec. Implementers of other libraries need not include it, and users should not assume it will be present in other implementations. """ return np.asarray(self._array, dtype=dtype) # These are various helper functions to make the array behavior match the # spec in places where it either deviates from or is more strict than # NumPy behavior def _check_allowed_dtypes(self, other: bool | int | float | Array, dtype_category: str, op: str) -> Array: """ Helper function for operators to only allow specific input dtypes Use like other = self._check_allowed_dtypes(other, 'numeric', '__add__') if other is NotImplemented: return other """ if self.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") if isinstance(other, (int, float, bool)): other = self._promote_scalar(other) elif isinstance(other, Array): if other.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") else: return NotImplemented # This will raise TypeError for type combinations that are not allowed # to promote in the spec (even if the NumPy array operator would # promote them). res_dtype = _result_type(self.dtype, other.dtype) if op.startswith("__i"): # Note: NumPy will allow in-place operators in some cases where # the type promoted operator does not match the left-hand side # operand. For example, # >>> a = np.array(1, dtype=np.int8) # >>> a += np.array(1, dtype=np.int16) # The spec explicitly disallows this. if res_dtype != self.dtype: raise TypeError( f"Cannot perform {op} with dtypes {self.dtype} and {other.dtype}" ) return other # Helper function to match the type promotion rules in the spec def _promote_scalar(self, scalar): """ Returns a promoted version of a Python scalar appropriate for use with operations on self. This may raise an OverflowError in cases where the scalar is an integer that is too large to fit in a NumPy integer dtype, or TypeError when the scalar type is incompatible with the dtype of self. """ # Note: Only Python scalar types that match the array dtype are # allowed. if isinstance(scalar, bool): if self.dtype not in _boolean_dtypes: raise TypeError( "Python bool scalars can only be promoted with bool arrays" ) elif isinstance(scalar, int): if self.dtype in _boolean_dtypes: raise TypeError( "Python int scalars cannot be promoted with bool arrays" ) elif isinstance(scalar, float): if self.dtype not in _floating_dtypes: raise TypeError( "Python float scalars can only be promoted with floating-point arrays." ) else: raise TypeError("'scalar' must be a Python scalar") # Note: scalars are unconditionally cast to the same dtype as the # array. # Note: the spec only specifies integer-dtype/int promotion # behavior for integers within the bounds of the integer dtype. # Outside of those bounds we use the default NumPy behavior (either # cast or raise OverflowError). return Array._new(np.array(scalar, self.dtype)) def _normalize_two_args(x1, x2) -> Tuple[Array, Array]: """ Normalize inputs to two arg functions to fix type promotion rules NumPy deviates from the spec type promotion rules in cases where one argument is 0-dimensional and the other is not. For example: >>> import numpy as np >>> a = np.array([1.0], dtype=np.float32) >>> b = np.array(1.0, dtype=np.float64) >>> np.add(a, b) # The spec says this should be float64 array([2.], dtype=float32) To fix this, we add a dimension to the 0-dimension array before passing it through. This works because a dimension would be added anyway from broadcasting, so the resulting shape is the same, but this prevents NumPy from not promoting the dtype. """ # Another option would be to use signature=(x1.dtype, x2.dtype, None), # but that only works for ufuncs, so we would have to call the ufuncs # directly in the operator methods. One should also note that this # sort of trick wouldn't work for functions like searchsorted, which # don't do normal broadcasting, but there aren't any functions like # that in the array API namespace. if x1.ndim == 0 and x2.ndim != 0: # The _array[None] workaround was chosen because it is relatively # performant. broadcast_to(x1._array, x2.shape) is much slower. We # could also manually type promote x2, but that is more complicated # and about the same performance as this. x1 = Array._new(x1._array[None]) elif x2.ndim == 0 and x1.ndim != 0: x2 = Array._new(x2._array[None]) return (x1, x2) # Note: A large fraction of allowed indices are disallowed here (see the # docstring below) def _validate_index(self, key): """ Validate an index according to the array API. The array API specification only requires a subset of indices that are supported by NumPy. This function will reject any index that is allowed by NumPy but not required by the array API specification. We always raise ``IndexError`` on such indices (the spec does not require any specific behavior on them, but this makes the NumPy array API namespace a minimal implementation of the spec). See https://data-apis.org/array-api/latest/API_specification/indexing.html for the full list of required indexing behavior This function raises IndexError if the index ``key`` is invalid. It only raises ``IndexError`` on indices that are not already rejected by NumPy, as NumPy will already raise the appropriate error on such indices. ``shape`` may be None, in which case, only cases that are independent of the array shape are checked. The following cases are allowed by NumPy, but not specified by the array API specification: - Indices to not include an implicit ellipsis at the end. That is, every axis of an array must be explicitly indexed or an ellipsis included. This behaviour is sometimes referred to as flat indexing. - The start and stop of a slice may not be out of bounds. In particular, for a slice ``i:j:k`` on an axis of size ``n``, only the following are allowed: - ``i`` or ``j`` omitted (``None``). - ``-n <= i <= max(0, n - 1)``. - For ``k > 0`` or ``k`` omitted (``None``), ``-n <= j <= n``. - For ``k < 0``, ``-n - 1 <= j <= max(0, n - 1)``. - Boolean array indices are not allowed as part of a larger tuple index. - Integer array indices are not allowed (with the exception of 0-D arrays, which are treated the same as scalars). Additionally, it should be noted that indices that would return a scalar in NumPy will return a 0-D array. Array scalars are not allowed in the specification, only 0-D arrays. This is done in the ``Array._new`` constructor, not this function. """ _key = key if isinstance(key, tuple) else (key,) for i in _key: if isinstance(i, bool) or not ( isinstance(i, SupportsIndex) # i.e. ints or isinstance(i, slice) or i == Ellipsis or i is None or isinstance(i, Array) or isinstance(i, np.ndarray) ): raise IndexError( f"Single-axes index {i} has {type(i)=}, but only " "integers, slices (:), ellipsis (...), newaxis (None), " "zero-dimensional integer arrays and boolean arrays " "are specified in the Array API." ) nonexpanding_key = [] single_axes = [] n_ellipsis = 0 key_has_mask = False for i in _key: if i is not None: nonexpanding_key.append(i) if isinstance(i, Array) or isinstance(i, np.ndarray): if i.dtype in _boolean_dtypes: key_has_mask = True single_axes.append(i) else: # i must not be an array here, to avoid elementwise equals if i == Ellipsis: n_ellipsis += 1 else: single_axes.append(i) n_single_axes = len(single_axes) if n_ellipsis > 1: return # handled by ndarray elif n_ellipsis == 0: # Note boolean masks must be the sole index, which we check for # later on. if not key_has_mask and n_single_axes < self.ndim: raise IndexError( f"{self.ndim=}, but the multi-axes index only specifies " f"{n_single_axes} dimensions. If this was intentional, " "add a trailing ellipsis (...) which expands into as many " "slices (:) as necessary - this is what np.ndarray arrays " "implicitly do, but such flat indexing behaviour is not " "specified in the Array API." ) if n_ellipsis == 0: indexed_shape = self.shape else: ellipsis_start = None for pos, i in enumerate(nonexpanding_key): if not (isinstance(i, Array) or isinstance(i, np.ndarray)): if i == Ellipsis: ellipsis_start = pos break assert ellipsis_start is not None # sanity check ellipsis_end = self.ndim - (n_single_axes - ellipsis_start) indexed_shape = ( self.shape[:ellipsis_start] + self.shape[ellipsis_end:] ) for i, side in zip(single_axes, indexed_shape): if isinstance(i, slice): if side == 0: f_range = "0 (or None)" else: f_range = f"between -{side} and {side - 1} (or None)" if i.start is not None: try: start = operator.index(i.start) except TypeError: pass # handled by ndarray else: if not (-side <= start <= side): raise IndexError( f"Slice {i} contains {start=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds starts are not specified in " "the Array API)" ) if i.stop is not None: try: stop = operator.index(i.stop) except TypeError: pass # handled by ndarray else: if not (-side <= stop <= side): raise IndexError( f"Slice {i} contains {stop=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds stops are not specified in " "the Array API)" ) elif isinstance(i, Array): if i.dtype in _boolean_dtypes and len(_key) != 1: assert isinstance(key, tuple) # sanity check raise IndexError( f"Single-axes index {i} is a boolean array and " f"{len(key)=}, but masking is only specified in the " "Array API when the array is the sole index." ) elif i.dtype in _integer_dtypes and i.ndim != 0: raise IndexError( f"Single-axes index {i} is a non-zero-dimensional " "integer array, but advanced integer indexing is not " "specified in the Array API." ) elif isinstance(i, tuple): raise IndexError( f"Single-axes index {i} is a tuple, but nested tuple " "indices are not specified in the Array API." ) # Everything below this line is required by the spec. def __abs__(self: Array, /) -> Array: """ Performs the operation __abs__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __abs__") res = self._array.__abs__() return self.__class__._new(res) def __add__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __add__. """ other = self._check_allowed_dtypes(other, "numeric", "__add__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__add__(other._array) return self.__class__._new(res) def __and__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __and__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__and__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__and__(other._array) return self.__class__._new(res) def __array_namespace__( self: Array, /, *, api_version: Optional[str] = None ) -> types.ModuleType: if api_version is not None and not api_version.startswith("2021."): raise ValueError(f"Unrecognized array API version: {api_version!r}") return array_api def __bool__(self: Array, /) -> bool: """ Performs the operation __bool__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("bool is only allowed on arrays with 0 dimensions") if self.dtype not in _boolean_dtypes: raise ValueError("bool is only allowed on boolean arrays") res = self._array.__bool__() return res def __dlpack__(self: Array, /, *, stream: None = None) -> PyCapsule: """ Performs the operation __dlpack__. """ return self._array.__dlpack__(stream=stream) def __dlpack_device__(self: Array, /) -> Tuple[IntEnum, int]: """ Performs the operation __dlpack_device__. """ # Note: device support is required for this return self._array.__dlpack_device__() def __eq__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __eq__. """ # Even though "all" dtypes are allowed, we still require them to be # promotable with each other. other = self._check_allowed_dtypes(other, "all", "__eq__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__eq__(other._array) return self.__class__._new(res) def __float__(self: Array, /) -> float: """ Performs the operation __float__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("float is only allowed on arrays with 0 dimensions") if self.dtype not in _floating_dtypes: raise ValueError("float is only allowed on floating-point arrays") res = self._array.__float__() return res def __floordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __floordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__floordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__floordiv__(other._array) return self.__class__._new(res) def __ge__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ge__. """ other = self._check_allowed_dtypes(other, "numeric", "__ge__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ge__(other._array) return self.__class__._new(res) def __getitem__( self: Array, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], /, ) -> Array: """ Performs the operation __getitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array res = self._array.__getitem__(key) return self._new(res) def __gt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __gt__. """ other = self._check_allowed_dtypes(other, "numeric", "__gt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__gt__(other._array) return self.__class__._new(res) def __int__(self: Array, /) -> int: """ Performs the operation __int__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("int is only allowed on arrays with 0 dimensions") if self.dtype not in _integer_dtypes: raise ValueError("int is only allowed on integer arrays") res = self._array.__int__() return res def __index__(self: Array, /) -> int: """ Performs the operation __index__. """ res = self._array.__index__() return res def __invert__(self: Array, /) -> Array: """ Performs the operation __invert__. """ if self.dtype not in _integer_or_boolean_dtypes: raise TypeError("Only integer or boolean dtypes are allowed in __invert__") res = self._array.__invert__() return self.__class__._new(res) def __le__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __le__. """ other = self._check_allowed_dtypes(other, "numeric", "__le__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__le__(other._array) return self.__class__._new(res) def __lshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __lshift__. """ other = self._check_allowed_dtypes(other, "integer", "__lshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lshift__(other._array) return self.__class__._new(res) def __lt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __lt__. """ other = self._check_allowed_dtypes(other, "numeric", "__lt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lt__(other._array) return self.__class__._new(res) def __matmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __matmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__matmul__") if other is NotImplemented: return other res = self._array.__matmul__(other._array) return self.__class__._new(res) def __mod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mod__. """ other = self._check_allowed_dtypes(other, "numeric", "__mod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mod__(other._array) return self.__class__._new(res) def __mul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mul__. """ other = self._check_allowed_dtypes(other, "numeric", "__mul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mul__(other._array) return self.__class__._new(res) def __ne__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __ne__. """ other = self._check_allowed_dtypes(other, "all", "__ne__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ne__(other._array) return self.__class__._new(res) def __neg__(self: Array, /) -> Array: """ Performs the operation __neg__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __neg__") res = self._array.__neg__() return self.__class__._new(res) def __or__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __or__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__or__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__or__(other._array) return self.__class__._new(res) def __pos__(self: Array, /) -> Array: """ Performs the operation __pos__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __pos__") res = self._array.__pos__() return self.__class__._new(res) def __pow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __pow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__pow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow type promotion rules for 0-d # arrays, so we use pow() here instead. return pow(self, other) def __rshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rshift__(other._array) return self.__class__._new(res) def __setitem__( self, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], value: Union[int, float, bool, Array], /, ) -> None: """ Performs the operation __setitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array self._array.__setitem__(key, asarray(value)._array) def __sub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __sub__. """ other = self._check_allowed_dtypes(other, "numeric", "__sub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__sub__(other._array) return self.__class__._new(res) # PEP 484 requires int to be a subtype of float, but __truediv__ should # not accept int. def __truediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __truediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__truediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__truediv__(other._array) return self.__class__._new(res) def __xor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __xor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__xor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__xor__(other._array) return self.__class__._new(res) def __iadd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __iadd__. """ other = self._check_allowed_dtypes(other, "numeric", "__iadd__") if other is NotImplemented: return other self._array.__iadd__(other._array) return self def __radd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __radd__. """ other = self._check_allowed_dtypes(other, "numeric", "__radd__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__radd__(other._array) return self.__class__._new(res) def __iand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __iand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__iand__") if other is NotImplemented: return other self._array.__iand__(other._array) return self def __rand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rand__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rand__(other._array) return self.__class__._new(res) def __ifloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ifloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__ifloordiv__") if other is NotImplemented: return other self._array.__ifloordiv__(other._array) return self def __rfloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rfloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__rfloordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rfloordiv__(other._array) return self.__class__._new(res) def __ilshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __ilshift__. """ other = self._check_allowed_dtypes(other, "integer", "__ilshift__") if other is NotImplemented: return other self._array.__ilshift__(other._array) return self def __rlshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rlshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rlshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rlshift__(other._array) return self.__class__._new(res) def __imatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __imatmul__. """ # Note: NumPy does not implement __imatmul__. # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__imatmul__") if other is NotImplemented: return other # __imatmul__ can only be allowed when it would not change the shape # of self. other_shape = other.shape if self.shape == () or other_shape == (): raise ValueError("@= requires at least one dimension") if len(other_shape) == 1 or other_shape[-1] != other_shape[-2]: raise ValueError("@= cannot change the shape of the input array") self._array[:] = self._array.__matmul__(other._array) return self def __rmatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __rmatmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__rmatmul__") if other is NotImplemented: return other res = self._array.__rmatmul__(other._array) return self.__class__._new(res) def __imod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imod__. """ other = self._check_allowed_dtypes(other, "numeric", "__imod__") if other is NotImplemented: return other self._array.__imod__(other._array) return self def __rmod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmod__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmod__(other._array) return self.__class__._new(res) def __imul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imul__. """ other = self._check_allowed_dtypes(other, "numeric", "__imul__") if other is NotImplemented: return other self._array.__imul__(other._array) return self def __rmul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmul__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmul__(other._array) return self.__class__._new(res) def __ior__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ior__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ior__") if other is NotImplemented: return other self._array.__ior__(other._array) return self def __ror__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ror__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ror__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ror__(other._array) return self.__class__._new(res) def __ipow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ipow__. """ other = self._check_allowed_dtypes(other, "numeric", "__ipow__") if other is NotImplemented: return other self._array.__ipow__(other._array) return self def __rpow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rpow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__rpow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow the spec type promotion rules # for 0-d arrays, so we use pow() here instead. return pow(other, self) def __irshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __irshift__. """ other = self._check_allowed_dtypes(other, "integer", "__irshift__") if other is NotImplemented: return other self._array.__irshift__(other._array) return self def __rrshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rrshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rrshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rrshift__(other._array) return self.__class__._new(res) def __isub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __isub__. """ other = self._check_allowed_dtypes(other, "numeric", "__isub__") if other is NotImplemented: return other self._array.__isub__(other._array) return self def __rsub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rsub__. """ other = self._check_allowed_dtypes(other, "numeric", "__rsub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rsub__(other._array) return self.__class__._new(res) def __itruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __itruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__itruediv__") if other is NotImplemented: return other self._array.__itruediv__(other._array) return self def __rtruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __rtruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__rtruediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rtruediv__(other._array) return self.__class__._new(res) def __ixor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ixor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ixor__") if other is NotImplemented: return other self._array.__ixor__(other._array) return self def __rxor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rxor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rxor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rxor__(other._array) return self.__class__._new(res) def to_device(self: Array, device: Device, /, stream: None = None) -> Array: if stream is not None: raise ValueError("The stream argument to to_device() is not supported") if device == 'cpu': return self raise ValueError(f"Unsupported device {device!r}") def dtype(self) -> Dtype: """ Array API compatible wrapper for :py:meth:`np.ndarray.dtype <numpy.ndarray.dtype>`. See its docstring for more information. """ return self._array.dtype def device(self) -> Device: return "cpu" # Note: mT is new in array API spec (see matrix_transpose) def mT(self) -> Array: from .linalg import matrix_transpose return matrix_transpose(self) def ndim(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.ndim <numpy.ndarray.ndim>`. See its docstring for more information. """ return self._array.ndim def shape(self) -> Tuple[int, ...]: """ Array API compatible wrapper for :py:meth:`np.ndarray.shape <numpy.ndarray.shape>`. See its docstring for more information. """ return self._array.shape def size(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.size <numpy.ndarray.size>`. See its docstring for more information. """ return self._array.size def T(self) -> Array: """ Array API compatible wrapper for :py:meth:`np.ndarray.T <numpy.ndarray.T>`. See its docstring for more information. """ # Note: T only works on 2-dimensional arrays. See the corresponding # note in the specification: # https://data-apis.org/array-api/latest/API_specification/array_object.html#t if self.ndim != 2: raise ValueError("x.T requires x to have 2 dimensions. Use x.mT to transpose stacks of matrices and permute_dims() to permute dimensions.") return self.__class__._new(self._array.T) The provided code snippet includes necessary dependencies for implementing the `greater` function. Write a Python function `def greater(x1: Array, x2: Array, /) -> Array` to solve the following problem: Array API compatible wrapper for :py:func:`np.greater <numpy.greater>`. See its docstring for more information. Here is the function: def greater(x1: Array, x2: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.greater <numpy.greater>`. See its docstring for more information. """ if x1.dtype not in _numeric_dtypes or x2.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in greater") # Call result type here just to raise on disallowed type combinations _result_type(x1.dtype, x2.dtype) x1, x2 = Array._normalize_two_args(x1, x2) return Array._new(np.greater(x1._array, x2._array))
Array API compatible wrapper for :py:func:`np.greater <numpy.greater>`. See its docstring for more information.
170,044
from __future__ import annotations from ._dtypes import ( _boolean_dtypes, _floating_dtypes, _integer_dtypes, _integer_or_boolean_dtypes, _numeric_dtypes, _result_type, ) from ._array_object import Array import numpy as np _numeric_dtypes = ( float32, float64, int8, int16, int32, int64, uint8, uint16, uint32, uint64, ) def _result_type(type1, type2): if (type1, type2) in _promotion_table: return _promotion_table[type1, type2] raise TypeError(f"{type1} and {type2} cannot be type promoted together") class Array: """ n-d array object for the array API namespace. See the docstring of :py:obj:`np.ndarray <numpy.ndarray>` for more information. This is a wrapper around numpy.ndarray that restricts the usage to only those things that are required by the array API namespace. Note, attributes on this object that start with a single underscore are not part of the API specification and should only be used internally. This object should not be constructed directly. Rather, use one of the creation functions, such as asarray(). """ _array: np.ndarray # Use a custom constructor instead of __init__, as manually initializing # this class is not supported API. def _new(cls, x, /): """ This is a private method for initializing the array API Array object. Functions outside of the array_api submodule should not use this method. Use one of the creation functions instead, such as ``asarray``. """ obj = super().__new__(cls) # Note: The spec does not have array scalars, only 0-D arrays. if isinstance(x, np.generic): # Convert the array scalar to a 0-D array x = np.asarray(x) if x.dtype not in _all_dtypes: raise TypeError( f"The array_api namespace does not support the dtype '{x.dtype}'" ) obj._array = x return obj # Prevent Array() from working def __new__(cls, *args, **kwargs): raise TypeError( "The array_api Array object should not be instantiated directly. Use an array creation function, such as asarray(), instead." ) # These functions are not required by the spec, but are implemented for # the sake of usability. def __str__(self: Array, /) -> str: """ Performs the operation __str__. """ return self._array.__str__().replace("array", "Array") def __repr__(self: Array, /) -> str: """ Performs the operation __repr__. """ suffix = f", dtype={self.dtype.name})" if 0 in self.shape: prefix = "empty(" mid = str(self.shape) else: prefix = "Array(" mid = np.array2string(self._array, separator=', ', prefix=prefix, suffix=suffix) return prefix + mid + suffix # This function is not required by the spec, but we implement it here for # convenience so that np.asarray(np.array_api.Array) will work. def __array__(self, dtype: None | np.dtype[Any] = None) -> npt.NDArray[Any]: """ Warning: this method is NOT part of the array API spec. Implementers of other libraries need not include it, and users should not assume it will be present in other implementations. """ return np.asarray(self._array, dtype=dtype) # These are various helper functions to make the array behavior match the # spec in places where it either deviates from or is more strict than # NumPy behavior def _check_allowed_dtypes(self, other: bool | int | float | Array, dtype_category: str, op: str) -> Array: """ Helper function for operators to only allow specific input dtypes Use like other = self._check_allowed_dtypes(other, 'numeric', '__add__') if other is NotImplemented: return other """ if self.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") if isinstance(other, (int, float, bool)): other = self._promote_scalar(other) elif isinstance(other, Array): if other.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") else: return NotImplemented # This will raise TypeError for type combinations that are not allowed # to promote in the spec (even if the NumPy array operator would # promote them). res_dtype = _result_type(self.dtype, other.dtype) if op.startswith("__i"): # Note: NumPy will allow in-place operators in some cases where # the type promoted operator does not match the left-hand side # operand. For example, # >>> a = np.array(1, dtype=np.int8) # >>> a += np.array(1, dtype=np.int16) # The spec explicitly disallows this. if res_dtype != self.dtype: raise TypeError( f"Cannot perform {op} with dtypes {self.dtype} and {other.dtype}" ) return other # Helper function to match the type promotion rules in the spec def _promote_scalar(self, scalar): """ Returns a promoted version of a Python scalar appropriate for use with operations on self. This may raise an OverflowError in cases where the scalar is an integer that is too large to fit in a NumPy integer dtype, or TypeError when the scalar type is incompatible with the dtype of self. """ # Note: Only Python scalar types that match the array dtype are # allowed. if isinstance(scalar, bool): if self.dtype not in _boolean_dtypes: raise TypeError( "Python bool scalars can only be promoted with bool arrays" ) elif isinstance(scalar, int): if self.dtype in _boolean_dtypes: raise TypeError( "Python int scalars cannot be promoted with bool arrays" ) elif isinstance(scalar, float): if self.dtype not in _floating_dtypes: raise TypeError( "Python float scalars can only be promoted with floating-point arrays." ) else: raise TypeError("'scalar' must be a Python scalar") # Note: scalars are unconditionally cast to the same dtype as the # array. # Note: the spec only specifies integer-dtype/int promotion # behavior for integers within the bounds of the integer dtype. # Outside of those bounds we use the default NumPy behavior (either # cast or raise OverflowError). return Array._new(np.array(scalar, self.dtype)) def _normalize_two_args(x1, x2) -> Tuple[Array, Array]: """ Normalize inputs to two arg functions to fix type promotion rules NumPy deviates from the spec type promotion rules in cases where one argument is 0-dimensional and the other is not. For example: >>> import numpy as np >>> a = np.array([1.0], dtype=np.float32) >>> b = np.array(1.0, dtype=np.float64) >>> np.add(a, b) # The spec says this should be float64 array([2.], dtype=float32) To fix this, we add a dimension to the 0-dimension array before passing it through. This works because a dimension would be added anyway from broadcasting, so the resulting shape is the same, but this prevents NumPy from not promoting the dtype. """ # Another option would be to use signature=(x1.dtype, x2.dtype, None), # but that only works for ufuncs, so we would have to call the ufuncs # directly in the operator methods. One should also note that this # sort of trick wouldn't work for functions like searchsorted, which # don't do normal broadcasting, but there aren't any functions like # that in the array API namespace. if x1.ndim == 0 and x2.ndim != 0: # The _array[None] workaround was chosen because it is relatively # performant. broadcast_to(x1._array, x2.shape) is much slower. We # could also manually type promote x2, but that is more complicated # and about the same performance as this. x1 = Array._new(x1._array[None]) elif x2.ndim == 0 and x1.ndim != 0: x2 = Array._new(x2._array[None]) return (x1, x2) # Note: A large fraction of allowed indices are disallowed here (see the # docstring below) def _validate_index(self, key): """ Validate an index according to the array API. The array API specification only requires a subset of indices that are supported by NumPy. This function will reject any index that is allowed by NumPy but not required by the array API specification. We always raise ``IndexError`` on such indices (the spec does not require any specific behavior on them, but this makes the NumPy array API namespace a minimal implementation of the spec). See https://data-apis.org/array-api/latest/API_specification/indexing.html for the full list of required indexing behavior This function raises IndexError if the index ``key`` is invalid. It only raises ``IndexError`` on indices that are not already rejected by NumPy, as NumPy will already raise the appropriate error on such indices. ``shape`` may be None, in which case, only cases that are independent of the array shape are checked. The following cases are allowed by NumPy, but not specified by the array API specification: - Indices to not include an implicit ellipsis at the end. That is, every axis of an array must be explicitly indexed or an ellipsis included. This behaviour is sometimes referred to as flat indexing. - The start and stop of a slice may not be out of bounds. In particular, for a slice ``i:j:k`` on an axis of size ``n``, only the following are allowed: - ``i`` or ``j`` omitted (``None``). - ``-n <= i <= max(0, n - 1)``. - For ``k > 0`` or ``k`` omitted (``None``), ``-n <= j <= n``. - For ``k < 0``, ``-n - 1 <= j <= max(0, n - 1)``. - Boolean array indices are not allowed as part of a larger tuple index. - Integer array indices are not allowed (with the exception of 0-D arrays, which are treated the same as scalars). Additionally, it should be noted that indices that would return a scalar in NumPy will return a 0-D array. Array scalars are not allowed in the specification, only 0-D arrays. This is done in the ``Array._new`` constructor, not this function. """ _key = key if isinstance(key, tuple) else (key,) for i in _key: if isinstance(i, bool) or not ( isinstance(i, SupportsIndex) # i.e. ints or isinstance(i, slice) or i == Ellipsis or i is None or isinstance(i, Array) or isinstance(i, np.ndarray) ): raise IndexError( f"Single-axes index {i} has {type(i)=}, but only " "integers, slices (:), ellipsis (...), newaxis (None), " "zero-dimensional integer arrays and boolean arrays " "are specified in the Array API." ) nonexpanding_key = [] single_axes = [] n_ellipsis = 0 key_has_mask = False for i in _key: if i is not None: nonexpanding_key.append(i) if isinstance(i, Array) or isinstance(i, np.ndarray): if i.dtype in _boolean_dtypes: key_has_mask = True single_axes.append(i) else: # i must not be an array here, to avoid elementwise equals if i == Ellipsis: n_ellipsis += 1 else: single_axes.append(i) n_single_axes = len(single_axes) if n_ellipsis > 1: return # handled by ndarray elif n_ellipsis == 0: # Note boolean masks must be the sole index, which we check for # later on. if not key_has_mask and n_single_axes < self.ndim: raise IndexError( f"{self.ndim=}, but the multi-axes index only specifies " f"{n_single_axes} dimensions. If this was intentional, " "add a trailing ellipsis (...) which expands into as many " "slices (:) as necessary - this is what np.ndarray arrays " "implicitly do, but such flat indexing behaviour is not " "specified in the Array API." ) if n_ellipsis == 0: indexed_shape = self.shape else: ellipsis_start = None for pos, i in enumerate(nonexpanding_key): if not (isinstance(i, Array) or isinstance(i, np.ndarray)): if i == Ellipsis: ellipsis_start = pos break assert ellipsis_start is not None # sanity check ellipsis_end = self.ndim - (n_single_axes - ellipsis_start) indexed_shape = ( self.shape[:ellipsis_start] + self.shape[ellipsis_end:] ) for i, side in zip(single_axes, indexed_shape): if isinstance(i, slice): if side == 0: f_range = "0 (or None)" else: f_range = f"between -{side} and {side - 1} (or None)" if i.start is not None: try: start = operator.index(i.start) except TypeError: pass # handled by ndarray else: if not (-side <= start <= side): raise IndexError( f"Slice {i} contains {start=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds starts are not specified in " "the Array API)" ) if i.stop is not None: try: stop = operator.index(i.stop) except TypeError: pass # handled by ndarray else: if not (-side <= stop <= side): raise IndexError( f"Slice {i} contains {stop=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds stops are not specified in " "the Array API)" ) elif isinstance(i, Array): if i.dtype in _boolean_dtypes and len(_key) != 1: assert isinstance(key, tuple) # sanity check raise IndexError( f"Single-axes index {i} is a boolean array and " f"{len(key)=}, but masking is only specified in the " "Array API when the array is the sole index." ) elif i.dtype in _integer_dtypes and i.ndim != 0: raise IndexError( f"Single-axes index {i} is a non-zero-dimensional " "integer array, but advanced integer indexing is not " "specified in the Array API." ) elif isinstance(i, tuple): raise IndexError( f"Single-axes index {i} is a tuple, but nested tuple " "indices are not specified in the Array API." ) # Everything below this line is required by the spec. def __abs__(self: Array, /) -> Array: """ Performs the operation __abs__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __abs__") res = self._array.__abs__() return self.__class__._new(res) def __add__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __add__. """ other = self._check_allowed_dtypes(other, "numeric", "__add__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__add__(other._array) return self.__class__._new(res) def __and__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __and__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__and__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__and__(other._array) return self.__class__._new(res) def __array_namespace__( self: Array, /, *, api_version: Optional[str] = None ) -> types.ModuleType: if api_version is not None and not api_version.startswith("2021."): raise ValueError(f"Unrecognized array API version: {api_version!r}") return array_api def __bool__(self: Array, /) -> bool: """ Performs the operation __bool__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("bool is only allowed on arrays with 0 dimensions") if self.dtype not in _boolean_dtypes: raise ValueError("bool is only allowed on boolean arrays") res = self._array.__bool__() return res def __dlpack__(self: Array, /, *, stream: None = None) -> PyCapsule: """ Performs the operation __dlpack__. """ return self._array.__dlpack__(stream=stream) def __dlpack_device__(self: Array, /) -> Tuple[IntEnum, int]: """ Performs the operation __dlpack_device__. """ # Note: device support is required for this return self._array.__dlpack_device__() def __eq__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __eq__. """ # Even though "all" dtypes are allowed, we still require them to be # promotable with each other. other = self._check_allowed_dtypes(other, "all", "__eq__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__eq__(other._array) return self.__class__._new(res) def __float__(self: Array, /) -> float: """ Performs the operation __float__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("float is only allowed on arrays with 0 dimensions") if self.dtype not in _floating_dtypes: raise ValueError("float is only allowed on floating-point arrays") res = self._array.__float__() return res def __floordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __floordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__floordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__floordiv__(other._array) return self.__class__._new(res) def __ge__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ge__. """ other = self._check_allowed_dtypes(other, "numeric", "__ge__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ge__(other._array) return self.__class__._new(res) def __getitem__( self: Array, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], /, ) -> Array: """ Performs the operation __getitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array res = self._array.__getitem__(key) return self._new(res) def __gt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __gt__. """ other = self._check_allowed_dtypes(other, "numeric", "__gt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__gt__(other._array) return self.__class__._new(res) def __int__(self: Array, /) -> int: """ Performs the operation __int__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("int is only allowed on arrays with 0 dimensions") if self.dtype not in _integer_dtypes: raise ValueError("int is only allowed on integer arrays") res = self._array.__int__() return res def __index__(self: Array, /) -> int: """ Performs the operation __index__. """ res = self._array.__index__() return res def __invert__(self: Array, /) -> Array: """ Performs the operation __invert__. """ if self.dtype not in _integer_or_boolean_dtypes: raise TypeError("Only integer or boolean dtypes are allowed in __invert__") res = self._array.__invert__() return self.__class__._new(res) def __le__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __le__. """ other = self._check_allowed_dtypes(other, "numeric", "__le__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__le__(other._array) return self.__class__._new(res) def __lshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __lshift__. """ other = self._check_allowed_dtypes(other, "integer", "__lshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lshift__(other._array) return self.__class__._new(res) def __lt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __lt__. """ other = self._check_allowed_dtypes(other, "numeric", "__lt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lt__(other._array) return self.__class__._new(res) def __matmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __matmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__matmul__") if other is NotImplemented: return other res = self._array.__matmul__(other._array) return self.__class__._new(res) def __mod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mod__. """ other = self._check_allowed_dtypes(other, "numeric", "__mod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mod__(other._array) return self.__class__._new(res) def __mul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mul__. """ other = self._check_allowed_dtypes(other, "numeric", "__mul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mul__(other._array) return self.__class__._new(res) def __ne__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __ne__. """ other = self._check_allowed_dtypes(other, "all", "__ne__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ne__(other._array) return self.__class__._new(res) def __neg__(self: Array, /) -> Array: """ Performs the operation __neg__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __neg__") res = self._array.__neg__() return self.__class__._new(res) def __or__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __or__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__or__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__or__(other._array) return self.__class__._new(res) def __pos__(self: Array, /) -> Array: """ Performs the operation __pos__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __pos__") res = self._array.__pos__() return self.__class__._new(res) def __pow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __pow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__pow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow type promotion rules for 0-d # arrays, so we use pow() here instead. return pow(self, other) def __rshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rshift__(other._array) return self.__class__._new(res) def __setitem__( self, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], value: Union[int, float, bool, Array], /, ) -> None: """ Performs the operation __setitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array self._array.__setitem__(key, asarray(value)._array) def __sub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __sub__. """ other = self._check_allowed_dtypes(other, "numeric", "__sub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__sub__(other._array) return self.__class__._new(res) # PEP 484 requires int to be a subtype of float, but __truediv__ should # not accept int. def __truediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __truediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__truediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__truediv__(other._array) return self.__class__._new(res) def __xor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __xor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__xor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__xor__(other._array) return self.__class__._new(res) def __iadd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __iadd__. """ other = self._check_allowed_dtypes(other, "numeric", "__iadd__") if other is NotImplemented: return other self._array.__iadd__(other._array) return self def __radd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __radd__. """ other = self._check_allowed_dtypes(other, "numeric", "__radd__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__radd__(other._array) return self.__class__._new(res) def __iand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __iand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__iand__") if other is NotImplemented: return other self._array.__iand__(other._array) return self def __rand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rand__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rand__(other._array) return self.__class__._new(res) def __ifloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ifloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__ifloordiv__") if other is NotImplemented: return other self._array.__ifloordiv__(other._array) return self def __rfloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rfloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__rfloordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rfloordiv__(other._array) return self.__class__._new(res) def __ilshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __ilshift__. """ other = self._check_allowed_dtypes(other, "integer", "__ilshift__") if other is NotImplemented: return other self._array.__ilshift__(other._array) return self def __rlshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rlshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rlshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rlshift__(other._array) return self.__class__._new(res) def __imatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __imatmul__. """ # Note: NumPy does not implement __imatmul__. # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__imatmul__") if other is NotImplemented: return other # __imatmul__ can only be allowed when it would not change the shape # of self. other_shape = other.shape if self.shape == () or other_shape == (): raise ValueError("@= requires at least one dimension") if len(other_shape) == 1 or other_shape[-1] != other_shape[-2]: raise ValueError("@= cannot change the shape of the input array") self._array[:] = self._array.__matmul__(other._array) return self def __rmatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __rmatmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__rmatmul__") if other is NotImplemented: return other res = self._array.__rmatmul__(other._array) return self.__class__._new(res) def __imod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imod__. """ other = self._check_allowed_dtypes(other, "numeric", "__imod__") if other is NotImplemented: return other self._array.__imod__(other._array) return self def __rmod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmod__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmod__(other._array) return self.__class__._new(res) def __imul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imul__. """ other = self._check_allowed_dtypes(other, "numeric", "__imul__") if other is NotImplemented: return other self._array.__imul__(other._array) return self def __rmul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmul__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmul__(other._array) return self.__class__._new(res) def __ior__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ior__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ior__") if other is NotImplemented: return other self._array.__ior__(other._array) return self def __ror__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ror__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ror__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ror__(other._array) return self.__class__._new(res) def __ipow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ipow__. """ other = self._check_allowed_dtypes(other, "numeric", "__ipow__") if other is NotImplemented: return other self._array.__ipow__(other._array) return self def __rpow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rpow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__rpow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow the spec type promotion rules # for 0-d arrays, so we use pow() here instead. return pow(other, self) def __irshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __irshift__. """ other = self._check_allowed_dtypes(other, "integer", "__irshift__") if other is NotImplemented: return other self._array.__irshift__(other._array) return self def __rrshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rrshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rrshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rrshift__(other._array) return self.__class__._new(res) def __isub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __isub__. """ other = self._check_allowed_dtypes(other, "numeric", "__isub__") if other is NotImplemented: return other self._array.__isub__(other._array) return self def __rsub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rsub__. """ other = self._check_allowed_dtypes(other, "numeric", "__rsub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rsub__(other._array) return self.__class__._new(res) def __itruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __itruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__itruediv__") if other is NotImplemented: return other self._array.__itruediv__(other._array) return self def __rtruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __rtruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__rtruediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rtruediv__(other._array) return self.__class__._new(res) def __ixor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ixor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ixor__") if other is NotImplemented: return other self._array.__ixor__(other._array) return self def __rxor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rxor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rxor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rxor__(other._array) return self.__class__._new(res) def to_device(self: Array, device: Device, /, stream: None = None) -> Array: if stream is not None: raise ValueError("The stream argument to to_device() is not supported") if device == 'cpu': return self raise ValueError(f"Unsupported device {device!r}") def dtype(self) -> Dtype: """ Array API compatible wrapper for :py:meth:`np.ndarray.dtype <numpy.ndarray.dtype>`. See its docstring for more information. """ return self._array.dtype def device(self) -> Device: return "cpu" # Note: mT is new in array API spec (see matrix_transpose) def mT(self) -> Array: from .linalg import matrix_transpose return matrix_transpose(self) def ndim(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.ndim <numpy.ndarray.ndim>`. See its docstring for more information. """ return self._array.ndim def shape(self) -> Tuple[int, ...]: """ Array API compatible wrapper for :py:meth:`np.ndarray.shape <numpy.ndarray.shape>`. See its docstring for more information. """ return self._array.shape def size(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.size <numpy.ndarray.size>`. See its docstring for more information. """ return self._array.size def T(self) -> Array: """ Array API compatible wrapper for :py:meth:`np.ndarray.T <numpy.ndarray.T>`. See its docstring for more information. """ # Note: T only works on 2-dimensional arrays. See the corresponding # note in the specification: # https://data-apis.org/array-api/latest/API_specification/array_object.html#t if self.ndim != 2: raise ValueError("x.T requires x to have 2 dimensions. Use x.mT to transpose stacks of matrices and permute_dims() to permute dimensions.") return self.__class__._new(self._array.T) The provided code snippet includes necessary dependencies for implementing the `greater_equal` function. Write a Python function `def greater_equal(x1: Array, x2: Array, /) -> Array` to solve the following problem: Array API compatible wrapper for :py:func:`np.greater_equal <numpy.greater_equal>`. See its docstring for more information. Here is the function: def greater_equal(x1: Array, x2: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.greater_equal <numpy.greater_equal>`. See its docstring for more information. """ if x1.dtype not in _numeric_dtypes or x2.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in greater_equal") # Call result type here just to raise on disallowed type combinations _result_type(x1.dtype, x2.dtype) x1, x2 = Array._normalize_two_args(x1, x2) return Array._new(np.greater_equal(x1._array, x2._array))
Array API compatible wrapper for :py:func:`np.greater_equal <numpy.greater_equal>`. See its docstring for more information.
170,045
from __future__ import annotations from ._dtypes import ( _boolean_dtypes, _floating_dtypes, _integer_dtypes, _integer_or_boolean_dtypes, _numeric_dtypes, _result_type, ) from ._array_object import Array import numpy as np _numeric_dtypes = ( float32, float64, int8, int16, int32, int64, uint8, uint16, uint32, uint64, ) class Array: """ n-d array object for the array API namespace. See the docstring of :py:obj:`np.ndarray <numpy.ndarray>` for more information. This is a wrapper around numpy.ndarray that restricts the usage to only those things that are required by the array API namespace. Note, attributes on this object that start with a single underscore are not part of the API specification and should only be used internally. This object should not be constructed directly. Rather, use one of the creation functions, such as asarray(). """ _array: np.ndarray # Use a custom constructor instead of __init__, as manually initializing # this class is not supported API. def _new(cls, x, /): """ This is a private method for initializing the array API Array object. Functions outside of the array_api submodule should not use this method. Use one of the creation functions instead, such as ``asarray``. """ obj = super().__new__(cls) # Note: The spec does not have array scalars, only 0-D arrays. if isinstance(x, np.generic): # Convert the array scalar to a 0-D array x = np.asarray(x) if x.dtype not in _all_dtypes: raise TypeError( f"The array_api namespace does not support the dtype '{x.dtype}'" ) obj._array = x return obj # Prevent Array() from working def __new__(cls, *args, **kwargs): raise TypeError( "The array_api Array object should not be instantiated directly. Use an array creation function, such as asarray(), instead." ) # These functions are not required by the spec, but are implemented for # the sake of usability. def __str__(self: Array, /) -> str: """ Performs the operation __str__. """ return self._array.__str__().replace("array", "Array") def __repr__(self: Array, /) -> str: """ Performs the operation __repr__. """ suffix = f", dtype={self.dtype.name})" if 0 in self.shape: prefix = "empty(" mid = str(self.shape) else: prefix = "Array(" mid = np.array2string(self._array, separator=', ', prefix=prefix, suffix=suffix) return prefix + mid + suffix # This function is not required by the spec, but we implement it here for # convenience so that np.asarray(np.array_api.Array) will work. def __array__(self, dtype: None | np.dtype[Any] = None) -> npt.NDArray[Any]: """ Warning: this method is NOT part of the array API spec. Implementers of other libraries need not include it, and users should not assume it will be present in other implementations. """ return np.asarray(self._array, dtype=dtype) # These are various helper functions to make the array behavior match the # spec in places where it either deviates from or is more strict than # NumPy behavior def _check_allowed_dtypes(self, other: bool | int | float | Array, dtype_category: str, op: str) -> Array: """ Helper function for operators to only allow specific input dtypes Use like other = self._check_allowed_dtypes(other, 'numeric', '__add__') if other is NotImplemented: return other """ if self.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") if isinstance(other, (int, float, bool)): other = self._promote_scalar(other) elif isinstance(other, Array): if other.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") else: return NotImplemented # This will raise TypeError for type combinations that are not allowed # to promote in the spec (even if the NumPy array operator would # promote them). res_dtype = _result_type(self.dtype, other.dtype) if op.startswith("__i"): # Note: NumPy will allow in-place operators in some cases where # the type promoted operator does not match the left-hand side # operand. For example, # >>> a = np.array(1, dtype=np.int8) # >>> a += np.array(1, dtype=np.int16) # The spec explicitly disallows this. if res_dtype != self.dtype: raise TypeError( f"Cannot perform {op} with dtypes {self.dtype} and {other.dtype}" ) return other # Helper function to match the type promotion rules in the spec def _promote_scalar(self, scalar): """ Returns a promoted version of a Python scalar appropriate for use with operations on self. This may raise an OverflowError in cases where the scalar is an integer that is too large to fit in a NumPy integer dtype, or TypeError when the scalar type is incompatible with the dtype of self. """ # Note: Only Python scalar types that match the array dtype are # allowed. if isinstance(scalar, bool): if self.dtype not in _boolean_dtypes: raise TypeError( "Python bool scalars can only be promoted with bool arrays" ) elif isinstance(scalar, int): if self.dtype in _boolean_dtypes: raise TypeError( "Python int scalars cannot be promoted with bool arrays" ) elif isinstance(scalar, float): if self.dtype not in _floating_dtypes: raise TypeError( "Python float scalars can only be promoted with floating-point arrays." ) else: raise TypeError("'scalar' must be a Python scalar") # Note: scalars are unconditionally cast to the same dtype as the # array. # Note: the spec only specifies integer-dtype/int promotion # behavior for integers within the bounds of the integer dtype. # Outside of those bounds we use the default NumPy behavior (either # cast or raise OverflowError). return Array._new(np.array(scalar, self.dtype)) def _normalize_two_args(x1, x2) -> Tuple[Array, Array]: """ Normalize inputs to two arg functions to fix type promotion rules NumPy deviates from the spec type promotion rules in cases where one argument is 0-dimensional and the other is not. For example: >>> import numpy as np >>> a = np.array([1.0], dtype=np.float32) >>> b = np.array(1.0, dtype=np.float64) >>> np.add(a, b) # The spec says this should be float64 array([2.], dtype=float32) To fix this, we add a dimension to the 0-dimension array before passing it through. This works because a dimension would be added anyway from broadcasting, so the resulting shape is the same, but this prevents NumPy from not promoting the dtype. """ # Another option would be to use signature=(x1.dtype, x2.dtype, None), # but that only works for ufuncs, so we would have to call the ufuncs # directly in the operator methods. One should also note that this # sort of trick wouldn't work for functions like searchsorted, which # don't do normal broadcasting, but there aren't any functions like # that in the array API namespace. if x1.ndim == 0 and x2.ndim != 0: # The _array[None] workaround was chosen because it is relatively # performant. broadcast_to(x1._array, x2.shape) is much slower. We # could also manually type promote x2, but that is more complicated # and about the same performance as this. x1 = Array._new(x1._array[None]) elif x2.ndim == 0 and x1.ndim != 0: x2 = Array._new(x2._array[None]) return (x1, x2) # Note: A large fraction of allowed indices are disallowed here (see the # docstring below) def _validate_index(self, key): """ Validate an index according to the array API. The array API specification only requires a subset of indices that are supported by NumPy. This function will reject any index that is allowed by NumPy but not required by the array API specification. We always raise ``IndexError`` on such indices (the spec does not require any specific behavior on them, but this makes the NumPy array API namespace a minimal implementation of the spec). See https://data-apis.org/array-api/latest/API_specification/indexing.html for the full list of required indexing behavior This function raises IndexError if the index ``key`` is invalid. It only raises ``IndexError`` on indices that are not already rejected by NumPy, as NumPy will already raise the appropriate error on such indices. ``shape`` may be None, in which case, only cases that are independent of the array shape are checked. The following cases are allowed by NumPy, but not specified by the array API specification: - Indices to not include an implicit ellipsis at the end. That is, every axis of an array must be explicitly indexed or an ellipsis included. This behaviour is sometimes referred to as flat indexing. - The start and stop of a slice may not be out of bounds. In particular, for a slice ``i:j:k`` on an axis of size ``n``, only the following are allowed: - ``i`` or ``j`` omitted (``None``). - ``-n <= i <= max(0, n - 1)``. - For ``k > 0`` or ``k`` omitted (``None``), ``-n <= j <= n``. - For ``k < 0``, ``-n - 1 <= j <= max(0, n - 1)``. - Boolean array indices are not allowed as part of a larger tuple index. - Integer array indices are not allowed (with the exception of 0-D arrays, which are treated the same as scalars). Additionally, it should be noted that indices that would return a scalar in NumPy will return a 0-D array. Array scalars are not allowed in the specification, only 0-D arrays. This is done in the ``Array._new`` constructor, not this function. """ _key = key if isinstance(key, tuple) else (key,) for i in _key: if isinstance(i, bool) or not ( isinstance(i, SupportsIndex) # i.e. ints or isinstance(i, slice) or i == Ellipsis or i is None or isinstance(i, Array) or isinstance(i, np.ndarray) ): raise IndexError( f"Single-axes index {i} has {type(i)=}, but only " "integers, slices (:), ellipsis (...), newaxis (None), " "zero-dimensional integer arrays and boolean arrays " "are specified in the Array API." ) nonexpanding_key = [] single_axes = [] n_ellipsis = 0 key_has_mask = False for i in _key: if i is not None: nonexpanding_key.append(i) if isinstance(i, Array) or isinstance(i, np.ndarray): if i.dtype in _boolean_dtypes: key_has_mask = True single_axes.append(i) else: # i must not be an array here, to avoid elementwise equals if i == Ellipsis: n_ellipsis += 1 else: single_axes.append(i) n_single_axes = len(single_axes) if n_ellipsis > 1: return # handled by ndarray elif n_ellipsis == 0: # Note boolean masks must be the sole index, which we check for # later on. if not key_has_mask and n_single_axes < self.ndim: raise IndexError( f"{self.ndim=}, but the multi-axes index only specifies " f"{n_single_axes} dimensions. If this was intentional, " "add a trailing ellipsis (...) which expands into as many " "slices (:) as necessary - this is what np.ndarray arrays " "implicitly do, but such flat indexing behaviour is not " "specified in the Array API." ) if n_ellipsis == 0: indexed_shape = self.shape else: ellipsis_start = None for pos, i in enumerate(nonexpanding_key): if not (isinstance(i, Array) or isinstance(i, np.ndarray)): if i == Ellipsis: ellipsis_start = pos break assert ellipsis_start is not None # sanity check ellipsis_end = self.ndim - (n_single_axes - ellipsis_start) indexed_shape = ( self.shape[:ellipsis_start] + self.shape[ellipsis_end:] ) for i, side in zip(single_axes, indexed_shape): if isinstance(i, slice): if side == 0: f_range = "0 (or None)" else: f_range = f"between -{side} and {side - 1} (or None)" if i.start is not None: try: start = operator.index(i.start) except TypeError: pass # handled by ndarray else: if not (-side <= start <= side): raise IndexError( f"Slice {i} contains {start=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds starts are not specified in " "the Array API)" ) if i.stop is not None: try: stop = operator.index(i.stop) except TypeError: pass # handled by ndarray else: if not (-side <= stop <= side): raise IndexError( f"Slice {i} contains {stop=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds stops are not specified in " "the Array API)" ) elif isinstance(i, Array): if i.dtype in _boolean_dtypes and len(_key) != 1: assert isinstance(key, tuple) # sanity check raise IndexError( f"Single-axes index {i} is a boolean array and " f"{len(key)=}, but masking is only specified in the " "Array API when the array is the sole index." ) elif i.dtype in _integer_dtypes and i.ndim != 0: raise IndexError( f"Single-axes index {i} is a non-zero-dimensional " "integer array, but advanced integer indexing is not " "specified in the Array API." ) elif isinstance(i, tuple): raise IndexError( f"Single-axes index {i} is a tuple, but nested tuple " "indices are not specified in the Array API." ) # Everything below this line is required by the spec. def __abs__(self: Array, /) -> Array: """ Performs the operation __abs__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __abs__") res = self._array.__abs__() return self.__class__._new(res) def __add__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __add__. """ other = self._check_allowed_dtypes(other, "numeric", "__add__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__add__(other._array) return self.__class__._new(res) def __and__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __and__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__and__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__and__(other._array) return self.__class__._new(res) def __array_namespace__( self: Array, /, *, api_version: Optional[str] = None ) -> types.ModuleType: if api_version is not None and not api_version.startswith("2021."): raise ValueError(f"Unrecognized array API version: {api_version!r}") return array_api def __bool__(self: Array, /) -> bool: """ Performs the operation __bool__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("bool is only allowed on arrays with 0 dimensions") if self.dtype not in _boolean_dtypes: raise ValueError("bool is only allowed on boolean arrays") res = self._array.__bool__() return res def __dlpack__(self: Array, /, *, stream: None = None) -> PyCapsule: """ Performs the operation __dlpack__. """ return self._array.__dlpack__(stream=stream) def __dlpack_device__(self: Array, /) -> Tuple[IntEnum, int]: """ Performs the operation __dlpack_device__. """ # Note: device support is required for this return self._array.__dlpack_device__() def __eq__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __eq__. """ # Even though "all" dtypes are allowed, we still require them to be # promotable with each other. other = self._check_allowed_dtypes(other, "all", "__eq__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__eq__(other._array) return self.__class__._new(res) def __float__(self: Array, /) -> float: """ Performs the operation __float__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("float is only allowed on arrays with 0 dimensions") if self.dtype not in _floating_dtypes: raise ValueError("float is only allowed on floating-point arrays") res = self._array.__float__() return res def __floordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __floordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__floordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__floordiv__(other._array) return self.__class__._new(res) def __ge__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ge__. """ other = self._check_allowed_dtypes(other, "numeric", "__ge__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ge__(other._array) return self.__class__._new(res) def __getitem__( self: Array, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], /, ) -> Array: """ Performs the operation __getitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array res = self._array.__getitem__(key) return self._new(res) def __gt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __gt__. """ other = self._check_allowed_dtypes(other, "numeric", "__gt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__gt__(other._array) return self.__class__._new(res) def __int__(self: Array, /) -> int: """ Performs the operation __int__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("int is only allowed on arrays with 0 dimensions") if self.dtype not in _integer_dtypes: raise ValueError("int is only allowed on integer arrays") res = self._array.__int__() return res def __index__(self: Array, /) -> int: """ Performs the operation __index__. """ res = self._array.__index__() return res def __invert__(self: Array, /) -> Array: """ Performs the operation __invert__. """ if self.dtype not in _integer_or_boolean_dtypes: raise TypeError("Only integer or boolean dtypes are allowed in __invert__") res = self._array.__invert__() return self.__class__._new(res) def __le__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __le__. """ other = self._check_allowed_dtypes(other, "numeric", "__le__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__le__(other._array) return self.__class__._new(res) def __lshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __lshift__. """ other = self._check_allowed_dtypes(other, "integer", "__lshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lshift__(other._array) return self.__class__._new(res) def __lt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __lt__. """ other = self._check_allowed_dtypes(other, "numeric", "__lt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lt__(other._array) return self.__class__._new(res) def __matmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __matmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__matmul__") if other is NotImplemented: return other res = self._array.__matmul__(other._array) return self.__class__._new(res) def __mod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mod__. """ other = self._check_allowed_dtypes(other, "numeric", "__mod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mod__(other._array) return self.__class__._new(res) def __mul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mul__. """ other = self._check_allowed_dtypes(other, "numeric", "__mul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mul__(other._array) return self.__class__._new(res) def __ne__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __ne__. """ other = self._check_allowed_dtypes(other, "all", "__ne__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ne__(other._array) return self.__class__._new(res) def __neg__(self: Array, /) -> Array: """ Performs the operation __neg__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __neg__") res = self._array.__neg__() return self.__class__._new(res) def __or__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __or__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__or__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__or__(other._array) return self.__class__._new(res) def __pos__(self: Array, /) -> Array: """ Performs the operation __pos__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __pos__") res = self._array.__pos__() return self.__class__._new(res) def __pow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __pow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__pow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow type promotion rules for 0-d # arrays, so we use pow() here instead. return pow(self, other) def __rshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rshift__(other._array) return self.__class__._new(res) def __setitem__( self, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], value: Union[int, float, bool, Array], /, ) -> None: """ Performs the operation __setitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array self._array.__setitem__(key, asarray(value)._array) def __sub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __sub__. """ other = self._check_allowed_dtypes(other, "numeric", "__sub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__sub__(other._array) return self.__class__._new(res) # PEP 484 requires int to be a subtype of float, but __truediv__ should # not accept int. def __truediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __truediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__truediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__truediv__(other._array) return self.__class__._new(res) def __xor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __xor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__xor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__xor__(other._array) return self.__class__._new(res) def __iadd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __iadd__. """ other = self._check_allowed_dtypes(other, "numeric", "__iadd__") if other is NotImplemented: return other self._array.__iadd__(other._array) return self def __radd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __radd__. """ other = self._check_allowed_dtypes(other, "numeric", "__radd__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__radd__(other._array) return self.__class__._new(res) def __iand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __iand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__iand__") if other is NotImplemented: return other self._array.__iand__(other._array) return self def __rand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rand__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rand__(other._array) return self.__class__._new(res) def __ifloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ifloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__ifloordiv__") if other is NotImplemented: return other self._array.__ifloordiv__(other._array) return self def __rfloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rfloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__rfloordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rfloordiv__(other._array) return self.__class__._new(res) def __ilshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __ilshift__. """ other = self._check_allowed_dtypes(other, "integer", "__ilshift__") if other is NotImplemented: return other self._array.__ilshift__(other._array) return self def __rlshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rlshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rlshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rlshift__(other._array) return self.__class__._new(res) def __imatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __imatmul__. """ # Note: NumPy does not implement __imatmul__. # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__imatmul__") if other is NotImplemented: return other # __imatmul__ can only be allowed when it would not change the shape # of self. other_shape = other.shape if self.shape == () or other_shape == (): raise ValueError("@= requires at least one dimension") if len(other_shape) == 1 or other_shape[-1] != other_shape[-2]: raise ValueError("@= cannot change the shape of the input array") self._array[:] = self._array.__matmul__(other._array) return self def __rmatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __rmatmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__rmatmul__") if other is NotImplemented: return other res = self._array.__rmatmul__(other._array) return self.__class__._new(res) def __imod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imod__. """ other = self._check_allowed_dtypes(other, "numeric", "__imod__") if other is NotImplemented: return other self._array.__imod__(other._array) return self def __rmod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmod__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmod__(other._array) return self.__class__._new(res) def __imul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imul__. """ other = self._check_allowed_dtypes(other, "numeric", "__imul__") if other is NotImplemented: return other self._array.__imul__(other._array) return self def __rmul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmul__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmul__(other._array) return self.__class__._new(res) def __ior__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ior__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ior__") if other is NotImplemented: return other self._array.__ior__(other._array) return self def __ror__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ror__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ror__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ror__(other._array) return self.__class__._new(res) def __ipow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ipow__. """ other = self._check_allowed_dtypes(other, "numeric", "__ipow__") if other is NotImplemented: return other self._array.__ipow__(other._array) return self def __rpow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rpow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__rpow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow the spec type promotion rules # for 0-d arrays, so we use pow() here instead. return pow(other, self) def __irshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __irshift__. """ other = self._check_allowed_dtypes(other, "integer", "__irshift__") if other is NotImplemented: return other self._array.__irshift__(other._array) return self def __rrshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rrshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rrshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rrshift__(other._array) return self.__class__._new(res) def __isub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __isub__. """ other = self._check_allowed_dtypes(other, "numeric", "__isub__") if other is NotImplemented: return other self._array.__isub__(other._array) return self def __rsub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rsub__. """ other = self._check_allowed_dtypes(other, "numeric", "__rsub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rsub__(other._array) return self.__class__._new(res) def __itruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __itruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__itruediv__") if other is NotImplemented: return other self._array.__itruediv__(other._array) return self def __rtruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __rtruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__rtruediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rtruediv__(other._array) return self.__class__._new(res) def __ixor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ixor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ixor__") if other is NotImplemented: return other self._array.__ixor__(other._array) return self def __rxor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rxor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rxor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rxor__(other._array) return self.__class__._new(res) def to_device(self: Array, device: Device, /, stream: None = None) -> Array: if stream is not None: raise ValueError("The stream argument to to_device() is not supported") if device == 'cpu': return self raise ValueError(f"Unsupported device {device!r}") def dtype(self) -> Dtype: """ Array API compatible wrapper for :py:meth:`np.ndarray.dtype <numpy.ndarray.dtype>`. See its docstring for more information. """ return self._array.dtype def device(self) -> Device: return "cpu" # Note: mT is new in array API spec (see matrix_transpose) def mT(self) -> Array: from .linalg import matrix_transpose return matrix_transpose(self) def ndim(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.ndim <numpy.ndarray.ndim>`. See its docstring for more information. """ return self._array.ndim def shape(self) -> Tuple[int, ...]: """ Array API compatible wrapper for :py:meth:`np.ndarray.shape <numpy.ndarray.shape>`. See its docstring for more information. """ return self._array.shape def size(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.size <numpy.ndarray.size>`. See its docstring for more information. """ return self._array.size def T(self) -> Array: """ Array API compatible wrapper for :py:meth:`np.ndarray.T <numpy.ndarray.T>`. See its docstring for more information. """ # Note: T only works on 2-dimensional arrays. See the corresponding # note in the specification: # https://data-apis.org/array-api/latest/API_specification/array_object.html#t if self.ndim != 2: raise ValueError("x.T requires x to have 2 dimensions. Use x.mT to transpose stacks of matrices and permute_dims() to permute dimensions.") return self.__class__._new(self._array.T) The provided code snippet includes necessary dependencies for implementing the `isfinite` function. Write a Python function `def isfinite(x: Array, /) -> Array` to solve the following problem: Array API compatible wrapper for :py:func:`np.isfinite <numpy.isfinite>`. See its docstring for more information. Here is the function: def isfinite(x: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.isfinite <numpy.isfinite>`. See its docstring for more information. """ if x.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in isfinite") return Array._new(np.isfinite(x._array))
Array API compatible wrapper for :py:func:`np.isfinite <numpy.isfinite>`. See its docstring for more information.
170,046
from __future__ import annotations from ._dtypes import ( _boolean_dtypes, _floating_dtypes, _integer_dtypes, _integer_or_boolean_dtypes, _numeric_dtypes, _result_type, ) from ._array_object import Array import numpy as np _numeric_dtypes = ( float32, float64, int8, int16, int32, int64, uint8, uint16, uint32, uint64, ) class Array: """ n-d array object for the array API namespace. See the docstring of :py:obj:`np.ndarray <numpy.ndarray>` for more information. This is a wrapper around numpy.ndarray that restricts the usage to only those things that are required by the array API namespace. Note, attributes on this object that start with a single underscore are not part of the API specification and should only be used internally. This object should not be constructed directly. Rather, use one of the creation functions, such as asarray(). """ _array: np.ndarray # Use a custom constructor instead of __init__, as manually initializing # this class is not supported API. def _new(cls, x, /): """ This is a private method for initializing the array API Array object. Functions outside of the array_api submodule should not use this method. Use one of the creation functions instead, such as ``asarray``. """ obj = super().__new__(cls) # Note: The spec does not have array scalars, only 0-D arrays. if isinstance(x, np.generic): # Convert the array scalar to a 0-D array x = np.asarray(x) if x.dtype not in _all_dtypes: raise TypeError( f"The array_api namespace does not support the dtype '{x.dtype}'" ) obj._array = x return obj # Prevent Array() from working def __new__(cls, *args, **kwargs): raise TypeError( "The array_api Array object should not be instantiated directly. Use an array creation function, such as asarray(), instead." ) # These functions are not required by the spec, but are implemented for # the sake of usability. def __str__(self: Array, /) -> str: """ Performs the operation __str__. """ return self._array.__str__().replace("array", "Array") def __repr__(self: Array, /) -> str: """ Performs the operation __repr__. """ suffix = f", dtype={self.dtype.name})" if 0 in self.shape: prefix = "empty(" mid = str(self.shape) else: prefix = "Array(" mid = np.array2string(self._array, separator=', ', prefix=prefix, suffix=suffix) return prefix + mid + suffix # This function is not required by the spec, but we implement it here for # convenience so that np.asarray(np.array_api.Array) will work. def __array__(self, dtype: None | np.dtype[Any] = None) -> npt.NDArray[Any]: """ Warning: this method is NOT part of the array API spec. Implementers of other libraries need not include it, and users should not assume it will be present in other implementations. """ return np.asarray(self._array, dtype=dtype) # These are various helper functions to make the array behavior match the # spec in places where it either deviates from or is more strict than # NumPy behavior def _check_allowed_dtypes(self, other: bool | int | float | Array, dtype_category: str, op: str) -> Array: """ Helper function for operators to only allow specific input dtypes Use like other = self._check_allowed_dtypes(other, 'numeric', '__add__') if other is NotImplemented: return other """ if self.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") if isinstance(other, (int, float, bool)): other = self._promote_scalar(other) elif isinstance(other, Array): if other.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") else: return NotImplemented # This will raise TypeError for type combinations that are not allowed # to promote in the spec (even if the NumPy array operator would # promote them). res_dtype = _result_type(self.dtype, other.dtype) if op.startswith("__i"): # Note: NumPy will allow in-place operators in some cases where # the type promoted operator does not match the left-hand side # operand. For example, # >>> a = np.array(1, dtype=np.int8) # >>> a += np.array(1, dtype=np.int16) # The spec explicitly disallows this. if res_dtype != self.dtype: raise TypeError( f"Cannot perform {op} with dtypes {self.dtype} and {other.dtype}" ) return other # Helper function to match the type promotion rules in the spec def _promote_scalar(self, scalar): """ Returns a promoted version of a Python scalar appropriate for use with operations on self. This may raise an OverflowError in cases where the scalar is an integer that is too large to fit in a NumPy integer dtype, or TypeError when the scalar type is incompatible with the dtype of self. """ # Note: Only Python scalar types that match the array dtype are # allowed. if isinstance(scalar, bool): if self.dtype not in _boolean_dtypes: raise TypeError( "Python bool scalars can only be promoted with bool arrays" ) elif isinstance(scalar, int): if self.dtype in _boolean_dtypes: raise TypeError( "Python int scalars cannot be promoted with bool arrays" ) elif isinstance(scalar, float): if self.dtype not in _floating_dtypes: raise TypeError( "Python float scalars can only be promoted with floating-point arrays." ) else: raise TypeError("'scalar' must be a Python scalar") # Note: scalars are unconditionally cast to the same dtype as the # array. # Note: the spec only specifies integer-dtype/int promotion # behavior for integers within the bounds of the integer dtype. # Outside of those bounds we use the default NumPy behavior (either # cast or raise OverflowError). return Array._new(np.array(scalar, self.dtype)) def _normalize_two_args(x1, x2) -> Tuple[Array, Array]: """ Normalize inputs to two arg functions to fix type promotion rules NumPy deviates from the spec type promotion rules in cases where one argument is 0-dimensional and the other is not. For example: >>> import numpy as np >>> a = np.array([1.0], dtype=np.float32) >>> b = np.array(1.0, dtype=np.float64) >>> np.add(a, b) # The spec says this should be float64 array([2.], dtype=float32) To fix this, we add a dimension to the 0-dimension array before passing it through. This works because a dimension would be added anyway from broadcasting, so the resulting shape is the same, but this prevents NumPy from not promoting the dtype. """ # Another option would be to use signature=(x1.dtype, x2.dtype, None), # but that only works for ufuncs, so we would have to call the ufuncs # directly in the operator methods. One should also note that this # sort of trick wouldn't work for functions like searchsorted, which # don't do normal broadcasting, but there aren't any functions like # that in the array API namespace. if x1.ndim == 0 and x2.ndim != 0: # The _array[None] workaround was chosen because it is relatively # performant. broadcast_to(x1._array, x2.shape) is much slower. We # could also manually type promote x2, but that is more complicated # and about the same performance as this. x1 = Array._new(x1._array[None]) elif x2.ndim == 0 and x1.ndim != 0: x2 = Array._new(x2._array[None]) return (x1, x2) # Note: A large fraction of allowed indices are disallowed here (see the # docstring below) def _validate_index(self, key): """ Validate an index according to the array API. The array API specification only requires a subset of indices that are supported by NumPy. This function will reject any index that is allowed by NumPy but not required by the array API specification. We always raise ``IndexError`` on such indices (the spec does not require any specific behavior on them, but this makes the NumPy array API namespace a minimal implementation of the spec). See https://data-apis.org/array-api/latest/API_specification/indexing.html for the full list of required indexing behavior This function raises IndexError if the index ``key`` is invalid. It only raises ``IndexError`` on indices that are not already rejected by NumPy, as NumPy will already raise the appropriate error on such indices. ``shape`` may be None, in which case, only cases that are independent of the array shape are checked. The following cases are allowed by NumPy, but not specified by the array API specification: - Indices to not include an implicit ellipsis at the end. That is, every axis of an array must be explicitly indexed or an ellipsis included. This behaviour is sometimes referred to as flat indexing. - The start and stop of a slice may not be out of bounds. In particular, for a slice ``i:j:k`` on an axis of size ``n``, only the following are allowed: - ``i`` or ``j`` omitted (``None``). - ``-n <= i <= max(0, n - 1)``. - For ``k > 0`` or ``k`` omitted (``None``), ``-n <= j <= n``. - For ``k < 0``, ``-n - 1 <= j <= max(0, n - 1)``. - Boolean array indices are not allowed as part of a larger tuple index. - Integer array indices are not allowed (with the exception of 0-D arrays, which are treated the same as scalars). Additionally, it should be noted that indices that would return a scalar in NumPy will return a 0-D array. Array scalars are not allowed in the specification, only 0-D arrays. This is done in the ``Array._new`` constructor, not this function. """ _key = key if isinstance(key, tuple) else (key,) for i in _key: if isinstance(i, bool) or not ( isinstance(i, SupportsIndex) # i.e. ints or isinstance(i, slice) or i == Ellipsis or i is None or isinstance(i, Array) or isinstance(i, np.ndarray) ): raise IndexError( f"Single-axes index {i} has {type(i)=}, but only " "integers, slices (:), ellipsis (...), newaxis (None), " "zero-dimensional integer arrays and boolean arrays " "are specified in the Array API." ) nonexpanding_key = [] single_axes = [] n_ellipsis = 0 key_has_mask = False for i in _key: if i is not None: nonexpanding_key.append(i) if isinstance(i, Array) or isinstance(i, np.ndarray): if i.dtype in _boolean_dtypes: key_has_mask = True single_axes.append(i) else: # i must not be an array here, to avoid elementwise equals if i == Ellipsis: n_ellipsis += 1 else: single_axes.append(i) n_single_axes = len(single_axes) if n_ellipsis > 1: return # handled by ndarray elif n_ellipsis == 0: # Note boolean masks must be the sole index, which we check for # later on. if not key_has_mask and n_single_axes < self.ndim: raise IndexError( f"{self.ndim=}, but the multi-axes index only specifies " f"{n_single_axes} dimensions. If this was intentional, " "add a trailing ellipsis (...) which expands into as many " "slices (:) as necessary - this is what np.ndarray arrays " "implicitly do, but such flat indexing behaviour is not " "specified in the Array API." ) if n_ellipsis == 0: indexed_shape = self.shape else: ellipsis_start = None for pos, i in enumerate(nonexpanding_key): if not (isinstance(i, Array) or isinstance(i, np.ndarray)): if i == Ellipsis: ellipsis_start = pos break assert ellipsis_start is not None # sanity check ellipsis_end = self.ndim - (n_single_axes - ellipsis_start) indexed_shape = ( self.shape[:ellipsis_start] + self.shape[ellipsis_end:] ) for i, side in zip(single_axes, indexed_shape): if isinstance(i, slice): if side == 0: f_range = "0 (or None)" else: f_range = f"between -{side} and {side - 1} (or None)" if i.start is not None: try: start = operator.index(i.start) except TypeError: pass # handled by ndarray else: if not (-side <= start <= side): raise IndexError( f"Slice {i} contains {start=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds starts are not specified in " "the Array API)" ) if i.stop is not None: try: stop = operator.index(i.stop) except TypeError: pass # handled by ndarray else: if not (-side <= stop <= side): raise IndexError( f"Slice {i} contains {stop=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds stops are not specified in " "the Array API)" ) elif isinstance(i, Array): if i.dtype in _boolean_dtypes and len(_key) != 1: assert isinstance(key, tuple) # sanity check raise IndexError( f"Single-axes index {i} is a boolean array and " f"{len(key)=}, but masking is only specified in the " "Array API when the array is the sole index." ) elif i.dtype in _integer_dtypes and i.ndim != 0: raise IndexError( f"Single-axes index {i} is a non-zero-dimensional " "integer array, but advanced integer indexing is not " "specified in the Array API." ) elif isinstance(i, tuple): raise IndexError( f"Single-axes index {i} is a tuple, but nested tuple " "indices are not specified in the Array API." ) # Everything below this line is required by the spec. def __abs__(self: Array, /) -> Array: """ Performs the operation __abs__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __abs__") res = self._array.__abs__() return self.__class__._new(res) def __add__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __add__. """ other = self._check_allowed_dtypes(other, "numeric", "__add__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__add__(other._array) return self.__class__._new(res) def __and__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __and__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__and__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__and__(other._array) return self.__class__._new(res) def __array_namespace__( self: Array, /, *, api_version: Optional[str] = None ) -> types.ModuleType: if api_version is not None and not api_version.startswith("2021."): raise ValueError(f"Unrecognized array API version: {api_version!r}") return array_api def __bool__(self: Array, /) -> bool: """ Performs the operation __bool__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("bool is only allowed on arrays with 0 dimensions") if self.dtype not in _boolean_dtypes: raise ValueError("bool is only allowed on boolean arrays") res = self._array.__bool__() return res def __dlpack__(self: Array, /, *, stream: None = None) -> PyCapsule: """ Performs the operation __dlpack__. """ return self._array.__dlpack__(stream=stream) def __dlpack_device__(self: Array, /) -> Tuple[IntEnum, int]: """ Performs the operation __dlpack_device__. """ # Note: device support is required for this return self._array.__dlpack_device__() def __eq__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __eq__. """ # Even though "all" dtypes are allowed, we still require them to be # promotable with each other. other = self._check_allowed_dtypes(other, "all", "__eq__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__eq__(other._array) return self.__class__._new(res) def __float__(self: Array, /) -> float: """ Performs the operation __float__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("float is only allowed on arrays with 0 dimensions") if self.dtype not in _floating_dtypes: raise ValueError("float is only allowed on floating-point arrays") res = self._array.__float__() return res def __floordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __floordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__floordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__floordiv__(other._array) return self.__class__._new(res) def __ge__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ge__. """ other = self._check_allowed_dtypes(other, "numeric", "__ge__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ge__(other._array) return self.__class__._new(res) def __getitem__( self: Array, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], /, ) -> Array: """ Performs the operation __getitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array res = self._array.__getitem__(key) return self._new(res) def __gt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __gt__. """ other = self._check_allowed_dtypes(other, "numeric", "__gt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__gt__(other._array) return self.__class__._new(res) def __int__(self: Array, /) -> int: """ Performs the operation __int__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("int is only allowed on arrays with 0 dimensions") if self.dtype not in _integer_dtypes: raise ValueError("int is only allowed on integer arrays") res = self._array.__int__() return res def __index__(self: Array, /) -> int: """ Performs the operation __index__. """ res = self._array.__index__() return res def __invert__(self: Array, /) -> Array: """ Performs the operation __invert__. """ if self.dtype not in _integer_or_boolean_dtypes: raise TypeError("Only integer or boolean dtypes are allowed in __invert__") res = self._array.__invert__() return self.__class__._new(res) def __le__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __le__. """ other = self._check_allowed_dtypes(other, "numeric", "__le__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__le__(other._array) return self.__class__._new(res) def __lshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __lshift__. """ other = self._check_allowed_dtypes(other, "integer", "__lshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lshift__(other._array) return self.__class__._new(res) def __lt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __lt__. """ other = self._check_allowed_dtypes(other, "numeric", "__lt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lt__(other._array) return self.__class__._new(res) def __matmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __matmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__matmul__") if other is NotImplemented: return other res = self._array.__matmul__(other._array) return self.__class__._new(res) def __mod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mod__. """ other = self._check_allowed_dtypes(other, "numeric", "__mod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mod__(other._array) return self.__class__._new(res) def __mul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mul__. """ other = self._check_allowed_dtypes(other, "numeric", "__mul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mul__(other._array) return self.__class__._new(res) def __ne__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __ne__. """ other = self._check_allowed_dtypes(other, "all", "__ne__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ne__(other._array) return self.__class__._new(res) def __neg__(self: Array, /) -> Array: """ Performs the operation __neg__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __neg__") res = self._array.__neg__() return self.__class__._new(res) def __or__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __or__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__or__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__or__(other._array) return self.__class__._new(res) def __pos__(self: Array, /) -> Array: """ Performs the operation __pos__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __pos__") res = self._array.__pos__() return self.__class__._new(res) def __pow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __pow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__pow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow type promotion rules for 0-d # arrays, so we use pow() here instead. return pow(self, other) def __rshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rshift__(other._array) return self.__class__._new(res) def __setitem__( self, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], value: Union[int, float, bool, Array], /, ) -> None: """ Performs the operation __setitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array self._array.__setitem__(key, asarray(value)._array) def __sub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __sub__. """ other = self._check_allowed_dtypes(other, "numeric", "__sub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__sub__(other._array) return self.__class__._new(res) # PEP 484 requires int to be a subtype of float, but __truediv__ should # not accept int. def __truediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __truediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__truediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__truediv__(other._array) return self.__class__._new(res) def __xor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __xor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__xor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__xor__(other._array) return self.__class__._new(res) def __iadd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __iadd__. """ other = self._check_allowed_dtypes(other, "numeric", "__iadd__") if other is NotImplemented: return other self._array.__iadd__(other._array) return self def __radd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __radd__. """ other = self._check_allowed_dtypes(other, "numeric", "__radd__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__radd__(other._array) return self.__class__._new(res) def __iand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __iand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__iand__") if other is NotImplemented: return other self._array.__iand__(other._array) return self def __rand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rand__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rand__(other._array) return self.__class__._new(res) def __ifloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ifloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__ifloordiv__") if other is NotImplemented: return other self._array.__ifloordiv__(other._array) return self def __rfloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rfloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__rfloordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rfloordiv__(other._array) return self.__class__._new(res) def __ilshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __ilshift__. """ other = self._check_allowed_dtypes(other, "integer", "__ilshift__") if other is NotImplemented: return other self._array.__ilshift__(other._array) return self def __rlshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rlshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rlshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rlshift__(other._array) return self.__class__._new(res) def __imatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __imatmul__. """ # Note: NumPy does not implement __imatmul__. # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__imatmul__") if other is NotImplemented: return other # __imatmul__ can only be allowed when it would not change the shape # of self. other_shape = other.shape if self.shape == () or other_shape == (): raise ValueError("@= requires at least one dimension") if len(other_shape) == 1 or other_shape[-1] != other_shape[-2]: raise ValueError("@= cannot change the shape of the input array") self._array[:] = self._array.__matmul__(other._array) return self def __rmatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __rmatmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__rmatmul__") if other is NotImplemented: return other res = self._array.__rmatmul__(other._array) return self.__class__._new(res) def __imod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imod__. """ other = self._check_allowed_dtypes(other, "numeric", "__imod__") if other is NotImplemented: return other self._array.__imod__(other._array) return self def __rmod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmod__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmod__(other._array) return self.__class__._new(res) def __imul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imul__. """ other = self._check_allowed_dtypes(other, "numeric", "__imul__") if other is NotImplemented: return other self._array.__imul__(other._array) return self def __rmul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmul__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmul__(other._array) return self.__class__._new(res) def __ior__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ior__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ior__") if other is NotImplemented: return other self._array.__ior__(other._array) return self def __ror__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ror__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ror__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ror__(other._array) return self.__class__._new(res) def __ipow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ipow__. """ other = self._check_allowed_dtypes(other, "numeric", "__ipow__") if other is NotImplemented: return other self._array.__ipow__(other._array) return self def __rpow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rpow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__rpow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow the spec type promotion rules # for 0-d arrays, so we use pow() here instead. return pow(other, self) def __irshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __irshift__. """ other = self._check_allowed_dtypes(other, "integer", "__irshift__") if other is NotImplemented: return other self._array.__irshift__(other._array) return self def __rrshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rrshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rrshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rrshift__(other._array) return self.__class__._new(res) def __isub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __isub__. """ other = self._check_allowed_dtypes(other, "numeric", "__isub__") if other is NotImplemented: return other self._array.__isub__(other._array) return self def __rsub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rsub__. """ other = self._check_allowed_dtypes(other, "numeric", "__rsub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rsub__(other._array) return self.__class__._new(res) def __itruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __itruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__itruediv__") if other is NotImplemented: return other self._array.__itruediv__(other._array) return self def __rtruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __rtruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__rtruediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rtruediv__(other._array) return self.__class__._new(res) def __ixor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ixor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ixor__") if other is NotImplemented: return other self._array.__ixor__(other._array) return self def __rxor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rxor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rxor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rxor__(other._array) return self.__class__._new(res) def to_device(self: Array, device: Device, /, stream: None = None) -> Array: if stream is not None: raise ValueError("The stream argument to to_device() is not supported") if device == 'cpu': return self raise ValueError(f"Unsupported device {device!r}") def dtype(self) -> Dtype: """ Array API compatible wrapper for :py:meth:`np.ndarray.dtype <numpy.ndarray.dtype>`. See its docstring for more information. """ return self._array.dtype def device(self) -> Device: return "cpu" # Note: mT is new in array API spec (see matrix_transpose) def mT(self) -> Array: from .linalg import matrix_transpose return matrix_transpose(self) def ndim(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.ndim <numpy.ndarray.ndim>`. See its docstring for more information. """ return self._array.ndim def shape(self) -> Tuple[int, ...]: """ Array API compatible wrapper for :py:meth:`np.ndarray.shape <numpy.ndarray.shape>`. See its docstring for more information. """ return self._array.shape def size(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.size <numpy.ndarray.size>`. See its docstring for more information. """ return self._array.size def T(self) -> Array: """ Array API compatible wrapper for :py:meth:`np.ndarray.T <numpy.ndarray.T>`. See its docstring for more information. """ # Note: T only works on 2-dimensional arrays. See the corresponding # note in the specification: # https://data-apis.org/array-api/latest/API_specification/array_object.html#t if self.ndim != 2: raise ValueError("x.T requires x to have 2 dimensions. Use x.mT to transpose stacks of matrices and permute_dims() to permute dimensions.") return self.__class__._new(self._array.T) The provided code snippet includes necessary dependencies for implementing the `isinf` function. Write a Python function `def isinf(x: Array, /) -> Array` to solve the following problem: Array API compatible wrapper for :py:func:`np.isinf <numpy.isinf>`. See its docstring for more information. Here is the function: def isinf(x: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.isinf <numpy.isinf>`. See its docstring for more information. """ if x.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in isinf") return Array._new(np.isinf(x._array))
Array API compatible wrapper for :py:func:`np.isinf <numpy.isinf>`. See its docstring for more information.
170,047
from __future__ import annotations from ._dtypes import ( _boolean_dtypes, _floating_dtypes, _integer_dtypes, _integer_or_boolean_dtypes, _numeric_dtypes, _result_type, ) from ._array_object import Array import numpy as np _numeric_dtypes = ( float32, float64, int8, int16, int32, int64, uint8, uint16, uint32, uint64, ) class Array: """ n-d array object for the array API namespace. See the docstring of :py:obj:`np.ndarray <numpy.ndarray>` for more information. This is a wrapper around numpy.ndarray that restricts the usage to only those things that are required by the array API namespace. Note, attributes on this object that start with a single underscore are not part of the API specification and should only be used internally. This object should not be constructed directly. Rather, use one of the creation functions, such as asarray(). """ _array: np.ndarray # Use a custom constructor instead of __init__, as manually initializing # this class is not supported API. def _new(cls, x, /): """ This is a private method for initializing the array API Array object. Functions outside of the array_api submodule should not use this method. Use one of the creation functions instead, such as ``asarray``. """ obj = super().__new__(cls) # Note: The spec does not have array scalars, only 0-D arrays. if isinstance(x, np.generic): # Convert the array scalar to a 0-D array x = np.asarray(x) if x.dtype not in _all_dtypes: raise TypeError( f"The array_api namespace does not support the dtype '{x.dtype}'" ) obj._array = x return obj # Prevent Array() from working def __new__(cls, *args, **kwargs): raise TypeError( "The array_api Array object should not be instantiated directly. Use an array creation function, such as asarray(), instead." ) # These functions are not required by the spec, but are implemented for # the sake of usability. def __str__(self: Array, /) -> str: """ Performs the operation __str__. """ return self._array.__str__().replace("array", "Array") def __repr__(self: Array, /) -> str: """ Performs the operation __repr__. """ suffix = f", dtype={self.dtype.name})" if 0 in self.shape: prefix = "empty(" mid = str(self.shape) else: prefix = "Array(" mid = np.array2string(self._array, separator=', ', prefix=prefix, suffix=suffix) return prefix + mid + suffix # This function is not required by the spec, but we implement it here for # convenience so that np.asarray(np.array_api.Array) will work. def __array__(self, dtype: None | np.dtype[Any] = None) -> npt.NDArray[Any]: """ Warning: this method is NOT part of the array API spec. Implementers of other libraries need not include it, and users should not assume it will be present in other implementations. """ return np.asarray(self._array, dtype=dtype) # These are various helper functions to make the array behavior match the # spec in places where it either deviates from or is more strict than # NumPy behavior def _check_allowed_dtypes(self, other: bool | int | float | Array, dtype_category: str, op: str) -> Array: """ Helper function for operators to only allow specific input dtypes Use like other = self._check_allowed_dtypes(other, 'numeric', '__add__') if other is NotImplemented: return other """ if self.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") if isinstance(other, (int, float, bool)): other = self._promote_scalar(other) elif isinstance(other, Array): if other.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") else: return NotImplemented # This will raise TypeError for type combinations that are not allowed # to promote in the spec (even if the NumPy array operator would # promote them). res_dtype = _result_type(self.dtype, other.dtype) if op.startswith("__i"): # Note: NumPy will allow in-place operators in some cases where # the type promoted operator does not match the left-hand side # operand. For example, # >>> a = np.array(1, dtype=np.int8) # >>> a += np.array(1, dtype=np.int16) # The spec explicitly disallows this. if res_dtype != self.dtype: raise TypeError( f"Cannot perform {op} with dtypes {self.dtype} and {other.dtype}" ) return other # Helper function to match the type promotion rules in the spec def _promote_scalar(self, scalar): """ Returns a promoted version of a Python scalar appropriate for use with operations on self. This may raise an OverflowError in cases where the scalar is an integer that is too large to fit in a NumPy integer dtype, or TypeError when the scalar type is incompatible with the dtype of self. """ # Note: Only Python scalar types that match the array dtype are # allowed. if isinstance(scalar, bool): if self.dtype not in _boolean_dtypes: raise TypeError( "Python bool scalars can only be promoted with bool arrays" ) elif isinstance(scalar, int): if self.dtype in _boolean_dtypes: raise TypeError( "Python int scalars cannot be promoted with bool arrays" ) elif isinstance(scalar, float): if self.dtype not in _floating_dtypes: raise TypeError( "Python float scalars can only be promoted with floating-point arrays." ) else: raise TypeError("'scalar' must be a Python scalar") # Note: scalars are unconditionally cast to the same dtype as the # array. # Note: the spec only specifies integer-dtype/int promotion # behavior for integers within the bounds of the integer dtype. # Outside of those bounds we use the default NumPy behavior (either # cast or raise OverflowError). return Array._new(np.array(scalar, self.dtype)) def _normalize_two_args(x1, x2) -> Tuple[Array, Array]: """ Normalize inputs to two arg functions to fix type promotion rules NumPy deviates from the spec type promotion rules in cases where one argument is 0-dimensional and the other is not. For example: >>> import numpy as np >>> a = np.array([1.0], dtype=np.float32) >>> b = np.array(1.0, dtype=np.float64) >>> np.add(a, b) # The spec says this should be float64 array([2.], dtype=float32) To fix this, we add a dimension to the 0-dimension array before passing it through. This works because a dimension would be added anyway from broadcasting, so the resulting shape is the same, but this prevents NumPy from not promoting the dtype. """ # Another option would be to use signature=(x1.dtype, x2.dtype, None), # but that only works for ufuncs, so we would have to call the ufuncs # directly in the operator methods. One should also note that this # sort of trick wouldn't work for functions like searchsorted, which # don't do normal broadcasting, but there aren't any functions like # that in the array API namespace. if x1.ndim == 0 and x2.ndim != 0: # The _array[None] workaround was chosen because it is relatively # performant. broadcast_to(x1._array, x2.shape) is much slower. We # could also manually type promote x2, but that is more complicated # and about the same performance as this. x1 = Array._new(x1._array[None]) elif x2.ndim == 0 and x1.ndim != 0: x2 = Array._new(x2._array[None]) return (x1, x2) # Note: A large fraction of allowed indices are disallowed here (see the # docstring below) def _validate_index(self, key): """ Validate an index according to the array API. The array API specification only requires a subset of indices that are supported by NumPy. This function will reject any index that is allowed by NumPy but not required by the array API specification. We always raise ``IndexError`` on such indices (the spec does not require any specific behavior on them, but this makes the NumPy array API namespace a minimal implementation of the spec). See https://data-apis.org/array-api/latest/API_specification/indexing.html for the full list of required indexing behavior This function raises IndexError if the index ``key`` is invalid. It only raises ``IndexError`` on indices that are not already rejected by NumPy, as NumPy will already raise the appropriate error on such indices. ``shape`` may be None, in which case, only cases that are independent of the array shape are checked. The following cases are allowed by NumPy, but not specified by the array API specification: - Indices to not include an implicit ellipsis at the end. That is, every axis of an array must be explicitly indexed or an ellipsis included. This behaviour is sometimes referred to as flat indexing. - The start and stop of a slice may not be out of bounds. In particular, for a slice ``i:j:k`` on an axis of size ``n``, only the following are allowed: - ``i`` or ``j`` omitted (``None``). - ``-n <= i <= max(0, n - 1)``. - For ``k > 0`` or ``k`` omitted (``None``), ``-n <= j <= n``. - For ``k < 0``, ``-n - 1 <= j <= max(0, n - 1)``. - Boolean array indices are not allowed as part of a larger tuple index. - Integer array indices are not allowed (with the exception of 0-D arrays, which are treated the same as scalars). Additionally, it should be noted that indices that would return a scalar in NumPy will return a 0-D array. Array scalars are not allowed in the specification, only 0-D arrays. This is done in the ``Array._new`` constructor, not this function. """ _key = key if isinstance(key, tuple) else (key,) for i in _key: if isinstance(i, bool) or not ( isinstance(i, SupportsIndex) # i.e. ints or isinstance(i, slice) or i == Ellipsis or i is None or isinstance(i, Array) or isinstance(i, np.ndarray) ): raise IndexError( f"Single-axes index {i} has {type(i)=}, but only " "integers, slices (:), ellipsis (...), newaxis (None), " "zero-dimensional integer arrays and boolean arrays " "are specified in the Array API." ) nonexpanding_key = [] single_axes = [] n_ellipsis = 0 key_has_mask = False for i in _key: if i is not None: nonexpanding_key.append(i) if isinstance(i, Array) or isinstance(i, np.ndarray): if i.dtype in _boolean_dtypes: key_has_mask = True single_axes.append(i) else: # i must not be an array here, to avoid elementwise equals if i == Ellipsis: n_ellipsis += 1 else: single_axes.append(i) n_single_axes = len(single_axes) if n_ellipsis > 1: return # handled by ndarray elif n_ellipsis == 0: # Note boolean masks must be the sole index, which we check for # later on. if not key_has_mask and n_single_axes < self.ndim: raise IndexError( f"{self.ndim=}, but the multi-axes index only specifies " f"{n_single_axes} dimensions. If this was intentional, " "add a trailing ellipsis (...) which expands into as many " "slices (:) as necessary - this is what np.ndarray arrays " "implicitly do, but such flat indexing behaviour is not " "specified in the Array API." ) if n_ellipsis == 0: indexed_shape = self.shape else: ellipsis_start = None for pos, i in enumerate(nonexpanding_key): if not (isinstance(i, Array) or isinstance(i, np.ndarray)): if i == Ellipsis: ellipsis_start = pos break assert ellipsis_start is not None # sanity check ellipsis_end = self.ndim - (n_single_axes - ellipsis_start) indexed_shape = ( self.shape[:ellipsis_start] + self.shape[ellipsis_end:] ) for i, side in zip(single_axes, indexed_shape): if isinstance(i, slice): if side == 0: f_range = "0 (or None)" else: f_range = f"between -{side} and {side - 1} (or None)" if i.start is not None: try: start = operator.index(i.start) except TypeError: pass # handled by ndarray else: if not (-side <= start <= side): raise IndexError( f"Slice {i} contains {start=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds starts are not specified in " "the Array API)" ) if i.stop is not None: try: stop = operator.index(i.stop) except TypeError: pass # handled by ndarray else: if not (-side <= stop <= side): raise IndexError( f"Slice {i} contains {stop=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds stops are not specified in " "the Array API)" ) elif isinstance(i, Array): if i.dtype in _boolean_dtypes and len(_key) != 1: assert isinstance(key, tuple) # sanity check raise IndexError( f"Single-axes index {i} is a boolean array and " f"{len(key)=}, but masking is only specified in the " "Array API when the array is the sole index." ) elif i.dtype in _integer_dtypes and i.ndim != 0: raise IndexError( f"Single-axes index {i} is a non-zero-dimensional " "integer array, but advanced integer indexing is not " "specified in the Array API." ) elif isinstance(i, tuple): raise IndexError( f"Single-axes index {i} is a tuple, but nested tuple " "indices are not specified in the Array API." ) # Everything below this line is required by the spec. def __abs__(self: Array, /) -> Array: """ Performs the operation __abs__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __abs__") res = self._array.__abs__() return self.__class__._new(res) def __add__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __add__. """ other = self._check_allowed_dtypes(other, "numeric", "__add__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__add__(other._array) return self.__class__._new(res) def __and__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __and__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__and__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__and__(other._array) return self.__class__._new(res) def __array_namespace__( self: Array, /, *, api_version: Optional[str] = None ) -> types.ModuleType: if api_version is not None and not api_version.startswith("2021."): raise ValueError(f"Unrecognized array API version: {api_version!r}") return array_api def __bool__(self: Array, /) -> bool: """ Performs the operation __bool__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("bool is only allowed on arrays with 0 dimensions") if self.dtype not in _boolean_dtypes: raise ValueError("bool is only allowed on boolean arrays") res = self._array.__bool__() return res def __dlpack__(self: Array, /, *, stream: None = None) -> PyCapsule: """ Performs the operation __dlpack__. """ return self._array.__dlpack__(stream=stream) def __dlpack_device__(self: Array, /) -> Tuple[IntEnum, int]: """ Performs the operation __dlpack_device__. """ # Note: device support is required for this return self._array.__dlpack_device__() def __eq__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __eq__. """ # Even though "all" dtypes are allowed, we still require them to be # promotable with each other. other = self._check_allowed_dtypes(other, "all", "__eq__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__eq__(other._array) return self.__class__._new(res) def __float__(self: Array, /) -> float: """ Performs the operation __float__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("float is only allowed on arrays with 0 dimensions") if self.dtype not in _floating_dtypes: raise ValueError("float is only allowed on floating-point arrays") res = self._array.__float__() return res def __floordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __floordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__floordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__floordiv__(other._array) return self.__class__._new(res) def __ge__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ge__. """ other = self._check_allowed_dtypes(other, "numeric", "__ge__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ge__(other._array) return self.__class__._new(res) def __getitem__( self: Array, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], /, ) -> Array: """ Performs the operation __getitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array res = self._array.__getitem__(key) return self._new(res) def __gt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __gt__. """ other = self._check_allowed_dtypes(other, "numeric", "__gt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__gt__(other._array) return self.__class__._new(res) def __int__(self: Array, /) -> int: """ Performs the operation __int__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("int is only allowed on arrays with 0 dimensions") if self.dtype not in _integer_dtypes: raise ValueError("int is only allowed on integer arrays") res = self._array.__int__() return res def __index__(self: Array, /) -> int: """ Performs the operation __index__. """ res = self._array.__index__() return res def __invert__(self: Array, /) -> Array: """ Performs the operation __invert__. """ if self.dtype not in _integer_or_boolean_dtypes: raise TypeError("Only integer or boolean dtypes are allowed in __invert__") res = self._array.__invert__() return self.__class__._new(res) def __le__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __le__. """ other = self._check_allowed_dtypes(other, "numeric", "__le__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__le__(other._array) return self.__class__._new(res) def __lshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __lshift__. """ other = self._check_allowed_dtypes(other, "integer", "__lshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lshift__(other._array) return self.__class__._new(res) def __lt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __lt__. """ other = self._check_allowed_dtypes(other, "numeric", "__lt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lt__(other._array) return self.__class__._new(res) def __matmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __matmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__matmul__") if other is NotImplemented: return other res = self._array.__matmul__(other._array) return self.__class__._new(res) def __mod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mod__. """ other = self._check_allowed_dtypes(other, "numeric", "__mod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mod__(other._array) return self.__class__._new(res) def __mul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mul__. """ other = self._check_allowed_dtypes(other, "numeric", "__mul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mul__(other._array) return self.__class__._new(res) def __ne__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __ne__. """ other = self._check_allowed_dtypes(other, "all", "__ne__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ne__(other._array) return self.__class__._new(res) def __neg__(self: Array, /) -> Array: """ Performs the operation __neg__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __neg__") res = self._array.__neg__() return self.__class__._new(res) def __or__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __or__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__or__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__or__(other._array) return self.__class__._new(res) def __pos__(self: Array, /) -> Array: """ Performs the operation __pos__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __pos__") res = self._array.__pos__() return self.__class__._new(res) def __pow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __pow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__pow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow type promotion rules for 0-d # arrays, so we use pow() here instead. return pow(self, other) def __rshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rshift__(other._array) return self.__class__._new(res) def __setitem__( self, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], value: Union[int, float, bool, Array], /, ) -> None: """ Performs the operation __setitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array self._array.__setitem__(key, asarray(value)._array) def __sub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __sub__. """ other = self._check_allowed_dtypes(other, "numeric", "__sub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__sub__(other._array) return self.__class__._new(res) # PEP 484 requires int to be a subtype of float, but __truediv__ should # not accept int. def __truediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __truediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__truediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__truediv__(other._array) return self.__class__._new(res) def __xor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __xor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__xor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__xor__(other._array) return self.__class__._new(res) def __iadd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __iadd__. """ other = self._check_allowed_dtypes(other, "numeric", "__iadd__") if other is NotImplemented: return other self._array.__iadd__(other._array) return self def __radd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __radd__. """ other = self._check_allowed_dtypes(other, "numeric", "__radd__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__radd__(other._array) return self.__class__._new(res) def __iand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __iand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__iand__") if other is NotImplemented: return other self._array.__iand__(other._array) return self def __rand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rand__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rand__(other._array) return self.__class__._new(res) def __ifloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ifloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__ifloordiv__") if other is NotImplemented: return other self._array.__ifloordiv__(other._array) return self def __rfloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rfloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__rfloordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rfloordiv__(other._array) return self.__class__._new(res) def __ilshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __ilshift__. """ other = self._check_allowed_dtypes(other, "integer", "__ilshift__") if other is NotImplemented: return other self._array.__ilshift__(other._array) return self def __rlshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rlshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rlshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rlshift__(other._array) return self.__class__._new(res) def __imatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __imatmul__. """ # Note: NumPy does not implement __imatmul__. # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__imatmul__") if other is NotImplemented: return other # __imatmul__ can only be allowed when it would not change the shape # of self. other_shape = other.shape if self.shape == () or other_shape == (): raise ValueError("@= requires at least one dimension") if len(other_shape) == 1 or other_shape[-1] != other_shape[-2]: raise ValueError("@= cannot change the shape of the input array") self._array[:] = self._array.__matmul__(other._array) return self def __rmatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __rmatmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__rmatmul__") if other is NotImplemented: return other res = self._array.__rmatmul__(other._array) return self.__class__._new(res) def __imod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imod__. """ other = self._check_allowed_dtypes(other, "numeric", "__imod__") if other is NotImplemented: return other self._array.__imod__(other._array) return self def __rmod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmod__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmod__(other._array) return self.__class__._new(res) def __imul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imul__. """ other = self._check_allowed_dtypes(other, "numeric", "__imul__") if other is NotImplemented: return other self._array.__imul__(other._array) return self def __rmul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmul__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmul__(other._array) return self.__class__._new(res) def __ior__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ior__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ior__") if other is NotImplemented: return other self._array.__ior__(other._array) return self def __ror__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ror__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ror__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ror__(other._array) return self.__class__._new(res) def __ipow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ipow__. """ other = self._check_allowed_dtypes(other, "numeric", "__ipow__") if other is NotImplemented: return other self._array.__ipow__(other._array) return self def __rpow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rpow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__rpow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow the spec type promotion rules # for 0-d arrays, so we use pow() here instead. return pow(other, self) def __irshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __irshift__. """ other = self._check_allowed_dtypes(other, "integer", "__irshift__") if other is NotImplemented: return other self._array.__irshift__(other._array) return self def __rrshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rrshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rrshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rrshift__(other._array) return self.__class__._new(res) def __isub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __isub__. """ other = self._check_allowed_dtypes(other, "numeric", "__isub__") if other is NotImplemented: return other self._array.__isub__(other._array) return self def __rsub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rsub__. """ other = self._check_allowed_dtypes(other, "numeric", "__rsub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rsub__(other._array) return self.__class__._new(res) def __itruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __itruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__itruediv__") if other is NotImplemented: return other self._array.__itruediv__(other._array) return self def __rtruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __rtruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__rtruediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rtruediv__(other._array) return self.__class__._new(res) def __ixor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ixor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ixor__") if other is NotImplemented: return other self._array.__ixor__(other._array) return self def __rxor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rxor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rxor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rxor__(other._array) return self.__class__._new(res) def to_device(self: Array, device: Device, /, stream: None = None) -> Array: if stream is not None: raise ValueError("The stream argument to to_device() is not supported") if device == 'cpu': return self raise ValueError(f"Unsupported device {device!r}") def dtype(self) -> Dtype: """ Array API compatible wrapper for :py:meth:`np.ndarray.dtype <numpy.ndarray.dtype>`. See its docstring for more information. """ return self._array.dtype def device(self) -> Device: return "cpu" # Note: mT is new in array API spec (see matrix_transpose) def mT(self) -> Array: from .linalg import matrix_transpose return matrix_transpose(self) def ndim(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.ndim <numpy.ndarray.ndim>`. See its docstring for more information. """ return self._array.ndim def shape(self) -> Tuple[int, ...]: """ Array API compatible wrapper for :py:meth:`np.ndarray.shape <numpy.ndarray.shape>`. See its docstring for more information. """ return self._array.shape def size(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.size <numpy.ndarray.size>`. See its docstring for more information. """ return self._array.size def T(self) -> Array: """ Array API compatible wrapper for :py:meth:`np.ndarray.T <numpy.ndarray.T>`. See its docstring for more information. """ # Note: T only works on 2-dimensional arrays. See the corresponding # note in the specification: # https://data-apis.org/array-api/latest/API_specification/array_object.html#t if self.ndim != 2: raise ValueError("x.T requires x to have 2 dimensions. Use x.mT to transpose stacks of matrices and permute_dims() to permute dimensions.") return self.__class__._new(self._array.T) The provided code snippet includes necessary dependencies for implementing the `isnan` function. Write a Python function `def isnan(x: Array, /) -> Array` to solve the following problem: Array API compatible wrapper for :py:func:`np.isnan <numpy.isnan>`. See its docstring for more information. Here is the function: def isnan(x: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.isnan <numpy.isnan>`. See its docstring for more information. """ if x.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in isnan") return Array._new(np.isnan(x._array))
Array API compatible wrapper for :py:func:`np.isnan <numpy.isnan>`. See its docstring for more information.
170,048
from __future__ import annotations from ._dtypes import ( _boolean_dtypes, _floating_dtypes, _integer_dtypes, _integer_or_boolean_dtypes, _numeric_dtypes, _result_type, ) from ._array_object import Array import numpy as np _numeric_dtypes = ( float32, float64, int8, int16, int32, int64, uint8, uint16, uint32, uint64, ) def _result_type(type1, type2): if (type1, type2) in _promotion_table: return _promotion_table[type1, type2] raise TypeError(f"{type1} and {type2} cannot be type promoted together") class Array: """ n-d array object for the array API namespace. See the docstring of :py:obj:`np.ndarray <numpy.ndarray>` for more information. This is a wrapper around numpy.ndarray that restricts the usage to only those things that are required by the array API namespace. Note, attributes on this object that start with a single underscore are not part of the API specification and should only be used internally. This object should not be constructed directly. Rather, use one of the creation functions, such as asarray(). """ _array: np.ndarray # Use a custom constructor instead of __init__, as manually initializing # this class is not supported API. def _new(cls, x, /): """ This is a private method for initializing the array API Array object. Functions outside of the array_api submodule should not use this method. Use one of the creation functions instead, such as ``asarray``. """ obj = super().__new__(cls) # Note: The spec does not have array scalars, only 0-D arrays. if isinstance(x, np.generic): # Convert the array scalar to a 0-D array x = np.asarray(x) if x.dtype not in _all_dtypes: raise TypeError( f"The array_api namespace does not support the dtype '{x.dtype}'" ) obj._array = x return obj # Prevent Array() from working def __new__(cls, *args, **kwargs): raise TypeError( "The array_api Array object should not be instantiated directly. Use an array creation function, such as asarray(), instead." ) # These functions are not required by the spec, but are implemented for # the sake of usability. def __str__(self: Array, /) -> str: """ Performs the operation __str__. """ return self._array.__str__().replace("array", "Array") def __repr__(self: Array, /) -> str: """ Performs the operation __repr__. """ suffix = f", dtype={self.dtype.name})" if 0 in self.shape: prefix = "empty(" mid = str(self.shape) else: prefix = "Array(" mid = np.array2string(self._array, separator=', ', prefix=prefix, suffix=suffix) return prefix + mid + suffix # This function is not required by the spec, but we implement it here for # convenience so that np.asarray(np.array_api.Array) will work. def __array__(self, dtype: None | np.dtype[Any] = None) -> npt.NDArray[Any]: """ Warning: this method is NOT part of the array API spec. Implementers of other libraries need not include it, and users should not assume it will be present in other implementations. """ return np.asarray(self._array, dtype=dtype) # These are various helper functions to make the array behavior match the # spec in places where it either deviates from or is more strict than # NumPy behavior def _check_allowed_dtypes(self, other: bool | int | float | Array, dtype_category: str, op: str) -> Array: """ Helper function for operators to only allow specific input dtypes Use like other = self._check_allowed_dtypes(other, 'numeric', '__add__') if other is NotImplemented: return other """ if self.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") if isinstance(other, (int, float, bool)): other = self._promote_scalar(other) elif isinstance(other, Array): if other.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") else: return NotImplemented # This will raise TypeError for type combinations that are not allowed # to promote in the spec (even if the NumPy array operator would # promote them). res_dtype = _result_type(self.dtype, other.dtype) if op.startswith("__i"): # Note: NumPy will allow in-place operators in some cases where # the type promoted operator does not match the left-hand side # operand. For example, # >>> a = np.array(1, dtype=np.int8) # >>> a += np.array(1, dtype=np.int16) # The spec explicitly disallows this. if res_dtype != self.dtype: raise TypeError( f"Cannot perform {op} with dtypes {self.dtype} and {other.dtype}" ) return other # Helper function to match the type promotion rules in the spec def _promote_scalar(self, scalar): """ Returns a promoted version of a Python scalar appropriate for use with operations on self. This may raise an OverflowError in cases where the scalar is an integer that is too large to fit in a NumPy integer dtype, or TypeError when the scalar type is incompatible with the dtype of self. """ # Note: Only Python scalar types that match the array dtype are # allowed. if isinstance(scalar, bool): if self.dtype not in _boolean_dtypes: raise TypeError( "Python bool scalars can only be promoted with bool arrays" ) elif isinstance(scalar, int): if self.dtype in _boolean_dtypes: raise TypeError( "Python int scalars cannot be promoted with bool arrays" ) elif isinstance(scalar, float): if self.dtype not in _floating_dtypes: raise TypeError( "Python float scalars can only be promoted with floating-point arrays." ) else: raise TypeError("'scalar' must be a Python scalar") # Note: scalars are unconditionally cast to the same dtype as the # array. # Note: the spec only specifies integer-dtype/int promotion # behavior for integers within the bounds of the integer dtype. # Outside of those bounds we use the default NumPy behavior (either # cast or raise OverflowError). return Array._new(np.array(scalar, self.dtype)) def _normalize_two_args(x1, x2) -> Tuple[Array, Array]: """ Normalize inputs to two arg functions to fix type promotion rules NumPy deviates from the spec type promotion rules in cases where one argument is 0-dimensional and the other is not. For example: >>> import numpy as np >>> a = np.array([1.0], dtype=np.float32) >>> b = np.array(1.0, dtype=np.float64) >>> np.add(a, b) # The spec says this should be float64 array([2.], dtype=float32) To fix this, we add a dimension to the 0-dimension array before passing it through. This works because a dimension would be added anyway from broadcasting, so the resulting shape is the same, but this prevents NumPy from not promoting the dtype. """ # Another option would be to use signature=(x1.dtype, x2.dtype, None), # but that only works for ufuncs, so we would have to call the ufuncs # directly in the operator methods. One should also note that this # sort of trick wouldn't work for functions like searchsorted, which # don't do normal broadcasting, but there aren't any functions like # that in the array API namespace. if x1.ndim == 0 and x2.ndim != 0: # The _array[None] workaround was chosen because it is relatively # performant. broadcast_to(x1._array, x2.shape) is much slower. We # could also manually type promote x2, but that is more complicated # and about the same performance as this. x1 = Array._new(x1._array[None]) elif x2.ndim == 0 and x1.ndim != 0: x2 = Array._new(x2._array[None]) return (x1, x2) # Note: A large fraction of allowed indices are disallowed here (see the # docstring below) def _validate_index(self, key): """ Validate an index according to the array API. The array API specification only requires a subset of indices that are supported by NumPy. This function will reject any index that is allowed by NumPy but not required by the array API specification. We always raise ``IndexError`` on such indices (the spec does not require any specific behavior on them, but this makes the NumPy array API namespace a minimal implementation of the spec). See https://data-apis.org/array-api/latest/API_specification/indexing.html for the full list of required indexing behavior This function raises IndexError if the index ``key`` is invalid. It only raises ``IndexError`` on indices that are not already rejected by NumPy, as NumPy will already raise the appropriate error on such indices. ``shape`` may be None, in which case, only cases that are independent of the array shape are checked. The following cases are allowed by NumPy, but not specified by the array API specification: - Indices to not include an implicit ellipsis at the end. That is, every axis of an array must be explicitly indexed or an ellipsis included. This behaviour is sometimes referred to as flat indexing. - The start and stop of a slice may not be out of bounds. In particular, for a slice ``i:j:k`` on an axis of size ``n``, only the following are allowed: - ``i`` or ``j`` omitted (``None``). - ``-n <= i <= max(0, n - 1)``. - For ``k > 0`` or ``k`` omitted (``None``), ``-n <= j <= n``. - For ``k < 0``, ``-n - 1 <= j <= max(0, n - 1)``. - Boolean array indices are not allowed as part of a larger tuple index. - Integer array indices are not allowed (with the exception of 0-D arrays, which are treated the same as scalars). Additionally, it should be noted that indices that would return a scalar in NumPy will return a 0-D array. Array scalars are not allowed in the specification, only 0-D arrays. This is done in the ``Array._new`` constructor, not this function. """ _key = key if isinstance(key, tuple) else (key,) for i in _key: if isinstance(i, bool) or not ( isinstance(i, SupportsIndex) # i.e. ints or isinstance(i, slice) or i == Ellipsis or i is None or isinstance(i, Array) or isinstance(i, np.ndarray) ): raise IndexError( f"Single-axes index {i} has {type(i)=}, but only " "integers, slices (:), ellipsis (...), newaxis (None), " "zero-dimensional integer arrays and boolean arrays " "are specified in the Array API." ) nonexpanding_key = [] single_axes = [] n_ellipsis = 0 key_has_mask = False for i in _key: if i is not None: nonexpanding_key.append(i) if isinstance(i, Array) or isinstance(i, np.ndarray): if i.dtype in _boolean_dtypes: key_has_mask = True single_axes.append(i) else: # i must not be an array here, to avoid elementwise equals if i == Ellipsis: n_ellipsis += 1 else: single_axes.append(i) n_single_axes = len(single_axes) if n_ellipsis > 1: return # handled by ndarray elif n_ellipsis == 0: # Note boolean masks must be the sole index, which we check for # later on. if not key_has_mask and n_single_axes < self.ndim: raise IndexError( f"{self.ndim=}, but the multi-axes index only specifies " f"{n_single_axes} dimensions. If this was intentional, " "add a trailing ellipsis (...) which expands into as many " "slices (:) as necessary - this is what np.ndarray arrays " "implicitly do, but such flat indexing behaviour is not " "specified in the Array API." ) if n_ellipsis == 0: indexed_shape = self.shape else: ellipsis_start = None for pos, i in enumerate(nonexpanding_key): if not (isinstance(i, Array) or isinstance(i, np.ndarray)): if i == Ellipsis: ellipsis_start = pos break assert ellipsis_start is not None # sanity check ellipsis_end = self.ndim - (n_single_axes - ellipsis_start) indexed_shape = ( self.shape[:ellipsis_start] + self.shape[ellipsis_end:] ) for i, side in zip(single_axes, indexed_shape): if isinstance(i, slice): if side == 0: f_range = "0 (or None)" else: f_range = f"between -{side} and {side - 1} (or None)" if i.start is not None: try: start = operator.index(i.start) except TypeError: pass # handled by ndarray else: if not (-side <= start <= side): raise IndexError( f"Slice {i} contains {start=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds starts are not specified in " "the Array API)" ) if i.stop is not None: try: stop = operator.index(i.stop) except TypeError: pass # handled by ndarray else: if not (-side <= stop <= side): raise IndexError( f"Slice {i} contains {stop=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds stops are not specified in " "the Array API)" ) elif isinstance(i, Array): if i.dtype in _boolean_dtypes and len(_key) != 1: assert isinstance(key, tuple) # sanity check raise IndexError( f"Single-axes index {i} is a boolean array and " f"{len(key)=}, but masking is only specified in the " "Array API when the array is the sole index." ) elif i.dtype in _integer_dtypes and i.ndim != 0: raise IndexError( f"Single-axes index {i} is a non-zero-dimensional " "integer array, but advanced integer indexing is not " "specified in the Array API." ) elif isinstance(i, tuple): raise IndexError( f"Single-axes index {i} is a tuple, but nested tuple " "indices are not specified in the Array API." ) # Everything below this line is required by the spec. def __abs__(self: Array, /) -> Array: """ Performs the operation __abs__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __abs__") res = self._array.__abs__() return self.__class__._new(res) def __add__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __add__. """ other = self._check_allowed_dtypes(other, "numeric", "__add__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__add__(other._array) return self.__class__._new(res) def __and__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __and__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__and__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__and__(other._array) return self.__class__._new(res) def __array_namespace__( self: Array, /, *, api_version: Optional[str] = None ) -> types.ModuleType: if api_version is not None and not api_version.startswith("2021."): raise ValueError(f"Unrecognized array API version: {api_version!r}") return array_api def __bool__(self: Array, /) -> bool: """ Performs the operation __bool__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("bool is only allowed on arrays with 0 dimensions") if self.dtype not in _boolean_dtypes: raise ValueError("bool is only allowed on boolean arrays") res = self._array.__bool__() return res def __dlpack__(self: Array, /, *, stream: None = None) -> PyCapsule: """ Performs the operation __dlpack__. """ return self._array.__dlpack__(stream=stream) def __dlpack_device__(self: Array, /) -> Tuple[IntEnum, int]: """ Performs the operation __dlpack_device__. """ # Note: device support is required for this return self._array.__dlpack_device__() def __eq__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __eq__. """ # Even though "all" dtypes are allowed, we still require them to be # promotable with each other. other = self._check_allowed_dtypes(other, "all", "__eq__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__eq__(other._array) return self.__class__._new(res) def __float__(self: Array, /) -> float: """ Performs the operation __float__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("float is only allowed on arrays with 0 dimensions") if self.dtype not in _floating_dtypes: raise ValueError("float is only allowed on floating-point arrays") res = self._array.__float__() return res def __floordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __floordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__floordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__floordiv__(other._array) return self.__class__._new(res) def __ge__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ge__. """ other = self._check_allowed_dtypes(other, "numeric", "__ge__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ge__(other._array) return self.__class__._new(res) def __getitem__( self: Array, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], /, ) -> Array: """ Performs the operation __getitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array res = self._array.__getitem__(key) return self._new(res) def __gt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __gt__. """ other = self._check_allowed_dtypes(other, "numeric", "__gt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__gt__(other._array) return self.__class__._new(res) def __int__(self: Array, /) -> int: """ Performs the operation __int__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("int is only allowed on arrays with 0 dimensions") if self.dtype not in _integer_dtypes: raise ValueError("int is only allowed on integer arrays") res = self._array.__int__() return res def __index__(self: Array, /) -> int: """ Performs the operation __index__. """ res = self._array.__index__() return res def __invert__(self: Array, /) -> Array: """ Performs the operation __invert__. """ if self.dtype not in _integer_or_boolean_dtypes: raise TypeError("Only integer or boolean dtypes are allowed in __invert__") res = self._array.__invert__() return self.__class__._new(res) def __le__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __le__. """ other = self._check_allowed_dtypes(other, "numeric", "__le__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__le__(other._array) return self.__class__._new(res) def __lshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __lshift__. """ other = self._check_allowed_dtypes(other, "integer", "__lshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lshift__(other._array) return self.__class__._new(res) def __lt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __lt__. """ other = self._check_allowed_dtypes(other, "numeric", "__lt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lt__(other._array) return self.__class__._new(res) def __matmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __matmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__matmul__") if other is NotImplemented: return other res = self._array.__matmul__(other._array) return self.__class__._new(res) def __mod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mod__. """ other = self._check_allowed_dtypes(other, "numeric", "__mod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mod__(other._array) return self.__class__._new(res) def __mul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mul__. """ other = self._check_allowed_dtypes(other, "numeric", "__mul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mul__(other._array) return self.__class__._new(res) def __ne__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __ne__. """ other = self._check_allowed_dtypes(other, "all", "__ne__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ne__(other._array) return self.__class__._new(res) def __neg__(self: Array, /) -> Array: """ Performs the operation __neg__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __neg__") res = self._array.__neg__() return self.__class__._new(res) def __or__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __or__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__or__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__or__(other._array) return self.__class__._new(res) def __pos__(self: Array, /) -> Array: """ Performs the operation __pos__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __pos__") res = self._array.__pos__() return self.__class__._new(res) def __pow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __pow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__pow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow type promotion rules for 0-d # arrays, so we use pow() here instead. return pow(self, other) def __rshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rshift__(other._array) return self.__class__._new(res) def __setitem__( self, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], value: Union[int, float, bool, Array], /, ) -> None: """ Performs the operation __setitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array self._array.__setitem__(key, asarray(value)._array) def __sub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __sub__. """ other = self._check_allowed_dtypes(other, "numeric", "__sub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__sub__(other._array) return self.__class__._new(res) # PEP 484 requires int to be a subtype of float, but __truediv__ should # not accept int. def __truediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __truediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__truediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__truediv__(other._array) return self.__class__._new(res) def __xor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __xor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__xor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__xor__(other._array) return self.__class__._new(res) def __iadd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __iadd__. """ other = self._check_allowed_dtypes(other, "numeric", "__iadd__") if other is NotImplemented: return other self._array.__iadd__(other._array) return self def __radd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __radd__. """ other = self._check_allowed_dtypes(other, "numeric", "__radd__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__radd__(other._array) return self.__class__._new(res) def __iand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __iand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__iand__") if other is NotImplemented: return other self._array.__iand__(other._array) return self def __rand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rand__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rand__(other._array) return self.__class__._new(res) def __ifloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ifloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__ifloordiv__") if other is NotImplemented: return other self._array.__ifloordiv__(other._array) return self def __rfloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rfloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__rfloordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rfloordiv__(other._array) return self.__class__._new(res) def __ilshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __ilshift__. """ other = self._check_allowed_dtypes(other, "integer", "__ilshift__") if other is NotImplemented: return other self._array.__ilshift__(other._array) return self def __rlshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rlshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rlshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rlshift__(other._array) return self.__class__._new(res) def __imatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __imatmul__. """ # Note: NumPy does not implement __imatmul__. # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__imatmul__") if other is NotImplemented: return other # __imatmul__ can only be allowed when it would not change the shape # of self. other_shape = other.shape if self.shape == () or other_shape == (): raise ValueError("@= requires at least one dimension") if len(other_shape) == 1 or other_shape[-1] != other_shape[-2]: raise ValueError("@= cannot change the shape of the input array") self._array[:] = self._array.__matmul__(other._array) return self def __rmatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __rmatmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__rmatmul__") if other is NotImplemented: return other res = self._array.__rmatmul__(other._array) return self.__class__._new(res) def __imod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imod__. """ other = self._check_allowed_dtypes(other, "numeric", "__imod__") if other is NotImplemented: return other self._array.__imod__(other._array) return self def __rmod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmod__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmod__(other._array) return self.__class__._new(res) def __imul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imul__. """ other = self._check_allowed_dtypes(other, "numeric", "__imul__") if other is NotImplemented: return other self._array.__imul__(other._array) return self def __rmul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmul__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmul__(other._array) return self.__class__._new(res) def __ior__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ior__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ior__") if other is NotImplemented: return other self._array.__ior__(other._array) return self def __ror__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ror__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ror__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ror__(other._array) return self.__class__._new(res) def __ipow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ipow__. """ other = self._check_allowed_dtypes(other, "numeric", "__ipow__") if other is NotImplemented: return other self._array.__ipow__(other._array) return self def __rpow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rpow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__rpow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow the spec type promotion rules # for 0-d arrays, so we use pow() here instead. return pow(other, self) def __irshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __irshift__. """ other = self._check_allowed_dtypes(other, "integer", "__irshift__") if other is NotImplemented: return other self._array.__irshift__(other._array) return self def __rrshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rrshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rrshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rrshift__(other._array) return self.__class__._new(res) def __isub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __isub__. """ other = self._check_allowed_dtypes(other, "numeric", "__isub__") if other is NotImplemented: return other self._array.__isub__(other._array) return self def __rsub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rsub__. """ other = self._check_allowed_dtypes(other, "numeric", "__rsub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rsub__(other._array) return self.__class__._new(res) def __itruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __itruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__itruediv__") if other is NotImplemented: return other self._array.__itruediv__(other._array) return self def __rtruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __rtruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__rtruediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rtruediv__(other._array) return self.__class__._new(res) def __ixor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ixor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ixor__") if other is NotImplemented: return other self._array.__ixor__(other._array) return self def __rxor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rxor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rxor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rxor__(other._array) return self.__class__._new(res) def to_device(self: Array, device: Device, /, stream: None = None) -> Array: if stream is not None: raise ValueError("The stream argument to to_device() is not supported") if device == 'cpu': return self raise ValueError(f"Unsupported device {device!r}") def dtype(self) -> Dtype: """ Array API compatible wrapper for :py:meth:`np.ndarray.dtype <numpy.ndarray.dtype>`. See its docstring for more information. """ return self._array.dtype def device(self) -> Device: return "cpu" # Note: mT is new in array API spec (see matrix_transpose) def mT(self) -> Array: from .linalg import matrix_transpose return matrix_transpose(self) def ndim(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.ndim <numpy.ndarray.ndim>`. See its docstring for more information. """ return self._array.ndim def shape(self) -> Tuple[int, ...]: """ Array API compatible wrapper for :py:meth:`np.ndarray.shape <numpy.ndarray.shape>`. See its docstring for more information. """ return self._array.shape def size(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.size <numpy.ndarray.size>`. See its docstring for more information. """ return self._array.size def T(self) -> Array: """ Array API compatible wrapper for :py:meth:`np.ndarray.T <numpy.ndarray.T>`. See its docstring for more information. """ # Note: T only works on 2-dimensional arrays. See the corresponding # note in the specification: # https://data-apis.org/array-api/latest/API_specification/array_object.html#t if self.ndim != 2: raise ValueError("x.T requires x to have 2 dimensions. Use x.mT to transpose stacks of matrices and permute_dims() to permute dimensions.") return self.__class__._new(self._array.T) The provided code snippet includes necessary dependencies for implementing the `less` function. Write a Python function `def less(x1: Array, x2: Array, /) -> Array` to solve the following problem: Array API compatible wrapper for :py:func:`np.less <numpy.less>`. See its docstring for more information. Here is the function: def less(x1: Array, x2: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.less <numpy.less>`. See its docstring for more information. """ if x1.dtype not in _numeric_dtypes or x2.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in less") # Call result type here just to raise on disallowed type combinations _result_type(x1.dtype, x2.dtype) x1, x2 = Array._normalize_two_args(x1, x2) return Array._new(np.less(x1._array, x2._array))
Array API compatible wrapper for :py:func:`np.less <numpy.less>`. See its docstring for more information.
170,049
from __future__ import annotations from ._dtypes import ( _boolean_dtypes, _floating_dtypes, _integer_dtypes, _integer_or_boolean_dtypes, _numeric_dtypes, _result_type, ) from ._array_object import Array import numpy as np _numeric_dtypes = ( float32, float64, int8, int16, int32, int64, uint8, uint16, uint32, uint64, ) def _result_type(type1, type2): if (type1, type2) in _promotion_table: return _promotion_table[type1, type2] raise TypeError(f"{type1} and {type2} cannot be type promoted together") class Array: """ n-d array object for the array API namespace. See the docstring of :py:obj:`np.ndarray <numpy.ndarray>` for more information. This is a wrapper around numpy.ndarray that restricts the usage to only those things that are required by the array API namespace. Note, attributes on this object that start with a single underscore are not part of the API specification and should only be used internally. This object should not be constructed directly. Rather, use one of the creation functions, such as asarray(). """ _array: np.ndarray # Use a custom constructor instead of __init__, as manually initializing # this class is not supported API. def _new(cls, x, /): """ This is a private method for initializing the array API Array object. Functions outside of the array_api submodule should not use this method. Use one of the creation functions instead, such as ``asarray``. """ obj = super().__new__(cls) # Note: The spec does not have array scalars, only 0-D arrays. if isinstance(x, np.generic): # Convert the array scalar to a 0-D array x = np.asarray(x) if x.dtype not in _all_dtypes: raise TypeError( f"The array_api namespace does not support the dtype '{x.dtype}'" ) obj._array = x return obj # Prevent Array() from working def __new__(cls, *args, **kwargs): raise TypeError( "The array_api Array object should not be instantiated directly. Use an array creation function, such as asarray(), instead." ) # These functions are not required by the spec, but are implemented for # the sake of usability. def __str__(self: Array, /) -> str: """ Performs the operation __str__. """ return self._array.__str__().replace("array", "Array") def __repr__(self: Array, /) -> str: """ Performs the operation __repr__. """ suffix = f", dtype={self.dtype.name})" if 0 in self.shape: prefix = "empty(" mid = str(self.shape) else: prefix = "Array(" mid = np.array2string(self._array, separator=', ', prefix=prefix, suffix=suffix) return prefix + mid + suffix # This function is not required by the spec, but we implement it here for # convenience so that np.asarray(np.array_api.Array) will work. def __array__(self, dtype: None | np.dtype[Any] = None) -> npt.NDArray[Any]: """ Warning: this method is NOT part of the array API spec. Implementers of other libraries need not include it, and users should not assume it will be present in other implementations. """ return np.asarray(self._array, dtype=dtype) # These are various helper functions to make the array behavior match the # spec in places where it either deviates from or is more strict than # NumPy behavior def _check_allowed_dtypes(self, other: bool | int | float | Array, dtype_category: str, op: str) -> Array: """ Helper function for operators to only allow specific input dtypes Use like other = self._check_allowed_dtypes(other, 'numeric', '__add__') if other is NotImplemented: return other """ if self.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") if isinstance(other, (int, float, bool)): other = self._promote_scalar(other) elif isinstance(other, Array): if other.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") else: return NotImplemented # This will raise TypeError for type combinations that are not allowed # to promote in the spec (even if the NumPy array operator would # promote them). res_dtype = _result_type(self.dtype, other.dtype) if op.startswith("__i"): # Note: NumPy will allow in-place operators in some cases where # the type promoted operator does not match the left-hand side # operand. For example, # >>> a = np.array(1, dtype=np.int8) # >>> a += np.array(1, dtype=np.int16) # The spec explicitly disallows this. if res_dtype != self.dtype: raise TypeError( f"Cannot perform {op} with dtypes {self.dtype} and {other.dtype}" ) return other # Helper function to match the type promotion rules in the spec def _promote_scalar(self, scalar): """ Returns a promoted version of a Python scalar appropriate for use with operations on self. This may raise an OverflowError in cases where the scalar is an integer that is too large to fit in a NumPy integer dtype, or TypeError when the scalar type is incompatible with the dtype of self. """ # Note: Only Python scalar types that match the array dtype are # allowed. if isinstance(scalar, bool): if self.dtype not in _boolean_dtypes: raise TypeError( "Python bool scalars can only be promoted with bool arrays" ) elif isinstance(scalar, int): if self.dtype in _boolean_dtypes: raise TypeError( "Python int scalars cannot be promoted with bool arrays" ) elif isinstance(scalar, float): if self.dtype not in _floating_dtypes: raise TypeError( "Python float scalars can only be promoted with floating-point arrays." ) else: raise TypeError("'scalar' must be a Python scalar") # Note: scalars are unconditionally cast to the same dtype as the # array. # Note: the spec only specifies integer-dtype/int promotion # behavior for integers within the bounds of the integer dtype. # Outside of those bounds we use the default NumPy behavior (either # cast or raise OverflowError). return Array._new(np.array(scalar, self.dtype)) def _normalize_two_args(x1, x2) -> Tuple[Array, Array]: """ Normalize inputs to two arg functions to fix type promotion rules NumPy deviates from the spec type promotion rules in cases where one argument is 0-dimensional and the other is not. For example: >>> import numpy as np >>> a = np.array([1.0], dtype=np.float32) >>> b = np.array(1.0, dtype=np.float64) >>> np.add(a, b) # The spec says this should be float64 array([2.], dtype=float32) To fix this, we add a dimension to the 0-dimension array before passing it through. This works because a dimension would be added anyway from broadcasting, so the resulting shape is the same, but this prevents NumPy from not promoting the dtype. """ # Another option would be to use signature=(x1.dtype, x2.dtype, None), # but that only works for ufuncs, so we would have to call the ufuncs # directly in the operator methods. One should also note that this # sort of trick wouldn't work for functions like searchsorted, which # don't do normal broadcasting, but there aren't any functions like # that in the array API namespace. if x1.ndim == 0 and x2.ndim != 0: # The _array[None] workaround was chosen because it is relatively # performant. broadcast_to(x1._array, x2.shape) is much slower. We # could also manually type promote x2, but that is more complicated # and about the same performance as this. x1 = Array._new(x1._array[None]) elif x2.ndim == 0 and x1.ndim != 0: x2 = Array._new(x2._array[None]) return (x1, x2) # Note: A large fraction of allowed indices are disallowed here (see the # docstring below) def _validate_index(self, key): """ Validate an index according to the array API. The array API specification only requires a subset of indices that are supported by NumPy. This function will reject any index that is allowed by NumPy but not required by the array API specification. We always raise ``IndexError`` on such indices (the spec does not require any specific behavior on them, but this makes the NumPy array API namespace a minimal implementation of the spec). See https://data-apis.org/array-api/latest/API_specification/indexing.html for the full list of required indexing behavior This function raises IndexError if the index ``key`` is invalid. It only raises ``IndexError`` on indices that are not already rejected by NumPy, as NumPy will already raise the appropriate error on such indices. ``shape`` may be None, in which case, only cases that are independent of the array shape are checked. The following cases are allowed by NumPy, but not specified by the array API specification: - Indices to not include an implicit ellipsis at the end. That is, every axis of an array must be explicitly indexed or an ellipsis included. This behaviour is sometimes referred to as flat indexing. - The start and stop of a slice may not be out of bounds. In particular, for a slice ``i:j:k`` on an axis of size ``n``, only the following are allowed: - ``i`` or ``j`` omitted (``None``). - ``-n <= i <= max(0, n - 1)``. - For ``k > 0`` or ``k`` omitted (``None``), ``-n <= j <= n``. - For ``k < 0``, ``-n - 1 <= j <= max(0, n - 1)``. - Boolean array indices are not allowed as part of a larger tuple index. - Integer array indices are not allowed (with the exception of 0-D arrays, which are treated the same as scalars). Additionally, it should be noted that indices that would return a scalar in NumPy will return a 0-D array. Array scalars are not allowed in the specification, only 0-D arrays. This is done in the ``Array._new`` constructor, not this function. """ _key = key if isinstance(key, tuple) else (key,) for i in _key: if isinstance(i, bool) or not ( isinstance(i, SupportsIndex) # i.e. ints or isinstance(i, slice) or i == Ellipsis or i is None or isinstance(i, Array) or isinstance(i, np.ndarray) ): raise IndexError( f"Single-axes index {i} has {type(i)=}, but only " "integers, slices (:), ellipsis (...), newaxis (None), " "zero-dimensional integer arrays and boolean arrays " "are specified in the Array API." ) nonexpanding_key = [] single_axes = [] n_ellipsis = 0 key_has_mask = False for i in _key: if i is not None: nonexpanding_key.append(i) if isinstance(i, Array) or isinstance(i, np.ndarray): if i.dtype in _boolean_dtypes: key_has_mask = True single_axes.append(i) else: # i must not be an array here, to avoid elementwise equals if i == Ellipsis: n_ellipsis += 1 else: single_axes.append(i) n_single_axes = len(single_axes) if n_ellipsis > 1: return # handled by ndarray elif n_ellipsis == 0: # Note boolean masks must be the sole index, which we check for # later on. if not key_has_mask and n_single_axes < self.ndim: raise IndexError( f"{self.ndim=}, but the multi-axes index only specifies " f"{n_single_axes} dimensions. If this was intentional, " "add a trailing ellipsis (...) which expands into as many " "slices (:) as necessary - this is what np.ndarray arrays " "implicitly do, but such flat indexing behaviour is not " "specified in the Array API." ) if n_ellipsis == 0: indexed_shape = self.shape else: ellipsis_start = None for pos, i in enumerate(nonexpanding_key): if not (isinstance(i, Array) or isinstance(i, np.ndarray)): if i == Ellipsis: ellipsis_start = pos break assert ellipsis_start is not None # sanity check ellipsis_end = self.ndim - (n_single_axes - ellipsis_start) indexed_shape = ( self.shape[:ellipsis_start] + self.shape[ellipsis_end:] ) for i, side in zip(single_axes, indexed_shape): if isinstance(i, slice): if side == 0: f_range = "0 (or None)" else: f_range = f"between -{side} and {side - 1} (or None)" if i.start is not None: try: start = operator.index(i.start) except TypeError: pass # handled by ndarray else: if not (-side <= start <= side): raise IndexError( f"Slice {i} contains {start=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds starts are not specified in " "the Array API)" ) if i.stop is not None: try: stop = operator.index(i.stop) except TypeError: pass # handled by ndarray else: if not (-side <= stop <= side): raise IndexError( f"Slice {i} contains {stop=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds stops are not specified in " "the Array API)" ) elif isinstance(i, Array): if i.dtype in _boolean_dtypes and len(_key) != 1: assert isinstance(key, tuple) # sanity check raise IndexError( f"Single-axes index {i} is a boolean array and " f"{len(key)=}, but masking is only specified in the " "Array API when the array is the sole index." ) elif i.dtype in _integer_dtypes and i.ndim != 0: raise IndexError( f"Single-axes index {i} is a non-zero-dimensional " "integer array, but advanced integer indexing is not " "specified in the Array API." ) elif isinstance(i, tuple): raise IndexError( f"Single-axes index {i} is a tuple, but nested tuple " "indices are not specified in the Array API." ) # Everything below this line is required by the spec. def __abs__(self: Array, /) -> Array: """ Performs the operation __abs__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __abs__") res = self._array.__abs__() return self.__class__._new(res) def __add__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __add__. """ other = self._check_allowed_dtypes(other, "numeric", "__add__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__add__(other._array) return self.__class__._new(res) def __and__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __and__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__and__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__and__(other._array) return self.__class__._new(res) def __array_namespace__( self: Array, /, *, api_version: Optional[str] = None ) -> types.ModuleType: if api_version is not None and not api_version.startswith("2021."): raise ValueError(f"Unrecognized array API version: {api_version!r}") return array_api def __bool__(self: Array, /) -> bool: """ Performs the operation __bool__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("bool is only allowed on arrays with 0 dimensions") if self.dtype not in _boolean_dtypes: raise ValueError("bool is only allowed on boolean arrays") res = self._array.__bool__() return res def __dlpack__(self: Array, /, *, stream: None = None) -> PyCapsule: """ Performs the operation __dlpack__. """ return self._array.__dlpack__(stream=stream) def __dlpack_device__(self: Array, /) -> Tuple[IntEnum, int]: """ Performs the operation __dlpack_device__. """ # Note: device support is required for this return self._array.__dlpack_device__() def __eq__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __eq__. """ # Even though "all" dtypes are allowed, we still require them to be # promotable with each other. other = self._check_allowed_dtypes(other, "all", "__eq__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__eq__(other._array) return self.__class__._new(res) def __float__(self: Array, /) -> float: """ Performs the operation __float__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("float is only allowed on arrays with 0 dimensions") if self.dtype not in _floating_dtypes: raise ValueError("float is only allowed on floating-point arrays") res = self._array.__float__() return res def __floordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __floordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__floordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__floordiv__(other._array) return self.__class__._new(res) def __ge__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ge__. """ other = self._check_allowed_dtypes(other, "numeric", "__ge__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ge__(other._array) return self.__class__._new(res) def __getitem__( self: Array, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], /, ) -> Array: """ Performs the operation __getitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array res = self._array.__getitem__(key) return self._new(res) def __gt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __gt__. """ other = self._check_allowed_dtypes(other, "numeric", "__gt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__gt__(other._array) return self.__class__._new(res) def __int__(self: Array, /) -> int: """ Performs the operation __int__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("int is only allowed on arrays with 0 dimensions") if self.dtype not in _integer_dtypes: raise ValueError("int is only allowed on integer arrays") res = self._array.__int__() return res def __index__(self: Array, /) -> int: """ Performs the operation __index__. """ res = self._array.__index__() return res def __invert__(self: Array, /) -> Array: """ Performs the operation __invert__. """ if self.dtype not in _integer_or_boolean_dtypes: raise TypeError("Only integer or boolean dtypes are allowed in __invert__") res = self._array.__invert__() return self.__class__._new(res) def __le__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __le__. """ other = self._check_allowed_dtypes(other, "numeric", "__le__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__le__(other._array) return self.__class__._new(res) def __lshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __lshift__. """ other = self._check_allowed_dtypes(other, "integer", "__lshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lshift__(other._array) return self.__class__._new(res) def __lt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __lt__. """ other = self._check_allowed_dtypes(other, "numeric", "__lt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lt__(other._array) return self.__class__._new(res) def __matmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __matmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__matmul__") if other is NotImplemented: return other res = self._array.__matmul__(other._array) return self.__class__._new(res) def __mod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mod__. """ other = self._check_allowed_dtypes(other, "numeric", "__mod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mod__(other._array) return self.__class__._new(res) def __mul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mul__. """ other = self._check_allowed_dtypes(other, "numeric", "__mul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mul__(other._array) return self.__class__._new(res) def __ne__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __ne__. """ other = self._check_allowed_dtypes(other, "all", "__ne__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ne__(other._array) return self.__class__._new(res) def __neg__(self: Array, /) -> Array: """ Performs the operation __neg__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __neg__") res = self._array.__neg__() return self.__class__._new(res) def __or__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __or__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__or__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__or__(other._array) return self.__class__._new(res) def __pos__(self: Array, /) -> Array: """ Performs the operation __pos__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __pos__") res = self._array.__pos__() return self.__class__._new(res) def __pow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __pow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__pow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow type promotion rules for 0-d # arrays, so we use pow() here instead. return pow(self, other) def __rshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rshift__(other._array) return self.__class__._new(res) def __setitem__( self, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], value: Union[int, float, bool, Array], /, ) -> None: """ Performs the operation __setitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array self._array.__setitem__(key, asarray(value)._array) def __sub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __sub__. """ other = self._check_allowed_dtypes(other, "numeric", "__sub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__sub__(other._array) return self.__class__._new(res) # PEP 484 requires int to be a subtype of float, but __truediv__ should # not accept int. def __truediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __truediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__truediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__truediv__(other._array) return self.__class__._new(res) def __xor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __xor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__xor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__xor__(other._array) return self.__class__._new(res) def __iadd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __iadd__. """ other = self._check_allowed_dtypes(other, "numeric", "__iadd__") if other is NotImplemented: return other self._array.__iadd__(other._array) return self def __radd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __radd__. """ other = self._check_allowed_dtypes(other, "numeric", "__radd__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__radd__(other._array) return self.__class__._new(res) def __iand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __iand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__iand__") if other is NotImplemented: return other self._array.__iand__(other._array) return self def __rand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rand__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rand__(other._array) return self.__class__._new(res) def __ifloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ifloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__ifloordiv__") if other is NotImplemented: return other self._array.__ifloordiv__(other._array) return self def __rfloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rfloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__rfloordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rfloordiv__(other._array) return self.__class__._new(res) def __ilshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __ilshift__. """ other = self._check_allowed_dtypes(other, "integer", "__ilshift__") if other is NotImplemented: return other self._array.__ilshift__(other._array) return self def __rlshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rlshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rlshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rlshift__(other._array) return self.__class__._new(res) def __imatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __imatmul__. """ # Note: NumPy does not implement __imatmul__. # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__imatmul__") if other is NotImplemented: return other # __imatmul__ can only be allowed when it would not change the shape # of self. other_shape = other.shape if self.shape == () or other_shape == (): raise ValueError("@= requires at least one dimension") if len(other_shape) == 1 or other_shape[-1] != other_shape[-2]: raise ValueError("@= cannot change the shape of the input array") self._array[:] = self._array.__matmul__(other._array) return self def __rmatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __rmatmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__rmatmul__") if other is NotImplemented: return other res = self._array.__rmatmul__(other._array) return self.__class__._new(res) def __imod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imod__. """ other = self._check_allowed_dtypes(other, "numeric", "__imod__") if other is NotImplemented: return other self._array.__imod__(other._array) return self def __rmod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmod__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmod__(other._array) return self.__class__._new(res) def __imul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imul__. """ other = self._check_allowed_dtypes(other, "numeric", "__imul__") if other is NotImplemented: return other self._array.__imul__(other._array) return self def __rmul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmul__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmul__(other._array) return self.__class__._new(res) def __ior__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ior__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ior__") if other is NotImplemented: return other self._array.__ior__(other._array) return self def __ror__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ror__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ror__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ror__(other._array) return self.__class__._new(res) def __ipow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ipow__. """ other = self._check_allowed_dtypes(other, "numeric", "__ipow__") if other is NotImplemented: return other self._array.__ipow__(other._array) return self def __rpow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rpow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__rpow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow the spec type promotion rules # for 0-d arrays, so we use pow() here instead. return pow(other, self) def __irshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __irshift__. """ other = self._check_allowed_dtypes(other, "integer", "__irshift__") if other is NotImplemented: return other self._array.__irshift__(other._array) return self def __rrshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rrshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rrshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rrshift__(other._array) return self.__class__._new(res) def __isub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __isub__. """ other = self._check_allowed_dtypes(other, "numeric", "__isub__") if other is NotImplemented: return other self._array.__isub__(other._array) return self def __rsub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rsub__. """ other = self._check_allowed_dtypes(other, "numeric", "__rsub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rsub__(other._array) return self.__class__._new(res) def __itruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __itruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__itruediv__") if other is NotImplemented: return other self._array.__itruediv__(other._array) return self def __rtruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __rtruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__rtruediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rtruediv__(other._array) return self.__class__._new(res) def __ixor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ixor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ixor__") if other is NotImplemented: return other self._array.__ixor__(other._array) return self def __rxor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rxor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rxor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rxor__(other._array) return self.__class__._new(res) def to_device(self: Array, device: Device, /, stream: None = None) -> Array: if stream is not None: raise ValueError("The stream argument to to_device() is not supported") if device == 'cpu': return self raise ValueError(f"Unsupported device {device!r}") def dtype(self) -> Dtype: """ Array API compatible wrapper for :py:meth:`np.ndarray.dtype <numpy.ndarray.dtype>`. See its docstring for more information. """ return self._array.dtype def device(self) -> Device: return "cpu" # Note: mT is new in array API spec (see matrix_transpose) def mT(self) -> Array: from .linalg import matrix_transpose return matrix_transpose(self) def ndim(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.ndim <numpy.ndarray.ndim>`. See its docstring for more information. """ return self._array.ndim def shape(self) -> Tuple[int, ...]: """ Array API compatible wrapper for :py:meth:`np.ndarray.shape <numpy.ndarray.shape>`. See its docstring for more information. """ return self._array.shape def size(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.size <numpy.ndarray.size>`. See its docstring for more information. """ return self._array.size def T(self) -> Array: """ Array API compatible wrapper for :py:meth:`np.ndarray.T <numpy.ndarray.T>`. See its docstring for more information. """ # Note: T only works on 2-dimensional arrays. See the corresponding # note in the specification: # https://data-apis.org/array-api/latest/API_specification/array_object.html#t if self.ndim != 2: raise ValueError("x.T requires x to have 2 dimensions. Use x.mT to transpose stacks of matrices and permute_dims() to permute dimensions.") return self.__class__._new(self._array.T) The provided code snippet includes necessary dependencies for implementing the `less_equal` function. Write a Python function `def less_equal(x1: Array, x2: Array, /) -> Array` to solve the following problem: Array API compatible wrapper for :py:func:`np.less_equal <numpy.less_equal>`. See its docstring for more information. Here is the function: def less_equal(x1: Array, x2: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.less_equal <numpy.less_equal>`. See its docstring for more information. """ if x1.dtype not in _numeric_dtypes or x2.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in less_equal") # Call result type here just to raise on disallowed type combinations _result_type(x1.dtype, x2.dtype) x1, x2 = Array._normalize_two_args(x1, x2) return Array._new(np.less_equal(x1._array, x2._array))
Array API compatible wrapper for :py:func:`np.less_equal <numpy.less_equal>`. See its docstring for more information.
170,050
from __future__ import annotations from ._dtypes import ( _boolean_dtypes, _floating_dtypes, _integer_dtypes, _integer_or_boolean_dtypes, _numeric_dtypes, _result_type, ) from ._array_object import Array import numpy as np _floating_dtypes = (float32, float64) class Array: """ n-d array object for the array API namespace. See the docstring of :py:obj:`np.ndarray <numpy.ndarray>` for more information. This is a wrapper around numpy.ndarray that restricts the usage to only those things that are required by the array API namespace. Note, attributes on this object that start with a single underscore are not part of the API specification and should only be used internally. This object should not be constructed directly. Rather, use one of the creation functions, such as asarray(). """ _array: np.ndarray # Use a custom constructor instead of __init__, as manually initializing # this class is not supported API. def _new(cls, x, /): """ This is a private method for initializing the array API Array object. Functions outside of the array_api submodule should not use this method. Use one of the creation functions instead, such as ``asarray``. """ obj = super().__new__(cls) # Note: The spec does not have array scalars, only 0-D arrays. if isinstance(x, np.generic): # Convert the array scalar to a 0-D array x = np.asarray(x) if x.dtype not in _all_dtypes: raise TypeError( f"The array_api namespace does not support the dtype '{x.dtype}'" ) obj._array = x return obj # Prevent Array() from working def __new__(cls, *args, **kwargs): raise TypeError( "The array_api Array object should not be instantiated directly. Use an array creation function, such as asarray(), instead." ) # These functions are not required by the spec, but are implemented for # the sake of usability. def __str__(self: Array, /) -> str: """ Performs the operation __str__. """ return self._array.__str__().replace("array", "Array") def __repr__(self: Array, /) -> str: """ Performs the operation __repr__. """ suffix = f", dtype={self.dtype.name})" if 0 in self.shape: prefix = "empty(" mid = str(self.shape) else: prefix = "Array(" mid = np.array2string(self._array, separator=', ', prefix=prefix, suffix=suffix) return prefix + mid + suffix # This function is not required by the spec, but we implement it here for # convenience so that np.asarray(np.array_api.Array) will work. def __array__(self, dtype: None | np.dtype[Any] = None) -> npt.NDArray[Any]: """ Warning: this method is NOT part of the array API spec. Implementers of other libraries need not include it, and users should not assume it will be present in other implementations. """ return np.asarray(self._array, dtype=dtype) # These are various helper functions to make the array behavior match the # spec in places where it either deviates from or is more strict than # NumPy behavior def _check_allowed_dtypes(self, other: bool | int | float | Array, dtype_category: str, op: str) -> Array: """ Helper function for operators to only allow specific input dtypes Use like other = self._check_allowed_dtypes(other, 'numeric', '__add__') if other is NotImplemented: return other """ if self.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") if isinstance(other, (int, float, bool)): other = self._promote_scalar(other) elif isinstance(other, Array): if other.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") else: return NotImplemented # This will raise TypeError for type combinations that are not allowed # to promote in the spec (even if the NumPy array operator would # promote them). res_dtype = _result_type(self.dtype, other.dtype) if op.startswith("__i"): # Note: NumPy will allow in-place operators in some cases where # the type promoted operator does not match the left-hand side # operand. For example, # >>> a = np.array(1, dtype=np.int8) # >>> a += np.array(1, dtype=np.int16) # The spec explicitly disallows this. if res_dtype != self.dtype: raise TypeError( f"Cannot perform {op} with dtypes {self.dtype} and {other.dtype}" ) return other # Helper function to match the type promotion rules in the spec def _promote_scalar(self, scalar): """ Returns a promoted version of a Python scalar appropriate for use with operations on self. This may raise an OverflowError in cases where the scalar is an integer that is too large to fit in a NumPy integer dtype, or TypeError when the scalar type is incompatible with the dtype of self. """ # Note: Only Python scalar types that match the array dtype are # allowed. if isinstance(scalar, bool): if self.dtype not in _boolean_dtypes: raise TypeError( "Python bool scalars can only be promoted with bool arrays" ) elif isinstance(scalar, int): if self.dtype in _boolean_dtypes: raise TypeError( "Python int scalars cannot be promoted with bool arrays" ) elif isinstance(scalar, float): if self.dtype not in _floating_dtypes: raise TypeError( "Python float scalars can only be promoted with floating-point arrays." ) else: raise TypeError("'scalar' must be a Python scalar") # Note: scalars are unconditionally cast to the same dtype as the # array. # Note: the spec only specifies integer-dtype/int promotion # behavior for integers within the bounds of the integer dtype. # Outside of those bounds we use the default NumPy behavior (either # cast or raise OverflowError). return Array._new(np.array(scalar, self.dtype)) def _normalize_two_args(x1, x2) -> Tuple[Array, Array]: """ Normalize inputs to two arg functions to fix type promotion rules NumPy deviates from the spec type promotion rules in cases where one argument is 0-dimensional and the other is not. For example: >>> import numpy as np >>> a = np.array([1.0], dtype=np.float32) >>> b = np.array(1.0, dtype=np.float64) >>> np.add(a, b) # The spec says this should be float64 array([2.], dtype=float32) To fix this, we add a dimension to the 0-dimension array before passing it through. This works because a dimension would be added anyway from broadcasting, so the resulting shape is the same, but this prevents NumPy from not promoting the dtype. """ # Another option would be to use signature=(x1.dtype, x2.dtype, None), # but that only works for ufuncs, so we would have to call the ufuncs # directly in the operator methods. One should also note that this # sort of trick wouldn't work for functions like searchsorted, which # don't do normal broadcasting, but there aren't any functions like # that in the array API namespace. if x1.ndim == 0 and x2.ndim != 0: # The _array[None] workaround was chosen because it is relatively # performant. broadcast_to(x1._array, x2.shape) is much slower. We # could also manually type promote x2, but that is more complicated # and about the same performance as this. x1 = Array._new(x1._array[None]) elif x2.ndim == 0 and x1.ndim != 0: x2 = Array._new(x2._array[None]) return (x1, x2) # Note: A large fraction of allowed indices are disallowed here (see the # docstring below) def _validate_index(self, key): """ Validate an index according to the array API. The array API specification only requires a subset of indices that are supported by NumPy. This function will reject any index that is allowed by NumPy but not required by the array API specification. We always raise ``IndexError`` on such indices (the spec does not require any specific behavior on them, but this makes the NumPy array API namespace a minimal implementation of the spec). See https://data-apis.org/array-api/latest/API_specification/indexing.html for the full list of required indexing behavior This function raises IndexError if the index ``key`` is invalid. It only raises ``IndexError`` on indices that are not already rejected by NumPy, as NumPy will already raise the appropriate error on such indices. ``shape`` may be None, in which case, only cases that are independent of the array shape are checked. The following cases are allowed by NumPy, but not specified by the array API specification: - Indices to not include an implicit ellipsis at the end. That is, every axis of an array must be explicitly indexed or an ellipsis included. This behaviour is sometimes referred to as flat indexing. - The start and stop of a slice may not be out of bounds. In particular, for a slice ``i:j:k`` on an axis of size ``n``, only the following are allowed: - ``i`` or ``j`` omitted (``None``). - ``-n <= i <= max(0, n - 1)``. - For ``k > 0`` or ``k`` omitted (``None``), ``-n <= j <= n``. - For ``k < 0``, ``-n - 1 <= j <= max(0, n - 1)``. - Boolean array indices are not allowed as part of a larger tuple index. - Integer array indices are not allowed (with the exception of 0-D arrays, which are treated the same as scalars). Additionally, it should be noted that indices that would return a scalar in NumPy will return a 0-D array. Array scalars are not allowed in the specification, only 0-D arrays. This is done in the ``Array._new`` constructor, not this function. """ _key = key if isinstance(key, tuple) else (key,) for i in _key: if isinstance(i, bool) or not ( isinstance(i, SupportsIndex) # i.e. ints or isinstance(i, slice) or i == Ellipsis or i is None or isinstance(i, Array) or isinstance(i, np.ndarray) ): raise IndexError( f"Single-axes index {i} has {type(i)=}, but only " "integers, slices (:), ellipsis (...), newaxis (None), " "zero-dimensional integer arrays and boolean arrays " "are specified in the Array API." ) nonexpanding_key = [] single_axes = [] n_ellipsis = 0 key_has_mask = False for i in _key: if i is not None: nonexpanding_key.append(i) if isinstance(i, Array) or isinstance(i, np.ndarray): if i.dtype in _boolean_dtypes: key_has_mask = True single_axes.append(i) else: # i must not be an array here, to avoid elementwise equals if i == Ellipsis: n_ellipsis += 1 else: single_axes.append(i) n_single_axes = len(single_axes) if n_ellipsis > 1: return # handled by ndarray elif n_ellipsis == 0: # Note boolean masks must be the sole index, which we check for # later on. if not key_has_mask and n_single_axes < self.ndim: raise IndexError( f"{self.ndim=}, but the multi-axes index only specifies " f"{n_single_axes} dimensions. If this was intentional, " "add a trailing ellipsis (...) which expands into as many " "slices (:) as necessary - this is what np.ndarray arrays " "implicitly do, but such flat indexing behaviour is not " "specified in the Array API." ) if n_ellipsis == 0: indexed_shape = self.shape else: ellipsis_start = None for pos, i in enumerate(nonexpanding_key): if not (isinstance(i, Array) or isinstance(i, np.ndarray)): if i == Ellipsis: ellipsis_start = pos break assert ellipsis_start is not None # sanity check ellipsis_end = self.ndim - (n_single_axes - ellipsis_start) indexed_shape = ( self.shape[:ellipsis_start] + self.shape[ellipsis_end:] ) for i, side in zip(single_axes, indexed_shape): if isinstance(i, slice): if side == 0: f_range = "0 (or None)" else: f_range = f"between -{side} and {side - 1} (or None)" if i.start is not None: try: start = operator.index(i.start) except TypeError: pass # handled by ndarray else: if not (-side <= start <= side): raise IndexError( f"Slice {i} contains {start=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds starts are not specified in " "the Array API)" ) if i.stop is not None: try: stop = operator.index(i.stop) except TypeError: pass # handled by ndarray else: if not (-side <= stop <= side): raise IndexError( f"Slice {i} contains {stop=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds stops are not specified in " "the Array API)" ) elif isinstance(i, Array): if i.dtype in _boolean_dtypes and len(_key) != 1: assert isinstance(key, tuple) # sanity check raise IndexError( f"Single-axes index {i} is a boolean array and " f"{len(key)=}, but masking is only specified in the " "Array API when the array is the sole index." ) elif i.dtype in _integer_dtypes and i.ndim != 0: raise IndexError( f"Single-axes index {i} is a non-zero-dimensional " "integer array, but advanced integer indexing is not " "specified in the Array API." ) elif isinstance(i, tuple): raise IndexError( f"Single-axes index {i} is a tuple, but nested tuple " "indices are not specified in the Array API." ) # Everything below this line is required by the spec. def __abs__(self: Array, /) -> Array: """ Performs the operation __abs__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __abs__") res = self._array.__abs__() return self.__class__._new(res) def __add__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __add__. """ other = self._check_allowed_dtypes(other, "numeric", "__add__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__add__(other._array) return self.__class__._new(res) def __and__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __and__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__and__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__and__(other._array) return self.__class__._new(res) def __array_namespace__( self: Array, /, *, api_version: Optional[str] = None ) -> types.ModuleType: if api_version is not None and not api_version.startswith("2021."): raise ValueError(f"Unrecognized array API version: {api_version!r}") return array_api def __bool__(self: Array, /) -> bool: """ Performs the operation __bool__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("bool is only allowed on arrays with 0 dimensions") if self.dtype not in _boolean_dtypes: raise ValueError("bool is only allowed on boolean arrays") res = self._array.__bool__() return res def __dlpack__(self: Array, /, *, stream: None = None) -> PyCapsule: """ Performs the operation __dlpack__. """ return self._array.__dlpack__(stream=stream) def __dlpack_device__(self: Array, /) -> Tuple[IntEnum, int]: """ Performs the operation __dlpack_device__. """ # Note: device support is required for this return self._array.__dlpack_device__() def __eq__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __eq__. """ # Even though "all" dtypes are allowed, we still require them to be # promotable with each other. other = self._check_allowed_dtypes(other, "all", "__eq__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__eq__(other._array) return self.__class__._new(res) def __float__(self: Array, /) -> float: """ Performs the operation __float__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("float is only allowed on arrays with 0 dimensions") if self.dtype not in _floating_dtypes: raise ValueError("float is only allowed on floating-point arrays") res = self._array.__float__() return res def __floordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __floordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__floordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__floordiv__(other._array) return self.__class__._new(res) def __ge__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ge__. """ other = self._check_allowed_dtypes(other, "numeric", "__ge__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ge__(other._array) return self.__class__._new(res) def __getitem__( self: Array, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], /, ) -> Array: """ Performs the operation __getitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array res = self._array.__getitem__(key) return self._new(res) def __gt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __gt__. """ other = self._check_allowed_dtypes(other, "numeric", "__gt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__gt__(other._array) return self.__class__._new(res) def __int__(self: Array, /) -> int: """ Performs the operation __int__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("int is only allowed on arrays with 0 dimensions") if self.dtype not in _integer_dtypes: raise ValueError("int is only allowed on integer arrays") res = self._array.__int__() return res def __index__(self: Array, /) -> int: """ Performs the operation __index__. """ res = self._array.__index__() return res def __invert__(self: Array, /) -> Array: """ Performs the operation __invert__. """ if self.dtype not in _integer_or_boolean_dtypes: raise TypeError("Only integer or boolean dtypes are allowed in __invert__") res = self._array.__invert__() return self.__class__._new(res) def __le__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __le__. """ other = self._check_allowed_dtypes(other, "numeric", "__le__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__le__(other._array) return self.__class__._new(res) def __lshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __lshift__. """ other = self._check_allowed_dtypes(other, "integer", "__lshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lshift__(other._array) return self.__class__._new(res) def __lt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __lt__. """ other = self._check_allowed_dtypes(other, "numeric", "__lt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lt__(other._array) return self.__class__._new(res) def __matmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __matmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__matmul__") if other is NotImplemented: return other res = self._array.__matmul__(other._array) return self.__class__._new(res) def __mod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mod__. """ other = self._check_allowed_dtypes(other, "numeric", "__mod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mod__(other._array) return self.__class__._new(res) def __mul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mul__. """ other = self._check_allowed_dtypes(other, "numeric", "__mul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mul__(other._array) return self.__class__._new(res) def __ne__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __ne__. """ other = self._check_allowed_dtypes(other, "all", "__ne__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ne__(other._array) return self.__class__._new(res) def __neg__(self: Array, /) -> Array: """ Performs the operation __neg__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __neg__") res = self._array.__neg__() return self.__class__._new(res) def __or__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __or__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__or__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__or__(other._array) return self.__class__._new(res) def __pos__(self: Array, /) -> Array: """ Performs the operation __pos__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __pos__") res = self._array.__pos__() return self.__class__._new(res) def __pow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __pow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__pow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow type promotion rules for 0-d # arrays, so we use pow() here instead. return pow(self, other) def __rshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rshift__(other._array) return self.__class__._new(res) def __setitem__( self, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], value: Union[int, float, bool, Array], /, ) -> None: """ Performs the operation __setitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array self._array.__setitem__(key, asarray(value)._array) def __sub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __sub__. """ other = self._check_allowed_dtypes(other, "numeric", "__sub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__sub__(other._array) return self.__class__._new(res) # PEP 484 requires int to be a subtype of float, but __truediv__ should # not accept int. def __truediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __truediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__truediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__truediv__(other._array) return self.__class__._new(res) def __xor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __xor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__xor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__xor__(other._array) return self.__class__._new(res) def __iadd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __iadd__. """ other = self._check_allowed_dtypes(other, "numeric", "__iadd__") if other is NotImplemented: return other self._array.__iadd__(other._array) return self def __radd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __radd__. """ other = self._check_allowed_dtypes(other, "numeric", "__radd__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__radd__(other._array) return self.__class__._new(res) def __iand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __iand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__iand__") if other is NotImplemented: return other self._array.__iand__(other._array) return self def __rand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rand__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rand__(other._array) return self.__class__._new(res) def __ifloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ifloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__ifloordiv__") if other is NotImplemented: return other self._array.__ifloordiv__(other._array) return self def __rfloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rfloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__rfloordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rfloordiv__(other._array) return self.__class__._new(res) def __ilshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __ilshift__. """ other = self._check_allowed_dtypes(other, "integer", "__ilshift__") if other is NotImplemented: return other self._array.__ilshift__(other._array) return self def __rlshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rlshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rlshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rlshift__(other._array) return self.__class__._new(res) def __imatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __imatmul__. """ # Note: NumPy does not implement __imatmul__. # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__imatmul__") if other is NotImplemented: return other # __imatmul__ can only be allowed when it would not change the shape # of self. other_shape = other.shape if self.shape == () or other_shape == (): raise ValueError("@= requires at least one dimension") if len(other_shape) == 1 or other_shape[-1] != other_shape[-2]: raise ValueError("@= cannot change the shape of the input array") self._array[:] = self._array.__matmul__(other._array) return self def __rmatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __rmatmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__rmatmul__") if other is NotImplemented: return other res = self._array.__rmatmul__(other._array) return self.__class__._new(res) def __imod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imod__. """ other = self._check_allowed_dtypes(other, "numeric", "__imod__") if other is NotImplemented: return other self._array.__imod__(other._array) return self def __rmod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmod__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmod__(other._array) return self.__class__._new(res) def __imul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imul__. """ other = self._check_allowed_dtypes(other, "numeric", "__imul__") if other is NotImplemented: return other self._array.__imul__(other._array) return self def __rmul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmul__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmul__(other._array) return self.__class__._new(res) def __ior__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ior__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ior__") if other is NotImplemented: return other self._array.__ior__(other._array) return self def __ror__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ror__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ror__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ror__(other._array) return self.__class__._new(res) def __ipow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ipow__. """ other = self._check_allowed_dtypes(other, "numeric", "__ipow__") if other is NotImplemented: return other self._array.__ipow__(other._array) return self def __rpow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rpow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__rpow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow the spec type promotion rules # for 0-d arrays, so we use pow() here instead. return pow(other, self) def __irshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __irshift__. """ other = self._check_allowed_dtypes(other, "integer", "__irshift__") if other is NotImplemented: return other self._array.__irshift__(other._array) return self def __rrshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rrshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rrshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rrshift__(other._array) return self.__class__._new(res) def __isub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __isub__. """ other = self._check_allowed_dtypes(other, "numeric", "__isub__") if other is NotImplemented: return other self._array.__isub__(other._array) return self def __rsub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rsub__. """ other = self._check_allowed_dtypes(other, "numeric", "__rsub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rsub__(other._array) return self.__class__._new(res) def __itruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __itruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__itruediv__") if other is NotImplemented: return other self._array.__itruediv__(other._array) return self def __rtruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __rtruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__rtruediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rtruediv__(other._array) return self.__class__._new(res) def __ixor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ixor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ixor__") if other is NotImplemented: return other self._array.__ixor__(other._array) return self def __rxor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rxor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rxor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rxor__(other._array) return self.__class__._new(res) def to_device(self: Array, device: Device, /, stream: None = None) -> Array: if stream is not None: raise ValueError("The stream argument to to_device() is not supported") if device == 'cpu': return self raise ValueError(f"Unsupported device {device!r}") def dtype(self) -> Dtype: """ Array API compatible wrapper for :py:meth:`np.ndarray.dtype <numpy.ndarray.dtype>`. See its docstring for more information. """ return self._array.dtype def device(self) -> Device: return "cpu" # Note: mT is new in array API spec (see matrix_transpose) def mT(self) -> Array: from .linalg import matrix_transpose return matrix_transpose(self) def ndim(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.ndim <numpy.ndarray.ndim>`. See its docstring for more information. """ return self._array.ndim def shape(self) -> Tuple[int, ...]: """ Array API compatible wrapper for :py:meth:`np.ndarray.shape <numpy.ndarray.shape>`. See its docstring for more information. """ return self._array.shape def size(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.size <numpy.ndarray.size>`. See its docstring for more information. """ return self._array.size def T(self) -> Array: """ Array API compatible wrapper for :py:meth:`np.ndarray.T <numpy.ndarray.T>`. See its docstring for more information. """ # Note: T only works on 2-dimensional arrays. See the corresponding # note in the specification: # https://data-apis.org/array-api/latest/API_specification/array_object.html#t if self.ndim != 2: raise ValueError("x.T requires x to have 2 dimensions. Use x.mT to transpose stacks of matrices and permute_dims() to permute dimensions.") return self.__class__._new(self._array.T) The provided code snippet includes necessary dependencies for implementing the `log` function. Write a Python function `def log(x: Array, /) -> Array` to solve the following problem: Array API compatible wrapper for :py:func:`np.log <numpy.log>`. See its docstring for more information. Here is the function: def log(x: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.log <numpy.log>`. See its docstring for more information. """ if x.dtype not in _floating_dtypes: raise TypeError("Only floating-point dtypes are allowed in log") return Array._new(np.log(x._array))
Array API compatible wrapper for :py:func:`np.log <numpy.log>`. See its docstring for more information.
170,051
from __future__ import annotations from ._dtypes import ( _boolean_dtypes, _floating_dtypes, _integer_dtypes, _integer_or_boolean_dtypes, _numeric_dtypes, _result_type, ) from ._array_object import Array import numpy as np _floating_dtypes = (float32, float64) class Array: """ n-d array object for the array API namespace. See the docstring of :py:obj:`np.ndarray <numpy.ndarray>` for more information. This is a wrapper around numpy.ndarray that restricts the usage to only those things that are required by the array API namespace. Note, attributes on this object that start with a single underscore are not part of the API specification and should only be used internally. This object should not be constructed directly. Rather, use one of the creation functions, such as asarray(). """ _array: np.ndarray # Use a custom constructor instead of __init__, as manually initializing # this class is not supported API. def _new(cls, x, /): """ This is a private method for initializing the array API Array object. Functions outside of the array_api submodule should not use this method. Use one of the creation functions instead, such as ``asarray``. """ obj = super().__new__(cls) # Note: The spec does not have array scalars, only 0-D arrays. if isinstance(x, np.generic): # Convert the array scalar to a 0-D array x = np.asarray(x) if x.dtype not in _all_dtypes: raise TypeError( f"The array_api namespace does not support the dtype '{x.dtype}'" ) obj._array = x return obj # Prevent Array() from working def __new__(cls, *args, **kwargs): raise TypeError( "The array_api Array object should not be instantiated directly. Use an array creation function, such as asarray(), instead." ) # These functions are not required by the spec, but are implemented for # the sake of usability. def __str__(self: Array, /) -> str: """ Performs the operation __str__. """ return self._array.__str__().replace("array", "Array") def __repr__(self: Array, /) -> str: """ Performs the operation __repr__. """ suffix = f", dtype={self.dtype.name})" if 0 in self.shape: prefix = "empty(" mid = str(self.shape) else: prefix = "Array(" mid = np.array2string(self._array, separator=', ', prefix=prefix, suffix=suffix) return prefix + mid + suffix # This function is not required by the spec, but we implement it here for # convenience so that np.asarray(np.array_api.Array) will work. def __array__(self, dtype: None | np.dtype[Any] = None) -> npt.NDArray[Any]: """ Warning: this method is NOT part of the array API spec. Implementers of other libraries need not include it, and users should not assume it will be present in other implementations. """ return np.asarray(self._array, dtype=dtype) # These are various helper functions to make the array behavior match the # spec in places where it either deviates from or is more strict than # NumPy behavior def _check_allowed_dtypes(self, other: bool | int | float | Array, dtype_category: str, op: str) -> Array: """ Helper function for operators to only allow specific input dtypes Use like other = self._check_allowed_dtypes(other, 'numeric', '__add__') if other is NotImplemented: return other """ if self.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") if isinstance(other, (int, float, bool)): other = self._promote_scalar(other) elif isinstance(other, Array): if other.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") else: return NotImplemented # This will raise TypeError for type combinations that are not allowed # to promote in the spec (even if the NumPy array operator would # promote them). res_dtype = _result_type(self.dtype, other.dtype) if op.startswith("__i"): # Note: NumPy will allow in-place operators in some cases where # the type promoted operator does not match the left-hand side # operand. For example, # >>> a = np.array(1, dtype=np.int8) # >>> a += np.array(1, dtype=np.int16) # The spec explicitly disallows this. if res_dtype != self.dtype: raise TypeError( f"Cannot perform {op} with dtypes {self.dtype} and {other.dtype}" ) return other # Helper function to match the type promotion rules in the spec def _promote_scalar(self, scalar): """ Returns a promoted version of a Python scalar appropriate for use with operations on self. This may raise an OverflowError in cases where the scalar is an integer that is too large to fit in a NumPy integer dtype, or TypeError when the scalar type is incompatible with the dtype of self. """ # Note: Only Python scalar types that match the array dtype are # allowed. if isinstance(scalar, bool): if self.dtype not in _boolean_dtypes: raise TypeError( "Python bool scalars can only be promoted with bool arrays" ) elif isinstance(scalar, int): if self.dtype in _boolean_dtypes: raise TypeError( "Python int scalars cannot be promoted with bool arrays" ) elif isinstance(scalar, float): if self.dtype not in _floating_dtypes: raise TypeError( "Python float scalars can only be promoted with floating-point arrays." ) else: raise TypeError("'scalar' must be a Python scalar") # Note: scalars are unconditionally cast to the same dtype as the # array. # Note: the spec only specifies integer-dtype/int promotion # behavior for integers within the bounds of the integer dtype. # Outside of those bounds we use the default NumPy behavior (either # cast or raise OverflowError). return Array._new(np.array(scalar, self.dtype)) def _normalize_two_args(x1, x2) -> Tuple[Array, Array]: """ Normalize inputs to two arg functions to fix type promotion rules NumPy deviates from the spec type promotion rules in cases where one argument is 0-dimensional and the other is not. For example: >>> import numpy as np >>> a = np.array([1.0], dtype=np.float32) >>> b = np.array(1.0, dtype=np.float64) >>> np.add(a, b) # The spec says this should be float64 array([2.], dtype=float32) To fix this, we add a dimension to the 0-dimension array before passing it through. This works because a dimension would be added anyway from broadcasting, so the resulting shape is the same, but this prevents NumPy from not promoting the dtype. """ # Another option would be to use signature=(x1.dtype, x2.dtype, None), # but that only works for ufuncs, so we would have to call the ufuncs # directly in the operator methods. One should also note that this # sort of trick wouldn't work for functions like searchsorted, which # don't do normal broadcasting, but there aren't any functions like # that in the array API namespace. if x1.ndim == 0 and x2.ndim != 0: # The _array[None] workaround was chosen because it is relatively # performant. broadcast_to(x1._array, x2.shape) is much slower. We # could also manually type promote x2, but that is more complicated # and about the same performance as this. x1 = Array._new(x1._array[None]) elif x2.ndim == 0 and x1.ndim != 0: x2 = Array._new(x2._array[None]) return (x1, x2) # Note: A large fraction of allowed indices are disallowed here (see the # docstring below) def _validate_index(self, key): """ Validate an index according to the array API. The array API specification only requires a subset of indices that are supported by NumPy. This function will reject any index that is allowed by NumPy but not required by the array API specification. We always raise ``IndexError`` on such indices (the spec does not require any specific behavior on them, but this makes the NumPy array API namespace a minimal implementation of the spec). See https://data-apis.org/array-api/latest/API_specification/indexing.html for the full list of required indexing behavior This function raises IndexError if the index ``key`` is invalid. It only raises ``IndexError`` on indices that are not already rejected by NumPy, as NumPy will already raise the appropriate error on such indices. ``shape`` may be None, in which case, only cases that are independent of the array shape are checked. The following cases are allowed by NumPy, but not specified by the array API specification: - Indices to not include an implicit ellipsis at the end. That is, every axis of an array must be explicitly indexed or an ellipsis included. This behaviour is sometimes referred to as flat indexing. - The start and stop of a slice may not be out of bounds. In particular, for a slice ``i:j:k`` on an axis of size ``n``, only the following are allowed: - ``i`` or ``j`` omitted (``None``). - ``-n <= i <= max(0, n - 1)``. - For ``k > 0`` or ``k`` omitted (``None``), ``-n <= j <= n``. - For ``k < 0``, ``-n - 1 <= j <= max(0, n - 1)``. - Boolean array indices are not allowed as part of a larger tuple index. - Integer array indices are not allowed (with the exception of 0-D arrays, which are treated the same as scalars). Additionally, it should be noted that indices that would return a scalar in NumPy will return a 0-D array. Array scalars are not allowed in the specification, only 0-D arrays. This is done in the ``Array._new`` constructor, not this function. """ _key = key if isinstance(key, tuple) else (key,) for i in _key: if isinstance(i, bool) or not ( isinstance(i, SupportsIndex) # i.e. ints or isinstance(i, slice) or i == Ellipsis or i is None or isinstance(i, Array) or isinstance(i, np.ndarray) ): raise IndexError( f"Single-axes index {i} has {type(i)=}, but only " "integers, slices (:), ellipsis (...), newaxis (None), " "zero-dimensional integer arrays and boolean arrays " "are specified in the Array API." ) nonexpanding_key = [] single_axes = [] n_ellipsis = 0 key_has_mask = False for i in _key: if i is not None: nonexpanding_key.append(i) if isinstance(i, Array) or isinstance(i, np.ndarray): if i.dtype in _boolean_dtypes: key_has_mask = True single_axes.append(i) else: # i must not be an array here, to avoid elementwise equals if i == Ellipsis: n_ellipsis += 1 else: single_axes.append(i) n_single_axes = len(single_axes) if n_ellipsis > 1: return # handled by ndarray elif n_ellipsis == 0: # Note boolean masks must be the sole index, which we check for # later on. if not key_has_mask and n_single_axes < self.ndim: raise IndexError( f"{self.ndim=}, but the multi-axes index only specifies " f"{n_single_axes} dimensions. If this was intentional, " "add a trailing ellipsis (...) which expands into as many " "slices (:) as necessary - this is what np.ndarray arrays " "implicitly do, but such flat indexing behaviour is not " "specified in the Array API." ) if n_ellipsis == 0: indexed_shape = self.shape else: ellipsis_start = None for pos, i in enumerate(nonexpanding_key): if not (isinstance(i, Array) or isinstance(i, np.ndarray)): if i == Ellipsis: ellipsis_start = pos break assert ellipsis_start is not None # sanity check ellipsis_end = self.ndim - (n_single_axes - ellipsis_start) indexed_shape = ( self.shape[:ellipsis_start] + self.shape[ellipsis_end:] ) for i, side in zip(single_axes, indexed_shape): if isinstance(i, slice): if side == 0: f_range = "0 (or None)" else: f_range = f"between -{side} and {side - 1} (or None)" if i.start is not None: try: start = operator.index(i.start) except TypeError: pass # handled by ndarray else: if not (-side <= start <= side): raise IndexError( f"Slice {i} contains {start=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds starts are not specified in " "the Array API)" ) if i.stop is not None: try: stop = operator.index(i.stop) except TypeError: pass # handled by ndarray else: if not (-side <= stop <= side): raise IndexError( f"Slice {i} contains {stop=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds stops are not specified in " "the Array API)" ) elif isinstance(i, Array): if i.dtype in _boolean_dtypes and len(_key) != 1: assert isinstance(key, tuple) # sanity check raise IndexError( f"Single-axes index {i} is a boolean array and " f"{len(key)=}, but masking is only specified in the " "Array API when the array is the sole index." ) elif i.dtype in _integer_dtypes and i.ndim != 0: raise IndexError( f"Single-axes index {i} is a non-zero-dimensional " "integer array, but advanced integer indexing is not " "specified in the Array API." ) elif isinstance(i, tuple): raise IndexError( f"Single-axes index {i} is a tuple, but nested tuple " "indices are not specified in the Array API." ) # Everything below this line is required by the spec. def __abs__(self: Array, /) -> Array: """ Performs the operation __abs__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __abs__") res = self._array.__abs__() return self.__class__._new(res) def __add__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __add__. """ other = self._check_allowed_dtypes(other, "numeric", "__add__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__add__(other._array) return self.__class__._new(res) def __and__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __and__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__and__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__and__(other._array) return self.__class__._new(res) def __array_namespace__( self: Array, /, *, api_version: Optional[str] = None ) -> types.ModuleType: if api_version is not None and not api_version.startswith("2021."): raise ValueError(f"Unrecognized array API version: {api_version!r}") return array_api def __bool__(self: Array, /) -> bool: """ Performs the operation __bool__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("bool is only allowed on arrays with 0 dimensions") if self.dtype not in _boolean_dtypes: raise ValueError("bool is only allowed on boolean arrays") res = self._array.__bool__() return res def __dlpack__(self: Array, /, *, stream: None = None) -> PyCapsule: """ Performs the operation __dlpack__. """ return self._array.__dlpack__(stream=stream) def __dlpack_device__(self: Array, /) -> Tuple[IntEnum, int]: """ Performs the operation __dlpack_device__. """ # Note: device support is required for this return self._array.__dlpack_device__() def __eq__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __eq__. """ # Even though "all" dtypes are allowed, we still require them to be # promotable with each other. other = self._check_allowed_dtypes(other, "all", "__eq__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__eq__(other._array) return self.__class__._new(res) def __float__(self: Array, /) -> float: """ Performs the operation __float__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("float is only allowed on arrays with 0 dimensions") if self.dtype not in _floating_dtypes: raise ValueError("float is only allowed on floating-point arrays") res = self._array.__float__() return res def __floordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __floordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__floordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__floordiv__(other._array) return self.__class__._new(res) def __ge__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ge__. """ other = self._check_allowed_dtypes(other, "numeric", "__ge__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ge__(other._array) return self.__class__._new(res) def __getitem__( self: Array, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], /, ) -> Array: """ Performs the operation __getitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array res = self._array.__getitem__(key) return self._new(res) def __gt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __gt__. """ other = self._check_allowed_dtypes(other, "numeric", "__gt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__gt__(other._array) return self.__class__._new(res) def __int__(self: Array, /) -> int: """ Performs the operation __int__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("int is only allowed on arrays with 0 dimensions") if self.dtype not in _integer_dtypes: raise ValueError("int is only allowed on integer arrays") res = self._array.__int__() return res def __index__(self: Array, /) -> int: """ Performs the operation __index__. """ res = self._array.__index__() return res def __invert__(self: Array, /) -> Array: """ Performs the operation __invert__. """ if self.dtype not in _integer_or_boolean_dtypes: raise TypeError("Only integer or boolean dtypes are allowed in __invert__") res = self._array.__invert__() return self.__class__._new(res) def __le__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __le__. """ other = self._check_allowed_dtypes(other, "numeric", "__le__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__le__(other._array) return self.__class__._new(res) def __lshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __lshift__. """ other = self._check_allowed_dtypes(other, "integer", "__lshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lshift__(other._array) return self.__class__._new(res) def __lt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __lt__. """ other = self._check_allowed_dtypes(other, "numeric", "__lt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lt__(other._array) return self.__class__._new(res) def __matmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __matmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__matmul__") if other is NotImplemented: return other res = self._array.__matmul__(other._array) return self.__class__._new(res) def __mod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mod__. """ other = self._check_allowed_dtypes(other, "numeric", "__mod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mod__(other._array) return self.__class__._new(res) def __mul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mul__. """ other = self._check_allowed_dtypes(other, "numeric", "__mul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mul__(other._array) return self.__class__._new(res) def __ne__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __ne__. """ other = self._check_allowed_dtypes(other, "all", "__ne__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ne__(other._array) return self.__class__._new(res) def __neg__(self: Array, /) -> Array: """ Performs the operation __neg__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __neg__") res = self._array.__neg__() return self.__class__._new(res) def __or__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __or__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__or__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__or__(other._array) return self.__class__._new(res) def __pos__(self: Array, /) -> Array: """ Performs the operation __pos__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __pos__") res = self._array.__pos__() return self.__class__._new(res) def __pow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __pow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__pow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow type promotion rules for 0-d # arrays, so we use pow() here instead. return pow(self, other) def __rshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rshift__(other._array) return self.__class__._new(res) def __setitem__( self, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], value: Union[int, float, bool, Array], /, ) -> None: """ Performs the operation __setitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array self._array.__setitem__(key, asarray(value)._array) def __sub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __sub__. """ other = self._check_allowed_dtypes(other, "numeric", "__sub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__sub__(other._array) return self.__class__._new(res) # PEP 484 requires int to be a subtype of float, but __truediv__ should # not accept int. def __truediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __truediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__truediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__truediv__(other._array) return self.__class__._new(res) def __xor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __xor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__xor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__xor__(other._array) return self.__class__._new(res) def __iadd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __iadd__. """ other = self._check_allowed_dtypes(other, "numeric", "__iadd__") if other is NotImplemented: return other self._array.__iadd__(other._array) return self def __radd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __radd__. """ other = self._check_allowed_dtypes(other, "numeric", "__radd__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__radd__(other._array) return self.__class__._new(res) def __iand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __iand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__iand__") if other is NotImplemented: return other self._array.__iand__(other._array) return self def __rand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rand__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rand__(other._array) return self.__class__._new(res) def __ifloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ifloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__ifloordiv__") if other is NotImplemented: return other self._array.__ifloordiv__(other._array) return self def __rfloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rfloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__rfloordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rfloordiv__(other._array) return self.__class__._new(res) def __ilshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __ilshift__. """ other = self._check_allowed_dtypes(other, "integer", "__ilshift__") if other is NotImplemented: return other self._array.__ilshift__(other._array) return self def __rlshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rlshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rlshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rlshift__(other._array) return self.__class__._new(res) def __imatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __imatmul__. """ # Note: NumPy does not implement __imatmul__. # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__imatmul__") if other is NotImplemented: return other # __imatmul__ can only be allowed when it would not change the shape # of self. other_shape = other.shape if self.shape == () or other_shape == (): raise ValueError("@= requires at least one dimension") if len(other_shape) == 1 or other_shape[-1] != other_shape[-2]: raise ValueError("@= cannot change the shape of the input array") self._array[:] = self._array.__matmul__(other._array) return self def __rmatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __rmatmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__rmatmul__") if other is NotImplemented: return other res = self._array.__rmatmul__(other._array) return self.__class__._new(res) def __imod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imod__. """ other = self._check_allowed_dtypes(other, "numeric", "__imod__") if other is NotImplemented: return other self._array.__imod__(other._array) return self def __rmod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmod__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmod__(other._array) return self.__class__._new(res) def __imul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imul__. """ other = self._check_allowed_dtypes(other, "numeric", "__imul__") if other is NotImplemented: return other self._array.__imul__(other._array) return self def __rmul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmul__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmul__(other._array) return self.__class__._new(res) def __ior__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ior__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ior__") if other is NotImplemented: return other self._array.__ior__(other._array) return self def __ror__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ror__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ror__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ror__(other._array) return self.__class__._new(res) def __ipow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ipow__. """ other = self._check_allowed_dtypes(other, "numeric", "__ipow__") if other is NotImplemented: return other self._array.__ipow__(other._array) return self def __rpow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rpow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__rpow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow the spec type promotion rules # for 0-d arrays, so we use pow() here instead. return pow(other, self) def __irshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __irshift__. """ other = self._check_allowed_dtypes(other, "integer", "__irshift__") if other is NotImplemented: return other self._array.__irshift__(other._array) return self def __rrshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rrshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rrshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rrshift__(other._array) return self.__class__._new(res) def __isub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __isub__. """ other = self._check_allowed_dtypes(other, "numeric", "__isub__") if other is NotImplemented: return other self._array.__isub__(other._array) return self def __rsub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rsub__. """ other = self._check_allowed_dtypes(other, "numeric", "__rsub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rsub__(other._array) return self.__class__._new(res) def __itruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __itruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__itruediv__") if other is NotImplemented: return other self._array.__itruediv__(other._array) return self def __rtruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __rtruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__rtruediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rtruediv__(other._array) return self.__class__._new(res) def __ixor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ixor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ixor__") if other is NotImplemented: return other self._array.__ixor__(other._array) return self def __rxor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rxor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rxor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rxor__(other._array) return self.__class__._new(res) def to_device(self: Array, device: Device, /, stream: None = None) -> Array: if stream is not None: raise ValueError("The stream argument to to_device() is not supported") if device == 'cpu': return self raise ValueError(f"Unsupported device {device!r}") def dtype(self) -> Dtype: """ Array API compatible wrapper for :py:meth:`np.ndarray.dtype <numpy.ndarray.dtype>`. See its docstring for more information. """ return self._array.dtype def device(self) -> Device: return "cpu" # Note: mT is new in array API spec (see matrix_transpose) def mT(self) -> Array: from .linalg import matrix_transpose return matrix_transpose(self) def ndim(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.ndim <numpy.ndarray.ndim>`. See its docstring for more information. """ return self._array.ndim def shape(self) -> Tuple[int, ...]: """ Array API compatible wrapper for :py:meth:`np.ndarray.shape <numpy.ndarray.shape>`. See its docstring for more information. """ return self._array.shape def size(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.size <numpy.ndarray.size>`. See its docstring for more information. """ return self._array.size def T(self) -> Array: """ Array API compatible wrapper for :py:meth:`np.ndarray.T <numpy.ndarray.T>`. See its docstring for more information. """ # Note: T only works on 2-dimensional arrays. See the corresponding # note in the specification: # https://data-apis.org/array-api/latest/API_specification/array_object.html#t if self.ndim != 2: raise ValueError("x.T requires x to have 2 dimensions. Use x.mT to transpose stacks of matrices and permute_dims() to permute dimensions.") return self.__class__._new(self._array.T) The provided code snippet includes necessary dependencies for implementing the `log1p` function. Write a Python function `def log1p(x: Array, /) -> Array` to solve the following problem: Array API compatible wrapper for :py:func:`np.log1p <numpy.log1p>`. See its docstring for more information. Here is the function: def log1p(x: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.log1p <numpy.log1p>`. See its docstring for more information. """ if x.dtype not in _floating_dtypes: raise TypeError("Only floating-point dtypes are allowed in log1p") return Array._new(np.log1p(x._array))
Array API compatible wrapper for :py:func:`np.log1p <numpy.log1p>`. See its docstring for more information.
170,052
from __future__ import annotations from ._dtypes import ( _boolean_dtypes, _floating_dtypes, _integer_dtypes, _integer_or_boolean_dtypes, _numeric_dtypes, _result_type, ) from ._array_object import Array import numpy as np _floating_dtypes = (float32, float64) class Array: """ n-d array object for the array API namespace. See the docstring of :py:obj:`np.ndarray <numpy.ndarray>` for more information. This is a wrapper around numpy.ndarray that restricts the usage to only those things that are required by the array API namespace. Note, attributes on this object that start with a single underscore are not part of the API specification and should only be used internally. This object should not be constructed directly. Rather, use one of the creation functions, such as asarray(). """ _array: np.ndarray # Use a custom constructor instead of __init__, as manually initializing # this class is not supported API. def _new(cls, x, /): """ This is a private method for initializing the array API Array object. Functions outside of the array_api submodule should not use this method. Use one of the creation functions instead, such as ``asarray``. """ obj = super().__new__(cls) # Note: The spec does not have array scalars, only 0-D arrays. if isinstance(x, np.generic): # Convert the array scalar to a 0-D array x = np.asarray(x) if x.dtype not in _all_dtypes: raise TypeError( f"The array_api namespace does not support the dtype '{x.dtype}'" ) obj._array = x return obj # Prevent Array() from working def __new__(cls, *args, **kwargs): raise TypeError( "The array_api Array object should not be instantiated directly. Use an array creation function, such as asarray(), instead." ) # These functions are not required by the spec, but are implemented for # the sake of usability. def __str__(self: Array, /) -> str: """ Performs the operation __str__. """ return self._array.__str__().replace("array", "Array") def __repr__(self: Array, /) -> str: """ Performs the operation __repr__. """ suffix = f", dtype={self.dtype.name})" if 0 in self.shape: prefix = "empty(" mid = str(self.shape) else: prefix = "Array(" mid = np.array2string(self._array, separator=', ', prefix=prefix, suffix=suffix) return prefix + mid + suffix # This function is not required by the spec, but we implement it here for # convenience so that np.asarray(np.array_api.Array) will work. def __array__(self, dtype: None | np.dtype[Any] = None) -> npt.NDArray[Any]: """ Warning: this method is NOT part of the array API spec. Implementers of other libraries need not include it, and users should not assume it will be present in other implementations. """ return np.asarray(self._array, dtype=dtype) # These are various helper functions to make the array behavior match the # spec in places where it either deviates from or is more strict than # NumPy behavior def _check_allowed_dtypes(self, other: bool | int | float | Array, dtype_category: str, op: str) -> Array: """ Helper function for operators to only allow specific input dtypes Use like other = self._check_allowed_dtypes(other, 'numeric', '__add__') if other is NotImplemented: return other """ if self.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") if isinstance(other, (int, float, bool)): other = self._promote_scalar(other) elif isinstance(other, Array): if other.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") else: return NotImplemented # This will raise TypeError for type combinations that are not allowed # to promote in the spec (even if the NumPy array operator would # promote them). res_dtype = _result_type(self.dtype, other.dtype) if op.startswith("__i"): # Note: NumPy will allow in-place operators in some cases where # the type promoted operator does not match the left-hand side # operand. For example, # >>> a = np.array(1, dtype=np.int8) # >>> a += np.array(1, dtype=np.int16) # The spec explicitly disallows this. if res_dtype != self.dtype: raise TypeError( f"Cannot perform {op} with dtypes {self.dtype} and {other.dtype}" ) return other # Helper function to match the type promotion rules in the spec def _promote_scalar(self, scalar): """ Returns a promoted version of a Python scalar appropriate for use with operations on self. This may raise an OverflowError in cases where the scalar is an integer that is too large to fit in a NumPy integer dtype, or TypeError when the scalar type is incompatible with the dtype of self. """ # Note: Only Python scalar types that match the array dtype are # allowed. if isinstance(scalar, bool): if self.dtype not in _boolean_dtypes: raise TypeError( "Python bool scalars can only be promoted with bool arrays" ) elif isinstance(scalar, int): if self.dtype in _boolean_dtypes: raise TypeError( "Python int scalars cannot be promoted with bool arrays" ) elif isinstance(scalar, float): if self.dtype not in _floating_dtypes: raise TypeError( "Python float scalars can only be promoted with floating-point arrays." ) else: raise TypeError("'scalar' must be a Python scalar") # Note: scalars are unconditionally cast to the same dtype as the # array. # Note: the spec only specifies integer-dtype/int promotion # behavior for integers within the bounds of the integer dtype. # Outside of those bounds we use the default NumPy behavior (either # cast or raise OverflowError). return Array._new(np.array(scalar, self.dtype)) def _normalize_two_args(x1, x2) -> Tuple[Array, Array]: """ Normalize inputs to two arg functions to fix type promotion rules NumPy deviates from the spec type promotion rules in cases where one argument is 0-dimensional and the other is not. For example: >>> import numpy as np >>> a = np.array([1.0], dtype=np.float32) >>> b = np.array(1.0, dtype=np.float64) >>> np.add(a, b) # The spec says this should be float64 array([2.], dtype=float32) To fix this, we add a dimension to the 0-dimension array before passing it through. This works because a dimension would be added anyway from broadcasting, so the resulting shape is the same, but this prevents NumPy from not promoting the dtype. """ # Another option would be to use signature=(x1.dtype, x2.dtype, None), # but that only works for ufuncs, so we would have to call the ufuncs # directly in the operator methods. One should also note that this # sort of trick wouldn't work for functions like searchsorted, which # don't do normal broadcasting, but there aren't any functions like # that in the array API namespace. if x1.ndim == 0 and x2.ndim != 0: # The _array[None] workaround was chosen because it is relatively # performant. broadcast_to(x1._array, x2.shape) is much slower. We # could also manually type promote x2, but that is more complicated # and about the same performance as this. x1 = Array._new(x1._array[None]) elif x2.ndim == 0 and x1.ndim != 0: x2 = Array._new(x2._array[None]) return (x1, x2) # Note: A large fraction of allowed indices are disallowed here (see the # docstring below) def _validate_index(self, key): """ Validate an index according to the array API. The array API specification only requires a subset of indices that are supported by NumPy. This function will reject any index that is allowed by NumPy but not required by the array API specification. We always raise ``IndexError`` on such indices (the spec does not require any specific behavior on them, but this makes the NumPy array API namespace a minimal implementation of the spec). See https://data-apis.org/array-api/latest/API_specification/indexing.html for the full list of required indexing behavior This function raises IndexError if the index ``key`` is invalid. It only raises ``IndexError`` on indices that are not already rejected by NumPy, as NumPy will already raise the appropriate error on such indices. ``shape`` may be None, in which case, only cases that are independent of the array shape are checked. The following cases are allowed by NumPy, but not specified by the array API specification: - Indices to not include an implicit ellipsis at the end. That is, every axis of an array must be explicitly indexed or an ellipsis included. This behaviour is sometimes referred to as flat indexing. - The start and stop of a slice may not be out of bounds. In particular, for a slice ``i:j:k`` on an axis of size ``n``, only the following are allowed: - ``i`` or ``j`` omitted (``None``). - ``-n <= i <= max(0, n - 1)``. - For ``k > 0`` or ``k`` omitted (``None``), ``-n <= j <= n``. - For ``k < 0``, ``-n - 1 <= j <= max(0, n - 1)``. - Boolean array indices are not allowed as part of a larger tuple index. - Integer array indices are not allowed (with the exception of 0-D arrays, which are treated the same as scalars). Additionally, it should be noted that indices that would return a scalar in NumPy will return a 0-D array. Array scalars are not allowed in the specification, only 0-D arrays. This is done in the ``Array._new`` constructor, not this function. """ _key = key if isinstance(key, tuple) else (key,) for i in _key: if isinstance(i, bool) or not ( isinstance(i, SupportsIndex) # i.e. ints or isinstance(i, slice) or i == Ellipsis or i is None or isinstance(i, Array) or isinstance(i, np.ndarray) ): raise IndexError( f"Single-axes index {i} has {type(i)=}, but only " "integers, slices (:), ellipsis (...), newaxis (None), " "zero-dimensional integer arrays and boolean arrays " "are specified in the Array API." ) nonexpanding_key = [] single_axes = [] n_ellipsis = 0 key_has_mask = False for i in _key: if i is not None: nonexpanding_key.append(i) if isinstance(i, Array) or isinstance(i, np.ndarray): if i.dtype in _boolean_dtypes: key_has_mask = True single_axes.append(i) else: # i must not be an array here, to avoid elementwise equals if i == Ellipsis: n_ellipsis += 1 else: single_axes.append(i) n_single_axes = len(single_axes) if n_ellipsis > 1: return # handled by ndarray elif n_ellipsis == 0: # Note boolean masks must be the sole index, which we check for # later on. if not key_has_mask and n_single_axes < self.ndim: raise IndexError( f"{self.ndim=}, but the multi-axes index only specifies " f"{n_single_axes} dimensions. If this was intentional, " "add a trailing ellipsis (...) which expands into as many " "slices (:) as necessary - this is what np.ndarray arrays " "implicitly do, but such flat indexing behaviour is not " "specified in the Array API." ) if n_ellipsis == 0: indexed_shape = self.shape else: ellipsis_start = None for pos, i in enumerate(nonexpanding_key): if not (isinstance(i, Array) or isinstance(i, np.ndarray)): if i == Ellipsis: ellipsis_start = pos break assert ellipsis_start is not None # sanity check ellipsis_end = self.ndim - (n_single_axes - ellipsis_start) indexed_shape = ( self.shape[:ellipsis_start] + self.shape[ellipsis_end:] ) for i, side in zip(single_axes, indexed_shape): if isinstance(i, slice): if side == 0: f_range = "0 (or None)" else: f_range = f"between -{side} and {side - 1} (or None)" if i.start is not None: try: start = operator.index(i.start) except TypeError: pass # handled by ndarray else: if not (-side <= start <= side): raise IndexError( f"Slice {i} contains {start=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds starts are not specified in " "the Array API)" ) if i.stop is not None: try: stop = operator.index(i.stop) except TypeError: pass # handled by ndarray else: if not (-side <= stop <= side): raise IndexError( f"Slice {i} contains {stop=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds stops are not specified in " "the Array API)" ) elif isinstance(i, Array): if i.dtype in _boolean_dtypes and len(_key) != 1: assert isinstance(key, tuple) # sanity check raise IndexError( f"Single-axes index {i} is a boolean array and " f"{len(key)=}, but masking is only specified in the " "Array API when the array is the sole index." ) elif i.dtype in _integer_dtypes and i.ndim != 0: raise IndexError( f"Single-axes index {i} is a non-zero-dimensional " "integer array, but advanced integer indexing is not " "specified in the Array API." ) elif isinstance(i, tuple): raise IndexError( f"Single-axes index {i} is a tuple, but nested tuple " "indices are not specified in the Array API." ) # Everything below this line is required by the spec. def __abs__(self: Array, /) -> Array: """ Performs the operation __abs__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __abs__") res = self._array.__abs__() return self.__class__._new(res) def __add__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __add__. """ other = self._check_allowed_dtypes(other, "numeric", "__add__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__add__(other._array) return self.__class__._new(res) def __and__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __and__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__and__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__and__(other._array) return self.__class__._new(res) def __array_namespace__( self: Array, /, *, api_version: Optional[str] = None ) -> types.ModuleType: if api_version is not None and not api_version.startswith("2021."): raise ValueError(f"Unrecognized array API version: {api_version!r}") return array_api def __bool__(self: Array, /) -> bool: """ Performs the operation __bool__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("bool is only allowed on arrays with 0 dimensions") if self.dtype not in _boolean_dtypes: raise ValueError("bool is only allowed on boolean arrays") res = self._array.__bool__() return res def __dlpack__(self: Array, /, *, stream: None = None) -> PyCapsule: """ Performs the operation __dlpack__. """ return self._array.__dlpack__(stream=stream) def __dlpack_device__(self: Array, /) -> Tuple[IntEnum, int]: """ Performs the operation __dlpack_device__. """ # Note: device support is required for this return self._array.__dlpack_device__() def __eq__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __eq__. """ # Even though "all" dtypes are allowed, we still require them to be # promotable with each other. other = self._check_allowed_dtypes(other, "all", "__eq__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__eq__(other._array) return self.__class__._new(res) def __float__(self: Array, /) -> float: """ Performs the operation __float__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("float is only allowed on arrays with 0 dimensions") if self.dtype not in _floating_dtypes: raise ValueError("float is only allowed on floating-point arrays") res = self._array.__float__() return res def __floordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __floordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__floordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__floordiv__(other._array) return self.__class__._new(res) def __ge__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ge__. """ other = self._check_allowed_dtypes(other, "numeric", "__ge__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ge__(other._array) return self.__class__._new(res) def __getitem__( self: Array, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], /, ) -> Array: """ Performs the operation __getitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array res = self._array.__getitem__(key) return self._new(res) def __gt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __gt__. """ other = self._check_allowed_dtypes(other, "numeric", "__gt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__gt__(other._array) return self.__class__._new(res) def __int__(self: Array, /) -> int: """ Performs the operation __int__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("int is only allowed on arrays with 0 dimensions") if self.dtype not in _integer_dtypes: raise ValueError("int is only allowed on integer arrays") res = self._array.__int__() return res def __index__(self: Array, /) -> int: """ Performs the operation __index__. """ res = self._array.__index__() return res def __invert__(self: Array, /) -> Array: """ Performs the operation __invert__. """ if self.dtype not in _integer_or_boolean_dtypes: raise TypeError("Only integer or boolean dtypes are allowed in __invert__") res = self._array.__invert__() return self.__class__._new(res) def __le__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __le__. """ other = self._check_allowed_dtypes(other, "numeric", "__le__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__le__(other._array) return self.__class__._new(res) def __lshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __lshift__. """ other = self._check_allowed_dtypes(other, "integer", "__lshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lshift__(other._array) return self.__class__._new(res) def __lt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __lt__. """ other = self._check_allowed_dtypes(other, "numeric", "__lt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lt__(other._array) return self.__class__._new(res) def __matmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __matmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__matmul__") if other is NotImplemented: return other res = self._array.__matmul__(other._array) return self.__class__._new(res) def __mod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mod__. """ other = self._check_allowed_dtypes(other, "numeric", "__mod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mod__(other._array) return self.__class__._new(res) def __mul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mul__. """ other = self._check_allowed_dtypes(other, "numeric", "__mul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mul__(other._array) return self.__class__._new(res) def __ne__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __ne__. """ other = self._check_allowed_dtypes(other, "all", "__ne__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ne__(other._array) return self.__class__._new(res) def __neg__(self: Array, /) -> Array: """ Performs the operation __neg__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __neg__") res = self._array.__neg__() return self.__class__._new(res) def __or__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __or__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__or__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__or__(other._array) return self.__class__._new(res) def __pos__(self: Array, /) -> Array: """ Performs the operation __pos__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __pos__") res = self._array.__pos__() return self.__class__._new(res) def __pow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __pow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__pow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow type promotion rules for 0-d # arrays, so we use pow() here instead. return pow(self, other) def __rshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rshift__(other._array) return self.__class__._new(res) def __setitem__( self, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], value: Union[int, float, bool, Array], /, ) -> None: """ Performs the operation __setitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array self._array.__setitem__(key, asarray(value)._array) def __sub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __sub__. """ other = self._check_allowed_dtypes(other, "numeric", "__sub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__sub__(other._array) return self.__class__._new(res) # PEP 484 requires int to be a subtype of float, but __truediv__ should # not accept int. def __truediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __truediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__truediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__truediv__(other._array) return self.__class__._new(res) def __xor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __xor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__xor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__xor__(other._array) return self.__class__._new(res) def __iadd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __iadd__. """ other = self._check_allowed_dtypes(other, "numeric", "__iadd__") if other is NotImplemented: return other self._array.__iadd__(other._array) return self def __radd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __radd__. """ other = self._check_allowed_dtypes(other, "numeric", "__radd__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__radd__(other._array) return self.__class__._new(res) def __iand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __iand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__iand__") if other is NotImplemented: return other self._array.__iand__(other._array) return self def __rand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rand__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rand__(other._array) return self.__class__._new(res) def __ifloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ifloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__ifloordiv__") if other is NotImplemented: return other self._array.__ifloordiv__(other._array) return self def __rfloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rfloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__rfloordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rfloordiv__(other._array) return self.__class__._new(res) def __ilshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __ilshift__. """ other = self._check_allowed_dtypes(other, "integer", "__ilshift__") if other is NotImplemented: return other self._array.__ilshift__(other._array) return self def __rlshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rlshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rlshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rlshift__(other._array) return self.__class__._new(res) def __imatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __imatmul__. """ # Note: NumPy does not implement __imatmul__. # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__imatmul__") if other is NotImplemented: return other # __imatmul__ can only be allowed when it would not change the shape # of self. other_shape = other.shape if self.shape == () or other_shape == (): raise ValueError("@= requires at least one dimension") if len(other_shape) == 1 or other_shape[-1] != other_shape[-2]: raise ValueError("@= cannot change the shape of the input array") self._array[:] = self._array.__matmul__(other._array) return self def __rmatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __rmatmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__rmatmul__") if other is NotImplemented: return other res = self._array.__rmatmul__(other._array) return self.__class__._new(res) def __imod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imod__. """ other = self._check_allowed_dtypes(other, "numeric", "__imod__") if other is NotImplemented: return other self._array.__imod__(other._array) return self def __rmod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmod__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmod__(other._array) return self.__class__._new(res) def __imul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imul__. """ other = self._check_allowed_dtypes(other, "numeric", "__imul__") if other is NotImplemented: return other self._array.__imul__(other._array) return self def __rmul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmul__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmul__(other._array) return self.__class__._new(res) def __ior__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ior__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ior__") if other is NotImplemented: return other self._array.__ior__(other._array) return self def __ror__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ror__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ror__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ror__(other._array) return self.__class__._new(res) def __ipow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ipow__. """ other = self._check_allowed_dtypes(other, "numeric", "__ipow__") if other is NotImplemented: return other self._array.__ipow__(other._array) return self def __rpow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rpow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__rpow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow the spec type promotion rules # for 0-d arrays, so we use pow() here instead. return pow(other, self) def __irshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __irshift__. """ other = self._check_allowed_dtypes(other, "integer", "__irshift__") if other is NotImplemented: return other self._array.__irshift__(other._array) return self def __rrshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rrshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rrshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rrshift__(other._array) return self.__class__._new(res) def __isub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __isub__. """ other = self._check_allowed_dtypes(other, "numeric", "__isub__") if other is NotImplemented: return other self._array.__isub__(other._array) return self def __rsub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rsub__. """ other = self._check_allowed_dtypes(other, "numeric", "__rsub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rsub__(other._array) return self.__class__._new(res) def __itruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __itruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__itruediv__") if other is NotImplemented: return other self._array.__itruediv__(other._array) return self def __rtruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __rtruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__rtruediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rtruediv__(other._array) return self.__class__._new(res) def __ixor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ixor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ixor__") if other is NotImplemented: return other self._array.__ixor__(other._array) return self def __rxor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rxor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rxor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rxor__(other._array) return self.__class__._new(res) def to_device(self: Array, device: Device, /, stream: None = None) -> Array: if stream is not None: raise ValueError("The stream argument to to_device() is not supported") if device == 'cpu': return self raise ValueError(f"Unsupported device {device!r}") def dtype(self) -> Dtype: """ Array API compatible wrapper for :py:meth:`np.ndarray.dtype <numpy.ndarray.dtype>`. See its docstring for more information. """ return self._array.dtype def device(self) -> Device: return "cpu" # Note: mT is new in array API spec (see matrix_transpose) def mT(self) -> Array: from .linalg import matrix_transpose return matrix_transpose(self) def ndim(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.ndim <numpy.ndarray.ndim>`. See its docstring for more information. """ return self._array.ndim def shape(self) -> Tuple[int, ...]: """ Array API compatible wrapper for :py:meth:`np.ndarray.shape <numpy.ndarray.shape>`. See its docstring for more information. """ return self._array.shape def size(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.size <numpy.ndarray.size>`. See its docstring for more information. """ return self._array.size def T(self) -> Array: """ Array API compatible wrapper for :py:meth:`np.ndarray.T <numpy.ndarray.T>`. See its docstring for more information. """ # Note: T only works on 2-dimensional arrays. See the corresponding # note in the specification: # https://data-apis.org/array-api/latest/API_specification/array_object.html#t if self.ndim != 2: raise ValueError("x.T requires x to have 2 dimensions. Use x.mT to transpose stacks of matrices and permute_dims() to permute dimensions.") return self.__class__._new(self._array.T) The provided code snippet includes necessary dependencies for implementing the `log2` function. Write a Python function `def log2(x: Array, /) -> Array` to solve the following problem: Array API compatible wrapper for :py:func:`np.log2 <numpy.log2>`. See its docstring for more information. Here is the function: def log2(x: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.log2 <numpy.log2>`. See its docstring for more information. """ if x.dtype not in _floating_dtypes: raise TypeError("Only floating-point dtypes are allowed in log2") return Array._new(np.log2(x._array))
Array API compatible wrapper for :py:func:`np.log2 <numpy.log2>`. See its docstring for more information.
170,053
from __future__ import annotations from ._dtypes import ( _boolean_dtypes, _floating_dtypes, _integer_dtypes, _integer_or_boolean_dtypes, _numeric_dtypes, _result_type, ) from ._array_object import Array import numpy as np _floating_dtypes = (float32, float64) class Array: """ n-d array object for the array API namespace. See the docstring of :py:obj:`np.ndarray <numpy.ndarray>` for more information. This is a wrapper around numpy.ndarray that restricts the usage to only those things that are required by the array API namespace. Note, attributes on this object that start with a single underscore are not part of the API specification and should only be used internally. This object should not be constructed directly. Rather, use one of the creation functions, such as asarray(). """ _array: np.ndarray # Use a custom constructor instead of __init__, as manually initializing # this class is not supported API. def _new(cls, x, /): """ This is a private method for initializing the array API Array object. Functions outside of the array_api submodule should not use this method. Use one of the creation functions instead, such as ``asarray``. """ obj = super().__new__(cls) # Note: The spec does not have array scalars, only 0-D arrays. if isinstance(x, np.generic): # Convert the array scalar to a 0-D array x = np.asarray(x) if x.dtype not in _all_dtypes: raise TypeError( f"The array_api namespace does not support the dtype '{x.dtype}'" ) obj._array = x return obj # Prevent Array() from working def __new__(cls, *args, **kwargs): raise TypeError( "The array_api Array object should not be instantiated directly. Use an array creation function, such as asarray(), instead." ) # These functions are not required by the spec, but are implemented for # the sake of usability. def __str__(self: Array, /) -> str: """ Performs the operation __str__. """ return self._array.__str__().replace("array", "Array") def __repr__(self: Array, /) -> str: """ Performs the operation __repr__. """ suffix = f", dtype={self.dtype.name})" if 0 in self.shape: prefix = "empty(" mid = str(self.shape) else: prefix = "Array(" mid = np.array2string(self._array, separator=', ', prefix=prefix, suffix=suffix) return prefix + mid + suffix # This function is not required by the spec, but we implement it here for # convenience so that np.asarray(np.array_api.Array) will work. def __array__(self, dtype: None | np.dtype[Any] = None) -> npt.NDArray[Any]: """ Warning: this method is NOT part of the array API spec. Implementers of other libraries need not include it, and users should not assume it will be present in other implementations. """ return np.asarray(self._array, dtype=dtype) # These are various helper functions to make the array behavior match the # spec in places where it either deviates from or is more strict than # NumPy behavior def _check_allowed_dtypes(self, other: bool | int | float | Array, dtype_category: str, op: str) -> Array: """ Helper function for operators to only allow specific input dtypes Use like other = self._check_allowed_dtypes(other, 'numeric', '__add__') if other is NotImplemented: return other """ if self.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") if isinstance(other, (int, float, bool)): other = self._promote_scalar(other) elif isinstance(other, Array): if other.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") else: return NotImplemented # This will raise TypeError for type combinations that are not allowed # to promote in the spec (even if the NumPy array operator would # promote them). res_dtype = _result_type(self.dtype, other.dtype) if op.startswith("__i"): # Note: NumPy will allow in-place operators in some cases where # the type promoted operator does not match the left-hand side # operand. For example, # >>> a = np.array(1, dtype=np.int8) # >>> a += np.array(1, dtype=np.int16) # The spec explicitly disallows this. if res_dtype != self.dtype: raise TypeError( f"Cannot perform {op} with dtypes {self.dtype} and {other.dtype}" ) return other # Helper function to match the type promotion rules in the spec def _promote_scalar(self, scalar): """ Returns a promoted version of a Python scalar appropriate for use with operations on self. This may raise an OverflowError in cases where the scalar is an integer that is too large to fit in a NumPy integer dtype, or TypeError when the scalar type is incompatible with the dtype of self. """ # Note: Only Python scalar types that match the array dtype are # allowed. if isinstance(scalar, bool): if self.dtype not in _boolean_dtypes: raise TypeError( "Python bool scalars can only be promoted with bool arrays" ) elif isinstance(scalar, int): if self.dtype in _boolean_dtypes: raise TypeError( "Python int scalars cannot be promoted with bool arrays" ) elif isinstance(scalar, float): if self.dtype not in _floating_dtypes: raise TypeError( "Python float scalars can only be promoted with floating-point arrays." ) else: raise TypeError("'scalar' must be a Python scalar") # Note: scalars are unconditionally cast to the same dtype as the # array. # Note: the spec only specifies integer-dtype/int promotion # behavior for integers within the bounds of the integer dtype. # Outside of those bounds we use the default NumPy behavior (either # cast or raise OverflowError). return Array._new(np.array(scalar, self.dtype)) def _normalize_two_args(x1, x2) -> Tuple[Array, Array]: """ Normalize inputs to two arg functions to fix type promotion rules NumPy deviates from the spec type promotion rules in cases where one argument is 0-dimensional and the other is not. For example: >>> import numpy as np >>> a = np.array([1.0], dtype=np.float32) >>> b = np.array(1.0, dtype=np.float64) >>> np.add(a, b) # The spec says this should be float64 array([2.], dtype=float32) To fix this, we add a dimension to the 0-dimension array before passing it through. This works because a dimension would be added anyway from broadcasting, so the resulting shape is the same, but this prevents NumPy from not promoting the dtype. """ # Another option would be to use signature=(x1.dtype, x2.dtype, None), # but that only works for ufuncs, so we would have to call the ufuncs # directly in the operator methods. One should also note that this # sort of trick wouldn't work for functions like searchsorted, which # don't do normal broadcasting, but there aren't any functions like # that in the array API namespace. if x1.ndim == 0 and x2.ndim != 0: # The _array[None] workaround was chosen because it is relatively # performant. broadcast_to(x1._array, x2.shape) is much slower. We # could also manually type promote x2, but that is more complicated # and about the same performance as this. x1 = Array._new(x1._array[None]) elif x2.ndim == 0 and x1.ndim != 0: x2 = Array._new(x2._array[None]) return (x1, x2) # Note: A large fraction of allowed indices are disallowed here (see the # docstring below) def _validate_index(self, key): """ Validate an index according to the array API. The array API specification only requires a subset of indices that are supported by NumPy. This function will reject any index that is allowed by NumPy but not required by the array API specification. We always raise ``IndexError`` on such indices (the spec does not require any specific behavior on them, but this makes the NumPy array API namespace a minimal implementation of the spec). See https://data-apis.org/array-api/latest/API_specification/indexing.html for the full list of required indexing behavior This function raises IndexError if the index ``key`` is invalid. It only raises ``IndexError`` on indices that are not already rejected by NumPy, as NumPy will already raise the appropriate error on such indices. ``shape`` may be None, in which case, only cases that are independent of the array shape are checked. The following cases are allowed by NumPy, but not specified by the array API specification: - Indices to not include an implicit ellipsis at the end. That is, every axis of an array must be explicitly indexed or an ellipsis included. This behaviour is sometimes referred to as flat indexing. - The start and stop of a slice may not be out of bounds. In particular, for a slice ``i:j:k`` on an axis of size ``n``, only the following are allowed: - ``i`` or ``j`` omitted (``None``). - ``-n <= i <= max(0, n - 1)``. - For ``k > 0`` or ``k`` omitted (``None``), ``-n <= j <= n``. - For ``k < 0``, ``-n - 1 <= j <= max(0, n - 1)``. - Boolean array indices are not allowed as part of a larger tuple index. - Integer array indices are not allowed (with the exception of 0-D arrays, which are treated the same as scalars). Additionally, it should be noted that indices that would return a scalar in NumPy will return a 0-D array. Array scalars are not allowed in the specification, only 0-D arrays. This is done in the ``Array._new`` constructor, not this function. """ _key = key if isinstance(key, tuple) else (key,) for i in _key: if isinstance(i, bool) or not ( isinstance(i, SupportsIndex) # i.e. ints or isinstance(i, slice) or i == Ellipsis or i is None or isinstance(i, Array) or isinstance(i, np.ndarray) ): raise IndexError( f"Single-axes index {i} has {type(i)=}, but only " "integers, slices (:), ellipsis (...), newaxis (None), " "zero-dimensional integer arrays and boolean arrays " "are specified in the Array API." ) nonexpanding_key = [] single_axes = [] n_ellipsis = 0 key_has_mask = False for i in _key: if i is not None: nonexpanding_key.append(i) if isinstance(i, Array) or isinstance(i, np.ndarray): if i.dtype in _boolean_dtypes: key_has_mask = True single_axes.append(i) else: # i must not be an array here, to avoid elementwise equals if i == Ellipsis: n_ellipsis += 1 else: single_axes.append(i) n_single_axes = len(single_axes) if n_ellipsis > 1: return # handled by ndarray elif n_ellipsis == 0: # Note boolean masks must be the sole index, which we check for # later on. if not key_has_mask and n_single_axes < self.ndim: raise IndexError( f"{self.ndim=}, but the multi-axes index only specifies " f"{n_single_axes} dimensions. If this was intentional, " "add a trailing ellipsis (...) which expands into as many " "slices (:) as necessary - this is what np.ndarray arrays " "implicitly do, but such flat indexing behaviour is not " "specified in the Array API." ) if n_ellipsis == 0: indexed_shape = self.shape else: ellipsis_start = None for pos, i in enumerate(nonexpanding_key): if not (isinstance(i, Array) or isinstance(i, np.ndarray)): if i == Ellipsis: ellipsis_start = pos break assert ellipsis_start is not None # sanity check ellipsis_end = self.ndim - (n_single_axes - ellipsis_start) indexed_shape = ( self.shape[:ellipsis_start] + self.shape[ellipsis_end:] ) for i, side in zip(single_axes, indexed_shape): if isinstance(i, slice): if side == 0: f_range = "0 (or None)" else: f_range = f"between -{side} and {side - 1} (or None)" if i.start is not None: try: start = operator.index(i.start) except TypeError: pass # handled by ndarray else: if not (-side <= start <= side): raise IndexError( f"Slice {i} contains {start=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds starts are not specified in " "the Array API)" ) if i.stop is not None: try: stop = operator.index(i.stop) except TypeError: pass # handled by ndarray else: if not (-side <= stop <= side): raise IndexError( f"Slice {i} contains {stop=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds stops are not specified in " "the Array API)" ) elif isinstance(i, Array): if i.dtype in _boolean_dtypes and len(_key) != 1: assert isinstance(key, tuple) # sanity check raise IndexError( f"Single-axes index {i} is a boolean array and " f"{len(key)=}, but masking is only specified in the " "Array API when the array is the sole index." ) elif i.dtype in _integer_dtypes and i.ndim != 0: raise IndexError( f"Single-axes index {i} is a non-zero-dimensional " "integer array, but advanced integer indexing is not " "specified in the Array API." ) elif isinstance(i, tuple): raise IndexError( f"Single-axes index {i} is a tuple, but nested tuple " "indices are not specified in the Array API." ) # Everything below this line is required by the spec. def __abs__(self: Array, /) -> Array: """ Performs the operation __abs__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __abs__") res = self._array.__abs__() return self.__class__._new(res) def __add__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __add__. """ other = self._check_allowed_dtypes(other, "numeric", "__add__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__add__(other._array) return self.__class__._new(res) def __and__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __and__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__and__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__and__(other._array) return self.__class__._new(res) def __array_namespace__( self: Array, /, *, api_version: Optional[str] = None ) -> types.ModuleType: if api_version is not None and not api_version.startswith("2021."): raise ValueError(f"Unrecognized array API version: {api_version!r}") return array_api def __bool__(self: Array, /) -> bool: """ Performs the operation __bool__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("bool is only allowed on arrays with 0 dimensions") if self.dtype not in _boolean_dtypes: raise ValueError("bool is only allowed on boolean arrays") res = self._array.__bool__() return res def __dlpack__(self: Array, /, *, stream: None = None) -> PyCapsule: """ Performs the operation __dlpack__. """ return self._array.__dlpack__(stream=stream) def __dlpack_device__(self: Array, /) -> Tuple[IntEnum, int]: """ Performs the operation __dlpack_device__. """ # Note: device support is required for this return self._array.__dlpack_device__() def __eq__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __eq__. """ # Even though "all" dtypes are allowed, we still require them to be # promotable with each other. other = self._check_allowed_dtypes(other, "all", "__eq__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__eq__(other._array) return self.__class__._new(res) def __float__(self: Array, /) -> float: """ Performs the operation __float__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("float is only allowed on arrays with 0 dimensions") if self.dtype not in _floating_dtypes: raise ValueError("float is only allowed on floating-point arrays") res = self._array.__float__() return res def __floordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __floordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__floordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__floordiv__(other._array) return self.__class__._new(res) def __ge__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ge__. """ other = self._check_allowed_dtypes(other, "numeric", "__ge__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ge__(other._array) return self.__class__._new(res) def __getitem__( self: Array, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], /, ) -> Array: """ Performs the operation __getitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array res = self._array.__getitem__(key) return self._new(res) def __gt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __gt__. """ other = self._check_allowed_dtypes(other, "numeric", "__gt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__gt__(other._array) return self.__class__._new(res) def __int__(self: Array, /) -> int: """ Performs the operation __int__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("int is only allowed on arrays with 0 dimensions") if self.dtype not in _integer_dtypes: raise ValueError("int is only allowed on integer arrays") res = self._array.__int__() return res def __index__(self: Array, /) -> int: """ Performs the operation __index__. """ res = self._array.__index__() return res def __invert__(self: Array, /) -> Array: """ Performs the operation __invert__. """ if self.dtype not in _integer_or_boolean_dtypes: raise TypeError("Only integer or boolean dtypes are allowed in __invert__") res = self._array.__invert__() return self.__class__._new(res) def __le__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __le__. """ other = self._check_allowed_dtypes(other, "numeric", "__le__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__le__(other._array) return self.__class__._new(res) def __lshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __lshift__. """ other = self._check_allowed_dtypes(other, "integer", "__lshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lshift__(other._array) return self.__class__._new(res) def __lt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __lt__. """ other = self._check_allowed_dtypes(other, "numeric", "__lt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lt__(other._array) return self.__class__._new(res) def __matmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __matmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__matmul__") if other is NotImplemented: return other res = self._array.__matmul__(other._array) return self.__class__._new(res) def __mod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mod__. """ other = self._check_allowed_dtypes(other, "numeric", "__mod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mod__(other._array) return self.__class__._new(res) def __mul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mul__. """ other = self._check_allowed_dtypes(other, "numeric", "__mul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mul__(other._array) return self.__class__._new(res) def __ne__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __ne__. """ other = self._check_allowed_dtypes(other, "all", "__ne__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ne__(other._array) return self.__class__._new(res) def __neg__(self: Array, /) -> Array: """ Performs the operation __neg__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __neg__") res = self._array.__neg__() return self.__class__._new(res) def __or__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __or__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__or__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__or__(other._array) return self.__class__._new(res) def __pos__(self: Array, /) -> Array: """ Performs the operation __pos__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __pos__") res = self._array.__pos__() return self.__class__._new(res) def __pow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __pow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__pow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow type promotion rules for 0-d # arrays, so we use pow() here instead. return pow(self, other) def __rshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rshift__(other._array) return self.__class__._new(res) def __setitem__( self, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], value: Union[int, float, bool, Array], /, ) -> None: """ Performs the operation __setitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array self._array.__setitem__(key, asarray(value)._array) def __sub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __sub__. """ other = self._check_allowed_dtypes(other, "numeric", "__sub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__sub__(other._array) return self.__class__._new(res) # PEP 484 requires int to be a subtype of float, but __truediv__ should # not accept int. def __truediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __truediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__truediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__truediv__(other._array) return self.__class__._new(res) def __xor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __xor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__xor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__xor__(other._array) return self.__class__._new(res) def __iadd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __iadd__. """ other = self._check_allowed_dtypes(other, "numeric", "__iadd__") if other is NotImplemented: return other self._array.__iadd__(other._array) return self def __radd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __radd__. """ other = self._check_allowed_dtypes(other, "numeric", "__radd__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__radd__(other._array) return self.__class__._new(res) def __iand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __iand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__iand__") if other is NotImplemented: return other self._array.__iand__(other._array) return self def __rand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rand__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rand__(other._array) return self.__class__._new(res) def __ifloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ifloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__ifloordiv__") if other is NotImplemented: return other self._array.__ifloordiv__(other._array) return self def __rfloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rfloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__rfloordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rfloordiv__(other._array) return self.__class__._new(res) def __ilshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __ilshift__. """ other = self._check_allowed_dtypes(other, "integer", "__ilshift__") if other is NotImplemented: return other self._array.__ilshift__(other._array) return self def __rlshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rlshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rlshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rlshift__(other._array) return self.__class__._new(res) def __imatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __imatmul__. """ # Note: NumPy does not implement __imatmul__. # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__imatmul__") if other is NotImplemented: return other # __imatmul__ can only be allowed when it would not change the shape # of self. other_shape = other.shape if self.shape == () or other_shape == (): raise ValueError("@= requires at least one dimension") if len(other_shape) == 1 or other_shape[-1] != other_shape[-2]: raise ValueError("@= cannot change the shape of the input array") self._array[:] = self._array.__matmul__(other._array) return self def __rmatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __rmatmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__rmatmul__") if other is NotImplemented: return other res = self._array.__rmatmul__(other._array) return self.__class__._new(res) def __imod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imod__. """ other = self._check_allowed_dtypes(other, "numeric", "__imod__") if other is NotImplemented: return other self._array.__imod__(other._array) return self def __rmod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmod__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmod__(other._array) return self.__class__._new(res) def __imul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imul__. """ other = self._check_allowed_dtypes(other, "numeric", "__imul__") if other is NotImplemented: return other self._array.__imul__(other._array) return self def __rmul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmul__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmul__(other._array) return self.__class__._new(res) def __ior__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ior__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ior__") if other is NotImplemented: return other self._array.__ior__(other._array) return self def __ror__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ror__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ror__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ror__(other._array) return self.__class__._new(res) def __ipow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ipow__. """ other = self._check_allowed_dtypes(other, "numeric", "__ipow__") if other is NotImplemented: return other self._array.__ipow__(other._array) return self def __rpow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rpow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__rpow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow the spec type promotion rules # for 0-d arrays, so we use pow() here instead. return pow(other, self) def __irshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __irshift__. """ other = self._check_allowed_dtypes(other, "integer", "__irshift__") if other is NotImplemented: return other self._array.__irshift__(other._array) return self def __rrshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rrshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rrshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rrshift__(other._array) return self.__class__._new(res) def __isub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __isub__. """ other = self._check_allowed_dtypes(other, "numeric", "__isub__") if other is NotImplemented: return other self._array.__isub__(other._array) return self def __rsub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rsub__. """ other = self._check_allowed_dtypes(other, "numeric", "__rsub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rsub__(other._array) return self.__class__._new(res) def __itruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __itruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__itruediv__") if other is NotImplemented: return other self._array.__itruediv__(other._array) return self def __rtruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __rtruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__rtruediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rtruediv__(other._array) return self.__class__._new(res) def __ixor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ixor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ixor__") if other is NotImplemented: return other self._array.__ixor__(other._array) return self def __rxor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rxor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rxor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rxor__(other._array) return self.__class__._new(res) def to_device(self: Array, device: Device, /, stream: None = None) -> Array: if stream is not None: raise ValueError("The stream argument to to_device() is not supported") if device == 'cpu': return self raise ValueError(f"Unsupported device {device!r}") def dtype(self) -> Dtype: """ Array API compatible wrapper for :py:meth:`np.ndarray.dtype <numpy.ndarray.dtype>`. See its docstring for more information. """ return self._array.dtype def device(self) -> Device: return "cpu" # Note: mT is new in array API spec (see matrix_transpose) def mT(self) -> Array: from .linalg import matrix_transpose return matrix_transpose(self) def ndim(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.ndim <numpy.ndarray.ndim>`. See its docstring for more information. """ return self._array.ndim def shape(self) -> Tuple[int, ...]: """ Array API compatible wrapper for :py:meth:`np.ndarray.shape <numpy.ndarray.shape>`. See its docstring for more information. """ return self._array.shape def size(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.size <numpy.ndarray.size>`. See its docstring for more information. """ return self._array.size def T(self) -> Array: """ Array API compatible wrapper for :py:meth:`np.ndarray.T <numpy.ndarray.T>`. See its docstring for more information. """ # Note: T only works on 2-dimensional arrays. See the corresponding # note in the specification: # https://data-apis.org/array-api/latest/API_specification/array_object.html#t if self.ndim != 2: raise ValueError("x.T requires x to have 2 dimensions. Use x.mT to transpose stacks of matrices and permute_dims() to permute dimensions.") return self.__class__._new(self._array.T) The provided code snippet includes necessary dependencies for implementing the `log10` function. Write a Python function `def log10(x: Array, /) -> Array` to solve the following problem: Array API compatible wrapper for :py:func:`np.log10 <numpy.log10>`. See its docstring for more information. Here is the function: def log10(x: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.log10 <numpy.log10>`. See its docstring for more information. """ if x.dtype not in _floating_dtypes: raise TypeError("Only floating-point dtypes are allowed in log10") return Array._new(np.log10(x._array))
Array API compatible wrapper for :py:func:`np.log10 <numpy.log10>`. See its docstring for more information.
170,054
from __future__ import annotations from ._dtypes import ( _boolean_dtypes, _floating_dtypes, _integer_dtypes, _integer_or_boolean_dtypes, _numeric_dtypes, _result_type, ) from ._array_object import Array import numpy as np _floating_dtypes = (float32, float64) def _result_type(type1, type2): if (type1, type2) in _promotion_table: return _promotion_table[type1, type2] raise TypeError(f"{type1} and {type2} cannot be type promoted together") class Array: """ n-d array object for the array API namespace. See the docstring of :py:obj:`np.ndarray <numpy.ndarray>` for more information. This is a wrapper around numpy.ndarray that restricts the usage to only those things that are required by the array API namespace. Note, attributes on this object that start with a single underscore are not part of the API specification and should only be used internally. This object should not be constructed directly. Rather, use one of the creation functions, such as asarray(). """ _array: np.ndarray # Use a custom constructor instead of __init__, as manually initializing # this class is not supported API. def _new(cls, x, /): """ This is a private method for initializing the array API Array object. Functions outside of the array_api submodule should not use this method. Use one of the creation functions instead, such as ``asarray``. """ obj = super().__new__(cls) # Note: The spec does not have array scalars, only 0-D arrays. if isinstance(x, np.generic): # Convert the array scalar to a 0-D array x = np.asarray(x) if x.dtype not in _all_dtypes: raise TypeError( f"The array_api namespace does not support the dtype '{x.dtype}'" ) obj._array = x return obj # Prevent Array() from working def __new__(cls, *args, **kwargs): raise TypeError( "The array_api Array object should not be instantiated directly. Use an array creation function, such as asarray(), instead." ) # These functions are not required by the spec, but are implemented for # the sake of usability. def __str__(self: Array, /) -> str: """ Performs the operation __str__. """ return self._array.__str__().replace("array", "Array") def __repr__(self: Array, /) -> str: """ Performs the operation __repr__. """ suffix = f", dtype={self.dtype.name})" if 0 in self.shape: prefix = "empty(" mid = str(self.shape) else: prefix = "Array(" mid = np.array2string(self._array, separator=', ', prefix=prefix, suffix=suffix) return prefix + mid + suffix # This function is not required by the spec, but we implement it here for # convenience so that np.asarray(np.array_api.Array) will work. def __array__(self, dtype: None | np.dtype[Any] = None) -> npt.NDArray[Any]: """ Warning: this method is NOT part of the array API spec. Implementers of other libraries need not include it, and users should not assume it will be present in other implementations. """ return np.asarray(self._array, dtype=dtype) # These are various helper functions to make the array behavior match the # spec in places where it either deviates from or is more strict than # NumPy behavior def _check_allowed_dtypes(self, other: bool | int | float | Array, dtype_category: str, op: str) -> Array: """ Helper function for operators to only allow specific input dtypes Use like other = self._check_allowed_dtypes(other, 'numeric', '__add__') if other is NotImplemented: return other """ if self.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") if isinstance(other, (int, float, bool)): other = self._promote_scalar(other) elif isinstance(other, Array): if other.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") else: return NotImplemented # This will raise TypeError for type combinations that are not allowed # to promote in the spec (even if the NumPy array operator would # promote them). res_dtype = _result_type(self.dtype, other.dtype) if op.startswith("__i"): # Note: NumPy will allow in-place operators in some cases where # the type promoted operator does not match the left-hand side # operand. For example, # >>> a = np.array(1, dtype=np.int8) # >>> a += np.array(1, dtype=np.int16) # The spec explicitly disallows this. if res_dtype != self.dtype: raise TypeError( f"Cannot perform {op} with dtypes {self.dtype} and {other.dtype}" ) return other # Helper function to match the type promotion rules in the spec def _promote_scalar(self, scalar): """ Returns a promoted version of a Python scalar appropriate for use with operations on self. This may raise an OverflowError in cases where the scalar is an integer that is too large to fit in a NumPy integer dtype, or TypeError when the scalar type is incompatible with the dtype of self. """ # Note: Only Python scalar types that match the array dtype are # allowed. if isinstance(scalar, bool): if self.dtype not in _boolean_dtypes: raise TypeError( "Python bool scalars can only be promoted with bool arrays" ) elif isinstance(scalar, int): if self.dtype in _boolean_dtypes: raise TypeError( "Python int scalars cannot be promoted with bool arrays" ) elif isinstance(scalar, float): if self.dtype not in _floating_dtypes: raise TypeError( "Python float scalars can only be promoted with floating-point arrays." ) else: raise TypeError("'scalar' must be a Python scalar") # Note: scalars are unconditionally cast to the same dtype as the # array. # Note: the spec only specifies integer-dtype/int promotion # behavior for integers within the bounds of the integer dtype. # Outside of those bounds we use the default NumPy behavior (either # cast or raise OverflowError). return Array._new(np.array(scalar, self.dtype)) def _normalize_two_args(x1, x2) -> Tuple[Array, Array]: """ Normalize inputs to two arg functions to fix type promotion rules NumPy deviates from the spec type promotion rules in cases where one argument is 0-dimensional and the other is not. For example: >>> import numpy as np >>> a = np.array([1.0], dtype=np.float32) >>> b = np.array(1.0, dtype=np.float64) >>> np.add(a, b) # The spec says this should be float64 array([2.], dtype=float32) To fix this, we add a dimension to the 0-dimension array before passing it through. This works because a dimension would be added anyway from broadcasting, so the resulting shape is the same, but this prevents NumPy from not promoting the dtype. """ # Another option would be to use signature=(x1.dtype, x2.dtype, None), # but that only works for ufuncs, so we would have to call the ufuncs # directly in the operator methods. One should also note that this # sort of trick wouldn't work for functions like searchsorted, which # don't do normal broadcasting, but there aren't any functions like # that in the array API namespace. if x1.ndim == 0 and x2.ndim != 0: # The _array[None] workaround was chosen because it is relatively # performant. broadcast_to(x1._array, x2.shape) is much slower. We # could also manually type promote x2, but that is more complicated # and about the same performance as this. x1 = Array._new(x1._array[None]) elif x2.ndim == 0 and x1.ndim != 0: x2 = Array._new(x2._array[None]) return (x1, x2) # Note: A large fraction of allowed indices are disallowed here (see the # docstring below) def _validate_index(self, key): """ Validate an index according to the array API. The array API specification only requires a subset of indices that are supported by NumPy. This function will reject any index that is allowed by NumPy but not required by the array API specification. We always raise ``IndexError`` on such indices (the spec does not require any specific behavior on them, but this makes the NumPy array API namespace a minimal implementation of the spec). See https://data-apis.org/array-api/latest/API_specification/indexing.html for the full list of required indexing behavior This function raises IndexError if the index ``key`` is invalid. It only raises ``IndexError`` on indices that are not already rejected by NumPy, as NumPy will already raise the appropriate error on such indices. ``shape`` may be None, in which case, only cases that are independent of the array shape are checked. The following cases are allowed by NumPy, but not specified by the array API specification: - Indices to not include an implicit ellipsis at the end. That is, every axis of an array must be explicitly indexed or an ellipsis included. This behaviour is sometimes referred to as flat indexing. - The start and stop of a slice may not be out of bounds. In particular, for a slice ``i:j:k`` on an axis of size ``n``, only the following are allowed: - ``i`` or ``j`` omitted (``None``). - ``-n <= i <= max(0, n - 1)``. - For ``k > 0`` or ``k`` omitted (``None``), ``-n <= j <= n``. - For ``k < 0``, ``-n - 1 <= j <= max(0, n - 1)``. - Boolean array indices are not allowed as part of a larger tuple index. - Integer array indices are not allowed (with the exception of 0-D arrays, which are treated the same as scalars). Additionally, it should be noted that indices that would return a scalar in NumPy will return a 0-D array. Array scalars are not allowed in the specification, only 0-D arrays. This is done in the ``Array._new`` constructor, not this function. """ _key = key if isinstance(key, tuple) else (key,) for i in _key: if isinstance(i, bool) or not ( isinstance(i, SupportsIndex) # i.e. ints or isinstance(i, slice) or i == Ellipsis or i is None or isinstance(i, Array) or isinstance(i, np.ndarray) ): raise IndexError( f"Single-axes index {i} has {type(i)=}, but only " "integers, slices (:), ellipsis (...), newaxis (None), " "zero-dimensional integer arrays and boolean arrays " "are specified in the Array API." ) nonexpanding_key = [] single_axes = [] n_ellipsis = 0 key_has_mask = False for i in _key: if i is not None: nonexpanding_key.append(i) if isinstance(i, Array) or isinstance(i, np.ndarray): if i.dtype in _boolean_dtypes: key_has_mask = True single_axes.append(i) else: # i must not be an array here, to avoid elementwise equals if i == Ellipsis: n_ellipsis += 1 else: single_axes.append(i) n_single_axes = len(single_axes) if n_ellipsis > 1: return # handled by ndarray elif n_ellipsis == 0: # Note boolean masks must be the sole index, which we check for # later on. if not key_has_mask and n_single_axes < self.ndim: raise IndexError( f"{self.ndim=}, but the multi-axes index only specifies " f"{n_single_axes} dimensions. If this was intentional, " "add a trailing ellipsis (...) which expands into as many " "slices (:) as necessary - this is what np.ndarray arrays " "implicitly do, but such flat indexing behaviour is not " "specified in the Array API." ) if n_ellipsis == 0: indexed_shape = self.shape else: ellipsis_start = None for pos, i in enumerate(nonexpanding_key): if not (isinstance(i, Array) or isinstance(i, np.ndarray)): if i == Ellipsis: ellipsis_start = pos break assert ellipsis_start is not None # sanity check ellipsis_end = self.ndim - (n_single_axes - ellipsis_start) indexed_shape = ( self.shape[:ellipsis_start] + self.shape[ellipsis_end:] ) for i, side in zip(single_axes, indexed_shape): if isinstance(i, slice): if side == 0: f_range = "0 (or None)" else: f_range = f"between -{side} and {side - 1} (or None)" if i.start is not None: try: start = operator.index(i.start) except TypeError: pass # handled by ndarray else: if not (-side <= start <= side): raise IndexError( f"Slice {i} contains {start=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds starts are not specified in " "the Array API)" ) if i.stop is not None: try: stop = operator.index(i.stop) except TypeError: pass # handled by ndarray else: if not (-side <= stop <= side): raise IndexError( f"Slice {i} contains {stop=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds stops are not specified in " "the Array API)" ) elif isinstance(i, Array): if i.dtype in _boolean_dtypes and len(_key) != 1: assert isinstance(key, tuple) # sanity check raise IndexError( f"Single-axes index {i} is a boolean array and " f"{len(key)=}, but masking is only specified in the " "Array API when the array is the sole index." ) elif i.dtype in _integer_dtypes and i.ndim != 0: raise IndexError( f"Single-axes index {i} is a non-zero-dimensional " "integer array, but advanced integer indexing is not " "specified in the Array API." ) elif isinstance(i, tuple): raise IndexError( f"Single-axes index {i} is a tuple, but nested tuple " "indices are not specified in the Array API." ) # Everything below this line is required by the spec. def __abs__(self: Array, /) -> Array: """ Performs the operation __abs__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __abs__") res = self._array.__abs__() return self.__class__._new(res) def __add__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __add__. """ other = self._check_allowed_dtypes(other, "numeric", "__add__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__add__(other._array) return self.__class__._new(res) def __and__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __and__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__and__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__and__(other._array) return self.__class__._new(res) def __array_namespace__( self: Array, /, *, api_version: Optional[str] = None ) -> types.ModuleType: if api_version is not None and not api_version.startswith("2021."): raise ValueError(f"Unrecognized array API version: {api_version!r}") return array_api def __bool__(self: Array, /) -> bool: """ Performs the operation __bool__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("bool is only allowed on arrays with 0 dimensions") if self.dtype not in _boolean_dtypes: raise ValueError("bool is only allowed on boolean arrays") res = self._array.__bool__() return res def __dlpack__(self: Array, /, *, stream: None = None) -> PyCapsule: """ Performs the operation __dlpack__. """ return self._array.__dlpack__(stream=stream) def __dlpack_device__(self: Array, /) -> Tuple[IntEnum, int]: """ Performs the operation __dlpack_device__. """ # Note: device support is required for this return self._array.__dlpack_device__() def __eq__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __eq__. """ # Even though "all" dtypes are allowed, we still require them to be # promotable with each other. other = self._check_allowed_dtypes(other, "all", "__eq__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__eq__(other._array) return self.__class__._new(res) def __float__(self: Array, /) -> float: """ Performs the operation __float__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("float is only allowed on arrays with 0 dimensions") if self.dtype not in _floating_dtypes: raise ValueError("float is only allowed on floating-point arrays") res = self._array.__float__() return res def __floordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __floordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__floordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__floordiv__(other._array) return self.__class__._new(res) def __ge__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ge__. """ other = self._check_allowed_dtypes(other, "numeric", "__ge__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ge__(other._array) return self.__class__._new(res) def __getitem__( self: Array, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], /, ) -> Array: """ Performs the operation __getitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array res = self._array.__getitem__(key) return self._new(res) def __gt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __gt__. """ other = self._check_allowed_dtypes(other, "numeric", "__gt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__gt__(other._array) return self.__class__._new(res) def __int__(self: Array, /) -> int: """ Performs the operation __int__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("int is only allowed on arrays with 0 dimensions") if self.dtype not in _integer_dtypes: raise ValueError("int is only allowed on integer arrays") res = self._array.__int__() return res def __index__(self: Array, /) -> int: """ Performs the operation __index__. """ res = self._array.__index__() return res def __invert__(self: Array, /) -> Array: """ Performs the operation __invert__. """ if self.dtype not in _integer_or_boolean_dtypes: raise TypeError("Only integer or boolean dtypes are allowed in __invert__") res = self._array.__invert__() return self.__class__._new(res) def __le__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __le__. """ other = self._check_allowed_dtypes(other, "numeric", "__le__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__le__(other._array) return self.__class__._new(res) def __lshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __lshift__. """ other = self._check_allowed_dtypes(other, "integer", "__lshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lshift__(other._array) return self.__class__._new(res) def __lt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __lt__. """ other = self._check_allowed_dtypes(other, "numeric", "__lt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lt__(other._array) return self.__class__._new(res) def __matmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __matmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__matmul__") if other is NotImplemented: return other res = self._array.__matmul__(other._array) return self.__class__._new(res) def __mod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mod__. """ other = self._check_allowed_dtypes(other, "numeric", "__mod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mod__(other._array) return self.__class__._new(res) def __mul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mul__. """ other = self._check_allowed_dtypes(other, "numeric", "__mul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mul__(other._array) return self.__class__._new(res) def __ne__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __ne__. """ other = self._check_allowed_dtypes(other, "all", "__ne__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ne__(other._array) return self.__class__._new(res) def __neg__(self: Array, /) -> Array: """ Performs the operation __neg__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __neg__") res = self._array.__neg__() return self.__class__._new(res) def __or__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __or__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__or__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__or__(other._array) return self.__class__._new(res) def __pos__(self: Array, /) -> Array: """ Performs the operation __pos__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __pos__") res = self._array.__pos__() return self.__class__._new(res) def __pow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __pow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__pow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow type promotion rules for 0-d # arrays, so we use pow() here instead. return pow(self, other) def __rshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rshift__(other._array) return self.__class__._new(res) def __setitem__( self, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], value: Union[int, float, bool, Array], /, ) -> None: """ Performs the operation __setitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array self._array.__setitem__(key, asarray(value)._array) def __sub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __sub__. """ other = self._check_allowed_dtypes(other, "numeric", "__sub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__sub__(other._array) return self.__class__._new(res) # PEP 484 requires int to be a subtype of float, but __truediv__ should # not accept int. def __truediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __truediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__truediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__truediv__(other._array) return self.__class__._new(res) def __xor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __xor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__xor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__xor__(other._array) return self.__class__._new(res) def __iadd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __iadd__. """ other = self._check_allowed_dtypes(other, "numeric", "__iadd__") if other is NotImplemented: return other self._array.__iadd__(other._array) return self def __radd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __radd__. """ other = self._check_allowed_dtypes(other, "numeric", "__radd__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__radd__(other._array) return self.__class__._new(res) def __iand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __iand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__iand__") if other is NotImplemented: return other self._array.__iand__(other._array) return self def __rand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rand__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rand__(other._array) return self.__class__._new(res) def __ifloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ifloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__ifloordiv__") if other is NotImplemented: return other self._array.__ifloordiv__(other._array) return self def __rfloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rfloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__rfloordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rfloordiv__(other._array) return self.__class__._new(res) def __ilshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __ilshift__. """ other = self._check_allowed_dtypes(other, "integer", "__ilshift__") if other is NotImplemented: return other self._array.__ilshift__(other._array) return self def __rlshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rlshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rlshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rlshift__(other._array) return self.__class__._new(res) def __imatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __imatmul__. """ # Note: NumPy does not implement __imatmul__. # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__imatmul__") if other is NotImplemented: return other # __imatmul__ can only be allowed when it would not change the shape # of self. other_shape = other.shape if self.shape == () or other_shape == (): raise ValueError("@= requires at least one dimension") if len(other_shape) == 1 or other_shape[-1] != other_shape[-2]: raise ValueError("@= cannot change the shape of the input array") self._array[:] = self._array.__matmul__(other._array) return self def __rmatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __rmatmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__rmatmul__") if other is NotImplemented: return other res = self._array.__rmatmul__(other._array) return self.__class__._new(res) def __imod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imod__. """ other = self._check_allowed_dtypes(other, "numeric", "__imod__") if other is NotImplemented: return other self._array.__imod__(other._array) return self def __rmod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmod__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmod__(other._array) return self.__class__._new(res) def __imul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imul__. """ other = self._check_allowed_dtypes(other, "numeric", "__imul__") if other is NotImplemented: return other self._array.__imul__(other._array) return self def __rmul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmul__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmul__(other._array) return self.__class__._new(res) def __ior__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ior__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ior__") if other is NotImplemented: return other self._array.__ior__(other._array) return self def __ror__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ror__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ror__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ror__(other._array) return self.__class__._new(res) def __ipow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ipow__. """ other = self._check_allowed_dtypes(other, "numeric", "__ipow__") if other is NotImplemented: return other self._array.__ipow__(other._array) return self def __rpow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rpow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__rpow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow the spec type promotion rules # for 0-d arrays, so we use pow() here instead. return pow(other, self) def __irshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __irshift__. """ other = self._check_allowed_dtypes(other, "integer", "__irshift__") if other is NotImplemented: return other self._array.__irshift__(other._array) return self def __rrshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rrshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rrshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rrshift__(other._array) return self.__class__._new(res) def __isub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __isub__. """ other = self._check_allowed_dtypes(other, "numeric", "__isub__") if other is NotImplemented: return other self._array.__isub__(other._array) return self def __rsub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rsub__. """ other = self._check_allowed_dtypes(other, "numeric", "__rsub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rsub__(other._array) return self.__class__._new(res) def __itruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __itruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__itruediv__") if other is NotImplemented: return other self._array.__itruediv__(other._array) return self def __rtruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __rtruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__rtruediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rtruediv__(other._array) return self.__class__._new(res) def __ixor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ixor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ixor__") if other is NotImplemented: return other self._array.__ixor__(other._array) return self def __rxor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rxor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rxor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rxor__(other._array) return self.__class__._new(res) def to_device(self: Array, device: Device, /, stream: None = None) -> Array: if stream is not None: raise ValueError("The stream argument to to_device() is not supported") if device == 'cpu': return self raise ValueError(f"Unsupported device {device!r}") def dtype(self) -> Dtype: """ Array API compatible wrapper for :py:meth:`np.ndarray.dtype <numpy.ndarray.dtype>`. See its docstring for more information. """ return self._array.dtype def device(self) -> Device: return "cpu" # Note: mT is new in array API spec (see matrix_transpose) def mT(self) -> Array: from .linalg import matrix_transpose return matrix_transpose(self) def ndim(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.ndim <numpy.ndarray.ndim>`. See its docstring for more information. """ return self._array.ndim def shape(self) -> Tuple[int, ...]: """ Array API compatible wrapper for :py:meth:`np.ndarray.shape <numpy.ndarray.shape>`. See its docstring for more information. """ return self._array.shape def size(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.size <numpy.ndarray.size>`. See its docstring for more information. """ return self._array.size def T(self) -> Array: """ Array API compatible wrapper for :py:meth:`np.ndarray.T <numpy.ndarray.T>`. See its docstring for more information. """ # Note: T only works on 2-dimensional arrays. See the corresponding # note in the specification: # https://data-apis.org/array-api/latest/API_specification/array_object.html#t if self.ndim != 2: raise ValueError("x.T requires x to have 2 dimensions. Use x.mT to transpose stacks of matrices and permute_dims() to permute dimensions.") return self.__class__._new(self._array.T) The provided code snippet includes necessary dependencies for implementing the `logaddexp` function. Write a Python function `def logaddexp(x1: Array, x2: Array) -> Array` to solve the following problem: Array API compatible wrapper for :py:func:`np.logaddexp <numpy.logaddexp>`. See its docstring for more information. Here is the function: def logaddexp(x1: Array, x2: Array) -> Array: """ Array API compatible wrapper for :py:func:`np.logaddexp <numpy.logaddexp>`. See its docstring for more information. """ if x1.dtype not in _floating_dtypes or x2.dtype not in _floating_dtypes: raise TypeError("Only floating-point dtypes are allowed in logaddexp") # Call result type here just to raise on disallowed type combinations _result_type(x1.dtype, x2.dtype) x1, x2 = Array._normalize_two_args(x1, x2) return Array._new(np.logaddexp(x1._array, x2._array))
Array API compatible wrapper for :py:func:`np.logaddexp <numpy.logaddexp>`. See its docstring for more information.
170,055
from __future__ import annotations from ._dtypes import ( _boolean_dtypes, _floating_dtypes, _integer_dtypes, _integer_or_boolean_dtypes, _numeric_dtypes, _result_type, ) from ._array_object import Array import numpy as np _boolean_dtypes = (bool,) def _result_type(type1, type2): if (type1, type2) in _promotion_table: return _promotion_table[type1, type2] raise TypeError(f"{type1} and {type2} cannot be type promoted together") class Array: """ n-d array object for the array API namespace. See the docstring of :py:obj:`np.ndarray <numpy.ndarray>` for more information. This is a wrapper around numpy.ndarray that restricts the usage to only those things that are required by the array API namespace. Note, attributes on this object that start with a single underscore are not part of the API specification and should only be used internally. This object should not be constructed directly. Rather, use one of the creation functions, such as asarray(). """ _array: np.ndarray # Use a custom constructor instead of __init__, as manually initializing # this class is not supported API. def _new(cls, x, /): """ This is a private method for initializing the array API Array object. Functions outside of the array_api submodule should not use this method. Use one of the creation functions instead, such as ``asarray``. """ obj = super().__new__(cls) # Note: The spec does not have array scalars, only 0-D arrays. if isinstance(x, np.generic): # Convert the array scalar to a 0-D array x = np.asarray(x) if x.dtype not in _all_dtypes: raise TypeError( f"The array_api namespace does not support the dtype '{x.dtype}'" ) obj._array = x return obj # Prevent Array() from working def __new__(cls, *args, **kwargs): raise TypeError( "The array_api Array object should not be instantiated directly. Use an array creation function, such as asarray(), instead." ) # These functions are not required by the spec, but are implemented for # the sake of usability. def __str__(self: Array, /) -> str: """ Performs the operation __str__. """ return self._array.__str__().replace("array", "Array") def __repr__(self: Array, /) -> str: """ Performs the operation __repr__. """ suffix = f", dtype={self.dtype.name})" if 0 in self.shape: prefix = "empty(" mid = str(self.shape) else: prefix = "Array(" mid = np.array2string(self._array, separator=', ', prefix=prefix, suffix=suffix) return prefix + mid + suffix # This function is not required by the spec, but we implement it here for # convenience so that np.asarray(np.array_api.Array) will work. def __array__(self, dtype: None | np.dtype[Any] = None) -> npt.NDArray[Any]: """ Warning: this method is NOT part of the array API spec. Implementers of other libraries need not include it, and users should not assume it will be present in other implementations. """ return np.asarray(self._array, dtype=dtype) # These are various helper functions to make the array behavior match the # spec in places where it either deviates from or is more strict than # NumPy behavior def _check_allowed_dtypes(self, other: bool | int | float | Array, dtype_category: str, op: str) -> Array: """ Helper function for operators to only allow specific input dtypes Use like other = self._check_allowed_dtypes(other, 'numeric', '__add__') if other is NotImplemented: return other """ if self.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") if isinstance(other, (int, float, bool)): other = self._promote_scalar(other) elif isinstance(other, Array): if other.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") else: return NotImplemented # This will raise TypeError for type combinations that are not allowed # to promote in the spec (even if the NumPy array operator would # promote them). res_dtype = _result_type(self.dtype, other.dtype) if op.startswith("__i"): # Note: NumPy will allow in-place operators in some cases where # the type promoted operator does not match the left-hand side # operand. For example, # >>> a = np.array(1, dtype=np.int8) # >>> a += np.array(1, dtype=np.int16) # The spec explicitly disallows this. if res_dtype != self.dtype: raise TypeError( f"Cannot perform {op} with dtypes {self.dtype} and {other.dtype}" ) return other # Helper function to match the type promotion rules in the spec def _promote_scalar(self, scalar): """ Returns a promoted version of a Python scalar appropriate for use with operations on self. This may raise an OverflowError in cases where the scalar is an integer that is too large to fit in a NumPy integer dtype, or TypeError when the scalar type is incompatible with the dtype of self. """ # Note: Only Python scalar types that match the array dtype are # allowed. if isinstance(scalar, bool): if self.dtype not in _boolean_dtypes: raise TypeError( "Python bool scalars can only be promoted with bool arrays" ) elif isinstance(scalar, int): if self.dtype in _boolean_dtypes: raise TypeError( "Python int scalars cannot be promoted with bool arrays" ) elif isinstance(scalar, float): if self.dtype not in _floating_dtypes: raise TypeError( "Python float scalars can only be promoted with floating-point arrays." ) else: raise TypeError("'scalar' must be a Python scalar") # Note: scalars are unconditionally cast to the same dtype as the # array. # Note: the spec only specifies integer-dtype/int promotion # behavior for integers within the bounds of the integer dtype. # Outside of those bounds we use the default NumPy behavior (either # cast or raise OverflowError). return Array._new(np.array(scalar, self.dtype)) def _normalize_two_args(x1, x2) -> Tuple[Array, Array]: """ Normalize inputs to two arg functions to fix type promotion rules NumPy deviates from the spec type promotion rules in cases where one argument is 0-dimensional and the other is not. For example: >>> import numpy as np >>> a = np.array([1.0], dtype=np.float32) >>> b = np.array(1.0, dtype=np.float64) >>> np.add(a, b) # The spec says this should be float64 array([2.], dtype=float32) To fix this, we add a dimension to the 0-dimension array before passing it through. This works because a dimension would be added anyway from broadcasting, so the resulting shape is the same, but this prevents NumPy from not promoting the dtype. """ # Another option would be to use signature=(x1.dtype, x2.dtype, None), # but that only works for ufuncs, so we would have to call the ufuncs # directly in the operator methods. One should also note that this # sort of trick wouldn't work for functions like searchsorted, which # don't do normal broadcasting, but there aren't any functions like # that in the array API namespace. if x1.ndim == 0 and x2.ndim != 0: # The _array[None] workaround was chosen because it is relatively # performant. broadcast_to(x1._array, x2.shape) is much slower. We # could also manually type promote x2, but that is more complicated # and about the same performance as this. x1 = Array._new(x1._array[None]) elif x2.ndim == 0 and x1.ndim != 0: x2 = Array._new(x2._array[None]) return (x1, x2) # Note: A large fraction of allowed indices are disallowed here (see the # docstring below) def _validate_index(self, key): """ Validate an index according to the array API. The array API specification only requires a subset of indices that are supported by NumPy. This function will reject any index that is allowed by NumPy but not required by the array API specification. We always raise ``IndexError`` on such indices (the spec does not require any specific behavior on them, but this makes the NumPy array API namespace a minimal implementation of the spec). See https://data-apis.org/array-api/latest/API_specification/indexing.html for the full list of required indexing behavior This function raises IndexError if the index ``key`` is invalid. It only raises ``IndexError`` on indices that are not already rejected by NumPy, as NumPy will already raise the appropriate error on such indices. ``shape`` may be None, in which case, only cases that are independent of the array shape are checked. The following cases are allowed by NumPy, but not specified by the array API specification: - Indices to not include an implicit ellipsis at the end. That is, every axis of an array must be explicitly indexed or an ellipsis included. This behaviour is sometimes referred to as flat indexing. - The start and stop of a slice may not be out of bounds. In particular, for a slice ``i:j:k`` on an axis of size ``n``, only the following are allowed: - ``i`` or ``j`` omitted (``None``). - ``-n <= i <= max(0, n - 1)``. - For ``k > 0`` or ``k`` omitted (``None``), ``-n <= j <= n``. - For ``k < 0``, ``-n - 1 <= j <= max(0, n - 1)``. - Boolean array indices are not allowed as part of a larger tuple index. - Integer array indices are not allowed (with the exception of 0-D arrays, which are treated the same as scalars). Additionally, it should be noted that indices that would return a scalar in NumPy will return a 0-D array. Array scalars are not allowed in the specification, only 0-D arrays. This is done in the ``Array._new`` constructor, not this function. """ _key = key if isinstance(key, tuple) else (key,) for i in _key: if isinstance(i, bool) or not ( isinstance(i, SupportsIndex) # i.e. ints or isinstance(i, slice) or i == Ellipsis or i is None or isinstance(i, Array) or isinstance(i, np.ndarray) ): raise IndexError( f"Single-axes index {i} has {type(i)=}, but only " "integers, slices (:), ellipsis (...), newaxis (None), " "zero-dimensional integer arrays and boolean arrays " "are specified in the Array API." ) nonexpanding_key = [] single_axes = [] n_ellipsis = 0 key_has_mask = False for i in _key: if i is not None: nonexpanding_key.append(i) if isinstance(i, Array) or isinstance(i, np.ndarray): if i.dtype in _boolean_dtypes: key_has_mask = True single_axes.append(i) else: # i must not be an array here, to avoid elementwise equals if i == Ellipsis: n_ellipsis += 1 else: single_axes.append(i) n_single_axes = len(single_axes) if n_ellipsis > 1: return # handled by ndarray elif n_ellipsis == 0: # Note boolean masks must be the sole index, which we check for # later on. if not key_has_mask and n_single_axes < self.ndim: raise IndexError( f"{self.ndim=}, but the multi-axes index only specifies " f"{n_single_axes} dimensions. If this was intentional, " "add a trailing ellipsis (...) which expands into as many " "slices (:) as necessary - this is what np.ndarray arrays " "implicitly do, but such flat indexing behaviour is not " "specified in the Array API." ) if n_ellipsis == 0: indexed_shape = self.shape else: ellipsis_start = None for pos, i in enumerate(nonexpanding_key): if not (isinstance(i, Array) or isinstance(i, np.ndarray)): if i == Ellipsis: ellipsis_start = pos break assert ellipsis_start is not None # sanity check ellipsis_end = self.ndim - (n_single_axes - ellipsis_start) indexed_shape = ( self.shape[:ellipsis_start] + self.shape[ellipsis_end:] ) for i, side in zip(single_axes, indexed_shape): if isinstance(i, slice): if side == 0: f_range = "0 (or None)" else: f_range = f"between -{side} and {side - 1} (or None)" if i.start is not None: try: start = operator.index(i.start) except TypeError: pass # handled by ndarray else: if not (-side <= start <= side): raise IndexError( f"Slice {i} contains {start=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds starts are not specified in " "the Array API)" ) if i.stop is not None: try: stop = operator.index(i.stop) except TypeError: pass # handled by ndarray else: if not (-side <= stop <= side): raise IndexError( f"Slice {i} contains {stop=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds stops are not specified in " "the Array API)" ) elif isinstance(i, Array): if i.dtype in _boolean_dtypes and len(_key) != 1: assert isinstance(key, tuple) # sanity check raise IndexError( f"Single-axes index {i} is a boolean array and " f"{len(key)=}, but masking is only specified in the " "Array API when the array is the sole index." ) elif i.dtype in _integer_dtypes and i.ndim != 0: raise IndexError( f"Single-axes index {i} is a non-zero-dimensional " "integer array, but advanced integer indexing is not " "specified in the Array API." ) elif isinstance(i, tuple): raise IndexError( f"Single-axes index {i} is a tuple, but nested tuple " "indices are not specified in the Array API." ) # Everything below this line is required by the spec. def __abs__(self: Array, /) -> Array: """ Performs the operation __abs__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __abs__") res = self._array.__abs__() return self.__class__._new(res) def __add__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __add__. """ other = self._check_allowed_dtypes(other, "numeric", "__add__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__add__(other._array) return self.__class__._new(res) def __and__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __and__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__and__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__and__(other._array) return self.__class__._new(res) def __array_namespace__( self: Array, /, *, api_version: Optional[str] = None ) -> types.ModuleType: if api_version is not None and not api_version.startswith("2021."): raise ValueError(f"Unrecognized array API version: {api_version!r}") return array_api def __bool__(self: Array, /) -> bool: """ Performs the operation __bool__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("bool is only allowed on arrays with 0 dimensions") if self.dtype not in _boolean_dtypes: raise ValueError("bool is only allowed on boolean arrays") res = self._array.__bool__() return res def __dlpack__(self: Array, /, *, stream: None = None) -> PyCapsule: """ Performs the operation __dlpack__. """ return self._array.__dlpack__(stream=stream) def __dlpack_device__(self: Array, /) -> Tuple[IntEnum, int]: """ Performs the operation __dlpack_device__. """ # Note: device support is required for this return self._array.__dlpack_device__() def __eq__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __eq__. """ # Even though "all" dtypes are allowed, we still require them to be # promotable with each other. other = self._check_allowed_dtypes(other, "all", "__eq__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__eq__(other._array) return self.__class__._new(res) def __float__(self: Array, /) -> float: """ Performs the operation __float__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("float is only allowed on arrays with 0 dimensions") if self.dtype not in _floating_dtypes: raise ValueError("float is only allowed on floating-point arrays") res = self._array.__float__() return res def __floordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __floordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__floordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__floordiv__(other._array) return self.__class__._new(res) def __ge__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ge__. """ other = self._check_allowed_dtypes(other, "numeric", "__ge__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ge__(other._array) return self.__class__._new(res) def __getitem__( self: Array, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], /, ) -> Array: """ Performs the operation __getitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array res = self._array.__getitem__(key) return self._new(res) def __gt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __gt__. """ other = self._check_allowed_dtypes(other, "numeric", "__gt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__gt__(other._array) return self.__class__._new(res) def __int__(self: Array, /) -> int: """ Performs the operation __int__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("int is only allowed on arrays with 0 dimensions") if self.dtype not in _integer_dtypes: raise ValueError("int is only allowed on integer arrays") res = self._array.__int__() return res def __index__(self: Array, /) -> int: """ Performs the operation __index__. """ res = self._array.__index__() return res def __invert__(self: Array, /) -> Array: """ Performs the operation __invert__. """ if self.dtype not in _integer_or_boolean_dtypes: raise TypeError("Only integer or boolean dtypes are allowed in __invert__") res = self._array.__invert__() return self.__class__._new(res) def __le__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __le__. """ other = self._check_allowed_dtypes(other, "numeric", "__le__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__le__(other._array) return self.__class__._new(res) def __lshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __lshift__. """ other = self._check_allowed_dtypes(other, "integer", "__lshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lshift__(other._array) return self.__class__._new(res) def __lt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __lt__. """ other = self._check_allowed_dtypes(other, "numeric", "__lt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lt__(other._array) return self.__class__._new(res) def __matmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __matmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__matmul__") if other is NotImplemented: return other res = self._array.__matmul__(other._array) return self.__class__._new(res) def __mod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mod__. """ other = self._check_allowed_dtypes(other, "numeric", "__mod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mod__(other._array) return self.__class__._new(res) def __mul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mul__. """ other = self._check_allowed_dtypes(other, "numeric", "__mul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mul__(other._array) return self.__class__._new(res) def __ne__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __ne__. """ other = self._check_allowed_dtypes(other, "all", "__ne__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ne__(other._array) return self.__class__._new(res) def __neg__(self: Array, /) -> Array: """ Performs the operation __neg__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __neg__") res = self._array.__neg__() return self.__class__._new(res) def __or__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __or__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__or__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__or__(other._array) return self.__class__._new(res) def __pos__(self: Array, /) -> Array: """ Performs the operation __pos__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __pos__") res = self._array.__pos__() return self.__class__._new(res) def __pow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __pow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__pow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow type promotion rules for 0-d # arrays, so we use pow() here instead. return pow(self, other) def __rshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rshift__(other._array) return self.__class__._new(res) def __setitem__( self, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], value: Union[int, float, bool, Array], /, ) -> None: """ Performs the operation __setitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array self._array.__setitem__(key, asarray(value)._array) def __sub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __sub__. """ other = self._check_allowed_dtypes(other, "numeric", "__sub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__sub__(other._array) return self.__class__._new(res) # PEP 484 requires int to be a subtype of float, but __truediv__ should # not accept int. def __truediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __truediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__truediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__truediv__(other._array) return self.__class__._new(res) def __xor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __xor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__xor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__xor__(other._array) return self.__class__._new(res) def __iadd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __iadd__. """ other = self._check_allowed_dtypes(other, "numeric", "__iadd__") if other is NotImplemented: return other self._array.__iadd__(other._array) return self def __radd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __radd__. """ other = self._check_allowed_dtypes(other, "numeric", "__radd__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__radd__(other._array) return self.__class__._new(res) def __iand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __iand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__iand__") if other is NotImplemented: return other self._array.__iand__(other._array) return self def __rand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rand__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rand__(other._array) return self.__class__._new(res) def __ifloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ifloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__ifloordiv__") if other is NotImplemented: return other self._array.__ifloordiv__(other._array) return self def __rfloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rfloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__rfloordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rfloordiv__(other._array) return self.__class__._new(res) def __ilshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __ilshift__. """ other = self._check_allowed_dtypes(other, "integer", "__ilshift__") if other is NotImplemented: return other self._array.__ilshift__(other._array) return self def __rlshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rlshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rlshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rlshift__(other._array) return self.__class__._new(res) def __imatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __imatmul__. """ # Note: NumPy does not implement __imatmul__. # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__imatmul__") if other is NotImplemented: return other # __imatmul__ can only be allowed when it would not change the shape # of self. other_shape = other.shape if self.shape == () or other_shape == (): raise ValueError("@= requires at least one dimension") if len(other_shape) == 1 or other_shape[-1] != other_shape[-2]: raise ValueError("@= cannot change the shape of the input array") self._array[:] = self._array.__matmul__(other._array) return self def __rmatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __rmatmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__rmatmul__") if other is NotImplemented: return other res = self._array.__rmatmul__(other._array) return self.__class__._new(res) def __imod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imod__. """ other = self._check_allowed_dtypes(other, "numeric", "__imod__") if other is NotImplemented: return other self._array.__imod__(other._array) return self def __rmod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmod__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmod__(other._array) return self.__class__._new(res) def __imul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imul__. """ other = self._check_allowed_dtypes(other, "numeric", "__imul__") if other is NotImplemented: return other self._array.__imul__(other._array) return self def __rmul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmul__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmul__(other._array) return self.__class__._new(res) def __ior__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ior__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ior__") if other is NotImplemented: return other self._array.__ior__(other._array) return self def __ror__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ror__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ror__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ror__(other._array) return self.__class__._new(res) def __ipow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ipow__. """ other = self._check_allowed_dtypes(other, "numeric", "__ipow__") if other is NotImplemented: return other self._array.__ipow__(other._array) return self def __rpow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rpow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__rpow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow the spec type promotion rules # for 0-d arrays, so we use pow() here instead. return pow(other, self) def __irshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __irshift__. """ other = self._check_allowed_dtypes(other, "integer", "__irshift__") if other is NotImplemented: return other self._array.__irshift__(other._array) return self def __rrshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rrshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rrshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rrshift__(other._array) return self.__class__._new(res) def __isub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __isub__. """ other = self._check_allowed_dtypes(other, "numeric", "__isub__") if other is NotImplemented: return other self._array.__isub__(other._array) return self def __rsub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rsub__. """ other = self._check_allowed_dtypes(other, "numeric", "__rsub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rsub__(other._array) return self.__class__._new(res) def __itruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __itruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__itruediv__") if other is NotImplemented: return other self._array.__itruediv__(other._array) return self def __rtruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __rtruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__rtruediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rtruediv__(other._array) return self.__class__._new(res) def __ixor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ixor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ixor__") if other is NotImplemented: return other self._array.__ixor__(other._array) return self def __rxor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rxor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rxor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rxor__(other._array) return self.__class__._new(res) def to_device(self: Array, device: Device, /, stream: None = None) -> Array: if stream is not None: raise ValueError("The stream argument to to_device() is not supported") if device == 'cpu': return self raise ValueError(f"Unsupported device {device!r}") def dtype(self) -> Dtype: """ Array API compatible wrapper for :py:meth:`np.ndarray.dtype <numpy.ndarray.dtype>`. See its docstring for more information. """ return self._array.dtype def device(self) -> Device: return "cpu" # Note: mT is new in array API spec (see matrix_transpose) def mT(self) -> Array: from .linalg import matrix_transpose return matrix_transpose(self) def ndim(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.ndim <numpy.ndarray.ndim>`. See its docstring for more information. """ return self._array.ndim def shape(self) -> Tuple[int, ...]: """ Array API compatible wrapper for :py:meth:`np.ndarray.shape <numpy.ndarray.shape>`. See its docstring for more information. """ return self._array.shape def size(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.size <numpy.ndarray.size>`. See its docstring for more information. """ return self._array.size def T(self) -> Array: """ Array API compatible wrapper for :py:meth:`np.ndarray.T <numpy.ndarray.T>`. See its docstring for more information. """ # Note: T only works on 2-dimensional arrays. See the corresponding # note in the specification: # https://data-apis.org/array-api/latest/API_specification/array_object.html#t if self.ndim != 2: raise ValueError("x.T requires x to have 2 dimensions. Use x.mT to transpose stacks of matrices and permute_dims() to permute dimensions.") return self.__class__._new(self._array.T) The provided code snippet includes necessary dependencies for implementing the `logical_and` function. Write a Python function `def logical_and(x1: Array, x2: Array, /) -> Array` to solve the following problem: Array API compatible wrapper for :py:func:`np.logical_and <numpy.logical_and>`. See its docstring for more information. Here is the function: def logical_and(x1: Array, x2: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.logical_and <numpy.logical_and>`. See its docstring for more information. """ if x1.dtype not in _boolean_dtypes or x2.dtype not in _boolean_dtypes: raise TypeError("Only boolean dtypes are allowed in logical_and") # Call result type here just to raise on disallowed type combinations _result_type(x1.dtype, x2.dtype) x1, x2 = Array._normalize_two_args(x1, x2) return Array._new(np.logical_and(x1._array, x2._array))
Array API compatible wrapper for :py:func:`np.logical_and <numpy.logical_and>`. See its docstring for more information.
170,056
from __future__ import annotations from ._dtypes import ( _boolean_dtypes, _floating_dtypes, _integer_dtypes, _integer_or_boolean_dtypes, _numeric_dtypes, _result_type, ) from ._array_object import Array import numpy as np _boolean_dtypes = (bool,) class Array: """ n-d array object for the array API namespace. See the docstring of :py:obj:`np.ndarray <numpy.ndarray>` for more information. This is a wrapper around numpy.ndarray that restricts the usage to only those things that are required by the array API namespace. Note, attributes on this object that start with a single underscore are not part of the API specification and should only be used internally. This object should not be constructed directly. Rather, use one of the creation functions, such as asarray(). """ _array: np.ndarray # Use a custom constructor instead of __init__, as manually initializing # this class is not supported API. def _new(cls, x, /): """ This is a private method for initializing the array API Array object. Functions outside of the array_api submodule should not use this method. Use one of the creation functions instead, such as ``asarray``. """ obj = super().__new__(cls) # Note: The spec does not have array scalars, only 0-D arrays. if isinstance(x, np.generic): # Convert the array scalar to a 0-D array x = np.asarray(x) if x.dtype not in _all_dtypes: raise TypeError( f"The array_api namespace does not support the dtype '{x.dtype}'" ) obj._array = x return obj # Prevent Array() from working def __new__(cls, *args, **kwargs): raise TypeError( "The array_api Array object should not be instantiated directly. Use an array creation function, such as asarray(), instead." ) # These functions are not required by the spec, but are implemented for # the sake of usability. def __str__(self: Array, /) -> str: """ Performs the operation __str__. """ return self._array.__str__().replace("array", "Array") def __repr__(self: Array, /) -> str: """ Performs the operation __repr__. """ suffix = f", dtype={self.dtype.name})" if 0 in self.shape: prefix = "empty(" mid = str(self.shape) else: prefix = "Array(" mid = np.array2string(self._array, separator=', ', prefix=prefix, suffix=suffix) return prefix + mid + suffix # This function is not required by the spec, but we implement it here for # convenience so that np.asarray(np.array_api.Array) will work. def __array__(self, dtype: None | np.dtype[Any] = None) -> npt.NDArray[Any]: """ Warning: this method is NOT part of the array API spec. Implementers of other libraries need not include it, and users should not assume it will be present in other implementations. """ return np.asarray(self._array, dtype=dtype) # These are various helper functions to make the array behavior match the # spec in places where it either deviates from or is more strict than # NumPy behavior def _check_allowed_dtypes(self, other: bool | int | float | Array, dtype_category: str, op: str) -> Array: """ Helper function for operators to only allow specific input dtypes Use like other = self._check_allowed_dtypes(other, 'numeric', '__add__') if other is NotImplemented: return other """ if self.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") if isinstance(other, (int, float, bool)): other = self._promote_scalar(other) elif isinstance(other, Array): if other.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") else: return NotImplemented # This will raise TypeError for type combinations that are not allowed # to promote in the spec (even if the NumPy array operator would # promote them). res_dtype = _result_type(self.dtype, other.dtype) if op.startswith("__i"): # Note: NumPy will allow in-place operators in some cases where # the type promoted operator does not match the left-hand side # operand. For example, # >>> a = np.array(1, dtype=np.int8) # >>> a += np.array(1, dtype=np.int16) # The spec explicitly disallows this. if res_dtype != self.dtype: raise TypeError( f"Cannot perform {op} with dtypes {self.dtype} and {other.dtype}" ) return other # Helper function to match the type promotion rules in the spec def _promote_scalar(self, scalar): """ Returns a promoted version of a Python scalar appropriate for use with operations on self. This may raise an OverflowError in cases where the scalar is an integer that is too large to fit in a NumPy integer dtype, or TypeError when the scalar type is incompatible with the dtype of self. """ # Note: Only Python scalar types that match the array dtype are # allowed. if isinstance(scalar, bool): if self.dtype not in _boolean_dtypes: raise TypeError( "Python bool scalars can only be promoted with bool arrays" ) elif isinstance(scalar, int): if self.dtype in _boolean_dtypes: raise TypeError( "Python int scalars cannot be promoted with bool arrays" ) elif isinstance(scalar, float): if self.dtype not in _floating_dtypes: raise TypeError( "Python float scalars can only be promoted with floating-point arrays." ) else: raise TypeError("'scalar' must be a Python scalar") # Note: scalars are unconditionally cast to the same dtype as the # array. # Note: the spec only specifies integer-dtype/int promotion # behavior for integers within the bounds of the integer dtype. # Outside of those bounds we use the default NumPy behavior (either # cast or raise OverflowError). return Array._new(np.array(scalar, self.dtype)) def _normalize_two_args(x1, x2) -> Tuple[Array, Array]: """ Normalize inputs to two arg functions to fix type promotion rules NumPy deviates from the spec type promotion rules in cases where one argument is 0-dimensional and the other is not. For example: >>> import numpy as np >>> a = np.array([1.0], dtype=np.float32) >>> b = np.array(1.0, dtype=np.float64) >>> np.add(a, b) # The spec says this should be float64 array([2.], dtype=float32) To fix this, we add a dimension to the 0-dimension array before passing it through. This works because a dimension would be added anyway from broadcasting, so the resulting shape is the same, but this prevents NumPy from not promoting the dtype. """ # Another option would be to use signature=(x1.dtype, x2.dtype, None), # but that only works for ufuncs, so we would have to call the ufuncs # directly in the operator methods. One should also note that this # sort of trick wouldn't work for functions like searchsorted, which # don't do normal broadcasting, but there aren't any functions like # that in the array API namespace. if x1.ndim == 0 and x2.ndim != 0: # The _array[None] workaround was chosen because it is relatively # performant. broadcast_to(x1._array, x2.shape) is much slower. We # could also manually type promote x2, but that is more complicated # and about the same performance as this. x1 = Array._new(x1._array[None]) elif x2.ndim == 0 and x1.ndim != 0: x2 = Array._new(x2._array[None]) return (x1, x2) # Note: A large fraction of allowed indices are disallowed here (see the # docstring below) def _validate_index(self, key): """ Validate an index according to the array API. The array API specification only requires a subset of indices that are supported by NumPy. This function will reject any index that is allowed by NumPy but not required by the array API specification. We always raise ``IndexError`` on such indices (the spec does not require any specific behavior on them, but this makes the NumPy array API namespace a minimal implementation of the spec). See https://data-apis.org/array-api/latest/API_specification/indexing.html for the full list of required indexing behavior This function raises IndexError if the index ``key`` is invalid. It only raises ``IndexError`` on indices that are not already rejected by NumPy, as NumPy will already raise the appropriate error on such indices. ``shape`` may be None, in which case, only cases that are independent of the array shape are checked. The following cases are allowed by NumPy, but not specified by the array API specification: - Indices to not include an implicit ellipsis at the end. That is, every axis of an array must be explicitly indexed or an ellipsis included. This behaviour is sometimes referred to as flat indexing. - The start and stop of a slice may not be out of bounds. In particular, for a slice ``i:j:k`` on an axis of size ``n``, only the following are allowed: - ``i`` or ``j`` omitted (``None``). - ``-n <= i <= max(0, n - 1)``. - For ``k > 0`` or ``k`` omitted (``None``), ``-n <= j <= n``. - For ``k < 0``, ``-n - 1 <= j <= max(0, n - 1)``. - Boolean array indices are not allowed as part of a larger tuple index. - Integer array indices are not allowed (with the exception of 0-D arrays, which are treated the same as scalars). Additionally, it should be noted that indices that would return a scalar in NumPy will return a 0-D array. Array scalars are not allowed in the specification, only 0-D arrays. This is done in the ``Array._new`` constructor, not this function. """ _key = key if isinstance(key, tuple) else (key,) for i in _key: if isinstance(i, bool) or not ( isinstance(i, SupportsIndex) # i.e. ints or isinstance(i, slice) or i == Ellipsis or i is None or isinstance(i, Array) or isinstance(i, np.ndarray) ): raise IndexError( f"Single-axes index {i} has {type(i)=}, but only " "integers, slices (:), ellipsis (...), newaxis (None), " "zero-dimensional integer arrays and boolean arrays " "are specified in the Array API." ) nonexpanding_key = [] single_axes = [] n_ellipsis = 0 key_has_mask = False for i in _key: if i is not None: nonexpanding_key.append(i) if isinstance(i, Array) or isinstance(i, np.ndarray): if i.dtype in _boolean_dtypes: key_has_mask = True single_axes.append(i) else: # i must not be an array here, to avoid elementwise equals if i == Ellipsis: n_ellipsis += 1 else: single_axes.append(i) n_single_axes = len(single_axes) if n_ellipsis > 1: return # handled by ndarray elif n_ellipsis == 0: # Note boolean masks must be the sole index, which we check for # later on. if not key_has_mask and n_single_axes < self.ndim: raise IndexError( f"{self.ndim=}, but the multi-axes index only specifies " f"{n_single_axes} dimensions. If this was intentional, " "add a trailing ellipsis (...) which expands into as many " "slices (:) as necessary - this is what np.ndarray arrays " "implicitly do, but such flat indexing behaviour is not " "specified in the Array API." ) if n_ellipsis == 0: indexed_shape = self.shape else: ellipsis_start = None for pos, i in enumerate(nonexpanding_key): if not (isinstance(i, Array) or isinstance(i, np.ndarray)): if i == Ellipsis: ellipsis_start = pos break assert ellipsis_start is not None # sanity check ellipsis_end = self.ndim - (n_single_axes - ellipsis_start) indexed_shape = ( self.shape[:ellipsis_start] + self.shape[ellipsis_end:] ) for i, side in zip(single_axes, indexed_shape): if isinstance(i, slice): if side == 0: f_range = "0 (or None)" else: f_range = f"between -{side} and {side - 1} (or None)" if i.start is not None: try: start = operator.index(i.start) except TypeError: pass # handled by ndarray else: if not (-side <= start <= side): raise IndexError( f"Slice {i} contains {start=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds starts are not specified in " "the Array API)" ) if i.stop is not None: try: stop = operator.index(i.stop) except TypeError: pass # handled by ndarray else: if not (-side <= stop <= side): raise IndexError( f"Slice {i} contains {stop=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds stops are not specified in " "the Array API)" ) elif isinstance(i, Array): if i.dtype in _boolean_dtypes and len(_key) != 1: assert isinstance(key, tuple) # sanity check raise IndexError( f"Single-axes index {i} is a boolean array and " f"{len(key)=}, but masking is only specified in the " "Array API when the array is the sole index." ) elif i.dtype in _integer_dtypes and i.ndim != 0: raise IndexError( f"Single-axes index {i} is a non-zero-dimensional " "integer array, but advanced integer indexing is not " "specified in the Array API." ) elif isinstance(i, tuple): raise IndexError( f"Single-axes index {i} is a tuple, but nested tuple " "indices are not specified in the Array API." ) # Everything below this line is required by the spec. def __abs__(self: Array, /) -> Array: """ Performs the operation __abs__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __abs__") res = self._array.__abs__() return self.__class__._new(res) def __add__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __add__. """ other = self._check_allowed_dtypes(other, "numeric", "__add__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__add__(other._array) return self.__class__._new(res) def __and__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __and__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__and__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__and__(other._array) return self.__class__._new(res) def __array_namespace__( self: Array, /, *, api_version: Optional[str] = None ) -> types.ModuleType: if api_version is not None and not api_version.startswith("2021."): raise ValueError(f"Unrecognized array API version: {api_version!r}") return array_api def __bool__(self: Array, /) -> bool: """ Performs the operation __bool__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("bool is only allowed on arrays with 0 dimensions") if self.dtype not in _boolean_dtypes: raise ValueError("bool is only allowed on boolean arrays") res = self._array.__bool__() return res def __dlpack__(self: Array, /, *, stream: None = None) -> PyCapsule: """ Performs the operation __dlpack__. """ return self._array.__dlpack__(stream=stream) def __dlpack_device__(self: Array, /) -> Tuple[IntEnum, int]: """ Performs the operation __dlpack_device__. """ # Note: device support is required for this return self._array.__dlpack_device__() def __eq__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __eq__. """ # Even though "all" dtypes are allowed, we still require them to be # promotable with each other. other = self._check_allowed_dtypes(other, "all", "__eq__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__eq__(other._array) return self.__class__._new(res) def __float__(self: Array, /) -> float: """ Performs the operation __float__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("float is only allowed on arrays with 0 dimensions") if self.dtype not in _floating_dtypes: raise ValueError("float is only allowed on floating-point arrays") res = self._array.__float__() return res def __floordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __floordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__floordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__floordiv__(other._array) return self.__class__._new(res) def __ge__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ge__. """ other = self._check_allowed_dtypes(other, "numeric", "__ge__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ge__(other._array) return self.__class__._new(res) def __getitem__( self: Array, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], /, ) -> Array: """ Performs the operation __getitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array res = self._array.__getitem__(key) return self._new(res) def __gt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __gt__. """ other = self._check_allowed_dtypes(other, "numeric", "__gt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__gt__(other._array) return self.__class__._new(res) def __int__(self: Array, /) -> int: """ Performs the operation __int__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("int is only allowed on arrays with 0 dimensions") if self.dtype not in _integer_dtypes: raise ValueError("int is only allowed on integer arrays") res = self._array.__int__() return res def __index__(self: Array, /) -> int: """ Performs the operation __index__. """ res = self._array.__index__() return res def __invert__(self: Array, /) -> Array: """ Performs the operation __invert__. """ if self.dtype not in _integer_or_boolean_dtypes: raise TypeError("Only integer or boolean dtypes are allowed in __invert__") res = self._array.__invert__() return self.__class__._new(res) def __le__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __le__. """ other = self._check_allowed_dtypes(other, "numeric", "__le__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__le__(other._array) return self.__class__._new(res) def __lshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __lshift__. """ other = self._check_allowed_dtypes(other, "integer", "__lshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lshift__(other._array) return self.__class__._new(res) def __lt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __lt__. """ other = self._check_allowed_dtypes(other, "numeric", "__lt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lt__(other._array) return self.__class__._new(res) def __matmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __matmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__matmul__") if other is NotImplemented: return other res = self._array.__matmul__(other._array) return self.__class__._new(res) def __mod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mod__. """ other = self._check_allowed_dtypes(other, "numeric", "__mod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mod__(other._array) return self.__class__._new(res) def __mul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mul__. """ other = self._check_allowed_dtypes(other, "numeric", "__mul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mul__(other._array) return self.__class__._new(res) def __ne__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __ne__. """ other = self._check_allowed_dtypes(other, "all", "__ne__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ne__(other._array) return self.__class__._new(res) def __neg__(self: Array, /) -> Array: """ Performs the operation __neg__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __neg__") res = self._array.__neg__() return self.__class__._new(res) def __or__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __or__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__or__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__or__(other._array) return self.__class__._new(res) def __pos__(self: Array, /) -> Array: """ Performs the operation __pos__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __pos__") res = self._array.__pos__() return self.__class__._new(res) def __pow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __pow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__pow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow type promotion rules for 0-d # arrays, so we use pow() here instead. return pow(self, other) def __rshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rshift__(other._array) return self.__class__._new(res) def __setitem__( self, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], value: Union[int, float, bool, Array], /, ) -> None: """ Performs the operation __setitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array self._array.__setitem__(key, asarray(value)._array) def __sub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __sub__. """ other = self._check_allowed_dtypes(other, "numeric", "__sub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__sub__(other._array) return self.__class__._new(res) # PEP 484 requires int to be a subtype of float, but __truediv__ should # not accept int. def __truediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __truediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__truediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__truediv__(other._array) return self.__class__._new(res) def __xor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __xor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__xor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__xor__(other._array) return self.__class__._new(res) def __iadd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __iadd__. """ other = self._check_allowed_dtypes(other, "numeric", "__iadd__") if other is NotImplemented: return other self._array.__iadd__(other._array) return self def __radd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __radd__. """ other = self._check_allowed_dtypes(other, "numeric", "__radd__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__radd__(other._array) return self.__class__._new(res) def __iand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __iand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__iand__") if other is NotImplemented: return other self._array.__iand__(other._array) return self def __rand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rand__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rand__(other._array) return self.__class__._new(res) def __ifloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ifloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__ifloordiv__") if other is NotImplemented: return other self._array.__ifloordiv__(other._array) return self def __rfloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rfloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__rfloordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rfloordiv__(other._array) return self.__class__._new(res) def __ilshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __ilshift__. """ other = self._check_allowed_dtypes(other, "integer", "__ilshift__") if other is NotImplemented: return other self._array.__ilshift__(other._array) return self def __rlshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rlshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rlshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rlshift__(other._array) return self.__class__._new(res) def __imatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __imatmul__. """ # Note: NumPy does not implement __imatmul__. # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__imatmul__") if other is NotImplemented: return other # __imatmul__ can only be allowed when it would not change the shape # of self. other_shape = other.shape if self.shape == () or other_shape == (): raise ValueError("@= requires at least one dimension") if len(other_shape) == 1 or other_shape[-1] != other_shape[-2]: raise ValueError("@= cannot change the shape of the input array") self._array[:] = self._array.__matmul__(other._array) return self def __rmatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __rmatmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__rmatmul__") if other is NotImplemented: return other res = self._array.__rmatmul__(other._array) return self.__class__._new(res) def __imod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imod__. """ other = self._check_allowed_dtypes(other, "numeric", "__imod__") if other is NotImplemented: return other self._array.__imod__(other._array) return self def __rmod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmod__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmod__(other._array) return self.__class__._new(res) def __imul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imul__. """ other = self._check_allowed_dtypes(other, "numeric", "__imul__") if other is NotImplemented: return other self._array.__imul__(other._array) return self def __rmul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmul__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmul__(other._array) return self.__class__._new(res) def __ior__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ior__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ior__") if other is NotImplemented: return other self._array.__ior__(other._array) return self def __ror__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ror__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ror__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ror__(other._array) return self.__class__._new(res) def __ipow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ipow__. """ other = self._check_allowed_dtypes(other, "numeric", "__ipow__") if other is NotImplemented: return other self._array.__ipow__(other._array) return self def __rpow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rpow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__rpow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow the spec type promotion rules # for 0-d arrays, so we use pow() here instead. return pow(other, self) def __irshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __irshift__. """ other = self._check_allowed_dtypes(other, "integer", "__irshift__") if other is NotImplemented: return other self._array.__irshift__(other._array) return self def __rrshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rrshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rrshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rrshift__(other._array) return self.__class__._new(res) def __isub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __isub__. """ other = self._check_allowed_dtypes(other, "numeric", "__isub__") if other is NotImplemented: return other self._array.__isub__(other._array) return self def __rsub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rsub__. """ other = self._check_allowed_dtypes(other, "numeric", "__rsub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rsub__(other._array) return self.__class__._new(res) def __itruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __itruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__itruediv__") if other is NotImplemented: return other self._array.__itruediv__(other._array) return self def __rtruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __rtruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__rtruediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rtruediv__(other._array) return self.__class__._new(res) def __ixor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ixor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ixor__") if other is NotImplemented: return other self._array.__ixor__(other._array) return self def __rxor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rxor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rxor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rxor__(other._array) return self.__class__._new(res) def to_device(self: Array, device: Device, /, stream: None = None) -> Array: if stream is not None: raise ValueError("The stream argument to to_device() is not supported") if device == 'cpu': return self raise ValueError(f"Unsupported device {device!r}") def dtype(self) -> Dtype: """ Array API compatible wrapper for :py:meth:`np.ndarray.dtype <numpy.ndarray.dtype>`. See its docstring for more information. """ return self._array.dtype def device(self) -> Device: return "cpu" # Note: mT is new in array API spec (see matrix_transpose) def mT(self) -> Array: from .linalg import matrix_transpose return matrix_transpose(self) def ndim(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.ndim <numpy.ndarray.ndim>`. See its docstring for more information. """ return self._array.ndim def shape(self) -> Tuple[int, ...]: """ Array API compatible wrapper for :py:meth:`np.ndarray.shape <numpy.ndarray.shape>`. See its docstring for more information. """ return self._array.shape def size(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.size <numpy.ndarray.size>`. See its docstring for more information. """ return self._array.size def T(self) -> Array: """ Array API compatible wrapper for :py:meth:`np.ndarray.T <numpy.ndarray.T>`. See its docstring for more information. """ # Note: T only works on 2-dimensional arrays. See the corresponding # note in the specification: # https://data-apis.org/array-api/latest/API_specification/array_object.html#t if self.ndim != 2: raise ValueError("x.T requires x to have 2 dimensions. Use x.mT to transpose stacks of matrices and permute_dims() to permute dimensions.") return self.__class__._new(self._array.T) The provided code snippet includes necessary dependencies for implementing the `logical_not` function. Write a Python function `def logical_not(x: Array, /) -> Array` to solve the following problem: Array API compatible wrapper for :py:func:`np.logical_not <numpy.logical_not>`. See its docstring for more information. Here is the function: def logical_not(x: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.logical_not <numpy.logical_not>`. See its docstring for more information. """ if x.dtype not in _boolean_dtypes: raise TypeError("Only boolean dtypes are allowed in logical_not") return Array._new(np.logical_not(x._array))
Array API compatible wrapper for :py:func:`np.logical_not <numpy.logical_not>`. See its docstring for more information.
170,057
from __future__ import annotations from ._dtypes import ( _boolean_dtypes, _floating_dtypes, _integer_dtypes, _integer_or_boolean_dtypes, _numeric_dtypes, _result_type, ) from ._array_object import Array import numpy as np _boolean_dtypes = (bool,) def _result_type(type1, type2): if (type1, type2) in _promotion_table: return _promotion_table[type1, type2] raise TypeError(f"{type1} and {type2} cannot be type promoted together") class Array: """ n-d array object for the array API namespace. See the docstring of :py:obj:`np.ndarray <numpy.ndarray>` for more information. This is a wrapper around numpy.ndarray that restricts the usage to only those things that are required by the array API namespace. Note, attributes on this object that start with a single underscore are not part of the API specification and should only be used internally. This object should not be constructed directly. Rather, use one of the creation functions, such as asarray(). """ _array: np.ndarray # Use a custom constructor instead of __init__, as manually initializing # this class is not supported API. def _new(cls, x, /): """ This is a private method for initializing the array API Array object. Functions outside of the array_api submodule should not use this method. Use one of the creation functions instead, such as ``asarray``. """ obj = super().__new__(cls) # Note: The spec does not have array scalars, only 0-D arrays. if isinstance(x, np.generic): # Convert the array scalar to a 0-D array x = np.asarray(x) if x.dtype not in _all_dtypes: raise TypeError( f"The array_api namespace does not support the dtype '{x.dtype}'" ) obj._array = x return obj # Prevent Array() from working def __new__(cls, *args, **kwargs): raise TypeError( "The array_api Array object should not be instantiated directly. Use an array creation function, such as asarray(), instead." ) # These functions are not required by the spec, but are implemented for # the sake of usability. def __str__(self: Array, /) -> str: """ Performs the operation __str__. """ return self._array.__str__().replace("array", "Array") def __repr__(self: Array, /) -> str: """ Performs the operation __repr__. """ suffix = f", dtype={self.dtype.name})" if 0 in self.shape: prefix = "empty(" mid = str(self.shape) else: prefix = "Array(" mid = np.array2string(self._array, separator=', ', prefix=prefix, suffix=suffix) return prefix + mid + suffix # This function is not required by the spec, but we implement it here for # convenience so that np.asarray(np.array_api.Array) will work. def __array__(self, dtype: None | np.dtype[Any] = None) -> npt.NDArray[Any]: """ Warning: this method is NOT part of the array API spec. Implementers of other libraries need not include it, and users should not assume it will be present in other implementations. """ return np.asarray(self._array, dtype=dtype) # These are various helper functions to make the array behavior match the # spec in places where it either deviates from or is more strict than # NumPy behavior def _check_allowed_dtypes(self, other: bool | int | float | Array, dtype_category: str, op: str) -> Array: """ Helper function for operators to only allow specific input dtypes Use like other = self._check_allowed_dtypes(other, 'numeric', '__add__') if other is NotImplemented: return other """ if self.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") if isinstance(other, (int, float, bool)): other = self._promote_scalar(other) elif isinstance(other, Array): if other.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") else: return NotImplemented # This will raise TypeError for type combinations that are not allowed # to promote in the spec (even if the NumPy array operator would # promote them). res_dtype = _result_type(self.dtype, other.dtype) if op.startswith("__i"): # Note: NumPy will allow in-place operators in some cases where # the type promoted operator does not match the left-hand side # operand. For example, # >>> a = np.array(1, dtype=np.int8) # >>> a += np.array(1, dtype=np.int16) # The spec explicitly disallows this. if res_dtype != self.dtype: raise TypeError( f"Cannot perform {op} with dtypes {self.dtype} and {other.dtype}" ) return other # Helper function to match the type promotion rules in the spec def _promote_scalar(self, scalar): """ Returns a promoted version of a Python scalar appropriate for use with operations on self. This may raise an OverflowError in cases where the scalar is an integer that is too large to fit in a NumPy integer dtype, or TypeError when the scalar type is incompatible with the dtype of self. """ # Note: Only Python scalar types that match the array dtype are # allowed. if isinstance(scalar, bool): if self.dtype not in _boolean_dtypes: raise TypeError( "Python bool scalars can only be promoted with bool arrays" ) elif isinstance(scalar, int): if self.dtype in _boolean_dtypes: raise TypeError( "Python int scalars cannot be promoted with bool arrays" ) elif isinstance(scalar, float): if self.dtype not in _floating_dtypes: raise TypeError( "Python float scalars can only be promoted with floating-point arrays." ) else: raise TypeError("'scalar' must be a Python scalar") # Note: scalars are unconditionally cast to the same dtype as the # array. # Note: the spec only specifies integer-dtype/int promotion # behavior for integers within the bounds of the integer dtype. # Outside of those bounds we use the default NumPy behavior (either # cast or raise OverflowError). return Array._new(np.array(scalar, self.dtype)) def _normalize_two_args(x1, x2) -> Tuple[Array, Array]: """ Normalize inputs to two arg functions to fix type promotion rules NumPy deviates from the spec type promotion rules in cases where one argument is 0-dimensional and the other is not. For example: >>> import numpy as np >>> a = np.array([1.0], dtype=np.float32) >>> b = np.array(1.0, dtype=np.float64) >>> np.add(a, b) # The spec says this should be float64 array([2.], dtype=float32) To fix this, we add a dimension to the 0-dimension array before passing it through. This works because a dimension would be added anyway from broadcasting, so the resulting shape is the same, but this prevents NumPy from not promoting the dtype. """ # Another option would be to use signature=(x1.dtype, x2.dtype, None), # but that only works for ufuncs, so we would have to call the ufuncs # directly in the operator methods. One should also note that this # sort of trick wouldn't work for functions like searchsorted, which # don't do normal broadcasting, but there aren't any functions like # that in the array API namespace. if x1.ndim == 0 and x2.ndim != 0: # The _array[None] workaround was chosen because it is relatively # performant. broadcast_to(x1._array, x2.shape) is much slower. We # could also manually type promote x2, but that is more complicated # and about the same performance as this. x1 = Array._new(x1._array[None]) elif x2.ndim == 0 and x1.ndim != 0: x2 = Array._new(x2._array[None]) return (x1, x2) # Note: A large fraction of allowed indices are disallowed here (see the # docstring below) def _validate_index(self, key): """ Validate an index according to the array API. The array API specification only requires a subset of indices that are supported by NumPy. This function will reject any index that is allowed by NumPy but not required by the array API specification. We always raise ``IndexError`` on such indices (the spec does not require any specific behavior on them, but this makes the NumPy array API namespace a minimal implementation of the spec). See https://data-apis.org/array-api/latest/API_specification/indexing.html for the full list of required indexing behavior This function raises IndexError if the index ``key`` is invalid. It only raises ``IndexError`` on indices that are not already rejected by NumPy, as NumPy will already raise the appropriate error on such indices. ``shape`` may be None, in which case, only cases that are independent of the array shape are checked. The following cases are allowed by NumPy, but not specified by the array API specification: - Indices to not include an implicit ellipsis at the end. That is, every axis of an array must be explicitly indexed or an ellipsis included. This behaviour is sometimes referred to as flat indexing. - The start and stop of a slice may not be out of bounds. In particular, for a slice ``i:j:k`` on an axis of size ``n``, only the following are allowed: - ``i`` or ``j`` omitted (``None``). - ``-n <= i <= max(0, n - 1)``. - For ``k > 0`` or ``k`` omitted (``None``), ``-n <= j <= n``. - For ``k < 0``, ``-n - 1 <= j <= max(0, n - 1)``. - Boolean array indices are not allowed as part of a larger tuple index. - Integer array indices are not allowed (with the exception of 0-D arrays, which are treated the same as scalars). Additionally, it should be noted that indices that would return a scalar in NumPy will return a 0-D array. Array scalars are not allowed in the specification, only 0-D arrays. This is done in the ``Array._new`` constructor, not this function. """ _key = key if isinstance(key, tuple) else (key,) for i in _key: if isinstance(i, bool) or not ( isinstance(i, SupportsIndex) # i.e. ints or isinstance(i, slice) or i == Ellipsis or i is None or isinstance(i, Array) or isinstance(i, np.ndarray) ): raise IndexError( f"Single-axes index {i} has {type(i)=}, but only " "integers, slices (:), ellipsis (...), newaxis (None), " "zero-dimensional integer arrays and boolean arrays " "are specified in the Array API." ) nonexpanding_key = [] single_axes = [] n_ellipsis = 0 key_has_mask = False for i in _key: if i is not None: nonexpanding_key.append(i) if isinstance(i, Array) or isinstance(i, np.ndarray): if i.dtype in _boolean_dtypes: key_has_mask = True single_axes.append(i) else: # i must not be an array here, to avoid elementwise equals if i == Ellipsis: n_ellipsis += 1 else: single_axes.append(i) n_single_axes = len(single_axes) if n_ellipsis > 1: return # handled by ndarray elif n_ellipsis == 0: # Note boolean masks must be the sole index, which we check for # later on. if not key_has_mask and n_single_axes < self.ndim: raise IndexError( f"{self.ndim=}, but the multi-axes index only specifies " f"{n_single_axes} dimensions. If this was intentional, " "add a trailing ellipsis (...) which expands into as many " "slices (:) as necessary - this is what np.ndarray arrays " "implicitly do, but such flat indexing behaviour is not " "specified in the Array API." ) if n_ellipsis == 0: indexed_shape = self.shape else: ellipsis_start = None for pos, i in enumerate(nonexpanding_key): if not (isinstance(i, Array) or isinstance(i, np.ndarray)): if i == Ellipsis: ellipsis_start = pos break assert ellipsis_start is not None # sanity check ellipsis_end = self.ndim - (n_single_axes - ellipsis_start) indexed_shape = ( self.shape[:ellipsis_start] + self.shape[ellipsis_end:] ) for i, side in zip(single_axes, indexed_shape): if isinstance(i, slice): if side == 0: f_range = "0 (or None)" else: f_range = f"between -{side} and {side - 1} (or None)" if i.start is not None: try: start = operator.index(i.start) except TypeError: pass # handled by ndarray else: if not (-side <= start <= side): raise IndexError( f"Slice {i} contains {start=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds starts are not specified in " "the Array API)" ) if i.stop is not None: try: stop = operator.index(i.stop) except TypeError: pass # handled by ndarray else: if not (-side <= stop <= side): raise IndexError( f"Slice {i} contains {stop=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds stops are not specified in " "the Array API)" ) elif isinstance(i, Array): if i.dtype in _boolean_dtypes and len(_key) != 1: assert isinstance(key, tuple) # sanity check raise IndexError( f"Single-axes index {i} is a boolean array and " f"{len(key)=}, but masking is only specified in the " "Array API when the array is the sole index." ) elif i.dtype in _integer_dtypes and i.ndim != 0: raise IndexError( f"Single-axes index {i} is a non-zero-dimensional " "integer array, but advanced integer indexing is not " "specified in the Array API." ) elif isinstance(i, tuple): raise IndexError( f"Single-axes index {i} is a tuple, but nested tuple " "indices are not specified in the Array API." ) # Everything below this line is required by the spec. def __abs__(self: Array, /) -> Array: """ Performs the operation __abs__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __abs__") res = self._array.__abs__() return self.__class__._new(res) def __add__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __add__. """ other = self._check_allowed_dtypes(other, "numeric", "__add__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__add__(other._array) return self.__class__._new(res) def __and__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __and__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__and__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__and__(other._array) return self.__class__._new(res) def __array_namespace__( self: Array, /, *, api_version: Optional[str] = None ) -> types.ModuleType: if api_version is not None and not api_version.startswith("2021."): raise ValueError(f"Unrecognized array API version: {api_version!r}") return array_api def __bool__(self: Array, /) -> bool: """ Performs the operation __bool__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("bool is only allowed on arrays with 0 dimensions") if self.dtype not in _boolean_dtypes: raise ValueError("bool is only allowed on boolean arrays") res = self._array.__bool__() return res def __dlpack__(self: Array, /, *, stream: None = None) -> PyCapsule: """ Performs the operation __dlpack__. """ return self._array.__dlpack__(stream=stream) def __dlpack_device__(self: Array, /) -> Tuple[IntEnum, int]: """ Performs the operation __dlpack_device__. """ # Note: device support is required for this return self._array.__dlpack_device__() def __eq__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __eq__. """ # Even though "all" dtypes are allowed, we still require them to be # promotable with each other. other = self._check_allowed_dtypes(other, "all", "__eq__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__eq__(other._array) return self.__class__._new(res) def __float__(self: Array, /) -> float: """ Performs the operation __float__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("float is only allowed on arrays with 0 dimensions") if self.dtype not in _floating_dtypes: raise ValueError("float is only allowed on floating-point arrays") res = self._array.__float__() return res def __floordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __floordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__floordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__floordiv__(other._array) return self.__class__._new(res) def __ge__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ge__. """ other = self._check_allowed_dtypes(other, "numeric", "__ge__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ge__(other._array) return self.__class__._new(res) def __getitem__( self: Array, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], /, ) -> Array: """ Performs the operation __getitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array res = self._array.__getitem__(key) return self._new(res) def __gt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __gt__. """ other = self._check_allowed_dtypes(other, "numeric", "__gt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__gt__(other._array) return self.__class__._new(res) def __int__(self: Array, /) -> int: """ Performs the operation __int__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("int is only allowed on arrays with 0 dimensions") if self.dtype not in _integer_dtypes: raise ValueError("int is only allowed on integer arrays") res = self._array.__int__() return res def __index__(self: Array, /) -> int: """ Performs the operation __index__. """ res = self._array.__index__() return res def __invert__(self: Array, /) -> Array: """ Performs the operation __invert__. """ if self.dtype not in _integer_or_boolean_dtypes: raise TypeError("Only integer or boolean dtypes are allowed in __invert__") res = self._array.__invert__() return self.__class__._new(res) def __le__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __le__. """ other = self._check_allowed_dtypes(other, "numeric", "__le__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__le__(other._array) return self.__class__._new(res) def __lshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __lshift__. """ other = self._check_allowed_dtypes(other, "integer", "__lshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lshift__(other._array) return self.__class__._new(res) def __lt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __lt__. """ other = self._check_allowed_dtypes(other, "numeric", "__lt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lt__(other._array) return self.__class__._new(res) def __matmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __matmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__matmul__") if other is NotImplemented: return other res = self._array.__matmul__(other._array) return self.__class__._new(res) def __mod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mod__. """ other = self._check_allowed_dtypes(other, "numeric", "__mod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mod__(other._array) return self.__class__._new(res) def __mul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mul__. """ other = self._check_allowed_dtypes(other, "numeric", "__mul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mul__(other._array) return self.__class__._new(res) def __ne__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __ne__. """ other = self._check_allowed_dtypes(other, "all", "__ne__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ne__(other._array) return self.__class__._new(res) def __neg__(self: Array, /) -> Array: """ Performs the operation __neg__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __neg__") res = self._array.__neg__() return self.__class__._new(res) def __or__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __or__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__or__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__or__(other._array) return self.__class__._new(res) def __pos__(self: Array, /) -> Array: """ Performs the operation __pos__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __pos__") res = self._array.__pos__() return self.__class__._new(res) def __pow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __pow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__pow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow type promotion rules for 0-d # arrays, so we use pow() here instead. return pow(self, other) def __rshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rshift__(other._array) return self.__class__._new(res) def __setitem__( self, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], value: Union[int, float, bool, Array], /, ) -> None: """ Performs the operation __setitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array self._array.__setitem__(key, asarray(value)._array) def __sub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __sub__. """ other = self._check_allowed_dtypes(other, "numeric", "__sub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__sub__(other._array) return self.__class__._new(res) # PEP 484 requires int to be a subtype of float, but __truediv__ should # not accept int. def __truediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __truediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__truediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__truediv__(other._array) return self.__class__._new(res) def __xor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __xor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__xor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__xor__(other._array) return self.__class__._new(res) def __iadd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __iadd__. """ other = self._check_allowed_dtypes(other, "numeric", "__iadd__") if other is NotImplemented: return other self._array.__iadd__(other._array) return self def __radd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __radd__. """ other = self._check_allowed_dtypes(other, "numeric", "__radd__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__radd__(other._array) return self.__class__._new(res) def __iand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __iand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__iand__") if other is NotImplemented: return other self._array.__iand__(other._array) return self def __rand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rand__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rand__(other._array) return self.__class__._new(res) def __ifloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ifloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__ifloordiv__") if other is NotImplemented: return other self._array.__ifloordiv__(other._array) return self def __rfloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rfloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__rfloordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rfloordiv__(other._array) return self.__class__._new(res) def __ilshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __ilshift__. """ other = self._check_allowed_dtypes(other, "integer", "__ilshift__") if other is NotImplemented: return other self._array.__ilshift__(other._array) return self def __rlshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rlshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rlshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rlshift__(other._array) return self.__class__._new(res) def __imatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __imatmul__. """ # Note: NumPy does not implement __imatmul__. # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__imatmul__") if other is NotImplemented: return other # __imatmul__ can only be allowed when it would not change the shape # of self. other_shape = other.shape if self.shape == () or other_shape == (): raise ValueError("@= requires at least one dimension") if len(other_shape) == 1 or other_shape[-1] != other_shape[-2]: raise ValueError("@= cannot change the shape of the input array") self._array[:] = self._array.__matmul__(other._array) return self def __rmatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __rmatmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__rmatmul__") if other is NotImplemented: return other res = self._array.__rmatmul__(other._array) return self.__class__._new(res) def __imod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imod__. """ other = self._check_allowed_dtypes(other, "numeric", "__imod__") if other is NotImplemented: return other self._array.__imod__(other._array) return self def __rmod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmod__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmod__(other._array) return self.__class__._new(res) def __imul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imul__. """ other = self._check_allowed_dtypes(other, "numeric", "__imul__") if other is NotImplemented: return other self._array.__imul__(other._array) return self def __rmul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmul__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmul__(other._array) return self.__class__._new(res) def __ior__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ior__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ior__") if other is NotImplemented: return other self._array.__ior__(other._array) return self def __ror__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ror__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ror__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ror__(other._array) return self.__class__._new(res) def __ipow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ipow__. """ other = self._check_allowed_dtypes(other, "numeric", "__ipow__") if other is NotImplemented: return other self._array.__ipow__(other._array) return self def __rpow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rpow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__rpow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow the spec type promotion rules # for 0-d arrays, so we use pow() here instead. return pow(other, self) def __irshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __irshift__. """ other = self._check_allowed_dtypes(other, "integer", "__irshift__") if other is NotImplemented: return other self._array.__irshift__(other._array) return self def __rrshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rrshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rrshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rrshift__(other._array) return self.__class__._new(res) def __isub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __isub__. """ other = self._check_allowed_dtypes(other, "numeric", "__isub__") if other is NotImplemented: return other self._array.__isub__(other._array) return self def __rsub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rsub__. """ other = self._check_allowed_dtypes(other, "numeric", "__rsub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rsub__(other._array) return self.__class__._new(res) def __itruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __itruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__itruediv__") if other is NotImplemented: return other self._array.__itruediv__(other._array) return self def __rtruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __rtruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__rtruediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rtruediv__(other._array) return self.__class__._new(res) def __ixor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ixor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ixor__") if other is NotImplemented: return other self._array.__ixor__(other._array) return self def __rxor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rxor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rxor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rxor__(other._array) return self.__class__._new(res) def to_device(self: Array, device: Device, /, stream: None = None) -> Array: if stream is not None: raise ValueError("The stream argument to to_device() is not supported") if device == 'cpu': return self raise ValueError(f"Unsupported device {device!r}") def dtype(self) -> Dtype: """ Array API compatible wrapper for :py:meth:`np.ndarray.dtype <numpy.ndarray.dtype>`. See its docstring for more information. """ return self._array.dtype def device(self) -> Device: return "cpu" # Note: mT is new in array API spec (see matrix_transpose) def mT(self) -> Array: from .linalg import matrix_transpose return matrix_transpose(self) def ndim(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.ndim <numpy.ndarray.ndim>`. See its docstring for more information. """ return self._array.ndim def shape(self) -> Tuple[int, ...]: """ Array API compatible wrapper for :py:meth:`np.ndarray.shape <numpy.ndarray.shape>`. See its docstring for more information. """ return self._array.shape def size(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.size <numpy.ndarray.size>`. See its docstring for more information. """ return self._array.size def T(self) -> Array: """ Array API compatible wrapper for :py:meth:`np.ndarray.T <numpy.ndarray.T>`. See its docstring for more information. """ # Note: T only works on 2-dimensional arrays. See the corresponding # note in the specification: # https://data-apis.org/array-api/latest/API_specification/array_object.html#t if self.ndim != 2: raise ValueError("x.T requires x to have 2 dimensions. Use x.mT to transpose stacks of matrices and permute_dims() to permute dimensions.") return self.__class__._new(self._array.T) The provided code snippet includes necessary dependencies for implementing the `logical_or` function. Write a Python function `def logical_or(x1: Array, x2: Array, /) -> Array` to solve the following problem: Array API compatible wrapper for :py:func:`np.logical_or <numpy.logical_or>`. See its docstring for more information. Here is the function: def logical_or(x1: Array, x2: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.logical_or <numpy.logical_or>`. See its docstring for more information. """ if x1.dtype not in _boolean_dtypes or x2.dtype not in _boolean_dtypes: raise TypeError("Only boolean dtypes are allowed in logical_or") # Call result type here just to raise on disallowed type combinations _result_type(x1.dtype, x2.dtype) x1, x2 = Array._normalize_two_args(x1, x2) return Array._new(np.logical_or(x1._array, x2._array))
Array API compatible wrapper for :py:func:`np.logical_or <numpy.logical_or>`. See its docstring for more information.
170,058
from __future__ import annotations from ._dtypes import ( _boolean_dtypes, _floating_dtypes, _integer_dtypes, _integer_or_boolean_dtypes, _numeric_dtypes, _result_type, ) from ._array_object import Array import numpy as np _boolean_dtypes = (bool,) def _result_type(type1, type2): if (type1, type2) in _promotion_table: return _promotion_table[type1, type2] raise TypeError(f"{type1} and {type2} cannot be type promoted together") class Array: """ n-d array object for the array API namespace. See the docstring of :py:obj:`np.ndarray <numpy.ndarray>` for more information. This is a wrapper around numpy.ndarray that restricts the usage to only those things that are required by the array API namespace. Note, attributes on this object that start with a single underscore are not part of the API specification and should only be used internally. This object should not be constructed directly. Rather, use one of the creation functions, such as asarray(). """ _array: np.ndarray # Use a custom constructor instead of __init__, as manually initializing # this class is not supported API. def _new(cls, x, /): """ This is a private method for initializing the array API Array object. Functions outside of the array_api submodule should not use this method. Use one of the creation functions instead, such as ``asarray``. """ obj = super().__new__(cls) # Note: The spec does not have array scalars, only 0-D arrays. if isinstance(x, np.generic): # Convert the array scalar to a 0-D array x = np.asarray(x) if x.dtype not in _all_dtypes: raise TypeError( f"The array_api namespace does not support the dtype '{x.dtype}'" ) obj._array = x return obj # Prevent Array() from working def __new__(cls, *args, **kwargs): raise TypeError( "The array_api Array object should not be instantiated directly. Use an array creation function, such as asarray(), instead." ) # These functions are not required by the spec, but are implemented for # the sake of usability. def __str__(self: Array, /) -> str: """ Performs the operation __str__. """ return self._array.__str__().replace("array", "Array") def __repr__(self: Array, /) -> str: """ Performs the operation __repr__. """ suffix = f", dtype={self.dtype.name})" if 0 in self.shape: prefix = "empty(" mid = str(self.shape) else: prefix = "Array(" mid = np.array2string(self._array, separator=', ', prefix=prefix, suffix=suffix) return prefix + mid + suffix # This function is not required by the spec, but we implement it here for # convenience so that np.asarray(np.array_api.Array) will work. def __array__(self, dtype: None | np.dtype[Any] = None) -> npt.NDArray[Any]: """ Warning: this method is NOT part of the array API spec. Implementers of other libraries need not include it, and users should not assume it will be present in other implementations. """ return np.asarray(self._array, dtype=dtype) # These are various helper functions to make the array behavior match the # spec in places where it either deviates from or is more strict than # NumPy behavior def _check_allowed_dtypes(self, other: bool | int | float | Array, dtype_category: str, op: str) -> Array: """ Helper function for operators to only allow specific input dtypes Use like other = self._check_allowed_dtypes(other, 'numeric', '__add__') if other is NotImplemented: return other """ if self.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") if isinstance(other, (int, float, bool)): other = self._promote_scalar(other) elif isinstance(other, Array): if other.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") else: return NotImplemented # This will raise TypeError for type combinations that are not allowed # to promote in the spec (even if the NumPy array operator would # promote them). res_dtype = _result_type(self.dtype, other.dtype) if op.startswith("__i"): # Note: NumPy will allow in-place operators in some cases where # the type promoted operator does not match the left-hand side # operand. For example, # >>> a = np.array(1, dtype=np.int8) # >>> a += np.array(1, dtype=np.int16) # The spec explicitly disallows this. if res_dtype != self.dtype: raise TypeError( f"Cannot perform {op} with dtypes {self.dtype} and {other.dtype}" ) return other # Helper function to match the type promotion rules in the spec def _promote_scalar(self, scalar): """ Returns a promoted version of a Python scalar appropriate for use with operations on self. This may raise an OverflowError in cases where the scalar is an integer that is too large to fit in a NumPy integer dtype, or TypeError when the scalar type is incompatible with the dtype of self. """ # Note: Only Python scalar types that match the array dtype are # allowed. if isinstance(scalar, bool): if self.dtype not in _boolean_dtypes: raise TypeError( "Python bool scalars can only be promoted with bool arrays" ) elif isinstance(scalar, int): if self.dtype in _boolean_dtypes: raise TypeError( "Python int scalars cannot be promoted with bool arrays" ) elif isinstance(scalar, float): if self.dtype not in _floating_dtypes: raise TypeError( "Python float scalars can only be promoted with floating-point arrays." ) else: raise TypeError("'scalar' must be a Python scalar") # Note: scalars are unconditionally cast to the same dtype as the # array. # Note: the spec only specifies integer-dtype/int promotion # behavior for integers within the bounds of the integer dtype. # Outside of those bounds we use the default NumPy behavior (either # cast or raise OverflowError). return Array._new(np.array(scalar, self.dtype)) def _normalize_two_args(x1, x2) -> Tuple[Array, Array]: """ Normalize inputs to two arg functions to fix type promotion rules NumPy deviates from the spec type promotion rules in cases where one argument is 0-dimensional and the other is not. For example: >>> import numpy as np >>> a = np.array([1.0], dtype=np.float32) >>> b = np.array(1.0, dtype=np.float64) >>> np.add(a, b) # The spec says this should be float64 array([2.], dtype=float32) To fix this, we add a dimension to the 0-dimension array before passing it through. This works because a dimension would be added anyway from broadcasting, so the resulting shape is the same, but this prevents NumPy from not promoting the dtype. """ # Another option would be to use signature=(x1.dtype, x2.dtype, None), # but that only works for ufuncs, so we would have to call the ufuncs # directly in the operator methods. One should also note that this # sort of trick wouldn't work for functions like searchsorted, which # don't do normal broadcasting, but there aren't any functions like # that in the array API namespace. if x1.ndim == 0 and x2.ndim != 0: # The _array[None] workaround was chosen because it is relatively # performant. broadcast_to(x1._array, x2.shape) is much slower. We # could also manually type promote x2, but that is more complicated # and about the same performance as this. x1 = Array._new(x1._array[None]) elif x2.ndim == 0 and x1.ndim != 0: x2 = Array._new(x2._array[None]) return (x1, x2) # Note: A large fraction of allowed indices are disallowed here (see the # docstring below) def _validate_index(self, key): """ Validate an index according to the array API. The array API specification only requires a subset of indices that are supported by NumPy. This function will reject any index that is allowed by NumPy but not required by the array API specification. We always raise ``IndexError`` on such indices (the spec does not require any specific behavior on them, but this makes the NumPy array API namespace a minimal implementation of the spec). See https://data-apis.org/array-api/latest/API_specification/indexing.html for the full list of required indexing behavior This function raises IndexError if the index ``key`` is invalid. It only raises ``IndexError`` on indices that are not already rejected by NumPy, as NumPy will already raise the appropriate error on such indices. ``shape`` may be None, in which case, only cases that are independent of the array shape are checked. The following cases are allowed by NumPy, but not specified by the array API specification: - Indices to not include an implicit ellipsis at the end. That is, every axis of an array must be explicitly indexed or an ellipsis included. This behaviour is sometimes referred to as flat indexing. - The start and stop of a slice may not be out of bounds. In particular, for a slice ``i:j:k`` on an axis of size ``n``, only the following are allowed: - ``i`` or ``j`` omitted (``None``). - ``-n <= i <= max(0, n - 1)``. - For ``k > 0`` or ``k`` omitted (``None``), ``-n <= j <= n``. - For ``k < 0``, ``-n - 1 <= j <= max(0, n - 1)``. - Boolean array indices are not allowed as part of a larger tuple index. - Integer array indices are not allowed (with the exception of 0-D arrays, which are treated the same as scalars). Additionally, it should be noted that indices that would return a scalar in NumPy will return a 0-D array. Array scalars are not allowed in the specification, only 0-D arrays. This is done in the ``Array._new`` constructor, not this function. """ _key = key if isinstance(key, tuple) else (key,) for i in _key: if isinstance(i, bool) or not ( isinstance(i, SupportsIndex) # i.e. ints or isinstance(i, slice) or i == Ellipsis or i is None or isinstance(i, Array) or isinstance(i, np.ndarray) ): raise IndexError( f"Single-axes index {i} has {type(i)=}, but only " "integers, slices (:), ellipsis (...), newaxis (None), " "zero-dimensional integer arrays and boolean arrays " "are specified in the Array API." ) nonexpanding_key = [] single_axes = [] n_ellipsis = 0 key_has_mask = False for i in _key: if i is not None: nonexpanding_key.append(i) if isinstance(i, Array) or isinstance(i, np.ndarray): if i.dtype in _boolean_dtypes: key_has_mask = True single_axes.append(i) else: # i must not be an array here, to avoid elementwise equals if i == Ellipsis: n_ellipsis += 1 else: single_axes.append(i) n_single_axes = len(single_axes) if n_ellipsis > 1: return # handled by ndarray elif n_ellipsis == 0: # Note boolean masks must be the sole index, which we check for # later on. if not key_has_mask and n_single_axes < self.ndim: raise IndexError( f"{self.ndim=}, but the multi-axes index only specifies " f"{n_single_axes} dimensions. If this was intentional, " "add a trailing ellipsis (...) which expands into as many " "slices (:) as necessary - this is what np.ndarray arrays " "implicitly do, but such flat indexing behaviour is not " "specified in the Array API." ) if n_ellipsis == 0: indexed_shape = self.shape else: ellipsis_start = None for pos, i in enumerate(nonexpanding_key): if not (isinstance(i, Array) or isinstance(i, np.ndarray)): if i == Ellipsis: ellipsis_start = pos break assert ellipsis_start is not None # sanity check ellipsis_end = self.ndim - (n_single_axes - ellipsis_start) indexed_shape = ( self.shape[:ellipsis_start] + self.shape[ellipsis_end:] ) for i, side in zip(single_axes, indexed_shape): if isinstance(i, slice): if side == 0: f_range = "0 (or None)" else: f_range = f"between -{side} and {side - 1} (or None)" if i.start is not None: try: start = operator.index(i.start) except TypeError: pass # handled by ndarray else: if not (-side <= start <= side): raise IndexError( f"Slice {i} contains {start=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds starts are not specified in " "the Array API)" ) if i.stop is not None: try: stop = operator.index(i.stop) except TypeError: pass # handled by ndarray else: if not (-side <= stop <= side): raise IndexError( f"Slice {i} contains {stop=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds stops are not specified in " "the Array API)" ) elif isinstance(i, Array): if i.dtype in _boolean_dtypes and len(_key) != 1: assert isinstance(key, tuple) # sanity check raise IndexError( f"Single-axes index {i} is a boolean array and " f"{len(key)=}, but masking is only specified in the " "Array API when the array is the sole index." ) elif i.dtype in _integer_dtypes and i.ndim != 0: raise IndexError( f"Single-axes index {i} is a non-zero-dimensional " "integer array, but advanced integer indexing is not " "specified in the Array API." ) elif isinstance(i, tuple): raise IndexError( f"Single-axes index {i} is a tuple, but nested tuple " "indices are not specified in the Array API." ) # Everything below this line is required by the spec. def __abs__(self: Array, /) -> Array: """ Performs the operation __abs__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __abs__") res = self._array.__abs__() return self.__class__._new(res) def __add__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __add__. """ other = self._check_allowed_dtypes(other, "numeric", "__add__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__add__(other._array) return self.__class__._new(res) def __and__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __and__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__and__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__and__(other._array) return self.__class__._new(res) def __array_namespace__( self: Array, /, *, api_version: Optional[str] = None ) -> types.ModuleType: if api_version is not None and not api_version.startswith("2021."): raise ValueError(f"Unrecognized array API version: {api_version!r}") return array_api def __bool__(self: Array, /) -> bool: """ Performs the operation __bool__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("bool is only allowed on arrays with 0 dimensions") if self.dtype not in _boolean_dtypes: raise ValueError("bool is only allowed on boolean arrays") res = self._array.__bool__() return res def __dlpack__(self: Array, /, *, stream: None = None) -> PyCapsule: """ Performs the operation __dlpack__. """ return self._array.__dlpack__(stream=stream) def __dlpack_device__(self: Array, /) -> Tuple[IntEnum, int]: """ Performs the operation __dlpack_device__. """ # Note: device support is required for this return self._array.__dlpack_device__() def __eq__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __eq__. """ # Even though "all" dtypes are allowed, we still require them to be # promotable with each other. other = self._check_allowed_dtypes(other, "all", "__eq__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__eq__(other._array) return self.__class__._new(res) def __float__(self: Array, /) -> float: """ Performs the operation __float__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("float is only allowed on arrays with 0 dimensions") if self.dtype not in _floating_dtypes: raise ValueError("float is only allowed on floating-point arrays") res = self._array.__float__() return res def __floordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __floordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__floordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__floordiv__(other._array) return self.__class__._new(res) def __ge__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ge__. """ other = self._check_allowed_dtypes(other, "numeric", "__ge__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ge__(other._array) return self.__class__._new(res) def __getitem__( self: Array, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], /, ) -> Array: """ Performs the operation __getitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array res = self._array.__getitem__(key) return self._new(res) def __gt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __gt__. """ other = self._check_allowed_dtypes(other, "numeric", "__gt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__gt__(other._array) return self.__class__._new(res) def __int__(self: Array, /) -> int: """ Performs the operation __int__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("int is only allowed on arrays with 0 dimensions") if self.dtype not in _integer_dtypes: raise ValueError("int is only allowed on integer arrays") res = self._array.__int__() return res def __index__(self: Array, /) -> int: """ Performs the operation __index__. """ res = self._array.__index__() return res def __invert__(self: Array, /) -> Array: """ Performs the operation __invert__. """ if self.dtype not in _integer_or_boolean_dtypes: raise TypeError("Only integer or boolean dtypes are allowed in __invert__") res = self._array.__invert__() return self.__class__._new(res) def __le__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __le__. """ other = self._check_allowed_dtypes(other, "numeric", "__le__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__le__(other._array) return self.__class__._new(res) def __lshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __lshift__. """ other = self._check_allowed_dtypes(other, "integer", "__lshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lshift__(other._array) return self.__class__._new(res) def __lt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __lt__. """ other = self._check_allowed_dtypes(other, "numeric", "__lt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lt__(other._array) return self.__class__._new(res) def __matmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __matmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__matmul__") if other is NotImplemented: return other res = self._array.__matmul__(other._array) return self.__class__._new(res) def __mod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mod__. """ other = self._check_allowed_dtypes(other, "numeric", "__mod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mod__(other._array) return self.__class__._new(res) def __mul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mul__. """ other = self._check_allowed_dtypes(other, "numeric", "__mul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mul__(other._array) return self.__class__._new(res) def __ne__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __ne__. """ other = self._check_allowed_dtypes(other, "all", "__ne__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ne__(other._array) return self.__class__._new(res) def __neg__(self: Array, /) -> Array: """ Performs the operation __neg__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __neg__") res = self._array.__neg__() return self.__class__._new(res) def __or__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __or__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__or__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__or__(other._array) return self.__class__._new(res) def __pos__(self: Array, /) -> Array: """ Performs the operation __pos__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __pos__") res = self._array.__pos__() return self.__class__._new(res) def __pow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __pow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__pow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow type promotion rules for 0-d # arrays, so we use pow() here instead. return pow(self, other) def __rshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rshift__(other._array) return self.__class__._new(res) def __setitem__( self, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], value: Union[int, float, bool, Array], /, ) -> None: """ Performs the operation __setitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array self._array.__setitem__(key, asarray(value)._array) def __sub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __sub__. """ other = self._check_allowed_dtypes(other, "numeric", "__sub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__sub__(other._array) return self.__class__._new(res) # PEP 484 requires int to be a subtype of float, but __truediv__ should # not accept int. def __truediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __truediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__truediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__truediv__(other._array) return self.__class__._new(res) def __xor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __xor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__xor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__xor__(other._array) return self.__class__._new(res) def __iadd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __iadd__. """ other = self._check_allowed_dtypes(other, "numeric", "__iadd__") if other is NotImplemented: return other self._array.__iadd__(other._array) return self def __radd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __radd__. """ other = self._check_allowed_dtypes(other, "numeric", "__radd__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__radd__(other._array) return self.__class__._new(res) def __iand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __iand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__iand__") if other is NotImplemented: return other self._array.__iand__(other._array) return self def __rand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rand__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rand__(other._array) return self.__class__._new(res) def __ifloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ifloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__ifloordiv__") if other is NotImplemented: return other self._array.__ifloordiv__(other._array) return self def __rfloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rfloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__rfloordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rfloordiv__(other._array) return self.__class__._new(res) def __ilshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __ilshift__. """ other = self._check_allowed_dtypes(other, "integer", "__ilshift__") if other is NotImplemented: return other self._array.__ilshift__(other._array) return self def __rlshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rlshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rlshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rlshift__(other._array) return self.__class__._new(res) def __imatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __imatmul__. """ # Note: NumPy does not implement __imatmul__. # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__imatmul__") if other is NotImplemented: return other # __imatmul__ can only be allowed when it would not change the shape # of self. other_shape = other.shape if self.shape == () or other_shape == (): raise ValueError("@= requires at least one dimension") if len(other_shape) == 1 or other_shape[-1] != other_shape[-2]: raise ValueError("@= cannot change the shape of the input array") self._array[:] = self._array.__matmul__(other._array) return self def __rmatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __rmatmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__rmatmul__") if other is NotImplemented: return other res = self._array.__rmatmul__(other._array) return self.__class__._new(res) def __imod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imod__. """ other = self._check_allowed_dtypes(other, "numeric", "__imod__") if other is NotImplemented: return other self._array.__imod__(other._array) return self def __rmod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmod__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmod__(other._array) return self.__class__._new(res) def __imul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imul__. """ other = self._check_allowed_dtypes(other, "numeric", "__imul__") if other is NotImplemented: return other self._array.__imul__(other._array) return self def __rmul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmul__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmul__(other._array) return self.__class__._new(res) def __ior__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ior__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ior__") if other is NotImplemented: return other self._array.__ior__(other._array) return self def __ror__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ror__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ror__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ror__(other._array) return self.__class__._new(res) def __ipow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ipow__. """ other = self._check_allowed_dtypes(other, "numeric", "__ipow__") if other is NotImplemented: return other self._array.__ipow__(other._array) return self def __rpow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rpow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__rpow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow the spec type promotion rules # for 0-d arrays, so we use pow() here instead. return pow(other, self) def __irshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __irshift__. """ other = self._check_allowed_dtypes(other, "integer", "__irshift__") if other is NotImplemented: return other self._array.__irshift__(other._array) return self def __rrshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rrshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rrshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rrshift__(other._array) return self.__class__._new(res) def __isub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __isub__. """ other = self._check_allowed_dtypes(other, "numeric", "__isub__") if other is NotImplemented: return other self._array.__isub__(other._array) return self def __rsub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rsub__. """ other = self._check_allowed_dtypes(other, "numeric", "__rsub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rsub__(other._array) return self.__class__._new(res) def __itruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __itruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__itruediv__") if other is NotImplemented: return other self._array.__itruediv__(other._array) return self def __rtruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __rtruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__rtruediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rtruediv__(other._array) return self.__class__._new(res) def __ixor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ixor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ixor__") if other is NotImplemented: return other self._array.__ixor__(other._array) return self def __rxor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rxor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rxor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rxor__(other._array) return self.__class__._new(res) def to_device(self: Array, device: Device, /, stream: None = None) -> Array: if stream is not None: raise ValueError("The stream argument to to_device() is not supported") if device == 'cpu': return self raise ValueError(f"Unsupported device {device!r}") def dtype(self) -> Dtype: """ Array API compatible wrapper for :py:meth:`np.ndarray.dtype <numpy.ndarray.dtype>`. See its docstring for more information. """ return self._array.dtype def device(self) -> Device: return "cpu" # Note: mT is new in array API spec (see matrix_transpose) def mT(self) -> Array: from .linalg import matrix_transpose return matrix_transpose(self) def ndim(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.ndim <numpy.ndarray.ndim>`. See its docstring for more information. """ return self._array.ndim def shape(self) -> Tuple[int, ...]: """ Array API compatible wrapper for :py:meth:`np.ndarray.shape <numpy.ndarray.shape>`. See its docstring for more information. """ return self._array.shape def size(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.size <numpy.ndarray.size>`. See its docstring for more information. """ return self._array.size def T(self) -> Array: """ Array API compatible wrapper for :py:meth:`np.ndarray.T <numpy.ndarray.T>`. See its docstring for more information. """ # Note: T only works on 2-dimensional arrays. See the corresponding # note in the specification: # https://data-apis.org/array-api/latest/API_specification/array_object.html#t if self.ndim != 2: raise ValueError("x.T requires x to have 2 dimensions. Use x.mT to transpose stacks of matrices and permute_dims() to permute dimensions.") return self.__class__._new(self._array.T) The provided code snippet includes necessary dependencies for implementing the `logical_xor` function. Write a Python function `def logical_xor(x1: Array, x2: Array, /) -> Array` to solve the following problem: Array API compatible wrapper for :py:func:`np.logical_xor <numpy.logical_xor>`. See its docstring for more information. Here is the function: def logical_xor(x1: Array, x2: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.logical_xor <numpy.logical_xor>`. See its docstring for more information. """ if x1.dtype not in _boolean_dtypes or x2.dtype not in _boolean_dtypes: raise TypeError("Only boolean dtypes are allowed in logical_xor") # Call result type here just to raise on disallowed type combinations _result_type(x1.dtype, x2.dtype) x1, x2 = Array._normalize_two_args(x1, x2) return Array._new(np.logical_xor(x1._array, x2._array))
Array API compatible wrapper for :py:func:`np.logical_xor <numpy.logical_xor>`. See its docstring for more information.
170,059
from __future__ import annotations from ._dtypes import ( _boolean_dtypes, _floating_dtypes, _integer_dtypes, _integer_or_boolean_dtypes, _numeric_dtypes, _result_type, ) from ._array_object import Array import numpy as np _numeric_dtypes = ( float32, float64, int8, int16, int32, int64, uint8, uint16, uint32, uint64, ) def _result_type(type1, type2): if (type1, type2) in _promotion_table: return _promotion_table[type1, type2] raise TypeError(f"{type1} and {type2} cannot be type promoted together") class Array: """ n-d array object for the array API namespace. See the docstring of :py:obj:`np.ndarray <numpy.ndarray>` for more information. This is a wrapper around numpy.ndarray that restricts the usage to only those things that are required by the array API namespace. Note, attributes on this object that start with a single underscore are not part of the API specification and should only be used internally. This object should not be constructed directly. Rather, use one of the creation functions, such as asarray(). """ _array: np.ndarray # Use a custom constructor instead of __init__, as manually initializing # this class is not supported API. def _new(cls, x, /): """ This is a private method for initializing the array API Array object. Functions outside of the array_api submodule should not use this method. Use one of the creation functions instead, such as ``asarray``. """ obj = super().__new__(cls) # Note: The spec does not have array scalars, only 0-D arrays. if isinstance(x, np.generic): # Convert the array scalar to a 0-D array x = np.asarray(x) if x.dtype not in _all_dtypes: raise TypeError( f"The array_api namespace does not support the dtype '{x.dtype}'" ) obj._array = x return obj # Prevent Array() from working def __new__(cls, *args, **kwargs): raise TypeError( "The array_api Array object should not be instantiated directly. Use an array creation function, such as asarray(), instead." ) # These functions are not required by the spec, but are implemented for # the sake of usability. def __str__(self: Array, /) -> str: """ Performs the operation __str__. """ return self._array.__str__().replace("array", "Array") def __repr__(self: Array, /) -> str: """ Performs the operation __repr__. """ suffix = f", dtype={self.dtype.name})" if 0 in self.shape: prefix = "empty(" mid = str(self.shape) else: prefix = "Array(" mid = np.array2string(self._array, separator=', ', prefix=prefix, suffix=suffix) return prefix + mid + suffix # This function is not required by the spec, but we implement it here for # convenience so that np.asarray(np.array_api.Array) will work. def __array__(self, dtype: None | np.dtype[Any] = None) -> npt.NDArray[Any]: """ Warning: this method is NOT part of the array API spec. Implementers of other libraries need not include it, and users should not assume it will be present in other implementations. """ return np.asarray(self._array, dtype=dtype) # These are various helper functions to make the array behavior match the # spec in places where it either deviates from or is more strict than # NumPy behavior def _check_allowed_dtypes(self, other: bool | int | float | Array, dtype_category: str, op: str) -> Array: """ Helper function for operators to only allow specific input dtypes Use like other = self._check_allowed_dtypes(other, 'numeric', '__add__') if other is NotImplemented: return other """ if self.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") if isinstance(other, (int, float, bool)): other = self._promote_scalar(other) elif isinstance(other, Array): if other.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") else: return NotImplemented # This will raise TypeError for type combinations that are not allowed # to promote in the spec (even if the NumPy array operator would # promote them). res_dtype = _result_type(self.dtype, other.dtype) if op.startswith("__i"): # Note: NumPy will allow in-place operators in some cases where # the type promoted operator does not match the left-hand side # operand. For example, # >>> a = np.array(1, dtype=np.int8) # >>> a += np.array(1, dtype=np.int16) # The spec explicitly disallows this. if res_dtype != self.dtype: raise TypeError( f"Cannot perform {op} with dtypes {self.dtype} and {other.dtype}" ) return other # Helper function to match the type promotion rules in the spec def _promote_scalar(self, scalar): """ Returns a promoted version of a Python scalar appropriate for use with operations on self. This may raise an OverflowError in cases where the scalar is an integer that is too large to fit in a NumPy integer dtype, or TypeError when the scalar type is incompatible with the dtype of self. """ # Note: Only Python scalar types that match the array dtype are # allowed. if isinstance(scalar, bool): if self.dtype not in _boolean_dtypes: raise TypeError( "Python bool scalars can only be promoted with bool arrays" ) elif isinstance(scalar, int): if self.dtype in _boolean_dtypes: raise TypeError( "Python int scalars cannot be promoted with bool arrays" ) elif isinstance(scalar, float): if self.dtype not in _floating_dtypes: raise TypeError( "Python float scalars can only be promoted with floating-point arrays." ) else: raise TypeError("'scalar' must be a Python scalar") # Note: scalars are unconditionally cast to the same dtype as the # array. # Note: the spec only specifies integer-dtype/int promotion # behavior for integers within the bounds of the integer dtype. # Outside of those bounds we use the default NumPy behavior (either # cast or raise OverflowError). return Array._new(np.array(scalar, self.dtype)) def _normalize_two_args(x1, x2) -> Tuple[Array, Array]: """ Normalize inputs to two arg functions to fix type promotion rules NumPy deviates from the spec type promotion rules in cases where one argument is 0-dimensional and the other is not. For example: >>> import numpy as np >>> a = np.array([1.0], dtype=np.float32) >>> b = np.array(1.0, dtype=np.float64) >>> np.add(a, b) # The spec says this should be float64 array([2.], dtype=float32) To fix this, we add a dimension to the 0-dimension array before passing it through. This works because a dimension would be added anyway from broadcasting, so the resulting shape is the same, but this prevents NumPy from not promoting the dtype. """ # Another option would be to use signature=(x1.dtype, x2.dtype, None), # but that only works for ufuncs, so we would have to call the ufuncs # directly in the operator methods. One should also note that this # sort of trick wouldn't work for functions like searchsorted, which # don't do normal broadcasting, but there aren't any functions like # that in the array API namespace. if x1.ndim == 0 and x2.ndim != 0: # The _array[None] workaround was chosen because it is relatively # performant. broadcast_to(x1._array, x2.shape) is much slower. We # could also manually type promote x2, but that is more complicated # and about the same performance as this. x1 = Array._new(x1._array[None]) elif x2.ndim == 0 and x1.ndim != 0: x2 = Array._new(x2._array[None]) return (x1, x2) # Note: A large fraction of allowed indices are disallowed here (see the # docstring below) def _validate_index(self, key): """ Validate an index according to the array API. The array API specification only requires a subset of indices that are supported by NumPy. This function will reject any index that is allowed by NumPy but not required by the array API specification. We always raise ``IndexError`` on such indices (the spec does not require any specific behavior on them, but this makes the NumPy array API namespace a minimal implementation of the spec). See https://data-apis.org/array-api/latest/API_specification/indexing.html for the full list of required indexing behavior This function raises IndexError if the index ``key`` is invalid. It only raises ``IndexError`` on indices that are not already rejected by NumPy, as NumPy will already raise the appropriate error on such indices. ``shape`` may be None, in which case, only cases that are independent of the array shape are checked. The following cases are allowed by NumPy, but not specified by the array API specification: - Indices to not include an implicit ellipsis at the end. That is, every axis of an array must be explicitly indexed or an ellipsis included. This behaviour is sometimes referred to as flat indexing. - The start and stop of a slice may not be out of bounds. In particular, for a slice ``i:j:k`` on an axis of size ``n``, only the following are allowed: - ``i`` or ``j`` omitted (``None``). - ``-n <= i <= max(0, n - 1)``. - For ``k > 0`` or ``k`` omitted (``None``), ``-n <= j <= n``. - For ``k < 0``, ``-n - 1 <= j <= max(0, n - 1)``. - Boolean array indices are not allowed as part of a larger tuple index. - Integer array indices are not allowed (with the exception of 0-D arrays, which are treated the same as scalars). Additionally, it should be noted that indices that would return a scalar in NumPy will return a 0-D array. Array scalars are not allowed in the specification, only 0-D arrays. This is done in the ``Array._new`` constructor, not this function. """ _key = key if isinstance(key, tuple) else (key,) for i in _key: if isinstance(i, bool) or not ( isinstance(i, SupportsIndex) # i.e. ints or isinstance(i, slice) or i == Ellipsis or i is None or isinstance(i, Array) or isinstance(i, np.ndarray) ): raise IndexError( f"Single-axes index {i} has {type(i)=}, but only " "integers, slices (:), ellipsis (...), newaxis (None), " "zero-dimensional integer arrays and boolean arrays " "are specified in the Array API." ) nonexpanding_key = [] single_axes = [] n_ellipsis = 0 key_has_mask = False for i in _key: if i is not None: nonexpanding_key.append(i) if isinstance(i, Array) or isinstance(i, np.ndarray): if i.dtype in _boolean_dtypes: key_has_mask = True single_axes.append(i) else: # i must not be an array here, to avoid elementwise equals if i == Ellipsis: n_ellipsis += 1 else: single_axes.append(i) n_single_axes = len(single_axes) if n_ellipsis > 1: return # handled by ndarray elif n_ellipsis == 0: # Note boolean masks must be the sole index, which we check for # later on. if not key_has_mask and n_single_axes < self.ndim: raise IndexError( f"{self.ndim=}, but the multi-axes index only specifies " f"{n_single_axes} dimensions. If this was intentional, " "add a trailing ellipsis (...) which expands into as many " "slices (:) as necessary - this is what np.ndarray arrays " "implicitly do, but such flat indexing behaviour is not " "specified in the Array API." ) if n_ellipsis == 0: indexed_shape = self.shape else: ellipsis_start = None for pos, i in enumerate(nonexpanding_key): if not (isinstance(i, Array) or isinstance(i, np.ndarray)): if i == Ellipsis: ellipsis_start = pos break assert ellipsis_start is not None # sanity check ellipsis_end = self.ndim - (n_single_axes - ellipsis_start) indexed_shape = ( self.shape[:ellipsis_start] + self.shape[ellipsis_end:] ) for i, side in zip(single_axes, indexed_shape): if isinstance(i, slice): if side == 0: f_range = "0 (or None)" else: f_range = f"between -{side} and {side - 1} (or None)" if i.start is not None: try: start = operator.index(i.start) except TypeError: pass # handled by ndarray else: if not (-side <= start <= side): raise IndexError( f"Slice {i} contains {start=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds starts are not specified in " "the Array API)" ) if i.stop is not None: try: stop = operator.index(i.stop) except TypeError: pass # handled by ndarray else: if not (-side <= stop <= side): raise IndexError( f"Slice {i} contains {stop=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds stops are not specified in " "the Array API)" ) elif isinstance(i, Array): if i.dtype in _boolean_dtypes and len(_key) != 1: assert isinstance(key, tuple) # sanity check raise IndexError( f"Single-axes index {i} is a boolean array and " f"{len(key)=}, but masking is only specified in the " "Array API when the array is the sole index." ) elif i.dtype in _integer_dtypes and i.ndim != 0: raise IndexError( f"Single-axes index {i} is a non-zero-dimensional " "integer array, but advanced integer indexing is not " "specified in the Array API." ) elif isinstance(i, tuple): raise IndexError( f"Single-axes index {i} is a tuple, but nested tuple " "indices are not specified in the Array API." ) # Everything below this line is required by the spec. def __abs__(self: Array, /) -> Array: """ Performs the operation __abs__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __abs__") res = self._array.__abs__() return self.__class__._new(res) def __add__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __add__. """ other = self._check_allowed_dtypes(other, "numeric", "__add__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__add__(other._array) return self.__class__._new(res) def __and__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __and__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__and__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__and__(other._array) return self.__class__._new(res) def __array_namespace__( self: Array, /, *, api_version: Optional[str] = None ) -> types.ModuleType: if api_version is not None and not api_version.startswith("2021."): raise ValueError(f"Unrecognized array API version: {api_version!r}") return array_api def __bool__(self: Array, /) -> bool: """ Performs the operation __bool__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("bool is only allowed on arrays with 0 dimensions") if self.dtype not in _boolean_dtypes: raise ValueError("bool is only allowed on boolean arrays") res = self._array.__bool__() return res def __dlpack__(self: Array, /, *, stream: None = None) -> PyCapsule: """ Performs the operation __dlpack__. """ return self._array.__dlpack__(stream=stream) def __dlpack_device__(self: Array, /) -> Tuple[IntEnum, int]: """ Performs the operation __dlpack_device__. """ # Note: device support is required for this return self._array.__dlpack_device__() def __eq__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __eq__. """ # Even though "all" dtypes are allowed, we still require them to be # promotable with each other. other = self._check_allowed_dtypes(other, "all", "__eq__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__eq__(other._array) return self.__class__._new(res) def __float__(self: Array, /) -> float: """ Performs the operation __float__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("float is only allowed on arrays with 0 dimensions") if self.dtype not in _floating_dtypes: raise ValueError("float is only allowed on floating-point arrays") res = self._array.__float__() return res def __floordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __floordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__floordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__floordiv__(other._array) return self.__class__._new(res) def __ge__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ge__. """ other = self._check_allowed_dtypes(other, "numeric", "__ge__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ge__(other._array) return self.__class__._new(res) def __getitem__( self: Array, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], /, ) -> Array: """ Performs the operation __getitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array res = self._array.__getitem__(key) return self._new(res) def __gt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __gt__. """ other = self._check_allowed_dtypes(other, "numeric", "__gt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__gt__(other._array) return self.__class__._new(res) def __int__(self: Array, /) -> int: """ Performs the operation __int__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("int is only allowed on arrays with 0 dimensions") if self.dtype not in _integer_dtypes: raise ValueError("int is only allowed on integer arrays") res = self._array.__int__() return res def __index__(self: Array, /) -> int: """ Performs the operation __index__. """ res = self._array.__index__() return res def __invert__(self: Array, /) -> Array: """ Performs the operation __invert__. """ if self.dtype not in _integer_or_boolean_dtypes: raise TypeError("Only integer or boolean dtypes are allowed in __invert__") res = self._array.__invert__() return self.__class__._new(res) def __le__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __le__. """ other = self._check_allowed_dtypes(other, "numeric", "__le__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__le__(other._array) return self.__class__._new(res) def __lshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __lshift__. """ other = self._check_allowed_dtypes(other, "integer", "__lshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lshift__(other._array) return self.__class__._new(res) def __lt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __lt__. """ other = self._check_allowed_dtypes(other, "numeric", "__lt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lt__(other._array) return self.__class__._new(res) def __matmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __matmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__matmul__") if other is NotImplemented: return other res = self._array.__matmul__(other._array) return self.__class__._new(res) def __mod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mod__. """ other = self._check_allowed_dtypes(other, "numeric", "__mod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mod__(other._array) return self.__class__._new(res) def __mul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mul__. """ other = self._check_allowed_dtypes(other, "numeric", "__mul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mul__(other._array) return self.__class__._new(res) def __ne__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __ne__. """ other = self._check_allowed_dtypes(other, "all", "__ne__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ne__(other._array) return self.__class__._new(res) def __neg__(self: Array, /) -> Array: """ Performs the operation __neg__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __neg__") res = self._array.__neg__() return self.__class__._new(res) def __or__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __or__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__or__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__or__(other._array) return self.__class__._new(res) def __pos__(self: Array, /) -> Array: """ Performs the operation __pos__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __pos__") res = self._array.__pos__() return self.__class__._new(res) def __pow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __pow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__pow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow type promotion rules for 0-d # arrays, so we use pow() here instead. return pow(self, other) def __rshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rshift__(other._array) return self.__class__._new(res) def __setitem__( self, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], value: Union[int, float, bool, Array], /, ) -> None: """ Performs the operation __setitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array self._array.__setitem__(key, asarray(value)._array) def __sub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __sub__. """ other = self._check_allowed_dtypes(other, "numeric", "__sub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__sub__(other._array) return self.__class__._new(res) # PEP 484 requires int to be a subtype of float, but __truediv__ should # not accept int. def __truediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __truediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__truediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__truediv__(other._array) return self.__class__._new(res) def __xor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __xor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__xor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__xor__(other._array) return self.__class__._new(res) def __iadd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __iadd__. """ other = self._check_allowed_dtypes(other, "numeric", "__iadd__") if other is NotImplemented: return other self._array.__iadd__(other._array) return self def __radd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __radd__. """ other = self._check_allowed_dtypes(other, "numeric", "__radd__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__radd__(other._array) return self.__class__._new(res) def __iand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __iand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__iand__") if other is NotImplemented: return other self._array.__iand__(other._array) return self def __rand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rand__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rand__(other._array) return self.__class__._new(res) def __ifloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ifloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__ifloordiv__") if other is NotImplemented: return other self._array.__ifloordiv__(other._array) return self def __rfloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rfloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__rfloordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rfloordiv__(other._array) return self.__class__._new(res) def __ilshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __ilshift__. """ other = self._check_allowed_dtypes(other, "integer", "__ilshift__") if other is NotImplemented: return other self._array.__ilshift__(other._array) return self def __rlshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rlshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rlshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rlshift__(other._array) return self.__class__._new(res) def __imatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __imatmul__. """ # Note: NumPy does not implement __imatmul__. # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__imatmul__") if other is NotImplemented: return other # __imatmul__ can only be allowed when it would not change the shape # of self. other_shape = other.shape if self.shape == () or other_shape == (): raise ValueError("@= requires at least one dimension") if len(other_shape) == 1 or other_shape[-1] != other_shape[-2]: raise ValueError("@= cannot change the shape of the input array") self._array[:] = self._array.__matmul__(other._array) return self def __rmatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __rmatmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__rmatmul__") if other is NotImplemented: return other res = self._array.__rmatmul__(other._array) return self.__class__._new(res) def __imod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imod__. """ other = self._check_allowed_dtypes(other, "numeric", "__imod__") if other is NotImplemented: return other self._array.__imod__(other._array) return self def __rmod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmod__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmod__(other._array) return self.__class__._new(res) def __imul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imul__. """ other = self._check_allowed_dtypes(other, "numeric", "__imul__") if other is NotImplemented: return other self._array.__imul__(other._array) return self def __rmul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmul__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmul__(other._array) return self.__class__._new(res) def __ior__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ior__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ior__") if other is NotImplemented: return other self._array.__ior__(other._array) return self def __ror__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ror__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ror__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ror__(other._array) return self.__class__._new(res) def __ipow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ipow__. """ other = self._check_allowed_dtypes(other, "numeric", "__ipow__") if other is NotImplemented: return other self._array.__ipow__(other._array) return self def __rpow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rpow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__rpow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow the spec type promotion rules # for 0-d arrays, so we use pow() here instead. return pow(other, self) def __irshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __irshift__. """ other = self._check_allowed_dtypes(other, "integer", "__irshift__") if other is NotImplemented: return other self._array.__irshift__(other._array) return self def __rrshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rrshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rrshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rrshift__(other._array) return self.__class__._new(res) def __isub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __isub__. """ other = self._check_allowed_dtypes(other, "numeric", "__isub__") if other is NotImplemented: return other self._array.__isub__(other._array) return self def __rsub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rsub__. """ other = self._check_allowed_dtypes(other, "numeric", "__rsub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rsub__(other._array) return self.__class__._new(res) def __itruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __itruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__itruediv__") if other is NotImplemented: return other self._array.__itruediv__(other._array) return self def __rtruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __rtruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__rtruediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rtruediv__(other._array) return self.__class__._new(res) def __ixor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ixor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ixor__") if other is NotImplemented: return other self._array.__ixor__(other._array) return self def __rxor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rxor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rxor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rxor__(other._array) return self.__class__._new(res) def to_device(self: Array, device: Device, /, stream: None = None) -> Array: if stream is not None: raise ValueError("The stream argument to to_device() is not supported") if device == 'cpu': return self raise ValueError(f"Unsupported device {device!r}") def dtype(self) -> Dtype: """ Array API compatible wrapper for :py:meth:`np.ndarray.dtype <numpy.ndarray.dtype>`. See its docstring for more information. """ return self._array.dtype def device(self) -> Device: return "cpu" # Note: mT is new in array API spec (see matrix_transpose) def mT(self) -> Array: from .linalg import matrix_transpose return matrix_transpose(self) def ndim(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.ndim <numpy.ndarray.ndim>`. See its docstring for more information. """ return self._array.ndim def shape(self) -> Tuple[int, ...]: """ Array API compatible wrapper for :py:meth:`np.ndarray.shape <numpy.ndarray.shape>`. See its docstring for more information. """ return self._array.shape def size(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.size <numpy.ndarray.size>`. See its docstring for more information. """ return self._array.size def T(self) -> Array: """ Array API compatible wrapper for :py:meth:`np.ndarray.T <numpy.ndarray.T>`. See its docstring for more information. """ # Note: T only works on 2-dimensional arrays. See the corresponding # note in the specification: # https://data-apis.org/array-api/latest/API_specification/array_object.html#t if self.ndim != 2: raise ValueError("x.T requires x to have 2 dimensions. Use x.mT to transpose stacks of matrices and permute_dims() to permute dimensions.") return self.__class__._new(self._array.T) The provided code snippet includes necessary dependencies for implementing the `multiply` function. Write a Python function `def multiply(x1: Array, x2: Array, /) -> Array` to solve the following problem: Array API compatible wrapper for :py:func:`np.multiply <numpy.multiply>`. See its docstring for more information. Here is the function: def multiply(x1: Array, x2: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.multiply <numpy.multiply>`. See its docstring for more information. """ if x1.dtype not in _numeric_dtypes or x2.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in multiply") # Call result type here just to raise on disallowed type combinations _result_type(x1.dtype, x2.dtype) x1, x2 = Array._normalize_two_args(x1, x2) return Array._new(np.multiply(x1._array, x2._array))
Array API compatible wrapper for :py:func:`np.multiply <numpy.multiply>`. See its docstring for more information.
170,060
from __future__ import annotations from ._dtypes import ( _boolean_dtypes, _floating_dtypes, _integer_dtypes, _integer_or_boolean_dtypes, _numeric_dtypes, _result_type, ) from ._array_object import Array import numpy as np _numeric_dtypes = ( float32, float64, int8, int16, int32, int64, uint8, uint16, uint32, uint64, ) class Array: """ n-d array object for the array API namespace. See the docstring of :py:obj:`np.ndarray <numpy.ndarray>` for more information. This is a wrapper around numpy.ndarray that restricts the usage to only those things that are required by the array API namespace. Note, attributes on this object that start with a single underscore are not part of the API specification and should only be used internally. This object should not be constructed directly. Rather, use one of the creation functions, such as asarray(). """ _array: np.ndarray # Use a custom constructor instead of __init__, as manually initializing # this class is not supported API. def _new(cls, x, /): """ This is a private method for initializing the array API Array object. Functions outside of the array_api submodule should not use this method. Use one of the creation functions instead, such as ``asarray``. """ obj = super().__new__(cls) # Note: The spec does not have array scalars, only 0-D arrays. if isinstance(x, np.generic): # Convert the array scalar to a 0-D array x = np.asarray(x) if x.dtype not in _all_dtypes: raise TypeError( f"The array_api namespace does not support the dtype '{x.dtype}'" ) obj._array = x return obj # Prevent Array() from working def __new__(cls, *args, **kwargs): raise TypeError( "The array_api Array object should not be instantiated directly. Use an array creation function, such as asarray(), instead." ) # These functions are not required by the spec, but are implemented for # the sake of usability. def __str__(self: Array, /) -> str: """ Performs the operation __str__. """ return self._array.__str__().replace("array", "Array") def __repr__(self: Array, /) -> str: """ Performs the operation __repr__. """ suffix = f", dtype={self.dtype.name})" if 0 in self.shape: prefix = "empty(" mid = str(self.shape) else: prefix = "Array(" mid = np.array2string(self._array, separator=', ', prefix=prefix, suffix=suffix) return prefix + mid + suffix # This function is not required by the spec, but we implement it here for # convenience so that np.asarray(np.array_api.Array) will work. def __array__(self, dtype: None | np.dtype[Any] = None) -> npt.NDArray[Any]: """ Warning: this method is NOT part of the array API spec. Implementers of other libraries need not include it, and users should not assume it will be present in other implementations. """ return np.asarray(self._array, dtype=dtype) # These are various helper functions to make the array behavior match the # spec in places where it either deviates from or is more strict than # NumPy behavior def _check_allowed_dtypes(self, other: bool | int | float | Array, dtype_category: str, op: str) -> Array: """ Helper function for operators to only allow specific input dtypes Use like other = self._check_allowed_dtypes(other, 'numeric', '__add__') if other is NotImplemented: return other """ if self.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") if isinstance(other, (int, float, bool)): other = self._promote_scalar(other) elif isinstance(other, Array): if other.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") else: return NotImplemented # This will raise TypeError for type combinations that are not allowed # to promote in the spec (even if the NumPy array operator would # promote them). res_dtype = _result_type(self.dtype, other.dtype) if op.startswith("__i"): # Note: NumPy will allow in-place operators in some cases where # the type promoted operator does not match the left-hand side # operand. For example, # >>> a = np.array(1, dtype=np.int8) # >>> a += np.array(1, dtype=np.int16) # The spec explicitly disallows this. if res_dtype != self.dtype: raise TypeError( f"Cannot perform {op} with dtypes {self.dtype} and {other.dtype}" ) return other # Helper function to match the type promotion rules in the spec def _promote_scalar(self, scalar): """ Returns a promoted version of a Python scalar appropriate for use with operations on self. This may raise an OverflowError in cases where the scalar is an integer that is too large to fit in a NumPy integer dtype, or TypeError when the scalar type is incompatible with the dtype of self. """ # Note: Only Python scalar types that match the array dtype are # allowed. if isinstance(scalar, bool): if self.dtype not in _boolean_dtypes: raise TypeError( "Python bool scalars can only be promoted with bool arrays" ) elif isinstance(scalar, int): if self.dtype in _boolean_dtypes: raise TypeError( "Python int scalars cannot be promoted with bool arrays" ) elif isinstance(scalar, float): if self.dtype not in _floating_dtypes: raise TypeError( "Python float scalars can only be promoted with floating-point arrays." ) else: raise TypeError("'scalar' must be a Python scalar") # Note: scalars are unconditionally cast to the same dtype as the # array. # Note: the spec only specifies integer-dtype/int promotion # behavior for integers within the bounds of the integer dtype. # Outside of those bounds we use the default NumPy behavior (either # cast or raise OverflowError). return Array._new(np.array(scalar, self.dtype)) def _normalize_two_args(x1, x2) -> Tuple[Array, Array]: """ Normalize inputs to two arg functions to fix type promotion rules NumPy deviates from the spec type promotion rules in cases where one argument is 0-dimensional and the other is not. For example: >>> import numpy as np >>> a = np.array([1.0], dtype=np.float32) >>> b = np.array(1.0, dtype=np.float64) >>> np.add(a, b) # The spec says this should be float64 array([2.], dtype=float32) To fix this, we add a dimension to the 0-dimension array before passing it through. This works because a dimension would be added anyway from broadcasting, so the resulting shape is the same, but this prevents NumPy from not promoting the dtype. """ # Another option would be to use signature=(x1.dtype, x2.dtype, None), # but that only works for ufuncs, so we would have to call the ufuncs # directly in the operator methods. One should also note that this # sort of trick wouldn't work for functions like searchsorted, which # don't do normal broadcasting, but there aren't any functions like # that in the array API namespace. if x1.ndim == 0 and x2.ndim != 0: # The _array[None] workaround was chosen because it is relatively # performant. broadcast_to(x1._array, x2.shape) is much slower. We # could also manually type promote x2, but that is more complicated # and about the same performance as this. x1 = Array._new(x1._array[None]) elif x2.ndim == 0 and x1.ndim != 0: x2 = Array._new(x2._array[None]) return (x1, x2) # Note: A large fraction of allowed indices are disallowed here (see the # docstring below) def _validate_index(self, key): """ Validate an index according to the array API. The array API specification only requires a subset of indices that are supported by NumPy. This function will reject any index that is allowed by NumPy but not required by the array API specification. We always raise ``IndexError`` on such indices (the spec does not require any specific behavior on them, but this makes the NumPy array API namespace a minimal implementation of the spec). See https://data-apis.org/array-api/latest/API_specification/indexing.html for the full list of required indexing behavior This function raises IndexError if the index ``key`` is invalid. It only raises ``IndexError`` on indices that are not already rejected by NumPy, as NumPy will already raise the appropriate error on such indices. ``shape`` may be None, in which case, only cases that are independent of the array shape are checked. The following cases are allowed by NumPy, but not specified by the array API specification: - Indices to not include an implicit ellipsis at the end. That is, every axis of an array must be explicitly indexed or an ellipsis included. This behaviour is sometimes referred to as flat indexing. - The start and stop of a slice may not be out of bounds. In particular, for a slice ``i:j:k`` on an axis of size ``n``, only the following are allowed: - ``i`` or ``j`` omitted (``None``). - ``-n <= i <= max(0, n - 1)``. - For ``k > 0`` or ``k`` omitted (``None``), ``-n <= j <= n``. - For ``k < 0``, ``-n - 1 <= j <= max(0, n - 1)``. - Boolean array indices are not allowed as part of a larger tuple index. - Integer array indices are not allowed (with the exception of 0-D arrays, which are treated the same as scalars). Additionally, it should be noted that indices that would return a scalar in NumPy will return a 0-D array. Array scalars are not allowed in the specification, only 0-D arrays. This is done in the ``Array._new`` constructor, not this function. """ _key = key if isinstance(key, tuple) else (key,) for i in _key: if isinstance(i, bool) or not ( isinstance(i, SupportsIndex) # i.e. ints or isinstance(i, slice) or i == Ellipsis or i is None or isinstance(i, Array) or isinstance(i, np.ndarray) ): raise IndexError( f"Single-axes index {i} has {type(i)=}, but only " "integers, slices (:), ellipsis (...), newaxis (None), " "zero-dimensional integer arrays and boolean arrays " "are specified in the Array API." ) nonexpanding_key = [] single_axes = [] n_ellipsis = 0 key_has_mask = False for i in _key: if i is not None: nonexpanding_key.append(i) if isinstance(i, Array) or isinstance(i, np.ndarray): if i.dtype in _boolean_dtypes: key_has_mask = True single_axes.append(i) else: # i must not be an array here, to avoid elementwise equals if i == Ellipsis: n_ellipsis += 1 else: single_axes.append(i) n_single_axes = len(single_axes) if n_ellipsis > 1: return # handled by ndarray elif n_ellipsis == 0: # Note boolean masks must be the sole index, which we check for # later on. if not key_has_mask and n_single_axes < self.ndim: raise IndexError( f"{self.ndim=}, but the multi-axes index only specifies " f"{n_single_axes} dimensions. If this was intentional, " "add a trailing ellipsis (...) which expands into as many " "slices (:) as necessary - this is what np.ndarray arrays " "implicitly do, but such flat indexing behaviour is not " "specified in the Array API." ) if n_ellipsis == 0: indexed_shape = self.shape else: ellipsis_start = None for pos, i in enumerate(nonexpanding_key): if not (isinstance(i, Array) or isinstance(i, np.ndarray)): if i == Ellipsis: ellipsis_start = pos break assert ellipsis_start is not None # sanity check ellipsis_end = self.ndim - (n_single_axes - ellipsis_start) indexed_shape = ( self.shape[:ellipsis_start] + self.shape[ellipsis_end:] ) for i, side in zip(single_axes, indexed_shape): if isinstance(i, slice): if side == 0: f_range = "0 (or None)" else: f_range = f"between -{side} and {side - 1} (or None)" if i.start is not None: try: start = operator.index(i.start) except TypeError: pass # handled by ndarray else: if not (-side <= start <= side): raise IndexError( f"Slice {i} contains {start=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds starts are not specified in " "the Array API)" ) if i.stop is not None: try: stop = operator.index(i.stop) except TypeError: pass # handled by ndarray else: if not (-side <= stop <= side): raise IndexError( f"Slice {i} contains {stop=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds stops are not specified in " "the Array API)" ) elif isinstance(i, Array): if i.dtype in _boolean_dtypes and len(_key) != 1: assert isinstance(key, tuple) # sanity check raise IndexError( f"Single-axes index {i} is a boolean array and " f"{len(key)=}, but masking is only specified in the " "Array API when the array is the sole index." ) elif i.dtype in _integer_dtypes and i.ndim != 0: raise IndexError( f"Single-axes index {i} is a non-zero-dimensional " "integer array, but advanced integer indexing is not " "specified in the Array API." ) elif isinstance(i, tuple): raise IndexError( f"Single-axes index {i} is a tuple, but nested tuple " "indices are not specified in the Array API." ) # Everything below this line is required by the spec. def __abs__(self: Array, /) -> Array: """ Performs the operation __abs__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __abs__") res = self._array.__abs__() return self.__class__._new(res) def __add__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __add__. """ other = self._check_allowed_dtypes(other, "numeric", "__add__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__add__(other._array) return self.__class__._new(res) def __and__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __and__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__and__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__and__(other._array) return self.__class__._new(res) def __array_namespace__( self: Array, /, *, api_version: Optional[str] = None ) -> types.ModuleType: if api_version is not None and not api_version.startswith("2021."): raise ValueError(f"Unrecognized array API version: {api_version!r}") return array_api def __bool__(self: Array, /) -> bool: """ Performs the operation __bool__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("bool is only allowed on arrays with 0 dimensions") if self.dtype not in _boolean_dtypes: raise ValueError("bool is only allowed on boolean arrays") res = self._array.__bool__() return res def __dlpack__(self: Array, /, *, stream: None = None) -> PyCapsule: """ Performs the operation __dlpack__. """ return self._array.__dlpack__(stream=stream) def __dlpack_device__(self: Array, /) -> Tuple[IntEnum, int]: """ Performs the operation __dlpack_device__. """ # Note: device support is required for this return self._array.__dlpack_device__() def __eq__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __eq__. """ # Even though "all" dtypes are allowed, we still require them to be # promotable with each other. other = self._check_allowed_dtypes(other, "all", "__eq__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__eq__(other._array) return self.__class__._new(res) def __float__(self: Array, /) -> float: """ Performs the operation __float__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("float is only allowed on arrays with 0 dimensions") if self.dtype not in _floating_dtypes: raise ValueError("float is only allowed on floating-point arrays") res = self._array.__float__() return res def __floordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __floordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__floordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__floordiv__(other._array) return self.__class__._new(res) def __ge__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ge__. """ other = self._check_allowed_dtypes(other, "numeric", "__ge__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ge__(other._array) return self.__class__._new(res) def __getitem__( self: Array, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], /, ) -> Array: """ Performs the operation __getitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array res = self._array.__getitem__(key) return self._new(res) def __gt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __gt__. """ other = self._check_allowed_dtypes(other, "numeric", "__gt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__gt__(other._array) return self.__class__._new(res) def __int__(self: Array, /) -> int: """ Performs the operation __int__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("int is only allowed on arrays with 0 dimensions") if self.dtype not in _integer_dtypes: raise ValueError("int is only allowed on integer arrays") res = self._array.__int__() return res def __index__(self: Array, /) -> int: """ Performs the operation __index__. """ res = self._array.__index__() return res def __invert__(self: Array, /) -> Array: """ Performs the operation __invert__. """ if self.dtype not in _integer_or_boolean_dtypes: raise TypeError("Only integer or boolean dtypes are allowed in __invert__") res = self._array.__invert__() return self.__class__._new(res) def __le__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __le__. """ other = self._check_allowed_dtypes(other, "numeric", "__le__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__le__(other._array) return self.__class__._new(res) def __lshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __lshift__. """ other = self._check_allowed_dtypes(other, "integer", "__lshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lshift__(other._array) return self.__class__._new(res) def __lt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __lt__. """ other = self._check_allowed_dtypes(other, "numeric", "__lt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lt__(other._array) return self.__class__._new(res) def __matmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __matmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__matmul__") if other is NotImplemented: return other res = self._array.__matmul__(other._array) return self.__class__._new(res) def __mod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mod__. """ other = self._check_allowed_dtypes(other, "numeric", "__mod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mod__(other._array) return self.__class__._new(res) def __mul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mul__. """ other = self._check_allowed_dtypes(other, "numeric", "__mul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mul__(other._array) return self.__class__._new(res) def __ne__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __ne__. """ other = self._check_allowed_dtypes(other, "all", "__ne__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ne__(other._array) return self.__class__._new(res) def __neg__(self: Array, /) -> Array: """ Performs the operation __neg__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __neg__") res = self._array.__neg__() return self.__class__._new(res) def __or__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __or__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__or__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__or__(other._array) return self.__class__._new(res) def __pos__(self: Array, /) -> Array: """ Performs the operation __pos__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __pos__") res = self._array.__pos__() return self.__class__._new(res) def __pow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __pow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__pow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow type promotion rules for 0-d # arrays, so we use pow() here instead. return pow(self, other) def __rshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rshift__(other._array) return self.__class__._new(res) def __setitem__( self, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], value: Union[int, float, bool, Array], /, ) -> None: """ Performs the operation __setitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array self._array.__setitem__(key, asarray(value)._array) def __sub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __sub__. """ other = self._check_allowed_dtypes(other, "numeric", "__sub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__sub__(other._array) return self.__class__._new(res) # PEP 484 requires int to be a subtype of float, but __truediv__ should # not accept int. def __truediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __truediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__truediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__truediv__(other._array) return self.__class__._new(res) def __xor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __xor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__xor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__xor__(other._array) return self.__class__._new(res) def __iadd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __iadd__. """ other = self._check_allowed_dtypes(other, "numeric", "__iadd__") if other is NotImplemented: return other self._array.__iadd__(other._array) return self def __radd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __radd__. """ other = self._check_allowed_dtypes(other, "numeric", "__radd__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__radd__(other._array) return self.__class__._new(res) def __iand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __iand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__iand__") if other is NotImplemented: return other self._array.__iand__(other._array) return self def __rand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rand__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rand__(other._array) return self.__class__._new(res) def __ifloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ifloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__ifloordiv__") if other is NotImplemented: return other self._array.__ifloordiv__(other._array) return self def __rfloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rfloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__rfloordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rfloordiv__(other._array) return self.__class__._new(res) def __ilshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __ilshift__. """ other = self._check_allowed_dtypes(other, "integer", "__ilshift__") if other is NotImplemented: return other self._array.__ilshift__(other._array) return self def __rlshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rlshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rlshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rlshift__(other._array) return self.__class__._new(res) def __imatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __imatmul__. """ # Note: NumPy does not implement __imatmul__. # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__imatmul__") if other is NotImplemented: return other # __imatmul__ can only be allowed when it would not change the shape # of self. other_shape = other.shape if self.shape == () or other_shape == (): raise ValueError("@= requires at least one dimension") if len(other_shape) == 1 or other_shape[-1] != other_shape[-2]: raise ValueError("@= cannot change the shape of the input array") self._array[:] = self._array.__matmul__(other._array) return self def __rmatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __rmatmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__rmatmul__") if other is NotImplemented: return other res = self._array.__rmatmul__(other._array) return self.__class__._new(res) def __imod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imod__. """ other = self._check_allowed_dtypes(other, "numeric", "__imod__") if other is NotImplemented: return other self._array.__imod__(other._array) return self def __rmod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmod__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmod__(other._array) return self.__class__._new(res) def __imul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imul__. """ other = self._check_allowed_dtypes(other, "numeric", "__imul__") if other is NotImplemented: return other self._array.__imul__(other._array) return self def __rmul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmul__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmul__(other._array) return self.__class__._new(res) def __ior__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ior__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ior__") if other is NotImplemented: return other self._array.__ior__(other._array) return self def __ror__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ror__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ror__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ror__(other._array) return self.__class__._new(res) def __ipow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ipow__. """ other = self._check_allowed_dtypes(other, "numeric", "__ipow__") if other is NotImplemented: return other self._array.__ipow__(other._array) return self def __rpow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rpow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__rpow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow the spec type promotion rules # for 0-d arrays, so we use pow() here instead. return pow(other, self) def __irshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __irshift__. """ other = self._check_allowed_dtypes(other, "integer", "__irshift__") if other is NotImplemented: return other self._array.__irshift__(other._array) return self def __rrshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rrshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rrshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rrshift__(other._array) return self.__class__._new(res) def __isub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __isub__. """ other = self._check_allowed_dtypes(other, "numeric", "__isub__") if other is NotImplemented: return other self._array.__isub__(other._array) return self def __rsub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rsub__. """ other = self._check_allowed_dtypes(other, "numeric", "__rsub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rsub__(other._array) return self.__class__._new(res) def __itruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __itruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__itruediv__") if other is NotImplemented: return other self._array.__itruediv__(other._array) return self def __rtruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __rtruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__rtruediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rtruediv__(other._array) return self.__class__._new(res) def __ixor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ixor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ixor__") if other is NotImplemented: return other self._array.__ixor__(other._array) return self def __rxor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rxor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rxor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rxor__(other._array) return self.__class__._new(res) def to_device(self: Array, device: Device, /, stream: None = None) -> Array: if stream is not None: raise ValueError("The stream argument to to_device() is not supported") if device == 'cpu': return self raise ValueError(f"Unsupported device {device!r}") def dtype(self) -> Dtype: """ Array API compatible wrapper for :py:meth:`np.ndarray.dtype <numpy.ndarray.dtype>`. See its docstring for more information. """ return self._array.dtype def device(self) -> Device: return "cpu" # Note: mT is new in array API spec (see matrix_transpose) def mT(self) -> Array: from .linalg import matrix_transpose return matrix_transpose(self) def ndim(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.ndim <numpy.ndarray.ndim>`. See its docstring for more information. """ return self._array.ndim def shape(self) -> Tuple[int, ...]: """ Array API compatible wrapper for :py:meth:`np.ndarray.shape <numpy.ndarray.shape>`. See its docstring for more information. """ return self._array.shape def size(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.size <numpy.ndarray.size>`. See its docstring for more information. """ return self._array.size def T(self) -> Array: """ Array API compatible wrapper for :py:meth:`np.ndarray.T <numpy.ndarray.T>`. See its docstring for more information. """ # Note: T only works on 2-dimensional arrays. See the corresponding # note in the specification: # https://data-apis.org/array-api/latest/API_specification/array_object.html#t if self.ndim != 2: raise ValueError("x.T requires x to have 2 dimensions. Use x.mT to transpose stacks of matrices and permute_dims() to permute dimensions.") return self.__class__._new(self._array.T) The provided code snippet includes necessary dependencies for implementing the `negative` function. Write a Python function `def negative(x: Array, /) -> Array` to solve the following problem: Array API compatible wrapper for :py:func:`np.negative <numpy.negative>`. See its docstring for more information. Here is the function: def negative(x: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.negative <numpy.negative>`. See its docstring for more information. """ if x.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in negative") return Array._new(np.negative(x._array))
Array API compatible wrapper for :py:func:`np.negative <numpy.negative>`. See its docstring for more information.
170,061
from __future__ import annotations from ._dtypes import ( _boolean_dtypes, _floating_dtypes, _integer_dtypes, _integer_or_boolean_dtypes, _numeric_dtypes, _result_type, ) from ._array_object import Array import numpy as np def _result_type(type1, type2): if (type1, type2) in _promotion_table: return _promotion_table[type1, type2] raise TypeError(f"{type1} and {type2} cannot be type promoted together") class Array: """ n-d array object for the array API namespace. See the docstring of :py:obj:`np.ndarray <numpy.ndarray>` for more information. This is a wrapper around numpy.ndarray that restricts the usage to only those things that are required by the array API namespace. Note, attributes on this object that start with a single underscore are not part of the API specification and should only be used internally. This object should not be constructed directly. Rather, use one of the creation functions, such as asarray(). """ _array: np.ndarray # Use a custom constructor instead of __init__, as manually initializing # this class is not supported API. def _new(cls, x, /): """ This is a private method for initializing the array API Array object. Functions outside of the array_api submodule should not use this method. Use one of the creation functions instead, such as ``asarray``. """ obj = super().__new__(cls) # Note: The spec does not have array scalars, only 0-D arrays. if isinstance(x, np.generic): # Convert the array scalar to a 0-D array x = np.asarray(x) if x.dtype not in _all_dtypes: raise TypeError( f"The array_api namespace does not support the dtype '{x.dtype}'" ) obj._array = x return obj # Prevent Array() from working def __new__(cls, *args, **kwargs): raise TypeError( "The array_api Array object should not be instantiated directly. Use an array creation function, such as asarray(), instead." ) # These functions are not required by the spec, but are implemented for # the sake of usability. def __str__(self: Array, /) -> str: """ Performs the operation __str__. """ return self._array.__str__().replace("array", "Array") def __repr__(self: Array, /) -> str: """ Performs the operation __repr__. """ suffix = f", dtype={self.dtype.name})" if 0 in self.shape: prefix = "empty(" mid = str(self.shape) else: prefix = "Array(" mid = np.array2string(self._array, separator=', ', prefix=prefix, suffix=suffix) return prefix + mid + suffix # This function is not required by the spec, but we implement it here for # convenience so that np.asarray(np.array_api.Array) will work. def __array__(self, dtype: None | np.dtype[Any] = None) -> npt.NDArray[Any]: """ Warning: this method is NOT part of the array API spec. Implementers of other libraries need not include it, and users should not assume it will be present in other implementations. """ return np.asarray(self._array, dtype=dtype) # These are various helper functions to make the array behavior match the # spec in places where it either deviates from or is more strict than # NumPy behavior def _check_allowed_dtypes(self, other: bool | int | float | Array, dtype_category: str, op: str) -> Array: """ Helper function for operators to only allow specific input dtypes Use like other = self._check_allowed_dtypes(other, 'numeric', '__add__') if other is NotImplemented: return other """ if self.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") if isinstance(other, (int, float, bool)): other = self._promote_scalar(other) elif isinstance(other, Array): if other.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") else: return NotImplemented # This will raise TypeError for type combinations that are not allowed # to promote in the spec (even if the NumPy array operator would # promote them). res_dtype = _result_type(self.dtype, other.dtype) if op.startswith("__i"): # Note: NumPy will allow in-place operators in some cases where # the type promoted operator does not match the left-hand side # operand. For example, # >>> a = np.array(1, dtype=np.int8) # >>> a += np.array(1, dtype=np.int16) # The spec explicitly disallows this. if res_dtype != self.dtype: raise TypeError( f"Cannot perform {op} with dtypes {self.dtype} and {other.dtype}" ) return other # Helper function to match the type promotion rules in the spec def _promote_scalar(self, scalar): """ Returns a promoted version of a Python scalar appropriate for use with operations on self. This may raise an OverflowError in cases where the scalar is an integer that is too large to fit in a NumPy integer dtype, or TypeError when the scalar type is incompatible with the dtype of self. """ # Note: Only Python scalar types that match the array dtype are # allowed. if isinstance(scalar, bool): if self.dtype not in _boolean_dtypes: raise TypeError( "Python bool scalars can only be promoted with bool arrays" ) elif isinstance(scalar, int): if self.dtype in _boolean_dtypes: raise TypeError( "Python int scalars cannot be promoted with bool arrays" ) elif isinstance(scalar, float): if self.dtype not in _floating_dtypes: raise TypeError( "Python float scalars can only be promoted with floating-point arrays." ) else: raise TypeError("'scalar' must be a Python scalar") # Note: scalars are unconditionally cast to the same dtype as the # array. # Note: the spec only specifies integer-dtype/int promotion # behavior for integers within the bounds of the integer dtype. # Outside of those bounds we use the default NumPy behavior (either # cast or raise OverflowError). return Array._new(np.array(scalar, self.dtype)) def _normalize_two_args(x1, x2) -> Tuple[Array, Array]: """ Normalize inputs to two arg functions to fix type promotion rules NumPy deviates from the spec type promotion rules in cases where one argument is 0-dimensional and the other is not. For example: >>> import numpy as np >>> a = np.array([1.0], dtype=np.float32) >>> b = np.array(1.0, dtype=np.float64) >>> np.add(a, b) # The spec says this should be float64 array([2.], dtype=float32) To fix this, we add a dimension to the 0-dimension array before passing it through. This works because a dimension would be added anyway from broadcasting, so the resulting shape is the same, but this prevents NumPy from not promoting the dtype. """ # Another option would be to use signature=(x1.dtype, x2.dtype, None), # but that only works for ufuncs, so we would have to call the ufuncs # directly in the operator methods. One should also note that this # sort of trick wouldn't work for functions like searchsorted, which # don't do normal broadcasting, but there aren't any functions like # that in the array API namespace. if x1.ndim == 0 and x2.ndim != 0: # The _array[None] workaround was chosen because it is relatively # performant. broadcast_to(x1._array, x2.shape) is much slower. We # could also manually type promote x2, but that is more complicated # and about the same performance as this. x1 = Array._new(x1._array[None]) elif x2.ndim == 0 and x1.ndim != 0: x2 = Array._new(x2._array[None]) return (x1, x2) # Note: A large fraction of allowed indices are disallowed here (see the # docstring below) def _validate_index(self, key): """ Validate an index according to the array API. The array API specification only requires a subset of indices that are supported by NumPy. This function will reject any index that is allowed by NumPy but not required by the array API specification. We always raise ``IndexError`` on such indices (the spec does not require any specific behavior on them, but this makes the NumPy array API namespace a minimal implementation of the spec). See https://data-apis.org/array-api/latest/API_specification/indexing.html for the full list of required indexing behavior This function raises IndexError if the index ``key`` is invalid. It only raises ``IndexError`` on indices that are not already rejected by NumPy, as NumPy will already raise the appropriate error on such indices. ``shape`` may be None, in which case, only cases that are independent of the array shape are checked. The following cases are allowed by NumPy, but not specified by the array API specification: - Indices to not include an implicit ellipsis at the end. That is, every axis of an array must be explicitly indexed or an ellipsis included. This behaviour is sometimes referred to as flat indexing. - The start and stop of a slice may not be out of bounds. In particular, for a slice ``i:j:k`` on an axis of size ``n``, only the following are allowed: - ``i`` or ``j`` omitted (``None``). - ``-n <= i <= max(0, n - 1)``. - For ``k > 0`` or ``k`` omitted (``None``), ``-n <= j <= n``. - For ``k < 0``, ``-n - 1 <= j <= max(0, n - 1)``. - Boolean array indices are not allowed as part of a larger tuple index. - Integer array indices are not allowed (with the exception of 0-D arrays, which are treated the same as scalars). Additionally, it should be noted that indices that would return a scalar in NumPy will return a 0-D array. Array scalars are not allowed in the specification, only 0-D arrays. This is done in the ``Array._new`` constructor, not this function. """ _key = key if isinstance(key, tuple) else (key,) for i in _key: if isinstance(i, bool) or not ( isinstance(i, SupportsIndex) # i.e. ints or isinstance(i, slice) or i == Ellipsis or i is None or isinstance(i, Array) or isinstance(i, np.ndarray) ): raise IndexError( f"Single-axes index {i} has {type(i)=}, but only " "integers, slices (:), ellipsis (...), newaxis (None), " "zero-dimensional integer arrays and boolean arrays " "are specified in the Array API." ) nonexpanding_key = [] single_axes = [] n_ellipsis = 0 key_has_mask = False for i in _key: if i is not None: nonexpanding_key.append(i) if isinstance(i, Array) or isinstance(i, np.ndarray): if i.dtype in _boolean_dtypes: key_has_mask = True single_axes.append(i) else: # i must not be an array here, to avoid elementwise equals if i == Ellipsis: n_ellipsis += 1 else: single_axes.append(i) n_single_axes = len(single_axes) if n_ellipsis > 1: return # handled by ndarray elif n_ellipsis == 0: # Note boolean masks must be the sole index, which we check for # later on. if not key_has_mask and n_single_axes < self.ndim: raise IndexError( f"{self.ndim=}, but the multi-axes index only specifies " f"{n_single_axes} dimensions. If this was intentional, " "add a trailing ellipsis (...) which expands into as many " "slices (:) as necessary - this is what np.ndarray arrays " "implicitly do, but such flat indexing behaviour is not " "specified in the Array API." ) if n_ellipsis == 0: indexed_shape = self.shape else: ellipsis_start = None for pos, i in enumerate(nonexpanding_key): if not (isinstance(i, Array) or isinstance(i, np.ndarray)): if i == Ellipsis: ellipsis_start = pos break assert ellipsis_start is not None # sanity check ellipsis_end = self.ndim - (n_single_axes - ellipsis_start) indexed_shape = ( self.shape[:ellipsis_start] + self.shape[ellipsis_end:] ) for i, side in zip(single_axes, indexed_shape): if isinstance(i, slice): if side == 0: f_range = "0 (or None)" else: f_range = f"between -{side} and {side - 1} (or None)" if i.start is not None: try: start = operator.index(i.start) except TypeError: pass # handled by ndarray else: if not (-side <= start <= side): raise IndexError( f"Slice {i} contains {start=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds starts are not specified in " "the Array API)" ) if i.stop is not None: try: stop = operator.index(i.stop) except TypeError: pass # handled by ndarray else: if not (-side <= stop <= side): raise IndexError( f"Slice {i} contains {stop=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds stops are not specified in " "the Array API)" ) elif isinstance(i, Array): if i.dtype in _boolean_dtypes and len(_key) != 1: assert isinstance(key, tuple) # sanity check raise IndexError( f"Single-axes index {i} is a boolean array and " f"{len(key)=}, but masking is only specified in the " "Array API when the array is the sole index." ) elif i.dtype in _integer_dtypes and i.ndim != 0: raise IndexError( f"Single-axes index {i} is a non-zero-dimensional " "integer array, but advanced integer indexing is not " "specified in the Array API." ) elif isinstance(i, tuple): raise IndexError( f"Single-axes index {i} is a tuple, but nested tuple " "indices are not specified in the Array API." ) # Everything below this line is required by the spec. def __abs__(self: Array, /) -> Array: """ Performs the operation __abs__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __abs__") res = self._array.__abs__() return self.__class__._new(res) def __add__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __add__. """ other = self._check_allowed_dtypes(other, "numeric", "__add__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__add__(other._array) return self.__class__._new(res) def __and__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __and__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__and__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__and__(other._array) return self.__class__._new(res) def __array_namespace__( self: Array, /, *, api_version: Optional[str] = None ) -> types.ModuleType: if api_version is not None and not api_version.startswith("2021."): raise ValueError(f"Unrecognized array API version: {api_version!r}") return array_api def __bool__(self: Array, /) -> bool: """ Performs the operation __bool__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("bool is only allowed on arrays with 0 dimensions") if self.dtype not in _boolean_dtypes: raise ValueError("bool is only allowed on boolean arrays") res = self._array.__bool__() return res def __dlpack__(self: Array, /, *, stream: None = None) -> PyCapsule: """ Performs the operation __dlpack__. """ return self._array.__dlpack__(stream=stream) def __dlpack_device__(self: Array, /) -> Tuple[IntEnum, int]: """ Performs the operation __dlpack_device__. """ # Note: device support is required for this return self._array.__dlpack_device__() def __eq__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __eq__. """ # Even though "all" dtypes are allowed, we still require them to be # promotable with each other. other = self._check_allowed_dtypes(other, "all", "__eq__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__eq__(other._array) return self.__class__._new(res) def __float__(self: Array, /) -> float: """ Performs the operation __float__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("float is only allowed on arrays with 0 dimensions") if self.dtype not in _floating_dtypes: raise ValueError("float is only allowed on floating-point arrays") res = self._array.__float__() return res def __floordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __floordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__floordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__floordiv__(other._array) return self.__class__._new(res) def __ge__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ge__. """ other = self._check_allowed_dtypes(other, "numeric", "__ge__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ge__(other._array) return self.__class__._new(res) def __getitem__( self: Array, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], /, ) -> Array: """ Performs the operation __getitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array res = self._array.__getitem__(key) return self._new(res) def __gt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __gt__. """ other = self._check_allowed_dtypes(other, "numeric", "__gt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__gt__(other._array) return self.__class__._new(res) def __int__(self: Array, /) -> int: """ Performs the operation __int__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("int is only allowed on arrays with 0 dimensions") if self.dtype not in _integer_dtypes: raise ValueError("int is only allowed on integer arrays") res = self._array.__int__() return res def __index__(self: Array, /) -> int: """ Performs the operation __index__. """ res = self._array.__index__() return res def __invert__(self: Array, /) -> Array: """ Performs the operation __invert__. """ if self.dtype not in _integer_or_boolean_dtypes: raise TypeError("Only integer or boolean dtypes are allowed in __invert__") res = self._array.__invert__() return self.__class__._new(res) def __le__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __le__. """ other = self._check_allowed_dtypes(other, "numeric", "__le__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__le__(other._array) return self.__class__._new(res) def __lshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __lshift__. """ other = self._check_allowed_dtypes(other, "integer", "__lshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lshift__(other._array) return self.__class__._new(res) def __lt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __lt__. """ other = self._check_allowed_dtypes(other, "numeric", "__lt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lt__(other._array) return self.__class__._new(res) def __matmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __matmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__matmul__") if other is NotImplemented: return other res = self._array.__matmul__(other._array) return self.__class__._new(res) def __mod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mod__. """ other = self._check_allowed_dtypes(other, "numeric", "__mod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mod__(other._array) return self.__class__._new(res) def __mul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mul__. """ other = self._check_allowed_dtypes(other, "numeric", "__mul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mul__(other._array) return self.__class__._new(res) def __ne__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __ne__. """ other = self._check_allowed_dtypes(other, "all", "__ne__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ne__(other._array) return self.__class__._new(res) def __neg__(self: Array, /) -> Array: """ Performs the operation __neg__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __neg__") res = self._array.__neg__() return self.__class__._new(res) def __or__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __or__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__or__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__or__(other._array) return self.__class__._new(res) def __pos__(self: Array, /) -> Array: """ Performs the operation __pos__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __pos__") res = self._array.__pos__() return self.__class__._new(res) def __pow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __pow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__pow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow type promotion rules for 0-d # arrays, so we use pow() here instead. return pow(self, other) def __rshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rshift__(other._array) return self.__class__._new(res) def __setitem__( self, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], value: Union[int, float, bool, Array], /, ) -> None: """ Performs the operation __setitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array self._array.__setitem__(key, asarray(value)._array) def __sub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __sub__. """ other = self._check_allowed_dtypes(other, "numeric", "__sub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__sub__(other._array) return self.__class__._new(res) # PEP 484 requires int to be a subtype of float, but __truediv__ should # not accept int. def __truediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __truediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__truediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__truediv__(other._array) return self.__class__._new(res) def __xor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __xor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__xor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__xor__(other._array) return self.__class__._new(res) def __iadd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __iadd__. """ other = self._check_allowed_dtypes(other, "numeric", "__iadd__") if other is NotImplemented: return other self._array.__iadd__(other._array) return self def __radd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __radd__. """ other = self._check_allowed_dtypes(other, "numeric", "__radd__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__radd__(other._array) return self.__class__._new(res) def __iand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __iand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__iand__") if other is NotImplemented: return other self._array.__iand__(other._array) return self def __rand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rand__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rand__(other._array) return self.__class__._new(res) def __ifloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ifloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__ifloordiv__") if other is NotImplemented: return other self._array.__ifloordiv__(other._array) return self def __rfloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rfloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__rfloordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rfloordiv__(other._array) return self.__class__._new(res) def __ilshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __ilshift__. """ other = self._check_allowed_dtypes(other, "integer", "__ilshift__") if other is NotImplemented: return other self._array.__ilshift__(other._array) return self def __rlshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rlshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rlshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rlshift__(other._array) return self.__class__._new(res) def __imatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __imatmul__. """ # Note: NumPy does not implement __imatmul__. # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__imatmul__") if other is NotImplemented: return other # __imatmul__ can only be allowed when it would not change the shape # of self. other_shape = other.shape if self.shape == () or other_shape == (): raise ValueError("@= requires at least one dimension") if len(other_shape) == 1 or other_shape[-1] != other_shape[-2]: raise ValueError("@= cannot change the shape of the input array") self._array[:] = self._array.__matmul__(other._array) return self def __rmatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __rmatmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__rmatmul__") if other is NotImplemented: return other res = self._array.__rmatmul__(other._array) return self.__class__._new(res) def __imod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imod__. """ other = self._check_allowed_dtypes(other, "numeric", "__imod__") if other is NotImplemented: return other self._array.__imod__(other._array) return self def __rmod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmod__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmod__(other._array) return self.__class__._new(res) def __imul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imul__. """ other = self._check_allowed_dtypes(other, "numeric", "__imul__") if other is NotImplemented: return other self._array.__imul__(other._array) return self def __rmul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmul__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmul__(other._array) return self.__class__._new(res) def __ior__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ior__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ior__") if other is NotImplemented: return other self._array.__ior__(other._array) return self def __ror__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ror__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ror__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ror__(other._array) return self.__class__._new(res) def __ipow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ipow__. """ other = self._check_allowed_dtypes(other, "numeric", "__ipow__") if other is NotImplemented: return other self._array.__ipow__(other._array) return self def __rpow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rpow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__rpow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow the spec type promotion rules # for 0-d arrays, so we use pow() here instead. return pow(other, self) def __irshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __irshift__. """ other = self._check_allowed_dtypes(other, "integer", "__irshift__") if other is NotImplemented: return other self._array.__irshift__(other._array) return self def __rrshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rrshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rrshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rrshift__(other._array) return self.__class__._new(res) def __isub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __isub__. """ other = self._check_allowed_dtypes(other, "numeric", "__isub__") if other is NotImplemented: return other self._array.__isub__(other._array) return self def __rsub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rsub__. """ other = self._check_allowed_dtypes(other, "numeric", "__rsub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rsub__(other._array) return self.__class__._new(res) def __itruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __itruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__itruediv__") if other is NotImplemented: return other self._array.__itruediv__(other._array) return self def __rtruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __rtruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__rtruediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rtruediv__(other._array) return self.__class__._new(res) def __ixor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ixor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ixor__") if other is NotImplemented: return other self._array.__ixor__(other._array) return self def __rxor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rxor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rxor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rxor__(other._array) return self.__class__._new(res) def to_device(self: Array, device: Device, /, stream: None = None) -> Array: if stream is not None: raise ValueError("The stream argument to to_device() is not supported") if device == 'cpu': return self raise ValueError(f"Unsupported device {device!r}") def dtype(self) -> Dtype: """ Array API compatible wrapper for :py:meth:`np.ndarray.dtype <numpy.ndarray.dtype>`. See its docstring for more information. """ return self._array.dtype def device(self) -> Device: return "cpu" # Note: mT is new in array API spec (see matrix_transpose) def mT(self) -> Array: from .linalg import matrix_transpose return matrix_transpose(self) def ndim(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.ndim <numpy.ndarray.ndim>`. See its docstring for more information. """ return self._array.ndim def shape(self) -> Tuple[int, ...]: """ Array API compatible wrapper for :py:meth:`np.ndarray.shape <numpy.ndarray.shape>`. See its docstring for more information. """ return self._array.shape def size(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.size <numpy.ndarray.size>`. See its docstring for more information. """ return self._array.size def T(self) -> Array: """ Array API compatible wrapper for :py:meth:`np.ndarray.T <numpy.ndarray.T>`. See its docstring for more information. """ # Note: T only works on 2-dimensional arrays. See the corresponding # note in the specification: # https://data-apis.org/array-api/latest/API_specification/array_object.html#t if self.ndim != 2: raise ValueError("x.T requires x to have 2 dimensions. Use x.mT to transpose stacks of matrices and permute_dims() to permute dimensions.") return self.__class__._new(self._array.T) The provided code snippet includes necessary dependencies for implementing the `not_equal` function. Write a Python function `def not_equal(x1: Array, x2: Array, /) -> Array` to solve the following problem: Array API compatible wrapper for :py:func:`np.not_equal <numpy.not_equal>`. See its docstring for more information. Here is the function: def not_equal(x1: Array, x2: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.not_equal <numpy.not_equal>`. See its docstring for more information. """ # Call result type here just to raise on disallowed type combinations _result_type(x1.dtype, x2.dtype) x1, x2 = Array._normalize_two_args(x1, x2) return Array._new(np.not_equal(x1._array, x2._array))
Array API compatible wrapper for :py:func:`np.not_equal <numpy.not_equal>`. See its docstring for more information.
170,062
from __future__ import annotations from ._dtypes import ( _boolean_dtypes, _floating_dtypes, _integer_dtypes, _integer_or_boolean_dtypes, _numeric_dtypes, _result_type, ) from ._array_object import Array import numpy as np _numeric_dtypes = ( float32, float64, int8, int16, int32, int64, uint8, uint16, uint32, uint64, ) class Array: """ n-d array object for the array API namespace. See the docstring of :py:obj:`np.ndarray <numpy.ndarray>` for more information. This is a wrapper around numpy.ndarray that restricts the usage to only those things that are required by the array API namespace. Note, attributes on this object that start with a single underscore are not part of the API specification and should only be used internally. This object should not be constructed directly. Rather, use one of the creation functions, such as asarray(). """ _array: np.ndarray # Use a custom constructor instead of __init__, as manually initializing # this class is not supported API. def _new(cls, x, /): """ This is a private method for initializing the array API Array object. Functions outside of the array_api submodule should not use this method. Use one of the creation functions instead, such as ``asarray``. """ obj = super().__new__(cls) # Note: The spec does not have array scalars, only 0-D arrays. if isinstance(x, np.generic): # Convert the array scalar to a 0-D array x = np.asarray(x) if x.dtype not in _all_dtypes: raise TypeError( f"The array_api namespace does not support the dtype '{x.dtype}'" ) obj._array = x return obj # Prevent Array() from working def __new__(cls, *args, **kwargs): raise TypeError( "The array_api Array object should not be instantiated directly. Use an array creation function, such as asarray(), instead." ) # These functions are not required by the spec, but are implemented for # the sake of usability. def __str__(self: Array, /) -> str: """ Performs the operation __str__. """ return self._array.__str__().replace("array", "Array") def __repr__(self: Array, /) -> str: """ Performs the operation __repr__. """ suffix = f", dtype={self.dtype.name})" if 0 in self.shape: prefix = "empty(" mid = str(self.shape) else: prefix = "Array(" mid = np.array2string(self._array, separator=', ', prefix=prefix, suffix=suffix) return prefix + mid + suffix # This function is not required by the spec, but we implement it here for # convenience so that np.asarray(np.array_api.Array) will work. def __array__(self, dtype: None | np.dtype[Any] = None) -> npt.NDArray[Any]: """ Warning: this method is NOT part of the array API spec. Implementers of other libraries need not include it, and users should not assume it will be present in other implementations. """ return np.asarray(self._array, dtype=dtype) # These are various helper functions to make the array behavior match the # spec in places where it either deviates from or is more strict than # NumPy behavior def _check_allowed_dtypes(self, other: bool | int | float | Array, dtype_category: str, op: str) -> Array: """ Helper function for operators to only allow specific input dtypes Use like other = self._check_allowed_dtypes(other, 'numeric', '__add__') if other is NotImplemented: return other """ if self.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") if isinstance(other, (int, float, bool)): other = self._promote_scalar(other) elif isinstance(other, Array): if other.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") else: return NotImplemented # This will raise TypeError for type combinations that are not allowed # to promote in the spec (even if the NumPy array operator would # promote them). res_dtype = _result_type(self.dtype, other.dtype) if op.startswith("__i"): # Note: NumPy will allow in-place operators in some cases where # the type promoted operator does not match the left-hand side # operand. For example, # >>> a = np.array(1, dtype=np.int8) # >>> a += np.array(1, dtype=np.int16) # The spec explicitly disallows this. if res_dtype != self.dtype: raise TypeError( f"Cannot perform {op} with dtypes {self.dtype} and {other.dtype}" ) return other # Helper function to match the type promotion rules in the spec def _promote_scalar(self, scalar): """ Returns a promoted version of a Python scalar appropriate for use with operations on self. This may raise an OverflowError in cases where the scalar is an integer that is too large to fit in a NumPy integer dtype, or TypeError when the scalar type is incompatible with the dtype of self. """ # Note: Only Python scalar types that match the array dtype are # allowed. if isinstance(scalar, bool): if self.dtype not in _boolean_dtypes: raise TypeError( "Python bool scalars can only be promoted with bool arrays" ) elif isinstance(scalar, int): if self.dtype in _boolean_dtypes: raise TypeError( "Python int scalars cannot be promoted with bool arrays" ) elif isinstance(scalar, float): if self.dtype not in _floating_dtypes: raise TypeError( "Python float scalars can only be promoted with floating-point arrays." ) else: raise TypeError("'scalar' must be a Python scalar") # Note: scalars are unconditionally cast to the same dtype as the # array. # Note: the spec only specifies integer-dtype/int promotion # behavior for integers within the bounds of the integer dtype. # Outside of those bounds we use the default NumPy behavior (either # cast or raise OverflowError). return Array._new(np.array(scalar, self.dtype)) def _normalize_two_args(x1, x2) -> Tuple[Array, Array]: """ Normalize inputs to two arg functions to fix type promotion rules NumPy deviates from the spec type promotion rules in cases where one argument is 0-dimensional and the other is not. For example: >>> import numpy as np >>> a = np.array([1.0], dtype=np.float32) >>> b = np.array(1.0, dtype=np.float64) >>> np.add(a, b) # The spec says this should be float64 array([2.], dtype=float32) To fix this, we add a dimension to the 0-dimension array before passing it through. This works because a dimension would be added anyway from broadcasting, so the resulting shape is the same, but this prevents NumPy from not promoting the dtype. """ # Another option would be to use signature=(x1.dtype, x2.dtype, None), # but that only works for ufuncs, so we would have to call the ufuncs # directly in the operator methods. One should also note that this # sort of trick wouldn't work for functions like searchsorted, which # don't do normal broadcasting, but there aren't any functions like # that in the array API namespace. if x1.ndim == 0 and x2.ndim != 0: # The _array[None] workaround was chosen because it is relatively # performant. broadcast_to(x1._array, x2.shape) is much slower. We # could also manually type promote x2, but that is more complicated # and about the same performance as this. x1 = Array._new(x1._array[None]) elif x2.ndim == 0 and x1.ndim != 0: x2 = Array._new(x2._array[None]) return (x1, x2) # Note: A large fraction of allowed indices are disallowed here (see the # docstring below) def _validate_index(self, key): """ Validate an index according to the array API. The array API specification only requires a subset of indices that are supported by NumPy. This function will reject any index that is allowed by NumPy but not required by the array API specification. We always raise ``IndexError`` on such indices (the spec does not require any specific behavior on them, but this makes the NumPy array API namespace a minimal implementation of the spec). See https://data-apis.org/array-api/latest/API_specification/indexing.html for the full list of required indexing behavior This function raises IndexError if the index ``key`` is invalid. It only raises ``IndexError`` on indices that are not already rejected by NumPy, as NumPy will already raise the appropriate error on such indices. ``shape`` may be None, in which case, only cases that are independent of the array shape are checked. The following cases are allowed by NumPy, but not specified by the array API specification: - Indices to not include an implicit ellipsis at the end. That is, every axis of an array must be explicitly indexed or an ellipsis included. This behaviour is sometimes referred to as flat indexing. - The start and stop of a slice may not be out of bounds. In particular, for a slice ``i:j:k`` on an axis of size ``n``, only the following are allowed: - ``i`` or ``j`` omitted (``None``). - ``-n <= i <= max(0, n - 1)``. - For ``k > 0`` or ``k`` omitted (``None``), ``-n <= j <= n``. - For ``k < 0``, ``-n - 1 <= j <= max(0, n - 1)``. - Boolean array indices are not allowed as part of a larger tuple index. - Integer array indices are not allowed (with the exception of 0-D arrays, which are treated the same as scalars). Additionally, it should be noted that indices that would return a scalar in NumPy will return a 0-D array. Array scalars are not allowed in the specification, only 0-D arrays. This is done in the ``Array._new`` constructor, not this function. """ _key = key if isinstance(key, tuple) else (key,) for i in _key: if isinstance(i, bool) or not ( isinstance(i, SupportsIndex) # i.e. ints or isinstance(i, slice) or i == Ellipsis or i is None or isinstance(i, Array) or isinstance(i, np.ndarray) ): raise IndexError( f"Single-axes index {i} has {type(i)=}, but only " "integers, slices (:), ellipsis (...), newaxis (None), " "zero-dimensional integer arrays and boolean arrays " "are specified in the Array API." ) nonexpanding_key = [] single_axes = [] n_ellipsis = 0 key_has_mask = False for i in _key: if i is not None: nonexpanding_key.append(i) if isinstance(i, Array) or isinstance(i, np.ndarray): if i.dtype in _boolean_dtypes: key_has_mask = True single_axes.append(i) else: # i must not be an array here, to avoid elementwise equals if i == Ellipsis: n_ellipsis += 1 else: single_axes.append(i) n_single_axes = len(single_axes) if n_ellipsis > 1: return # handled by ndarray elif n_ellipsis == 0: # Note boolean masks must be the sole index, which we check for # later on. if not key_has_mask and n_single_axes < self.ndim: raise IndexError( f"{self.ndim=}, but the multi-axes index only specifies " f"{n_single_axes} dimensions. If this was intentional, " "add a trailing ellipsis (...) which expands into as many " "slices (:) as necessary - this is what np.ndarray arrays " "implicitly do, but such flat indexing behaviour is not " "specified in the Array API." ) if n_ellipsis == 0: indexed_shape = self.shape else: ellipsis_start = None for pos, i in enumerate(nonexpanding_key): if not (isinstance(i, Array) or isinstance(i, np.ndarray)): if i == Ellipsis: ellipsis_start = pos break assert ellipsis_start is not None # sanity check ellipsis_end = self.ndim - (n_single_axes - ellipsis_start) indexed_shape = ( self.shape[:ellipsis_start] + self.shape[ellipsis_end:] ) for i, side in zip(single_axes, indexed_shape): if isinstance(i, slice): if side == 0: f_range = "0 (or None)" else: f_range = f"between -{side} and {side - 1} (or None)" if i.start is not None: try: start = operator.index(i.start) except TypeError: pass # handled by ndarray else: if not (-side <= start <= side): raise IndexError( f"Slice {i} contains {start=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds starts are not specified in " "the Array API)" ) if i.stop is not None: try: stop = operator.index(i.stop) except TypeError: pass # handled by ndarray else: if not (-side <= stop <= side): raise IndexError( f"Slice {i} contains {stop=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds stops are not specified in " "the Array API)" ) elif isinstance(i, Array): if i.dtype in _boolean_dtypes and len(_key) != 1: assert isinstance(key, tuple) # sanity check raise IndexError( f"Single-axes index {i} is a boolean array and " f"{len(key)=}, but masking is only specified in the " "Array API when the array is the sole index." ) elif i.dtype in _integer_dtypes and i.ndim != 0: raise IndexError( f"Single-axes index {i} is a non-zero-dimensional " "integer array, but advanced integer indexing is not " "specified in the Array API." ) elif isinstance(i, tuple): raise IndexError( f"Single-axes index {i} is a tuple, but nested tuple " "indices are not specified in the Array API." ) # Everything below this line is required by the spec. def __abs__(self: Array, /) -> Array: """ Performs the operation __abs__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __abs__") res = self._array.__abs__() return self.__class__._new(res) def __add__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __add__. """ other = self._check_allowed_dtypes(other, "numeric", "__add__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__add__(other._array) return self.__class__._new(res) def __and__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __and__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__and__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__and__(other._array) return self.__class__._new(res) def __array_namespace__( self: Array, /, *, api_version: Optional[str] = None ) -> types.ModuleType: if api_version is not None and not api_version.startswith("2021."): raise ValueError(f"Unrecognized array API version: {api_version!r}") return array_api def __bool__(self: Array, /) -> bool: """ Performs the operation __bool__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("bool is only allowed on arrays with 0 dimensions") if self.dtype not in _boolean_dtypes: raise ValueError("bool is only allowed on boolean arrays") res = self._array.__bool__() return res def __dlpack__(self: Array, /, *, stream: None = None) -> PyCapsule: """ Performs the operation __dlpack__. """ return self._array.__dlpack__(stream=stream) def __dlpack_device__(self: Array, /) -> Tuple[IntEnum, int]: """ Performs the operation __dlpack_device__. """ # Note: device support is required for this return self._array.__dlpack_device__() def __eq__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __eq__. """ # Even though "all" dtypes are allowed, we still require them to be # promotable with each other. other = self._check_allowed_dtypes(other, "all", "__eq__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__eq__(other._array) return self.__class__._new(res) def __float__(self: Array, /) -> float: """ Performs the operation __float__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("float is only allowed on arrays with 0 dimensions") if self.dtype not in _floating_dtypes: raise ValueError("float is only allowed on floating-point arrays") res = self._array.__float__() return res def __floordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __floordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__floordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__floordiv__(other._array) return self.__class__._new(res) def __ge__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ge__. """ other = self._check_allowed_dtypes(other, "numeric", "__ge__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ge__(other._array) return self.__class__._new(res) def __getitem__( self: Array, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], /, ) -> Array: """ Performs the operation __getitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array res = self._array.__getitem__(key) return self._new(res) def __gt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __gt__. """ other = self._check_allowed_dtypes(other, "numeric", "__gt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__gt__(other._array) return self.__class__._new(res) def __int__(self: Array, /) -> int: """ Performs the operation __int__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("int is only allowed on arrays with 0 dimensions") if self.dtype not in _integer_dtypes: raise ValueError("int is only allowed on integer arrays") res = self._array.__int__() return res def __index__(self: Array, /) -> int: """ Performs the operation __index__. """ res = self._array.__index__() return res def __invert__(self: Array, /) -> Array: """ Performs the operation __invert__. """ if self.dtype not in _integer_or_boolean_dtypes: raise TypeError("Only integer or boolean dtypes are allowed in __invert__") res = self._array.__invert__() return self.__class__._new(res) def __le__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __le__. """ other = self._check_allowed_dtypes(other, "numeric", "__le__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__le__(other._array) return self.__class__._new(res) def __lshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __lshift__. """ other = self._check_allowed_dtypes(other, "integer", "__lshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lshift__(other._array) return self.__class__._new(res) def __lt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __lt__. """ other = self._check_allowed_dtypes(other, "numeric", "__lt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lt__(other._array) return self.__class__._new(res) def __matmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __matmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__matmul__") if other is NotImplemented: return other res = self._array.__matmul__(other._array) return self.__class__._new(res) def __mod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mod__. """ other = self._check_allowed_dtypes(other, "numeric", "__mod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mod__(other._array) return self.__class__._new(res) def __mul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mul__. """ other = self._check_allowed_dtypes(other, "numeric", "__mul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mul__(other._array) return self.__class__._new(res) def __ne__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __ne__. """ other = self._check_allowed_dtypes(other, "all", "__ne__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ne__(other._array) return self.__class__._new(res) def __neg__(self: Array, /) -> Array: """ Performs the operation __neg__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __neg__") res = self._array.__neg__() return self.__class__._new(res) def __or__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __or__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__or__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__or__(other._array) return self.__class__._new(res) def __pos__(self: Array, /) -> Array: """ Performs the operation __pos__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __pos__") res = self._array.__pos__() return self.__class__._new(res) def __pow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __pow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__pow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow type promotion rules for 0-d # arrays, so we use pow() here instead. return pow(self, other) def __rshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rshift__(other._array) return self.__class__._new(res) def __setitem__( self, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], value: Union[int, float, bool, Array], /, ) -> None: """ Performs the operation __setitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array self._array.__setitem__(key, asarray(value)._array) def __sub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __sub__. """ other = self._check_allowed_dtypes(other, "numeric", "__sub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__sub__(other._array) return self.__class__._new(res) # PEP 484 requires int to be a subtype of float, but __truediv__ should # not accept int. def __truediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __truediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__truediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__truediv__(other._array) return self.__class__._new(res) def __xor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __xor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__xor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__xor__(other._array) return self.__class__._new(res) def __iadd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __iadd__. """ other = self._check_allowed_dtypes(other, "numeric", "__iadd__") if other is NotImplemented: return other self._array.__iadd__(other._array) return self def __radd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __radd__. """ other = self._check_allowed_dtypes(other, "numeric", "__radd__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__radd__(other._array) return self.__class__._new(res) def __iand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __iand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__iand__") if other is NotImplemented: return other self._array.__iand__(other._array) return self def __rand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rand__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rand__(other._array) return self.__class__._new(res) def __ifloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ifloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__ifloordiv__") if other is NotImplemented: return other self._array.__ifloordiv__(other._array) return self def __rfloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rfloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__rfloordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rfloordiv__(other._array) return self.__class__._new(res) def __ilshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __ilshift__. """ other = self._check_allowed_dtypes(other, "integer", "__ilshift__") if other is NotImplemented: return other self._array.__ilshift__(other._array) return self def __rlshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rlshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rlshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rlshift__(other._array) return self.__class__._new(res) def __imatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __imatmul__. """ # Note: NumPy does not implement __imatmul__. # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__imatmul__") if other is NotImplemented: return other # __imatmul__ can only be allowed when it would not change the shape # of self. other_shape = other.shape if self.shape == () or other_shape == (): raise ValueError("@= requires at least one dimension") if len(other_shape) == 1 or other_shape[-1] != other_shape[-2]: raise ValueError("@= cannot change the shape of the input array") self._array[:] = self._array.__matmul__(other._array) return self def __rmatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __rmatmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__rmatmul__") if other is NotImplemented: return other res = self._array.__rmatmul__(other._array) return self.__class__._new(res) def __imod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imod__. """ other = self._check_allowed_dtypes(other, "numeric", "__imod__") if other is NotImplemented: return other self._array.__imod__(other._array) return self def __rmod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmod__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmod__(other._array) return self.__class__._new(res) def __imul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imul__. """ other = self._check_allowed_dtypes(other, "numeric", "__imul__") if other is NotImplemented: return other self._array.__imul__(other._array) return self def __rmul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmul__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmul__(other._array) return self.__class__._new(res) def __ior__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ior__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ior__") if other is NotImplemented: return other self._array.__ior__(other._array) return self def __ror__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ror__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ror__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ror__(other._array) return self.__class__._new(res) def __ipow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ipow__. """ other = self._check_allowed_dtypes(other, "numeric", "__ipow__") if other is NotImplemented: return other self._array.__ipow__(other._array) return self def __rpow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rpow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__rpow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow the spec type promotion rules # for 0-d arrays, so we use pow() here instead. return pow(other, self) def __irshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __irshift__. """ other = self._check_allowed_dtypes(other, "integer", "__irshift__") if other is NotImplemented: return other self._array.__irshift__(other._array) return self def __rrshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rrshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rrshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rrshift__(other._array) return self.__class__._new(res) def __isub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __isub__. """ other = self._check_allowed_dtypes(other, "numeric", "__isub__") if other is NotImplemented: return other self._array.__isub__(other._array) return self def __rsub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rsub__. """ other = self._check_allowed_dtypes(other, "numeric", "__rsub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rsub__(other._array) return self.__class__._new(res) def __itruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __itruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__itruediv__") if other is NotImplemented: return other self._array.__itruediv__(other._array) return self def __rtruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __rtruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__rtruediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rtruediv__(other._array) return self.__class__._new(res) def __ixor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ixor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ixor__") if other is NotImplemented: return other self._array.__ixor__(other._array) return self def __rxor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rxor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rxor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rxor__(other._array) return self.__class__._new(res) def to_device(self: Array, device: Device, /, stream: None = None) -> Array: if stream is not None: raise ValueError("The stream argument to to_device() is not supported") if device == 'cpu': return self raise ValueError(f"Unsupported device {device!r}") def dtype(self) -> Dtype: """ Array API compatible wrapper for :py:meth:`np.ndarray.dtype <numpy.ndarray.dtype>`. See its docstring for more information. """ return self._array.dtype def device(self) -> Device: return "cpu" # Note: mT is new in array API spec (see matrix_transpose) def mT(self) -> Array: from .linalg import matrix_transpose return matrix_transpose(self) def ndim(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.ndim <numpy.ndarray.ndim>`. See its docstring for more information. """ return self._array.ndim def shape(self) -> Tuple[int, ...]: """ Array API compatible wrapper for :py:meth:`np.ndarray.shape <numpy.ndarray.shape>`. See its docstring for more information. """ return self._array.shape def size(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.size <numpy.ndarray.size>`. See its docstring for more information. """ return self._array.size def T(self) -> Array: """ Array API compatible wrapper for :py:meth:`np.ndarray.T <numpy.ndarray.T>`. See its docstring for more information. """ # Note: T only works on 2-dimensional arrays. See the corresponding # note in the specification: # https://data-apis.org/array-api/latest/API_specification/array_object.html#t if self.ndim != 2: raise ValueError("x.T requires x to have 2 dimensions. Use x.mT to transpose stacks of matrices and permute_dims() to permute dimensions.") return self.__class__._new(self._array.T) The provided code snippet includes necessary dependencies for implementing the `positive` function. Write a Python function `def positive(x: Array, /) -> Array` to solve the following problem: Array API compatible wrapper for :py:func:`np.positive <numpy.positive>`. See its docstring for more information. Here is the function: def positive(x: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.positive <numpy.positive>`. See its docstring for more information. """ if x.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in positive") return Array._new(np.positive(x._array))
Array API compatible wrapper for :py:func:`np.positive <numpy.positive>`. See its docstring for more information.
170,063
from __future__ import annotations from ._dtypes import ( _boolean_dtypes, _floating_dtypes, _integer_dtypes, _integer_or_boolean_dtypes, _numeric_dtypes, _result_type, ) from ._array_object import Array import numpy as np _numeric_dtypes = ( float32, float64, int8, int16, int32, int64, uint8, uint16, uint32, uint64, ) def _result_type(type1, type2): if (type1, type2) in _promotion_table: return _promotion_table[type1, type2] raise TypeError(f"{type1} and {type2} cannot be type promoted together") class Array: """ n-d array object for the array API namespace. See the docstring of :py:obj:`np.ndarray <numpy.ndarray>` for more information. This is a wrapper around numpy.ndarray that restricts the usage to only those things that are required by the array API namespace. Note, attributes on this object that start with a single underscore are not part of the API specification and should only be used internally. This object should not be constructed directly. Rather, use one of the creation functions, such as asarray(). """ _array: np.ndarray # Use a custom constructor instead of __init__, as manually initializing # this class is not supported API. def _new(cls, x, /): """ This is a private method for initializing the array API Array object. Functions outside of the array_api submodule should not use this method. Use one of the creation functions instead, such as ``asarray``. """ obj = super().__new__(cls) # Note: The spec does not have array scalars, only 0-D arrays. if isinstance(x, np.generic): # Convert the array scalar to a 0-D array x = np.asarray(x) if x.dtype not in _all_dtypes: raise TypeError( f"The array_api namespace does not support the dtype '{x.dtype}'" ) obj._array = x return obj # Prevent Array() from working def __new__(cls, *args, **kwargs): raise TypeError( "The array_api Array object should not be instantiated directly. Use an array creation function, such as asarray(), instead." ) # These functions are not required by the spec, but are implemented for # the sake of usability. def __str__(self: Array, /) -> str: """ Performs the operation __str__. """ return self._array.__str__().replace("array", "Array") def __repr__(self: Array, /) -> str: """ Performs the operation __repr__. """ suffix = f", dtype={self.dtype.name})" if 0 in self.shape: prefix = "empty(" mid = str(self.shape) else: prefix = "Array(" mid = np.array2string(self._array, separator=', ', prefix=prefix, suffix=suffix) return prefix + mid + suffix # This function is not required by the spec, but we implement it here for # convenience so that np.asarray(np.array_api.Array) will work. def __array__(self, dtype: None | np.dtype[Any] = None) -> npt.NDArray[Any]: """ Warning: this method is NOT part of the array API spec. Implementers of other libraries need not include it, and users should not assume it will be present in other implementations. """ return np.asarray(self._array, dtype=dtype) # These are various helper functions to make the array behavior match the # spec in places where it either deviates from or is more strict than # NumPy behavior def _check_allowed_dtypes(self, other: bool | int | float | Array, dtype_category: str, op: str) -> Array: """ Helper function for operators to only allow specific input dtypes Use like other = self._check_allowed_dtypes(other, 'numeric', '__add__') if other is NotImplemented: return other """ if self.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") if isinstance(other, (int, float, bool)): other = self._promote_scalar(other) elif isinstance(other, Array): if other.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") else: return NotImplemented # This will raise TypeError for type combinations that are not allowed # to promote in the spec (even if the NumPy array operator would # promote them). res_dtype = _result_type(self.dtype, other.dtype) if op.startswith("__i"): # Note: NumPy will allow in-place operators in some cases where # the type promoted operator does not match the left-hand side # operand. For example, # >>> a = np.array(1, dtype=np.int8) # >>> a += np.array(1, dtype=np.int16) # The spec explicitly disallows this. if res_dtype != self.dtype: raise TypeError( f"Cannot perform {op} with dtypes {self.dtype} and {other.dtype}" ) return other # Helper function to match the type promotion rules in the spec def _promote_scalar(self, scalar): """ Returns a promoted version of a Python scalar appropriate for use with operations on self. This may raise an OverflowError in cases where the scalar is an integer that is too large to fit in a NumPy integer dtype, or TypeError when the scalar type is incompatible with the dtype of self. """ # Note: Only Python scalar types that match the array dtype are # allowed. if isinstance(scalar, bool): if self.dtype not in _boolean_dtypes: raise TypeError( "Python bool scalars can only be promoted with bool arrays" ) elif isinstance(scalar, int): if self.dtype in _boolean_dtypes: raise TypeError( "Python int scalars cannot be promoted with bool arrays" ) elif isinstance(scalar, float): if self.dtype not in _floating_dtypes: raise TypeError( "Python float scalars can only be promoted with floating-point arrays." ) else: raise TypeError("'scalar' must be a Python scalar") # Note: scalars are unconditionally cast to the same dtype as the # array. # Note: the spec only specifies integer-dtype/int promotion # behavior for integers within the bounds of the integer dtype. # Outside of those bounds we use the default NumPy behavior (either # cast or raise OverflowError). return Array._new(np.array(scalar, self.dtype)) def _normalize_two_args(x1, x2) -> Tuple[Array, Array]: """ Normalize inputs to two arg functions to fix type promotion rules NumPy deviates from the spec type promotion rules in cases where one argument is 0-dimensional and the other is not. For example: >>> import numpy as np >>> a = np.array([1.0], dtype=np.float32) >>> b = np.array(1.0, dtype=np.float64) >>> np.add(a, b) # The spec says this should be float64 array([2.], dtype=float32) To fix this, we add a dimension to the 0-dimension array before passing it through. This works because a dimension would be added anyway from broadcasting, so the resulting shape is the same, but this prevents NumPy from not promoting the dtype. """ # Another option would be to use signature=(x1.dtype, x2.dtype, None), # but that only works for ufuncs, so we would have to call the ufuncs # directly in the operator methods. One should also note that this # sort of trick wouldn't work for functions like searchsorted, which # don't do normal broadcasting, but there aren't any functions like # that in the array API namespace. if x1.ndim == 0 and x2.ndim != 0: # The _array[None] workaround was chosen because it is relatively # performant. broadcast_to(x1._array, x2.shape) is much slower. We # could also manually type promote x2, but that is more complicated # and about the same performance as this. x1 = Array._new(x1._array[None]) elif x2.ndim == 0 and x1.ndim != 0: x2 = Array._new(x2._array[None]) return (x1, x2) # Note: A large fraction of allowed indices are disallowed here (see the # docstring below) def _validate_index(self, key): """ Validate an index according to the array API. The array API specification only requires a subset of indices that are supported by NumPy. This function will reject any index that is allowed by NumPy but not required by the array API specification. We always raise ``IndexError`` on such indices (the spec does not require any specific behavior on them, but this makes the NumPy array API namespace a minimal implementation of the spec). See https://data-apis.org/array-api/latest/API_specification/indexing.html for the full list of required indexing behavior This function raises IndexError if the index ``key`` is invalid. It only raises ``IndexError`` on indices that are not already rejected by NumPy, as NumPy will already raise the appropriate error on such indices. ``shape`` may be None, in which case, only cases that are independent of the array shape are checked. The following cases are allowed by NumPy, but not specified by the array API specification: - Indices to not include an implicit ellipsis at the end. That is, every axis of an array must be explicitly indexed or an ellipsis included. This behaviour is sometimes referred to as flat indexing. - The start and stop of a slice may not be out of bounds. In particular, for a slice ``i:j:k`` on an axis of size ``n``, only the following are allowed: - ``i`` or ``j`` omitted (``None``). - ``-n <= i <= max(0, n - 1)``. - For ``k > 0`` or ``k`` omitted (``None``), ``-n <= j <= n``. - For ``k < 0``, ``-n - 1 <= j <= max(0, n - 1)``. - Boolean array indices are not allowed as part of a larger tuple index. - Integer array indices are not allowed (with the exception of 0-D arrays, which are treated the same as scalars). Additionally, it should be noted that indices that would return a scalar in NumPy will return a 0-D array. Array scalars are not allowed in the specification, only 0-D arrays. This is done in the ``Array._new`` constructor, not this function. """ _key = key if isinstance(key, tuple) else (key,) for i in _key: if isinstance(i, bool) or not ( isinstance(i, SupportsIndex) # i.e. ints or isinstance(i, slice) or i == Ellipsis or i is None or isinstance(i, Array) or isinstance(i, np.ndarray) ): raise IndexError( f"Single-axes index {i} has {type(i)=}, but only " "integers, slices (:), ellipsis (...), newaxis (None), " "zero-dimensional integer arrays and boolean arrays " "are specified in the Array API." ) nonexpanding_key = [] single_axes = [] n_ellipsis = 0 key_has_mask = False for i in _key: if i is not None: nonexpanding_key.append(i) if isinstance(i, Array) or isinstance(i, np.ndarray): if i.dtype in _boolean_dtypes: key_has_mask = True single_axes.append(i) else: # i must not be an array here, to avoid elementwise equals if i == Ellipsis: n_ellipsis += 1 else: single_axes.append(i) n_single_axes = len(single_axes) if n_ellipsis > 1: return # handled by ndarray elif n_ellipsis == 0: # Note boolean masks must be the sole index, which we check for # later on. if not key_has_mask and n_single_axes < self.ndim: raise IndexError( f"{self.ndim=}, but the multi-axes index only specifies " f"{n_single_axes} dimensions. If this was intentional, " "add a trailing ellipsis (...) which expands into as many " "slices (:) as necessary - this is what np.ndarray arrays " "implicitly do, but such flat indexing behaviour is not " "specified in the Array API." ) if n_ellipsis == 0: indexed_shape = self.shape else: ellipsis_start = None for pos, i in enumerate(nonexpanding_key): if not (isinstance(i, Array) or isinstance(i, np.ndarray)): if i == Ellipsis: ellipsis_start = pos break assert ellipsis_start is not None # sanity check ellipsis_end = self.ndim - (n_single_axes - ellipsis_start) indexed_shape = ( self.shape[:ellipsis_start] + self.shape[ellipsis_end:] ) for i, side in zip(single_axes, indexed_shape): if isinstance(i, slice): if side == 0: f_range = "0 (or None)" else: f_range = f"between -{side} and {side - 1} (or None)" if i.start is not None: try: start = operator.index(i.start) except TypeError: pass # handled by ndarray else: if not (-side <= start <= side): raise IndexError( f"Slice {i} contains {start=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds starts are not specified in " "the Array API)" ) if i.stop is not None: try: stop = operator.index(i.stop) except TypeError: pass # handled by ndarray else: if not (-side <= stop <= side): raise IndexError( f"Slice {i} contains {stop=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds stops are not specified in " "the Array API)" ) elif isinstance(i, Array): if i.dtype in _boolean_dtypes and len(_key) != 1: assert isinstance(key, tuple) # sanity check raise IndexError( f"Single-axes index {i} is a boolean array and " f"{len(key)=}, but masking is only specified in the " "Array API when the array is the sole index." ) elif i.dtype in _integer_dtypes and i.ndim != 0: raise IndexError( f"Single-axes index {i} is a non-zero-dimensional " "integer array, but advanced integer indexing is not " "specified in the Array API." ) elif isinstance(i, tuple): raise IndexError( f"Single-axes index {i} is a tuple, but nested tuple " "indices are not specified in the Array API." ) # Everything below this line is required by the spec. def __abs__(self: Array, /) -> Array: """ Performs the operation __abs__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __abs__") res = self._array.__abs__() return self.__class__._new(res) def __add__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __add__. """ other = self._check_allowed_dtypes(other, "numeric", "__add__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__add__(other._array) return self.__class__._new(res) def __and__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __and__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__and__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__and__(other._array) return self.__class__._new(res) def __array_namespace__( self: Array, /, *, api_version: Optional[str] = None ) -> types.ModuleType: if api_version is not None and not api_version.startswith("2021."): raise ValueError(f"Unrecognized array API version: {api_version!r}") return array_api def __bool__(self: Array, /) -> bool: """ Performs the operation __bool__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("bool is only allowed on arrays with 0 dimensions") if self.dtype not in _boolean_dtypes: raise ValueError("bool is only allowed on boolean arrays") res = self._array.__bool__() return res def __dlpack__(self: Array, /, *, stream: None = None) -> PyCapsule: """ Performs the operation __dlpack__. """ return self._array.__dlpack__(stream=stream) def __dlpack_device__(self: Array, /) -> Tuple[IntEnum, int]: """ Performs the operation __dlpack_device__. """ # Note: device support is required for this return self._array.__dlpack_device__() def __eq__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __eq__. """ # Even though "all" dtypes are allowed, we still require them to be # promotable with each other. other = self._check_allowed_dtypes(other, "all", "__eq__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__eq__(other._array) return self.__class__._new(res) def __float__(self: Array, /) -> float: """ Performs the operation __float__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("float is only allowed on arrays with 0 dimensions") if self.dtype not in _floating_dtypes: raise ValueError("float is only allowed on floating-point arrays") res = self._array.__float__() return res def __floordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __floordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__floordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__floordiv__(other._array) return self.__class__._new(res) def __ge__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ge__. """ other = self._check_allowed_dtypes(other, "numeric", "__ge__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ge__(other._array) return self.__class__._new(res) def __getitem__( self: Array, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], /, ) -> Array: """ Performs the operation __getitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array res = self._array.__getitem__(key) return self._new(res) def __gt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __gt__. """ other = self._check_allowed_dtypes(other, "numeric", "__gt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__gt__(other._array) return self.__class__._new(res) def __int__(self: Array, /) -> int: """ Performs the operation __int__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("int is only allowed on arrays with 0 dimensions") if self.dtype not in _integer_dtypes: raise ValueError("int is only allowed on integer arrays") res = self._array.__int__() return res def __index__(self: Array, /) -> int: """ Performs the operation __index__. """ res = self._array.__index__() return res def __invert__(self: Array, /) -> Array: """ Performs the operation __invert__. """ if self.dtype not in _integer_or_boolean_dtypes: raise TypeError("Only integer or boolean dtypes are allowed in __invert__") res = self._array.__invert__() return self.__class__._new(res) def __le__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __le__. """ other = self._check_allowed_dtypes(other, "numeric", "__le__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__le__(other._array) return self.__class__._new(res) def __lshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __lshift__. """ other = self._check_allowed_dtypes(other, "integer", "__lshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lshift__(other._array) return self.__class__._new(res) def __lt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __lt__. """ other = self._check_allowed_dtypes(other, "numeric", "__lt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lt__(other._array) return self.__class__._new(res) def __matmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __matmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__matmul__") if other is NotImplemented: return other res = self._array.__matmul__(other._array) return self.__class__._new(res) def __mod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mod__. """ other = self._check_allowed_dtypes(other, "numeric", "__mod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mod__(other._array) return self.__class__._new(res) def __mul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mul__. """ other = self._check_allowed_dtypes(other, "numeric", "__mul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mul__(other._array) return self.__class__._new(res) def __ne__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __ne__. """ other = self._check_allowed_dtypes(other, "all", "__ne__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ne__(other._array) return self.__class__._new(res) def __neg__(self: Array, /) -> Array: """ Performs the operation __neg__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __neg__") res = self._array.__neg__() return self.__class__._new(res) def __or__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __or__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__or__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__or__(other._array) return self.__class__._new(res) def __pos__(self: Array, /) -> Array: """ Performs the operation __pos__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __pos__") res = self._array.__pos__() return self.__class__._new(res) def __pow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __pow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__pow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow type promotion rules for 0-d # arrays, so we use pow() here instead. return pow(self, other) def __rshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rshift__(other._array) return self.__class__._new(res) def __setitem__( self, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], value: Union[int, float, bool, Array], /, ) -> None: """ Performs the operation __setitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array self._array.__setitem__(key, asarray(value)._array) def __sub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __sub__. """ other = self._check_allowed_dtypes(other, "numeric", "__sub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__sub__(other._array) return self.__class__._new(res) # PEP 484 requires int to be a subtype of float, but __truediv__ should # not accept int. def __truediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __truediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__truediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__truediv__(other._array) return self.__class__._new(res) def __xor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __xor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__xor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__xor__(other._array) return self.__class__._new(res) def __iadd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __iadd__. """ other = self._check_allowed_dtypes(other, "numeric", "__iadd__") if other is NotImplemented: return other self._array.__iadd__(other._array) return self def __radd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __radd__. """ other = self._check_allowed_dtypes(other, "numeric", "__radd__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__radd__(other._array) return self.__class__._new(res) def __iand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __iand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__iand__") if other is NotImplemented: return other self._array.__iand__(other._array) return self def __rand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rand__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rand__(other._array) return self.__class__._new(res) def __ifloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ifloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__ifloordiv__") if other is NotImplemented: return other self._array.__ifloordiv__(other._array) return self def __rfloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rfloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__rfloordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rfloordiv__(other._array) return self.__class__._new(res) def __ilshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __ilshift__. """ other = self._check_allowed_dtypes(other, "integer", "__ilshift__") if other is NotImplemented: return other self._array.__ilshift__(other._array) return self def __rlshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rlshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rlshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rlshift__(other._array) return self.__class__._new(res) def __imatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __imatmul__. """ # Note: NumPy does not implement __imatmul__. # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__imatmul__") if other is NotImplemented: return other # __imatmul__ can only be allowed when it would not change the shape # of self. other_shape = other.shape if self.shape == () or other_shape == (): raise ValueError("@= requires at least one dimension") if len(other_shape) == 1 or other_shape[-1] != other_shape[-2]: raise ValueError("@= cannot change the shape of the input array") self._array[:] = self._array.__matmul__(other._array) return self def __rmatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __rmatmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__rmatmul__") if other is NotImplemented: return other res = self._array.__rmatmul__(other._array) return self.__class__._new(res) def __imod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imod__. """ other = self._check_allowed_dtypes(other, "numeric", "__imod__") if other is NotImplemented: return other self._array.__imod__(other._array) return self def __rmod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmod__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmod__(other._array) return self.__class__._new(res) def __imul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imul__. """ other = self._check_allowed_dtypes(other, "numeric", "__imul__") if other is NotImplemented: return other self._array.__imul__(other._array) return self def __rmul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmul__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmul__(other._array) return self.__class__._new(res) def __ior__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ior__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ior__") if other is NotImplemented: return other self._array.__ior__(other._array) return self def __ror__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ror__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ror__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ror__(other._array) return self.__class__._new(res) def __ipow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ipow__. """ other = self._check_allowed_dtypes(other, "numeric", "__ipow__") if other is NotImplemented: return other self._array.__ipow__(other._array) return self def __rpow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rpow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__rpow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow the spec type promotion rules # for 0-d arrays, so we use pow() here instead. return pow(other, self) def __irshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __irshift__. """ other = self._check_allowed_dtypes(other, "integer", "__irshift__") if other is NotImplemented: return other self._array.__irshift__(other._array) return self def __rrshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rrshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rrshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rrshift__(other._array) return self.__class__._new(res) def __isub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __isub__. """ other = self._check_allowed_dtypes(other, "numeric", "__isub__") if other is NotImplemented: return other self._array.__isub__(other._array) return self def __rsub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rsub__. """ other = self._check_allowed_dtypes(other, "numeric", "__rsub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rsub__(other._array) return self.__class__._new(res) def __itruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __itruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__itruediv__") if other is NotImplemented: return other self._array.__itruediv__(other._array) return self def __rtruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __rtruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__rtruediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rtruediv__(other._array) return self.__class__._new(res) def __ixor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ixor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ixor__") if other is NotImplemented: return other self._array.__ixor__(other._array) return self def __rxor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rxor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rxor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rxor__(other._array) return self.__class__._new(res) def to_device(self: Array, device: Device, /, stream: None = None) -> Array: if stream is not None: raise ValueError("The stream argument to to_device() is not supported") if device == 'cpu': return self raise ValueError(f"Unsupported device {device!r}") def dtype(self) -> Dtype: """ Array API compatible wrapper for :py:meth:`np.ndarray.dtype <numpy.ndarray.dtype>`. See its docstring for more information. """ return self._array.dtype def device(self) -> Device: return "cpu" # Note: mT is new in array API spec (see matrix_transpose) def mT(self) -> Array: from .linalg import matrix_transpose return matrix_transpose(self) def ndim(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.ndim <numpy.ndarray.ndim>`. See its docstring for more information. """ return self._array.ndim def shape(self) -> Tuple[int, ...]: """ Array API compatible wrapper for :py:meth:`np.ndarray.shape <numpy.ndarray.shape>`. See its docstring for more information. """ return self._array.shape def size(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.size <numpy.ndarray.size>`. See its docstring for more information. """ return self._array.size def T(self) -> Array: """ Array API compatible wrapper for :py:meth:`np.ndarray.T <numpy.ndarray.T>`. See its docstring for more information. """ # Note: T only works on 2-dimensional arrays. See the corresponding # note in the specification: # https://data-apis.org/array-api/latest/API_specification/array_object.html#t if self.ndim != 2: raise ValueError("x.T requires x to have 2 dimensions. Use x.mT to transpose stacks of matrices and permute_dims() to permute dimensions.") return self.__class__._new(self._array.T) The provided code snippet includes necessary dependencies for implementing the `pow` function. Write a Python function `def pow(x1: Array, x2: Array, /) -> Array` to solve the following problem: Array API compatible wrapper for :py:func:`np.power <numpy.power>`. See its docstring for more information. Here is the function: def pow(x1: Array, x2: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.power <numpy.power>`. See its docstring for more information. """ if x1.dtype not in _numeric_dtypes or x2.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in pow") # Call result type here just to raise on disallowed type combinations _result_type(x1.dtype, x2.dtype) x1, x2 = Array._normalize_two_args(x1, x2) return Array._new(np.power(x1._array, x2._array))
Array API compatible wrapper for :py:func:`np.power <numpy.power>`. See its docstring for more information.
170,064
from __future__ import annotations from ._dtypes import ( _boolean_dtypes, _floating_dtypes, _integer_dtypes, _integer_or_boolean_dtypes, _numeric_dtypes, _result_type, ) from ._array_object import Array import numpy as np _numeric_dtypes = ( float32, float64, int8, int16, int32, int64, uint8, uint16, uint32, uint64, ) def _result_type(type1, type2): if (type1, type2) in _promotion_table: return _promotion_table[type1, type2] raise TypeError(f"{type1} and {type2} cannot be type promoted together") class Array: """ n-d array object for the array API namespace. See the docstring of :py:obj:`np.ndarray <numpy.ndarray>` for more information. This is a wrapper around numpy.ndarray that restricts the usage to only those things that are required by the array API namespace. Note, attributes on this object that start with a single underscore are not part of the API specification and should only be used internally. This object should not be constructed directly. Rather, use one of the creation functions, such as asarray(). """ _array: np.ndarray # Use a custom constructor instead of __init__, as manually initializing # this class is not supported API. def _new(cls, x, /): """ This is a private method for initializing the array API Array object. Functions outside of the array_api submodule should not use this method. Use one of the creation functions instead, such as ``asarray``. """ obj = super().__new__(cls) # Note: The spec does not have array scalars, only 0-D arrays. if isinstance(x, np.generic): # Convert the array scalar to a 0-D array x = np.asarray(x) if x.dtype not in _all_dtypes: raise TypeError( f"The array_api namespace does not support the dtype '{x.dtype}'" ) obj._array = x return obj # Prevent Array() from working def __new__(cls, *args, **kwargs): raise TypeError( "The array_api Array object should not be instantiated directly. Use an array creation function, such as asarray(), instead." ) # These functions are not required by the spec, but are implemented for # the sake of usability. def __str__(self: Array, /) -> str: """ Performs the operation __str__. """ return self._array.__str__().replace("array", "Array") def __repr__(self: Array, /) -> str: """ Performs the operation __repr__. """ suffix = f", dtype={self.dtype.name})" if 0 in self.shape: prefix = "empty(" mid = str(self.shape) else: prefix = "Array(" mid = np.array2string(self._array, separator=', ', prefix=prefix, suffix=suffix) return prefix + mid + suffix # This function is not required by the spec, but we implement it here for # convenience so that np.asarray(np.array_api.Array) will work. def __array__(self, dtype: None | np.dtype[Any] = None) -> npt.NDArray[Any]: """ Warning: this method is NOT part of the array API spec. Implementers of other libraries need not include it, and users should not assume it will be present in other implementations. """ return np.asarray(self._array, dtype=dtype) # These are various helper functions to make the array behavior match the # spec in places where it either deviates from or is more strict than # NumPy behavior def _check_allowed_dtypes(self, other: bool | int | float | Array, dtype_category: str, op: str) -> Array: """ Helper function for operators to only allow specific input dtypes Use like other = self._check_allowed_dtypes(other, 'numeric', '__add__') if other is NotImplemented: return other """ if self.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") if isinstance(other, (int, float, bool)): other = self._promote_scalar(other) elif isinstance(other, Array): if other.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") else: return NotImplemented # This will raise TypeError for type combinations that are not allowed # to promote in the spec (even if the NumPy array operator would # promote them). res_dtype = _result_type(self.dtype, other.dtype) if op.startswith("__i"): # Note: NumPy will allow in-place operators in some cases where # the type promoted operator does not match the left-hand side # operand. For example, # >>> a = np.array(1, dtype=np.int8) # >>> a += np.array(1, dtype=np.int16) # The spec explicitly disallows this. if res_dtype != self.dtype: raise TypeError( f"Cannot perform {op} with dtypes {self.dtype} and {other.dtype}" ) return other # Helper function to match the type promotion rules in the spec def _promote_scalar(self, scalar): """ Returns a promoted version of a Python scalar appropriate for use with operations on self. This may raise an OverflowError in cases where the scalar is an integer that is too large to fit in a NumPy integer dtype, or TypeError when the scalar type is incompatible with the dtype of self. """ # Note: Only Python scalar types that match the array dtype are # allowed. if isinstance(scalar, bool): if self.dtype not in _boolean_dtypes: raise TypeError( "Python bool scalars can only be promoted with bool arrays" ) elif isinstance(scalar, int): if self.dtype in _boolean_dtypes: raise TypeError( "Python int scalars cannot be promoted with bool arrays" ) elif isinstance(scalar, float): if self.dtype not in _floating_dtypes: raise TypeError( "Python float scalars can only be promoted with floating-point arrays." ) else: raise TypeError("'scalar' must be a Python scalar") # Note: scalars are unconditionally cast to the same dtype as the # array. # Note: the spec only specifies integer-dtype/int promotion # behavior for integers within the bounds of the integer dtype. # Outside of those bounds we use the default NumPy behavior (either # cast or raise OverflowError). return Array._new(np.array(scalar, self.dtype)) def _normalize_two_args(x1, x2) -> Tuple[Array, Array]: """ Normalize inputs to two arg functions to fix type promotion rules NumPy deviates from the spec type promotion rules in cases where one argument is 0-dimensional and the other is not. For example: >>> import numpy as np >>> a = np.array([1.0], dtype=np.float32) >>> b = np.array(1.0, dtype=np.float64) >>> np.add(a, b) # The spec says this should be float64 array([2.], dtype=float32) To fix this, we add a dimension to the 0-dimension array before passing it through. This works because a dimension would be added anyway from broadcasting, so the resulting shape is the same, but this prevents NumPy from not promoting the dtype. """ # Another option would be to use signature=(x1.dtype, x2.dtype, None), # but that only works for ufuncs, so we would have to call the ufuncs # directly in the operator methods. One should also note that this # sort of trick wouldn't work for functions like searchsorted, which # don't do normal broadcasting, but there aren't any functions like # that in the array API namespace. if x1.ndim == 0 and x2.ndim != 0: # The _array[None] workaround was chosen because it is relatively # performant. broadcast_to(x1._array, x2.shape) is much slower. We # could also manually type promote x2, but that is more complicated # and about the same performance as this. x1 = Array._new(x1._array[None]) elif x2.ndim == 0 and x1.ndim != 0: x2 = Array._new(x2._array[None]) return (x1, x2) # Note: A large fraction of allowed indices are disallowed here (see the # docstring below) def _validate_index(self, key): """ Validate an index according to the array API. The array API specification only requires a subset of indices that are supported by NumPy. This function will reject any index that is allowed by NumPy but not required by the array API specification. We always raise ``IndexError`` on such indices (the spec does not require any specific behavior on them, but this makes the NumPy array API namespace a minimal implementation of the spec). See https://data-apis.org/array-api/latest/API_specification/indexing.html for the full list of required indexing behavior This function raises IndexError if the index ``key`` is invalid. It only raises ``IndexError`` on indices that are not already rejected by NumPy, as NumPy will already raise the appropriate error on such indices. ``shape`` may be None, in which case, only cases that are independent of the array shape are checked. The following cases are allowed by NumPy, but not specified by the array API specification: - Indices to not include an implicit ellipsis at the end. That is, every axis of an array must be explicitly indexed or an ellipsis included. This behaviour is sometimes referred to as flat indexing. - The start and stop of a slice may not be out of bounds. In particular, for a slice ``i:j:k`` on an axis of size ``n``, only the following are allowed: - ``i`` or ``j`` omitted (``None``). - ``-n <= i <= max(0, n - 1)``. - For ``k > 0`` or ``k`` omitted (``None``), ``-n <= j <= n``. - For ``k < 0``, ``-n - 1 <= j <= max(0, n - 1)``. - Boolean array indices are not allowed as part of a larger tuple index. - Integer array indices are not allowed (with the exception of 0-D arrays, which are treated the same as scalars). Additionally, it should be noted that indices that would return a scalar in NumPy will return a 0-D array. Array scalars are not allowed in the specification, only 0-D arrays. This is done in the ``Array._new`` constructor, not this function. """ _key = key if isinstance(key, tuple) else (key,) for i in _key: if isinstance(i, bool) or not ( isinstance(i, SupportsIndex) # i.e. ints or isinstance(i, slice) or i == Ellipsis or i is None or isinstance(i, Array) or isinstance(i, np.ndarray) ): raise IndexError( f"Single-axes index {i} has {type(i)=}, but only " "integers, slices (:), ellipsis (...), newaxis (None), " "zero-dimensional integer arrays and boolean arrays " "are specified in the Array API." ) nonexpanding_key = [] single_axes = [] n_ellipsis = 0 key_has_mask = False for i in _key: if i is not None: nonexpanding_key.append(i) if isinstance(i, Array) or isinstance(i, np.ndarray): if i.dtype in _boolean_dtypes: key_has_mask = True single_axes.append(i) else: # i must not be an array here, to avoid elementwise equals if i == Ellipsis: n_ellipsis += 1 else: single_axes.append(i) n_single_axes = len(single_axes) if n_ellipsis > 1: return # handled by ndarray elif n_ellipsis == 0: # Note boolean masks must be the sole index, which we check for # later on. if not key_has_mask and n_single_axes < self.ndim: raise IndexError( f"{self.ndim=}, but the multi-axes index only specifies " f"{n_single_axes} dimensions. If this was intentional, " "add a trailing ellipsis (...) which expands into as many " "slices (:) as necessary - this is what np.ndarray arrays " "implicitly do, but such flat indexing behaviour is not " "specified in the Array API." ) if n_ellipsis == 0: indexed_shape = self.shape else: ellipsis_start = None for pos, i in enumerate(nonexpanding_key): if not (isinstance(i, Array) or isinstance(i, np.ndarray)): if i == Ellipsis: ellipsis_start = pos break assert ellipsis_start is not None # sanity check ellipsis_end = self.ndim - (n_single_axes - ellipsis_start) indexed_shape = ( self.shape[:ellipsis_start] + self.shape[ellipsis_end:] ) for i, side in zip(single_axes, indexed_shape): if isinstance(i, slice): if side == 0: f_range = "0 (or None)" else: f_range = f"between -{side} and {side - 1} (or None)" if i.start is not None: try: start = operator.index(i.start) except TypeError: pass # handled by ndarray else: if not (-side <= start <= side): raise IndexError( f"Slice {i} contains {start=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds starts are not specified in " "the Array API)" ) if i.stop is not None: try: stop = operator.index(i.stop) except TypeError: pass # handled by ndarray else: if not (-side <= stop <= side): raise IndexError( f"Slice {i} contains {stop=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds stops are not specified in " "the Array API)" ) elif isinstance(i, Array): if i.dtype in _boolean_dtypes and len(_key) != 1: assert isinstance(key, tuple) # sanity check raise IndexError( f"Single-axes index {i} is a boolean array and " f"{len(key)=}, but masking is only specified in the " "Array API when the array is the sole index." ) elif i.dtype in _integer_dtypes and i.ndim != 0: raise IndexError( f"Single-axes index {i} is a non-zero-dimensional " "integer array, but advanced integer indexing is not " "specified in the Array API." ) elif isinstance(i, tuple): raise IndexError( f"Single-axes index {i} is a tuple, but nested tuple " "indices are not specified in the Array API." ) # Everything below this line is required by the spec. def __abs__(self: Array, /) -> Array: """ Performs the operation __abs__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __abs__") res = self._array.__abs__() return self.__class__._new(res) def __add__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __add__. """ other = self._check_allowed_dtypes(other, "numeric", "__add__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__add__(other._array) return self.__class__._new(res) def __and__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __and__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__and__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__and__(other._array) return self.__class__._new(res) def __array_namespace__( self: Array, /, *, api_version: Optional[str] = None ) -> types.ModuleType: if api_version is not None and not api_version.startswith("2021."): raise ValueError(f"Unrecognized array API version: {api_version!r}") return array_api def __bool__(self: Array, /) -> bool: """ Performs the operation __bool__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("bool is only allowed on arrays with 0 dimensions") if self.dtype not in _boolean_dtypes: raise ValueError("bool is only allowed on boolean arrays") res = self._array.__bool__() return res def __dlpack__(self: Array, /, *, stream: None = None) -> PyCapsule: """ Performs the operation __dlpack__. """ return self._array.__dlpack__(stream=stream) def __dlpack_device__(self: Array, /) -> Tuple[IntEnum, int]: """ Performs the operation __dlpack_device__. """ # Note: device support is required for this return self._array.__dlpack_device__() def __eq__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __eq__. """ # Even though "all" dtypes are allowed, we still require them to be # promotable with each other. other = self._check_allowed_dtypes(other, "all", "__eq__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__eq__(other._array) return self.__class__._new(res) def __float__(self: Array, /) -> float: """ Performs the operation __float__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("float is only allowed on arrays with 0 dimensions") if self.dtype not in _floating_dtypes: raise ValueError("float is only allowed on floating-point arrays") res = self._array.__float__() return res def __floordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __floordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__floordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__floordiv__(other._array) return self.__class__._new(res) def __ge__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ge__. """ other = self._check_allowed_dtypes(other, "numeric", "__ge__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ge__(other._array) return self.__class__._new(res) def __getitem__( self: Array, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], /, ) -> Array: """ Performs the operation __getitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array res = self._array.__getitem__(key) return self._new(res) def __gt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __gt__. """ other = self._check_allowed_dtypes(other, "numeric", "__gt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__gt__(other._array) return self.__class__._new(res) def __int__(self: Array, /) -> int: """ Performs the operation __int__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("int is only allowed on arrays with 0 dimensions") if self.dtype not in _integer_dtypes: raise ValueError("int is only allowed on integer arrays") res = self._array.__int__() return res def __index__(self: Array, /) -> int: """ Performs the operation __index__. """ res = self._array.__index__() return res def __invert__(self: Array, /) -> Array: """ Performs the operation __invert__. """ if self.dtype not in _integer_or_boolean_dtypes: raise TypeError("Only integer or boolean dtypes are allowed in __invert__") res = self._array.__invert__() return self.__class__._new(res) def __le__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __le__. """ other = self._check_allowed_dtypes(other, "numeric", "__le__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__le__(other._array) return self.__class__._new(res) def __lshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __lshift__. """ other = self._check_allowed_dtypes(other, "integer", "__lshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lshift__(other._array) return self.__class__._new(res) def __lt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __lt__. """ other = self._check_allowed_dtypes(other, "numeric", "__lt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lt__(other._array) return self.__class__._new(res) def __matmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __matmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__matmul__") if other is NotImplemented: return other res = self._array.__matmul__(other._array) return self.__class__._new(res) def __mod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mod__. """ other = self._check_allowed_dtypes(other, "numeric", "__mod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mod__(other._array) return self.__class__._new(res) def __mul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mul__. """ other = self._check_allowed_dtypes(other, "numeric", "__mul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mul__(other._array) return self.__class__._new(res) def __ne__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __ne__. """ other = self._check_allowed_dtypes(other, "all", "__ne__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ne__(other._array) return self.__class__._new(res) def __neg__(self: Array, /) -> Array: """ Performs the operation __neg__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __neg__") res = self._array.__neg__() return self.__class__._new(res) def __or__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __or__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__or__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__or__(other._array) return self.__class__._new(res) def __pos__(self: Array, /) -> Array: """ Performs the operation __pos__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __pos__") res = self._array.__pos__() return self.__class__._new(res) def __pow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __pow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__pow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow type promotion rules for 0-d # arrays, so we use pow() here instead. return pow(self, other) def __rshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rshift__(other._array) return self.__class__._new(res) def __setitem__( self, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], value: Union[int, float, bool, Array], /, ) -> None: """ Performs the operation __setitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array self._array.__setitem__(key, asarray(value)._array) def __sub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __sub__. """ other = self._check_allowed_dtypes(other, "numeric", "__sub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__sub__(other._array) return self.__class__._new(res) # PEP 484 requires int to be a subtype of float, but __truediv__ should # not accept int. def __truediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __truediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__truediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__truediv__(other._array) return self.__class__._new(res) def __xor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __xor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__xor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__xor__(other._array) return self.__class__._new(res) def __iadd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __iadd__. """ other = self._check_allowed_dtypes(other, "numeric", "__iadd__") if other is NotImplemented: return other self._array.__iadd__(other._array) return self def __radd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __radd__. """ other = self._check_allowed_dtypes(other, "numeric", "__radd__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__radd__(other._array) return self.__class__._new(res) def __iand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __iand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__iand__") if other is NotImplemented: return other self._array.__iand__(other._array) return self def __rand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rand__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rand__(other._array) return self.__class__._new(res) def __ifloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ifloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__ifloordiv__") if other is NotImplemented: return other self._array.__ifloordiv__(other._array) return self def __rfloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rfloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__rfloordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rfloordiv__(other._array) return self.__class__._new(res) def __ilshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __ilshift__. """ other = self._check_allowed_dtypes(other, "integer", "__ilshift__") if other is NotImplemented: return other self._array.__ilshift__(other._array) return self def __rlshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rlshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rlshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rlshift__(other._array) return self.__class__._new(res) def __imatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __imatmul__. """ # Note: NumPy does not implement __imatmul__. # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__imatmul__") if other is NotImplemented: return other # __imatmul__ can only be allowed when it would not change the shape # of self. other_shape = other.shape if self.shape == () or other_shape == (): raise ValueError("@= requires at least one dimension") if len(other_shape) == 1 or other_shape[-1] != other_shape[-2]: raise ValueError("@= cannot change the shape of the input array") self._array[:] = self._array.__matmul__(other._array) return self def __rmatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __rmatmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__rmatmul__") if other is NotImplemented: return other res = self._array.__rmatmul__(other._array) return self.__class__._new(res) def __imod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imod__. """ other = self._check_allowed_dtypes(other, "numeric", "__imod__") if other is NotImplemented: return other self._array.__imod__(other._array) return self def __rmod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmod__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmod__(other._array) return self.__class__._new(res) def __imul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imul__. """ other = self._check_allowed_dtypes(other, "numeric", "__imul__") if other is NotImplemented: return other self._array.__imul__(other._array) return self def __rmul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmul__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmul__(other._array) return self.__class__._new(res) def __ior__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ior__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ior__") if other is NotImplemented: return other self._array.__ior__(other._array) return self def __ror__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ror__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ror__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ror__(other._array) return self.__class__._new(res) def __ipow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ipow__. """ other = self._check_allowed_dtypes(other, "numeric", "__ipow__") if other is NotImplemented: return other self._array.__ipow__(other._array) return self def __rpow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rpow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__rpow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow the spec type promotion rules # for 0-d arrays, so we use pow() here instead. return pow(other, self) def __irshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __irshift__. """ other = self._check_allowed_dtypes(other, "integer", "__irshift__") if other is NotImplemented: return other self._array.__irshift__(other._array) return self def __rrshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rrshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rrshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rrshift__(other._array) return self.__class__._new(res) def __isub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __isub__. """ other = self._check_allowed_dtypes(other, "numeric", "__isub__") if other is NotImplemented: return other self._array.__isub__(other._array) return self def __rsub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rsub__. """ other = self._check_allowed_dtypes(other, "numeric", "__rsub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rsub__(other._array) return self.__class__._new(res) def __itruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __itruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__itruediv__") if other is NotImplemented: return other self._array.__itruediv__(other._array) return self def __rtruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __rtruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__rtruediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rtruediv__(other._array) return self.__class__._new(res) def __ixor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ixor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ixor__") if other is NotImplemented: return other self._array.__ixor__(other._array) return self def __rxor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rxor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rxor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rxor__(other._array) return self.__class__._new(res) def to_device(self: Array, device: Device, /, stream: None = None) -> Array: if stream is not None: raise ValueError("The stream argument to to_device() is not supported") if device == 'cpu': return self raise ValueError(f"Unsupported device {device!r}") def dtype(self) -> Dtype: """ Array API compatible wrapper for :py:meth:`np.ndarray.dtype <numpy.ndarray.dtype>`. See its docstring for more information. """ return self._array.dtype def device(self) -> Device: return "cpu" # Note: mT is new in array API spec (see matrix_transpose) def mT(self) -> Array: from .linalg import matrix_transpose return matrix_transpose(self) def ndim(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.ndim <numpy.ndarray.ndim>`. See its docstring for more information. """ return self._array.ndim def shape(self) -> Tuple[int, ...]: """ Array API compatible wrapper for :py:meth:`np.ndarray.shape <numpy.ndarray.shape>`. See its docstring for more information. """ return self._array.shape def size(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.size <numpy.ndarray.size>`. See its docstring for more information. """ return self._array.size def T(self) -> Array: """ Array API compatible wrapper for :py:meth:`np.ndarray.T <numpy.ndarray.T>`. See its docstring for more information. """ # Note: T only works on 2-dimensional arrays. See the corresponding # note in the specification: # https://data-apis.org/array-api/latest/API_specification/array_object.html#t if self.ndim != 2: raise ValueError("x.T requires x to have 2 dimensions. Use x.mT to transpose stacks of matrices and permute_dims() to permute dimensions.") return self.__class__._new(self._array.T) The provided code snippet includes necessary dependencies for implementing the `remainder` function. Write a Python function `def remainder(x1: Array, x2: Array, /) -> Array` to solve the following problem: Array API compatible wrapper for :py:func:`np.remainder <numpy.remainder>`. See its docstring for more information. Here is the function: def remainder(x1: Array, x2: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.remainder <numpy.remainder>`. See its docstring for more information. """ if x1.dtype not in _numeric_dtypes or x2.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in remainder") # Call result type here just to raise on disallowed type combinations _result_type(x1.dtype, x2.dtype) x1, x2 = Array._normalize_two_args(x1, x2) return Array._new(np.remainder(x1._array, x2._array))
Array API compatible wrapper for :py:func:`np.remainder <numpy.remainder>`. See its docstring for more information.
170,065
from __future__ import annotations from ._dtypes import ( _boolean_dtypes, _floating_dtypes, _integer_dtypes, _integer_or_boolean_dtypes, _numeric_dtypes, _result_type, ) from ._array_object import Array import numpy as np _numeric_dtypes = ( float32, float64, int8, int16, int32, int64, uint8, uint16, uint32, uint64, ) class Array: """ n-d array object for the array API namespace. See the docstring of :py:obj:`np.ndarray <numpy.ndarray>` for more information. This is a wrapper around numpy.ndarray that restricts the usage to only those things that are required by the array API namespace. Note, attributes on this object that start with a single underscore are not part of the API specification and should only be used internally. This object should not be constructed directly. Rather, use one of the creation functions, such as asarray(). """ _array: np.ndarray # Use a custom constructor instead of __init__, as manually initializing # this class is not supported API. def _new(cls, x, /): """ This is a private method for initializing the array API Array object. Functions outside of the array_api submodule should not use this method. Use one of the creation functions instead, such as ``asarray``. """ obj = super().__new__(cls) # Note: The spec does not have array scalars, only 0-D arrays. if isinstance(x, np.generic): # Convert the array scalar to a 0-D array x = np.asarray(x) if x.dtype not in _all_dtypes: raise TypeError( f"The array_api namespace does not support the dtype '{x.dtype}'" ) obj._array = x return obj # Prevent Array() from working def __new__(cls, *args, **kwargs): raise TypeError( "The array_api Array object should not be instantiated directly. Use an array creation function, such as asarray(), instead." ) # These functions are not required by the spec, but are implemented for # the sake of usability. def __str__(self: Array, /) -> str: """ Performs the operation __str__. """ return self._array.__str__().replace("array", "Array") def __repr__(self: Array, /) -> str: """ Performs the operation __repr__. """ suffix = f", dtype={self.dtype.name})" if 0 in self.shape: prefix = "empty(" mid = str(self.shape) else: prefix = "Array(" mid = np.array2string(self._array, separator=', ', prefix=prefix, suffix=suffix) return prefix + mid + suffix # This function is not required by the spec, but we implement it here for # convenience so that np.asarray(np.array_api.Array) will work. def __array__(self, dtype: None | np.dtype[Any] = None) -> npt.NDArray[Any]: """ Warning: this method is NOT part of the array API spec. Implementers of other libraries need not include it, and users should not assume it will be present in other implementations. """ return np.asarray(self._array, dtype=dtype) # These are various helper functions to make the array behavior match the # spec in places where it either deviates from or is more strict than # NumPy behavior def _check_allowed_dtypes(self, other: bool | int | float | Array, dtype_category: str, op: str) -> Array: """ Helper function for operators to only allow specific input dtypes Use like other = self._check_allowed_dtypes(other, 'numeric', '__add__') if other is NotImplemented: return other """ if self.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") if isinstance(other, (int, float, bool)): other = self._promote_scalar(other) elif isinstance(other, Array): if other.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") else: return NotImplemented # This will raise TypeError for type combinations that are not allowed # to promote in the spec (even if the NumPy array operator would # promote them). res_dtype = _result_type(self.dtype, other.dtype) if op.startswith("__i"): # Note: NumPy will allow in-place operators in some cases where # the type promoted operator does not match the left-hand side # operand. For example, # >>> a = np.array(1, dtype=np.int8) # >>> a += np.array(1, dtype=np.int16) # The spec explicitly disallows this. if res_dtype != self.dtype: raise TypeError( f"Cannot perform {op} with dtypes {self.dtype} and {other.dtype}" ) return other # Helper function to match the type promotion rules in the spec def _promote_scalar(self, scalar): """ Returns a promoted version of a Python scalar appropriate for use with operations on self. This may raise an OverflowError in cases where the scalar is an integer that is too large to fit in a NumPy integer dtype, or TypeError when the scalar type is incompatible with the dtype of self. """ # Note: Only Python scalar types that match the array dtype are # allowed. if isinstance(scalar, bool): if self.dtype not in _boolean_dtypes: raise TypeError( "Python bool scalars can only be promoted with bool arrays" ) elif isinstance(scalar, int): if self.dtype in _boolean_dtypes: raise TypeError( "Python int scalars cannot be promoted with bool arrays" ) elif isinstance(scalar, float): if self.dtype not in _floating_dtypes: raise TypeError( "Python float scalars can only be promoted with floating-point arrays." ) else: raise TypeError("'scalar' must be a Python scalar") # Note: scalars are unconditionally cast to the same dtype as the # array. # Note: the spec only specifies integer-dtype/int promotion # behavior for integers within the bounds of the integer dtype. # Outside of those bounds we use the default NumPy behavior (either # cast or raise OverflowError). return Array._new(np.array(scalar, self.dtype)) def _normalize_two_args(x1, x2) -> Tuple[Array, Array]: """ Normalize inputs to two arg functions to fix type promotion rules NumPy deviates from the spec type promotion rules in cases where one argument is 0-dimensional and the other is not. For example: >>> import numpy as np >>> a = np.array([1.0], dtype=np.float32) >>> b = np.array(1.0, dtype=np.float64) >>> np.add(a, b) # The spec says this should be float64 array([2.], dtype=float32) To fix this, we add a dimension to the 0-dimension array before passing it through. This works because a dimension would be added anyway from broadcasting, so the resulting shape is the same, but this prevents NumPy from not promoting the dtype. """ # Another option would be to use signature=(x1.dtype, x2.dtype, None), # but that only works for ufuncs, so we would have to call the ufuncs # directly in the operator methods. One should also note that this # sort of trick wouldn't work for functions like searchsorted, which # don't do normal broadcasting, but there aren't any functions like # that in the array API namespace. if x1.ndim == 0 and x2.ndim != 0: # The _array[None] workaround was chosen because it is relatively # performant. broadcast_to(x1._array, x2.shape) is much slower. We # could also manually type promote x2, but that is more complicated # and about the same performance as this. x1 = Array._new(x1._array[None]) elif x2.ndim == 0 and x1.ndim != 0: x2 = Array._new(x2._array[None]) return (x1, x2) # Note: A large fraction of allowed indices are disallowed here (see the # docstring below) def _validate_index(self, key): """ Validate an index according to the array API. The array API specification only requires a subset of indices that are supported by NumPy. This function will reject any index that is allowed by NumPy but not required by the array API specification. We always raise ``IndexError`` on such indices (the spec does not require any specific behavior on them, but this makes the NumPy array API namespace a minimal implementation of the spec). See https://data-apis.org/array-api/latest/API_specification/indexing.html for the full list of required indexing behavior This function raises IndexError if the index ``key`` is invalid. It only raises ``IndexError`` on indices that are not already rejected by NumPy, as NumPy will already raise the appropriate error on such indices. ``shape`` may be None, in which case, only cases that are independent of the array shape are checked. The following cases are allowed by NumPy, but not specified by the array API specification: - Indices to not include an implicit ellipsis at the end. That is, every axis of an array must be explicitly indexed or an ellipsis included. This behaviour is sometimes referred to as flat indexing. - The start and stop of a slice may not be out of bounds. In particular, for a slice ``i:j:k`` on an axis of size ``n``, only the following are allowed: - ``i`` or ``j`` omitted (``None``). - ``-n <= i <= max(0, n - 1)``. - For ``k > 0`` or ``k`` omitted (``None``), ``-n <= j <= n``. - For ``k < 0``, ``-n - 1 <= j <= max(0, n - 1)``. - Boolean array indices are not allowed as part of a larger tuple index. - Integer array indices are not allowed (with the exception of 0-D arrays, which are treated the same as scalars). Additionally, it should be noted that indices that would return a scalar in NumPy will return a 0-D array. Array scalars are not allowed in the specification, only 0-D arrays. This is done in the ``Array._new`` constructor, not this function. """ _key = key if isinstance(key, tuple) else (key,) for i in _key: if isinstance(i, bool) or not ( isinstance(i, SupportsIndex) # i.e. ints or isinstance(i, slice) or i == Ellipsis or i is None or isinstance(i, Array) or isinstance(i, np.ndarray) ): raise IndexError( f"Single-axes index {i} has {type(i)=}, but only " "integers, slices (:), ellipsis (...), newaxis (None), " "zero-dimensional integer arrays and boolean arrays " "are specified in the Array API." ) nonexpanding_key = [] single_axes = [] n_ellipsis = 0 key_has_mask = False for i in _key: if i is not None: nonexpanding_key.append(i) if isinstance(i, Array) or isinstance(i, np.ndarray): if i.dtype in _boolean_dtypes: key_has_mask = True single_axes.append(i) else: # i must not be an array here, to avoid elementwise equals if i == Ellipsis: n_ellipsis += 1 else: single_axes.append(i) n_single_axes = len(single_axes) if n_ellipsis > 1: return # handled by ndarray elif n_ellipsis == 0: # Note boolean masks must be the sole index, which we check for # later on. if not key_has_mask and n_single_axes < self.ndim: raise IndexError( f"{self.ndim=}, but the multi-axes index only specifies " f"{n_single_axes} dimensions. If this was intentional, " "add a trailing ellipsis (...) which expands into as many " "slices (:) as necessary - this is what np.ndarray arrays " "implicitly do, but such flat indexing behaviour is not " "specified in the Array API." ) if n_ellipsis == 0: indexed_shape = self.shape else: ellipsis_start = None for pos, i in enumerate(nonexpanding_key): if not (isinstance(i, Array) or isinstance(i, np.ndarray)): if i == Ellipsis: ellipsis_start = pos break assert ellipsis_start is not None # sanity check ellipsis_end = self.ndim - (n_single_axes - ellipsis_start) indexed_shape = ( self.shape[:ellipsis_start] + self.shape[ellipsis_end:] ) for i, side in zip(single_axes, indexed_shape): if isinstance(i, slice): if side == 0: f_range = "0 (or None)" else: f_range = f"between -{side} and {side - 1} (or None)" if i.start is not None: try: start = operator.index(i.start) except TypeError: pass # handled by ndarray else: if not (-side <= start <= side): raise IndexError( f"Slice {i} contains {start=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds starts are not specified in " "the Array API)" ) if i.stop is not None: try: stop = operator.index(i.stop) except TypeError: pass # handled by ndarray else: if not (-side <= stop <= side): raise IndexError( f"Slice {i} contains {stop=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds stops are not specified in " "the Array API)" ) elif isinstance(i, Array): if i.dtype in _boolean_dtypes and len(_key) != 1: assert isinstance(key, tuple) # sanity check raise IndexError( f"Single-axes index {i} is a boolean array and " f"{len(key)=}, but masking is only specified in the " "Array API when the array is the sole index." ) elif i.dtype in _integer_dtypes and i.ndim != 0: raise IndexError( f"Single-axes index {i} is a non-zero-dimensional " "integer array, but advanced integer indexing is not " "specified in the Array API." ) elif isinstance(i, tuple): raise IndexError( f"Single-axes index {i} is a tuple, but nested tuple " "indices are not specified in the Array API." ) # Everything below this line is required by the spec. def __abs__(self: Array, /) -> Array: """ Performs the operation __abs__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __abs__") res = self._array.__abs__() return self.__class__._new(res) def __add__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __add__. """ other = self._check_allowed_dtypes(other, "numeric", "__add__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__add__(other._array) return self.__class__._new(res) def __and__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __and__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__and__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__and__(other._array) return self.__class__._new(res) def __array_namespace__( self: Array, /, *, api_version: Optional[str] = None ) -> types.ModuleType: if api_version is not None and not api_version.startswith("2021."): raise ValueError(f"Unrecognized array API version: {api_version!r}") return array_api def __bool__(self: Array, /) -> bool: """ Performs the operation __bool__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("bool is only allowed on arrays with 0 dimensions") if self.dtype not in _boolean_dtypes: raise ValueError("bool is only allowed on boolean arrays") res = self._array.__bool__() return res def __dlpack__(self: Array, /, *, stream: None = None) -> PyCapsule: """ Performs the operation __dlpack__. """ return self._array.__dlpack__(stream=stream) def __dlpack_device__(self: Array, /) -> Tuple[IntEnum, int]: """ Performs the operation __dlpack_device__. """ # Note: device support is required for this return self._array.__dlpack_device__() def __eq__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __eq__. """ # Even though "all" dtypes are allowed, we still require them to be # promotable with each other. other = self._check_allowed_dtypes(other, "all", "__eq__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__eq__(other._array) return self.__class__._new(res) def __float__(self: Array, /) -> float: """ Performs the operation __float__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("float is only allowed on arrays with 0 dimensions") if self.dtype not in _floating_dtypes: raise ValueError("float is only allowed on floating-point arrays") res = self._array.__float__() return res def __floordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __floordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__floordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__floordiv__(other._array) return self.__class__._new(res) def __ge__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ge__. """ other = self._check_allowed_dtypes(other, "numeric", "__ge__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ge__(other._array) return self.__class__._new(res) def __getitem__( self: Array, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], /, ) -> Array: """ Performs the operation __getitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array res = self._array.__getitem__(key) return self._new(res) def __gt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __gt__. """ other = self._check_allowed_dtypes(other, "numeric", "__gt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__gt__(other._array) return self.__class__._new(res) def __int__(self: Array, /) -> int: """ Performs the operation __int__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("int is only allowed on arrays with 0 dimensions") if self.dtype not in _integer_dtypes: raise ValueError("int is only allowed on integer arrays") res = self._array.__int__() return res def __index__(self: Array, /) -> int: """ Performs the operation __index__. """ res = self._array.__index__() return res def __invert__(self: Array, /) -> Array: """ Performs the operation __invert__. """ if self.dtype not in _integer_or_boolean_dtypes: raise TypeError("Only integer or boolean dtypes are allowed in __invert__") res = self._array.__invert__() return self.__class__._new(res) def __le__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __le__. """ other = self._check_allowed_dtypes(other, "numeric", "__le__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__le__(other._array) return self.__class__._new(res) def __lshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __lshift__. """ other = self._check_allowed_dtypes(other, "integer", "__lshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lshift__(other._array) return self.__class__._new(res) def __lt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __lt__. """ other = self._check_allowed_dtypes(other, "numeric", "__lt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lt__(other._array) return self.__class__._new(res) def __matmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __matmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__matmul__") if other is NotImplemented: return other res = self._array.__matmul__(other._array) return self.__class__._new(res) def __mod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mod__. """ other = self._check_allowed_dtypes(other, "numeric", "__mod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mod__(other._array) return self.__class__._new(res) def __mul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mul__. """ other = self._check_allowed_dtypes(other, "numeric", "__mul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mul__(other._array) return self.__class__._new(res) def __ne__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __ne__. """ other = self._check_allowed_dtypes(other, "all", "__ne__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ne__(other._array) return self.__class__._new(res) def __neg__(self: Array, /) -> Array: """ Performs the operation __neg__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __neg__") res = self._array.__neg__() return self.__class__._new(res) def __or__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __or__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__or__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__or__(other._array) return self.__class__._new(res) def __pos__(self: Array, /) -> Array: """ Performs the operation __pos__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __pos__") res = self._array.__pos__() return self.__class__._new(res) def __pow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __pow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__pow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow type promotion rules for 0-d # arrays, so we use pow() here instead. return pow(self, other) def __rshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rshift__(other._array) return self.__class__._new(res) def __setitem__( self, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], value: Union[int, float, bool, Array], /, ) -> None: """ Performs the operation __setitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array self._array.__setitem__(key, asarray(value)._array) def __sub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __sub__. """ other = self._check_allowed_dtypes(other, "numeric", "__sub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__sub__(other._array) return self.__class__._new(res) # PEP 484 requires int to be a subtype of float, but __truediv__ should # not accept int. def __truediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __truediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__truediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__truediv__(other._array) return self.__class__._new(res) def __xor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __xor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__xor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__xor__(other._array) return self.__class__._new(res) def __iadd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __iadd__. """ other = self._check_allowed_dtypes(other, "numeric", "__iadd__") if other is NotImplemented: return other self._array.__iadd__(other._array) return self def __radd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __radd__. """ other = self._check_allowed_dtypes(other, "numeric", "__radd__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__radd__(other._array) return self.__class__._new(res) def __iand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __iand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__iand__") if other is NotImplemented: return other self._array.__iand__(other._array) return self def __rand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rand__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rand__(other._array) return self.__class__._new(res) def __ifloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ifloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__ifloordiv__") if other is NotImplemented: return other self._array.__ifloordiv__(other._array) return self def __rfloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rfloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__rfloordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rfloordiv__(other._array) return self.__class__._new(res) def __ilshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __ilshift__. """ other = self._check_allowed_dtypes(other, "integer", "__ilshift__") if other is NotImplemented: return other self._array.__ilshift__(other._array) return self def __rlshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rlshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rlshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rlshift__(other._array) return self.__class__._new(res) def __imatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __imatmul__. """ # Note: NumPy does not implement __imatmul__. # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__imatmul__") if other is NotImplemented: return other # __imatmul__ can only be allowed when it would not change the shape # of self. other_shape = other.shape if self.shape == () or other_shape == (): raise ValueError("@= requires at least one dimension") if len(other_shape) == 1 or other_shape[-1] != other_shape[-2]: raise ValueError("@= cannot change the shape of the input array") self._array[:] = self._array.__matmul__(other._array) return self def __rmatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __rmatmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__rmatmul__") if other is NotImplemented: return other res = self._array.__rmatmul__(other._array) return self.__class__._new(res) def __imod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imod__. """ other = self._check_allowed_dtypes(other, "numeric", "__imod__") if other is NotImplemented: return other self._array.__imod__(other._array) return self def __rmod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmod__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmod__(other._array) return self.__class__._new(res) def __imul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imul__. """ other = self._check_allowed_dtypes(other, "numeric", "__imul__") if other is NotImplemented: return other self._array.__imul__(other._array) return self def __rmul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmul__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmul__(other._array) return self.__class__._new(res) def __ior__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ior__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ior__") if other is NotImplemented: return other self._array.__ior__(other._array) return self def __ror__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ror__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ror__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ror__(other._array) return self.__class__._new(res) def __ipow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ipow__. """ other = self._check_allowed_dtypes(other, "numeric", "__ipow__") if other is NotImplemented: return other self._array.__ipow__(other._array) return self def __rpow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rpow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__rpow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow the spec type promotion rules # for 0-d arrays, so we use pow() here instead. return pow(other, self) def __irshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __irshift__. """ other = self._check_allowed_dtypes(other, "integer", "__irshift__") if other is NotImplemented: return other self._array.__irshift__(other._array) return self def __rrshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rrshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rrshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rrshift__(other._array) return self.__class__._new(res) def __isub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __isub__. """ other = self._check_allowed_dtypes(other, "numeric", "__isub__") if other is NotImplemented: return other self._array.__isub__(other._array) return self def __rsub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rsub__. """ other = self._check_allowed_dtypes(other, "numeric", "__rsub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rsub__(other._array) return self.__class__._new(res) def __itruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __itruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__itruediv__") if other is NotImplemented: return other self._array.__itruediv__(other._array) return self def __rtruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __rtruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__rtruediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rtruediv__(other._array) return self.__class__._new(res) def __ixor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ixor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ixor__") if other is NotImplemented: return other self._array.__ixor__(other._array) return self def __rxor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rxor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rxor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rxor__(other._array) return self.__class__._new(res) def to_device(self: Array, device: Device, /, stream: None = None) -> Array: if stream is not None: raise ValueError("The stream argument to to_device() is not supported") if device == 'cpu': return self raise ValueError(f"Unsupported device {device!r}") def dtype(self) -> Dtype: """ Array API compatible wrapper for :py:meth:`np.ndarray.dtype <numpy.ndarray.dtype>`. See its docstring for more information. """ return self._array.dtype def device(self) -> Device: return "cpu" # Note: mT is new in array API spec (see matrix_transpose) def mT(self) -> Array: from .linalg import matrix_transpose return matrix_transpose(self) def ndim(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.ndim <numpy.ndarray.ndim>`. See its docstring for more information. """ return self._array.ndim def shape(self) -> Tuple[int, ...]: """ Array API compatible wrapper for :py:meth:`np.ndarray.shape <numpy.ndarray.shape>`. See its docstring for more information. """ return self._array.shape def size(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.size <numpy.ndarray.size>`. See its docstring for more information. """ return self._array.size def T(self) -> Array: """ Array API compatible wrapper for :py:meth:`np.ndarray.T <numpy.ndarray.T>`. See its docstring for more information. """ # Note: T only works on 2-dimensional arrays. See the corresponding # note in the specification: # https://data-apis.org/array-api/latest/API_specification/array_object.html#t if self.ndim != 2: raise ValueError("x.T requires x to have 2 dimensions. Use x.mT to transpose stacks of matrices and permute_dims() to permute dimensions.") return self.__class__._new(self._array.T) The provided code snippet includes necessary dependencies for implementing the `round` function. Write a Python function `def round(x: Array, /) -> Array` to solve the following problem: Array API compatible wrapper for :py:func:`np.round <numpy.round>`. See its docstring for more information. Here is the function: def round(x: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.round <numpy.round>`. See its docstring for more information. """ if x.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in round") return Array._new(np.round(x._array))
Array API compatible wrapper for :py:func:`np.round <numpy.round>`. See its docstring for more information.
170,066
from __future__ import annotations from ._dtypes import ( _boolean_dtypes, _floating_dtypes, _integer_dtypes, _integer_or_boolean_dtypes, _numeric_dtypes, _result_type, ) from ._array_object import Array import numpy as np _numeric_dtypes = ( float32, float64, int8, int16, int32, int64, uint8, uint16, uint32, uint64, ) class Array: """ n-d array object for the array API namespace. See the docstring of :py:obj:`np.ndarray <numpy.ndarray>` for more information. This is a wrapper around numpy.ndarray that restricts the usage to only those things that are required by the array API namespace. Note, attributes on this object that start with a single underscore are not part of the API specification and should only be used internally. This object should not be constructed directly. Rather, use one of the creation functions, such as asarray(). """ _array: np.ndarray # Use a custom constructor instead of __init__, as manually initializing # this class is not supported API. def _new(cls, x, /): """ This is a private method for initializing the array API Array object. Functions outside of the array_api submodule should not use this method. Use one of the creation functions instead, such as ``asarray``. """ obj = super().__new__(cls) # Note: The spec does not have array scalars, only 0-D arrays. if isinstance(x, np.generic): # Convert the array scalar to a 0-D array x = np.asarray(x) if x.dtype not in _all_dtypes: raise TypeError( f"The array_api namespace does not support the dtype '{x.dtype}'" ) obj._array = x return obj # Prevent Array() from working def __new__(cls, *args, **kwargs): raise TypeError( "The array_api Array object should not be instantiated directly. Use an array creation function, such as asarray(), instead." ) # These functions are not required by the spec, but are implemented for # the sake of usability. def __str__(self: Array, /) -> str: """ Performs the operation __str__. """ return self._array.__str__().replace("array", "Array") def __repr__(self: Array, /) -> str: """ Performs the operation __repr__. """ suffix = f", dtype={self.dtype.name})" if 0 in self.shape: prefix = "empty(" mid = str(self.shape) else: prefix = "Array(" mid = np.array2string(self._array, separator=', ', prefix=prefix, suffix=suffix) return prefix + mid + suffix # This function is not required by the spec, but we implement it here for # convenience so that np.asarray(np.array_api.Array) will work. def __array__(self, dtype: None | np.dtype[Any] = None) -> npt.NDArray[Any]: """ Warning: this method is NOT part of the array API spec. Implementers of other libraries need not include it, and users should not assume it will be present in other implementations. """ return np.asarray(self._array, dtype=dtype) # These are various helper functions to make the array behavior match the # spec in places where it either deviates from or is more strict than # NumPy behavior def _check_allowed_dtypes(self, other: bool | int | float | Array, dtype_category: str, op: str) -> Array: """ Helper function for operators to only allow specific input dtypes Use like other = self._check_allowed_dtypes(other, 'numeric', '__add__') if other is NotImplemented: return other """ if self.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") if isinstance(other, (int, float, bool)): other = self._promote_scalar(other) elif isinstance(other, Array): if other.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") else: return NotImplemented # This will raise TypeError for type combinations that are not allowed # to promote in the spec (even if the NumPy array operator would # promote them). res_dtype = _result_type(self.dtype, other.dtype) if op.startswith("__i"): # Note: NumPy will allow in-place operators in some cases where # the type promoted operator does not match the left-hand side # operand. For example, # >>> a = np.array(1, dtype=np.int8) # >>> a += np.array(1, dtype=np.int16) # The spec explicitly disallows this. if res_dtype != self.dtype: raise TypeError( f"Cannot perform {op} with dtypes {self.dtype} and {other.dtype}" ) return other # Helper function to match the type promotion rules in the spec def _promote_scalar(self, scalar): """ Returns a promoted version of a Python scalar appropriate for use with operations on self. This may raise an OverflowError in cases where the scalar is an integer that is too large to fit in a NumPy integer dtype, or TypeError when the scalar type is incompatible with the dtype of self. """ # Note: Only Python scalar types that match the array dtype are # allowed. if isinstance(scalar, bool): if self.dtype not in _boolean_dtypes: raise TypeError( "Python bool scalars can only be promoted with bool arrays" ) elif isinstance(scalar, int): if self.dtype in _boolean_dtypes: raise TypeError( "Python int scalars cannot be promoted with bool arrays" ) elif isinstance(scalar, float): if self.dtype not in _floating_dtypes: raise TypeError( "Python float scalars can only be promoted with floating-point arrays." ) else: raise TypeError("'scalar' must be a Python scalar") # Note: scalars are unconditionally cast to the same dtype as the # array. # Note: the spec only specifies integer-dtype/int promotion # behavior for integers within the bounds of the integer dtype. # Outside of those bounds we use the default NumPy behavior (either # cast or raise OverflowError). return Array._new(np.array(scalar, self.dtype)) def _normalize_two_args(x1, x2) -> Tuple[Array, Array]: """ Normalize inputs to two arg functions to fix type promotion rules NumPy deviates from the spec type promotion rules in cases where one argument is 0-dimensional and the other is not. For example: >>> import numpy as np >>> a = np.array([1.0], dtype=np.float32) >>> b = np.array(1.0, dtype=np.float64) >>> np.add(a, b) # The spec says this should be float64 array([2.], dtype=float32) To fix this, we add a dimension to the 0-dimension array before passing it through. This works because a dimension would be added anyway from broadcasting, so the resulting shape is the same, but this prevents NumPy from not promoting the dtype. """ # Another option would be to use signature=(x1.dtype, x2.dtype, None), # but that only works for ufuncs, so we would have to call the ufuncs # directly in the operator methods. One should also note that this # sort of trick wouldn't work for functions like searchsorted, which # don't do normal broadcasting, but there aren't any functions like # that in the array API namespace. if x1.ndim == 0 and x2.ndim != 0: # The _array[None] workaround was chosen because it is relatively # performant. broadcast_to(x1._array, x2.shape) is much slower. We # could also manually type promote x2, but that is more complicated # and about the same performance as this. x1 = Array._new(x1._array[None]) elif x2.ndim == 0 and x1.ndim != 0: x2 = Array._new(x2._array[None]) return (x1, x2) # Note: A large fraction of allowed indices are disallowed here (see the # docstring below) def _validate_index(self, key): """ Validate an index according to the array API. The array API specification only requires a subset of indices that are supported by NumPy. This function will reject any index that is allowed by NumPy but not required by the array API specification. We always raise ``IndexError`` on such indices (the spec does not require any specific behavior on them, but this makes the NumPy array API namespace a minimal implementation of the spec). See https://data-apis.org/array-api/latest/API_specification/indexing.html for the full list of required indexing behavior This function raises IndexError if the index ``key`` is invalid. It only raises ``IndexError`` on indices that are not already rejected by NumPy, as NumPy will already raise the appropriate error on such indices. ``shape`` may be None, in which case, only cases that are independent of the array shape are checked. The following cases are allowed by NumPy, but not specified by the array API specification: - Indices to not include an implicit ellipsis at the end. That is, every axis of an array must be explicitly indexed or an ellipsis included. This behaviour is sometimes referred to as flat indexing. - The start and stop of a slice may not be out of bounds. In particular, for a slice ``i:j:k`` on an axis of size ``n``, only the following are allowed: - ``i`` or ``j`` omitted (``None``). - ``-n <= i <= max(0, n - 1)``. - For ``k > 0`` or ``k`` omitted (``None``), ``-n <= j <= n``. - For ``k < 0``, ``-n - 1 <= j <= max(0, n - 1)``. - Boolean array indices are not allowed as part of a larger tuple index. - Integer array indices are not allowed (with the exception of 0-D arrays, which are treated the same as scalars). Additionally, it should be noted that indices that would return a scalar in NumPy will return a 0-D array. Array scalars are not allowed in the specification, only 0-D arrays. This is done in the ``Array._new`` constructor, not this function. """ _key = key if isinstance(key, tuple) else (key,) for i in _key: if isinstance(i, bool) or not ( isinstance(i, SupportsIndex) # i.e. ints or isinstance(i, slice) or i == Ellipsis or i is None or isinstance(i, Array) or isinstance(i, np.ndarray) ): raise IndexError( f"Single-axes index {i} has {type(i)=}, but only " "integers, slices (:), ellipsis (...), newaxis (None), " "zero-dimensional integer arrays and boolean arrays " "are specified in the Array API." ) nonexpanding_key = [] single_axes = [] n_ellipsis = 0 key_has_mask = False for i in _key: if i is not None: nonexpanding_key.append(i) if isinstance(i, Array) or isinstance(i, np.ndarray): if i.dtype in _boolean_dtypes: key_has_mask = True single_axes.append(i) else: # i must not be an array here, to avoid elementwise equals if i == Ellipsis: n_ellipsis += 1 else: single_axes.append(i) n_single_axes = len(single_axes) if n_ellipsis > 1: return # handled by ndarray elif n_ellipsis == 0: # Note boolean masks must be the sole index, which we check for # later on. if not key_has_mask and n_single_axes < self.ndim: raise IndexError( f"{self.ndim=}, but the multi-axes index only specifies " f"{n_single_axes} dimensions. If this was intentional, " "add a trailing ellipsis (...) which expands into as many " "slices (:) as necessary - this is what np.ndarray arrays " "implicitly do, but such flat indexing behaviour is not " "specified in the Array API." ) if n_ellipsis == 0: indexed_shape = self.shape else: ellipsis_start = None for pos, i in enumerate(nonexpanding_key): if not (isinstance(i, Array) or isinstance(i, np.ndarray)): if i == Ellipsis: ellipsis_start = pos break assert ellipsis_start is not None # sanity check ellipsis_end = self.ndim - (n_single_axes - ellipsis_start) indexed_shape = ( self.shape[:ellipsis_start] + self.shape[ellipsis_end:] ) for i, side in zip(single_axes, indexed_shape): if isinstance(i, slice): if side == 0: f_range = "0 (or None)" else: f_range = f"between -{side} and {side - 1} (or None)" if i.start is not None: try: start = operator.index(i.start) except TypeError: pass # handled by ndarray else: if not (-side <= start <= side): raise IndexError( f"Slice {i} contains {start=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds starts are not specified in " "the Array API)" ) if i.stop is not None: try: stop = operator.index(i.stop) except TypeError: pass # handled by ndarray else: if not (-side <= stop <= side): raise IndexError( f"Slice {i} contains {stop=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds stops are not specified in " "the Array API)" ) elif isinstance(i, Array): if i.dtype in _boolean_dtypes and len(_key) != 1: assert isinstance(key, tuple) # sanity check raise IndexError( f"Single-axes index {i} is a boolean array and " f"{len(key)=}, but masking is only specified in the " "Array API when the array is the sole index." ) elif i.dtype in _integer_dtypes and i.ndim != 0: raise IndexError( f"Single-axes index {i} is a non-zero-dimensional " "integer array, but advanced integer indexing is not " "specified in the Array API." ) elif isinstance(i, tuple): raise IndexError( f"Single-axes index {i} is a tuple, but nested tuple " "indices are not specified in the Array API." ) # Everything below this line is required by the spec. def __abs__(self: Array, /) -> Array: """ Performs the operation __abs__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __abs__") res = self._array.__abs__() return self.__class__._new(res) def __add__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __add__. """ other = self._check_allowed_dtypes(other, "numeric", "__add__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__add__(other._array) return self.__class__._new(res) def __and__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __and__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__and__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__and__(other._array) return self.__class__._new(res) def __array_namespace__( self: Array, /, *, api_version: Optional[str] = None ) -> types.ModuleType: if api_version is not None and not api_version.startswith("2021."): raise ValueError(f"Unrecognized array API version: {api_version!r}") return array_api def __bool__(self: Array, /) -> bool: """ Performs the operation __bool__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("bool is only allowed on arrays with 0 dimensions") if self.dtype not in _boolean_dtypes: raise ValueError("bool is only allowed on boolean arrays") res = self._array.__bool__() return res def __dlpack__(self: Array, /, *, stream: None = None) -> PyCapsule: """ Performs the operation __dlpack__. """ return self._array.__dlpack__(stream=stream) def __dlpack_device__(self: Array, /) -> Tuple[IntEnum, int]: """ Performs the operation __dlpack_device__. """ # Note: device support is required for this return self._array.__dlpack_device__() def __eq__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __eq__. """ # Even though "all" dtypes are allowed, we still require them to be # promotable with each other. other = self._check_allowed_dtypes(other, "all", "__eq__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__eq__(other._array) return self.__class__._new(res) def __float__(self: Array, /) -> float: """ Performs the operation __float__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("float is only allowed on arrays with 0 dimensions") if self.dtype not in _floating_dtypes: raise ValueError("float is only allowed on floating-point arrays") res = self._array.__float__() return res def __floordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __floordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__floordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__floordiv__(other._array) return self.__class__._new(res) def __ge__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ge__. """ other = self._check_allowed_dtypes(other, "numeric", "__ge__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ge__(other._array) return self.__class__._new(res) def __getitem__( self: Array, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], /, ) -> Array: """ Performs the operation __getitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array res = self._array.__getitem__(key) return self._new(res) def __gt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __gt__. """ other = self._check_allowed_dtypes(other, "numeric", "__gt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__gt__(other._array) return self.__class__._new(res) def __int__(self: Array, /) -> int: """ Performs the operation __int__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("int is only allowed on arrays with 0 dimensions") if self.dtype not in _integer_dtypes: raise ValueError("int is only allowed on integer arrays") res = self._array.__int__() return res def __index__(self: Array, /) -> int: """ Performs the operation __index__. """ res = self._array.__index__() return res def __invert__(self: Array, /) -> Array: """ Performs the operation __invert__. """ if self.dtype not in _integer_or_boolean_dtypes: raise TypeError("Only integer or boolean dtypes are allowed in __invert__") res = self._array.__invert__() return self.__class__._new(res) def __le__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __le__. """ other = self._check_allowed_dtypes(other, "numeric", "__le__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__le__(other._array) return self.__class__._new(res) def __lshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __lshift__. """ other = self._check_allowed_dtypes(other, "integer", "__lshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lshift__(other._array) return self.__class__._new(res) def __lt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __lt__. """ other = self._check_allowed_dtypes(other, "numeric", "__lt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lt__(other._array) return self.__class__._new(res) def __matmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __matmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__matmul__") if other is NotImplemented: return other res = self._array.__matmul__(other._array) return self.__class__._new(res) def __mod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mod__. """ other = self._check_allowed_dtypes(other, "numeric", "__mod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mod__(other._array) return self.__class__._new(res) def __mul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mul__. """ other = self._check_allowed_dtypes(other, "numeric", "__mul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mul__(other._array) return self.__class__._new(res) def __ne__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __ne__. """ other = self._check_allowed_dtypes(other, "all", "__ne__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ne__(other._array) return self.__class__._new(res) def __neg__(self: Array, /) -> Array: """ Performs the operation __neg__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __neg__") res = self._array.__neg__() return self.__class__._new(res) def __or__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __or__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__or__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__or__(other._array) return self.__class__._new(res) def __pos__(self: Array, /) -> Array: """ Performs the operation __pos__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __pos__") res = self._array.__pos__() return self.__class__._new(res) def __pow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __pow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__pow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow type promotion rules for 0-d # arrays, so we use pow() here instead. return pow(self, other) def __rshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rshift__(other._array) return self.__class__._new(res) def __setitem__( self, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], value: Union[int, float, bool, Array], /, ) -> None: """ Performs the operation __setitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array self._array.__setitem__(key, asarray(value)._array) def __sub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __sub__. """ other = self._check_allowed_dtypes(other, "numeric", "__sub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__sub__(other._array) return self.__class__._new(res) # PEP 484 requires int to be a subtype of float, but __truediv__ should # not accept int. def __truediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __truediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__truediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__truediv__(other._array) return self.__class__._new(res) def __xor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __xor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__xor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__xor__(other._array) return self.__class__._new(res) def __iadd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __iadd__. """ other = self._check_allowed_dtypes(other, "numeric", "__iadd__") if other is NotImplemented: return other self._array.__iadd__(other._array) return self def __radd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __radd__. """ other = self._check_allowed_dtypes(other, "numeric", "__radd__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__radd__(other._array) return self.__class__._new(res) def __iand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __iand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__iand__") if other is NotImplemented: return other self._array.__iand__(other._array) return self def __rand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rand__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rand__(other._array) return self.__class__._new(res) def __ifloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ifloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__ifloordiv__") if other is NotImplemented: return other self._array.__ifloordiv__(other._array) return self def __rfloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rfloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__rfloordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rfloordiv__(other._array) return self.__class__._new(res) def __ilshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __ilshift__. """ other = self._check_allowed_dtypes(other, "integer", "__ilshift__") if other is NotImplemented: return other self._array.__ilshift__(other._array) return self def __rlshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rlshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rlshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rlshift__(other._array) return self.__class__._new(res) def __imatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __imatmul__. """ # Note: NumPy does not implement __imatmul__. # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__imatmul__") if other is NotImplemented: return other # __imatmul__ can only be allowed when it would not change the shape # of self. other_shape = other.shape if self.shape == () or other_shape == (): raise ValueError("@= requires at least one dimension") if len(other_shape) == 1 or other_shape[-1] != other_shape[-2]: raise ValueError("@= cannot change the shape of the input array") self._array[:] = self._array.__matmul__(other._array) return self def __rmatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __rmatmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__rmatmul__") if other is NotImplemented: return other res = self._array.__rmatmul__(other._array) return self.__class__._new(res) def __imod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imod__. """ other = self._check_allowed_dtypes(other, "numeric", "__imod__") if other is NotImplemented: return other self._array.__imod__(other._array) return self def __rmod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmod__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmod__(other._array) return self.__class__._new(res) def __imul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imul__. """ other = self._check_allowed_dtypes(other, "numeric", "__imul__") if other is NotImplemented: return other self._array.__imul__(other._array) return self def __rmul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmul__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmul__(other._array) return self.__class__._new(res) def __ior__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ior__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ior__") if other is NotImplemented: return other self._array.__ior__(other._array) return self def __ror__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ror__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ror__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ror__(other._array) return self.__class__._new(res) def __ipow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ipow__. """ other = self._check_allowed_dtypes(other, "numeric", "__ipow__") if other is NotImplemented: return other self._array.__ipow__(other._array) return self def __rpow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rpow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__rpow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow the spec type promotion rules # for 0-d arrays, so we use pow() here instead. return pow(other, self) def __irshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __irshift__. """ other = self._check_allowed_dtypes(other, "integer", "__irshift__") if other is NotImplemented: return other self._array.__irshift__(other._array) return self def __rrshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rrshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rrshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rrshift__(other._array) return self.__class__._new(res) def __isub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __isub__. """ other = self._check_allowed_dtypes(other, "numeric", "__isub__") if other is NotImplemented: return other self._array.__isub__(other._array) return self def __rsub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rsub__. """ other = self._check_allowed_dtypes(other, "numeric", "__rsub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rsub__(other._array) return self.__class__._new(res) def __itruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __itruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__itruediv__") if other is NotImplemented: return other self._array.__itruediv__(other._array) return self def __rtruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __rtruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__rtruediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rtruediv__(other._array) return self.__class__._new(res) def __ixor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ixor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ixor__") if other is NotImplemented: return other self._array.__ixor__(other._array) return self def __rxor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rxor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rxor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rxor__(other._array) return self.__class__._new(res) def to_device(self: Array, device: Device, /, stream: None = None) -> Array: if stream is not None: raise ValueError("The stream argument to to_device() is not supported") if device == 'cpu': return self raise ValueError(f"Unsupported device {device!r}") def dtype(self) -> Dtype: """ Array API compatible wrapper for :py:meth:`np.ndarray.dtype <numpy.ndarray.dtype>`. See its docstring for more information. """ return self._array.dtype def device(self) -> Device: return "cpu" # Note: mT is new in array API spec (see matrix_transpose) def mT(self) -> Array: from .linalg import matrix_transpose return matrix_transpose(self) def ndim(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.ndim <numpy.ndarray.ndim>`. See its docstring for more information. """ return self._array.ndim def shape(self) -> Tuple[int, ...]: """ Array API compatible wrapper for :py:meth:`np.ndarray.shape <numpy.ndarray.shape>`. See its docstring for more information. """ return self._array.shape def size(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.size <numpy.ndarray.size>`. See its docstring for more information. """ return self._array.size def T(self) -> Array: """ Array API compatible wrapper for :py:meth:`np.ndarray.T <numpy.ndarray.T>`. See its docstring for more information. """ # Note: T only works on 2-dimensional arrays. See the corresponding # note in the specification: # https://data-apis.org/array-api/latest/API_specification/array_object.html#t if self.ndim != 2: raise ValueError("x.T requires x to have 2 dimensions. Use x.mT to transpose stacks of matrices and permute_dims() to permute dimensions.") return self.__class__._new(self._array.T) The provided code snippet includes necessary dependencies for implementing the `sign` function. Write a Python function `def sign(x: Array, /) -> Array` to solve the following problem: Array API compatible wrapper for :py:func:`np.sign <numpy.sign>`. See its docstring for more information. Here is the function: def sign(x: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.sign <numpy.sign>`. See its docstring for more information. """ if x.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in sign") return Array._new(np.sign(x._array))
Array API compatible wrapper for :py:func:`np.sign <numpy.sign>`. See its docstring for more information.
170,067
from __future__ import annotations from ._dtypes import ( _boolean_dtypes, _floating_dtypes, _integer_dtypes, _integer_or_boolean_dtypes, _numeric_dtypes, _result_type, ) from ._array_object import Array import numpy as np _floating_dtypes = (float32, float64) class Array: """ n-d array object for the array API namespace. See the docstring of :py:obj:`np.ndarray <numpy.ndarray>` for more information. This is a wrapper around numpy.ndarray that restricts the usage to only those things that are required by the array API namespace. Note, attributes on this object that start with a single underscore are not part of the API specification and should only be used internally. This object should not be constructed directly. Rather, use one of the creation functions, such as asarray(). """ _array: np.ndarray # Use a custom constructor instead of __init__, as manually initializing # this class is not supported API. def _new(cls, x, /): """ This is a private method for initializing the array API Array object. Functions outside of the array_api submodule should not use this method. Use one of the creation functions instead, such as ``asarray``. """ obj = super().__new__(cls) # Note: The spec does not have array scalars, only 0-D arrays. if isinstance(x, np.generic): # Convert the array scalar to a 0-D array x = np.asarray(x) if x.dtype not in _all_dtypes: raise TypeError( f"The array_api namespace does not support the dtype '{x.dtype}'" ) obj._array = x return obj # Prevent Array() from working def __new__(cls, *args, **kwargs): raise TypeError( "The array_api Array object should not be instantiated directly. Use an array creation function, such as asarray(), instead." ) # These functions are not required by the spec, but are implemented for # the sake of usability. def __str__(self: Array, /) -> str: """ Performs the operation __str__. """ return self._array.__str__().replace("array", "Array") def __repr__(self: Array, /) -> str: """ Performs the operation __repr__. """ suffix = f", dtype={self.dtype.name})" if 0 in self.shape: prefix = "empty(" mid = str(self.shape) else: prefix = "Array(" mid = np.array2string(self._array, separator=', ', prefix=prefix, suffix=suffix) return prefix + mid + suffix # This function is not required by the spec, but we implement it here for # convenience so that np.asarray(np.array_api.Array) will work. def __array__(self, dtype: None | np.dtype[Any] = None) -> npt.NDArray[Any]: """ Warning: this method is NOT part of the array API spec. Implementers of other libraries need not include it, and users should not assume it will be present in other implementations. """ return np.asarray(self._array, dtype=dtype) # These are various helper functions to make the array behavior match the # spec in places where it either deviates from or is more strict than # NumPy behavior def _check_allowed_dtypes(self, other: bool | int | float | Array, dtype_category: str, op: str) -> Array: """ Helper function for operators to only allow specific input dtypes Use like other = self._check_allowed_dtypes(other, 'numeric', '__add__') if other is NotImplemented: return other """ if self.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") if isinstance(other, (int, float, bool)): other = self._promote_scalar(other) elif isinstance(other, Array): if other.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") else: return NotImplemented # This will raise TypeError for type combinations that are not allowed # to promote in the spec (even if the NumPy array operator would # promote them). res_dtype = _result_type(self.dtype, other.dtype) if op.startswith("__i"): # Note: NumPy will allow in-place operators in some cases where # the type promoted operator does not match the left-hand side # operand. For example, # >>> a = np.array(1, dtype=np.int8) # >>> a += np.array(1, dtype=np.int16) # The spec explicitly disallows this. if res_dtype != self.dtype: raise TypeError( f"Cannot perform {op} with dtypes {self.dtype} and {other.dtype}" ) return other # Helper function to match the type promotion rules in the spec def _promote_scalar(self, scalar): """ Returns a promoted version of a Python scalar appropriate for use with operations on self. This may raise an OverflowError in cases where the scalar is an integer that is too large to fit in a NumPy integer dtype, or TypeError when the scalar type is incompatible with the dtype of self. """ # Note: Only Python scalar types that match the array dtype are # allowed. if isinstance(scalar, bool): if self.dtype not in _boolean_dtypes: raise TypeError( "Python bool scalars can only be promoted with bool arrays" ) elif isinstance(scalar, int): if self.dtype in _boolean_dtypes: raise TypeError( "Python int scalars cannot be promoted with bool arrays" ) elif isinstance(scalar, float): if self.dtype not in _floating_dtypes: raise TypeError( "Python float scalars can only be promoted with floating-point arrays." ) else: raise TypeError("'scalar' must be a Python scalar") # Note: scalars are unconditionally cast to the same dtype as the # array. # Note: the spec only specifies integer-dtype/int promotion # behavior for integers within the bounds of the integer dtype. # Outside of those bounds we use the default NumPy behavior (either # cast or raise OverflowError). return Array._new(np.array(scalar, self.dtype)) def _normalize_two_args(x1, x2) -> Tuple[Array, Array]: """ Normalize inputs to two arg functions to fix type promotion rules NumPy deviates from the spec type promotion rules in cases where one argument is 0-dimensional and the other is not. For example: >>> import numpy as np >>> a = np.array([1.0], dtype=np.float32) >>> b = np.array(1.0, dtype=np.float64) >>> np.add(a, b) # The spec says this should be float64 array([2.], dtype=float32) To fix this, we add a dimension to the 0-dimension array before passing it through. This works because a dimension would be added anyway from broadcasting, so the resulting shape is the same, but this prevents NumPy from not promoting the dtype. """ # Another option would be to use signature=(x1.dtype, x2.dtype, None), # but that only works for ufuncs, so we would have to call the ufuncs # directly in the operator methods. One should also note that this # sort of trick wouldn't work for functions like searchsorted, which # don't do normal broadcasting, but there aren't any functions like # that in the array API namespace. if x1.ndim == 0 and x2.ndim != 0: # The _array[None] workaround was chosen because it is relatively # performant. broadcast_to(x1._array, x2.shape) is much slower. We # could also manually type promote x2, but that is more complicated # and about the same performance as this. x1 = Array._new(x1._array[None]) elif x2.ndim == 0 and x1.ndim != 0: x2 = Array._new(x2._array[None]) return (x1, x2) # Note: A large fraction of allowed indices are disallowed here (see the # docstring below) def _validate_index(self, key): """ Validate an index according to the array API. The array API specification only requires a subset of indices that are supported by NumPy. This function will reject any index that is allowed by NumPy but not required by the array API specification. We always raise ``IndexError`` on such indices (the spec does not require any specific behavior on them, but this makes the NumPy array API namespace a minimal implementation of the spec). See https://data-apis.org/array-api/latest/API_specification/indexing.html for the full list of required indexing behavior This function raises IndexError if the index ``key`` is invalid. It only raises ``IndexError`` on indices that are not already rejected by NumPy, as NumPy will already raise the appropriate error on such indices. ``shape`` may be None, in which case, only cases that are independent of the array shape are checked. The following cases are allowed by NumPy, but not specified by the array API specification: - Indices to not include an implicit ellipsis at the end. That is, every axis of an array must be explicitly indexed or an ellipsis included. This behaviour is sometimes referred to as flat indexing. - The start and stop of a slice may not be out of bounds. In particular, for a slice ``i:j:k`` on an axis of size ``n``, only the following are allowed: - ``i`` or ``j`` omitted (``None``). - ``-n <= i <= max(0, n - 1)``. - For ``k > 0`` or ``k`` omitted (``None``), ``-n <= j <= n``. - For ``k < 0``, ``-n - 1 <= j <= max(0, n - 1)``. - Boolean array indices are not allowed as part of a larger tuple index. - Integer array indices are not allowed (with the exception of 0-D arrays, which are treated the same as scalars). Additionally, it should be noted that indices that would return a scalar in NumPy will return a 0-D array. Array scalars are not allowed in the specification, only 0-D arrays. This is done in the ``Array._new`` constructor, not this function. """ _key = key if isinstance(key, tuple) else (key,) for i in _key: if isinstance(i, bool) or not ( isinstance(i, SupportsIndex) # i.e. ints or isinstance(i, slice) or i == Ellipsis or i is None or isinstance(i, Array) or isinstance(i, np.ndarray) ): raise IndexError( f"Single-axes index {i} has {type(i)=}, but only " "integers, slices (:), ellipsis (...), newaxis (None), " "zero-dimensional integer arrays and boolean arrays " "are specified in the Array API." ) nonexpanding_key = [] single_axes = [] n_ellipsis = 0 key_has_mask = False for i in _key: if i is not None: nonexpanding_key.append(i) if isinstance(i, Array) or isinstance(i, np.ndarray): if i.dtype in _boolean_dtypes: key_has_mask = True single_axes.append(i) else: # i must not be an array here, to avoid elementwise equals if i == Ellipsis: n_ellipsis += 1 else: single_axes.append(i) n_single_axes = len(single_axes) if n_ellipsis > 1: return # handled by ndarray elif n_ellipsis == 0: # Note boolean masks must be the sole index, which we check for # later on. if not key_has_mask and n_single_axes < self.ndim: raise IndexError( f"{self.ndim=}, but the multi-axes index only specifies " f"{n_single_axes} dimensions. If this was intentional, " "add a trailing ellipsis (...) which expands into as many " "slices (:) as necessary - this is what np.ndarray arrays " "implicitly do, but such flat indexing behaviour is not " "specified in the Array API." ) if n_ellipsis == 0: indexed_shape = self.shape else: ellipsis_start = None for pos, i in enumerate(nonexpanding_key): if not (isinstance(i, Array) or isinstance(i, np.ndarray)): if i == Ellipsis: ellipsis_start = pos break assert ellipsis_start is not None # sanity check ellipsis_end = self.ndim - (n_single_axes - ellipsis_start) indexed_shape = ( self.shape[:ellipsis_start] + self.shape[ellipsis_end:] ) for i, side in zip(single_axes, indexed_shape): if isinstance(i, slice): if side == 0: f_range = "0 (or None)" else: f_range = f"between -{side} and {side - 1} (or None)" if i.start is not None: try: start = operator.index(i.start) except TypeError: pass # handled by ndarray else: if not (-side <= start <= side): raise IndexError( f"Slice {i} contains {start=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds starts are not specified in " "the Array API)" ) if i.stop is not None: try: stop = operator.index(i.stop) except TypeError: pass # handled by ndarray else: if not (-side <= stop <= side): raise IndexError( f"Slice {i} contains {stop=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds stops are not specified in " "the Array API)" ) elif isinstance(i, Array): if i.dtype in _boolean_dtypes and len(_key) != 1: assert isinstance(key, tuple) # sanity check raise IndexError( f"Single-axes index {i} is a boolean array and " f"{len(key)=}, but masking is only specified in the " "Array API when the array is the sole index." ) elif i.dtype in _integer_dtypes and i.ndim != 0: raise IndexError( f"Single-axes index {i} is a non-zero-dimensional " "integer array, but advanced integer indexing is not " "specified in the Array API." ) elif isinstance(i, tuple): raise IndexError( f"Single-axes index {i} is a tuple, but nested tuple " "indices are not specified in the Array API." ) # Everything below this line is required by the spec. def __abs__(self: Array, /) -> Array: """ Performs the operation __abs__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __abs__") res = self._array.__abs__() return self.__class__._new(res) def __add__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __add__. """ other = self._check_allowed_dtypes(other, "numeric", "__add__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__add__(other._array) return self.__class__._new(res) def __and__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __and__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__and__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__and__(other._array) return self.__class__._new(res) def __array_namespace__( self: Array, /, *, api_version: Optional[str] = None ) -> types.ModuleType: if api_version is not None and not api_version.startswith("2021."): raise ValueError(f"Unrecognized array API version: {api_version!r}") return array_api def __bool__(self: Array, /) -> bool: """ Performs the operation __bool__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("bool is only allowed on arrays with 0 dimensions") if self.dtype not in _boolean_dtypes: raise ValueError("bool is only allowed on boolean arrays") res = self._array.__bool__() return res def __dlpack__(self: Array, /, *, stream: None = None) -> PyCapsule: """ Performs the operation __dlpack__. """ return self._array.__dlpack__(stream=stream) def __dlpack_device__(self: Array, /) -> Tuple[IntEnum, int]: """ Performs the operation __dlpack_device__. """ # Note: device support is required for this return self._array.__dlpack_device__() def __eq__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __eq__. """ # Even though "all" dtypes are allowed, we still require them to be # promotable with each other. other = self._check_allowed_dtypes(other, "all", "__eq__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__eq__(other._array) return self.__class__._new(res) def __float__(self: Array, /) -> float: """ Performs the operation __float__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("float is only allowed on arrays with 0 dimensions") if self.dtype not in _floating_dtypes: raise ValueError("float is only allowed on floating-point arrays") res = self._array.__float__() return res def __floordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __floordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__floordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__floordiv__(other._array) return self.__class__._new(res) def __ge__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ge__. """ other = self._check_allowed_dtypes(other, "numeric", "__ge__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ge__(other._array) return self.__class__._new(res) def __getitem__( self: Array, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], /, ) -> Array: """ Performs the operation __getitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array res = self._array.__getitem__(key) return self._new(res) def __gt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __gt__. """ other = self._check_allowed_dtypes(other, "numeric", "__gt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__gt__(other._array) return self.__class__._new(res) def __int__(self: Array, /) -> int: """ Performs the operation __int__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("int is only allowed on arrays with 0 dimensions") if self.dtype not in _integer_dtypes: raise ValueError("int is only allowed on integer arrays") res = self._array.__int__() return res def __index__(self: Array, /) -> int: """ Performs the operation __index__. """ res = self._array.__index__() return res def __invert__(self: Array, /) -> Array: """ Performs the operation __invert__. """ if self.dtype not in _integer_or_boolean_dtypes: raise TypeError("Only integer or boolean dtypes are allowed in __invert__") res = self._array.__invert__() return self.__class__._new(res) def __le__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __le__. """ other = self._check_allowed_dtypes(other, "numeric", "__le__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__le__(other._array) return self.__class__._new(res) def __lshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __lshift__. """ other = self._check_allowed_dtypes(other, "integer", "__lshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lshift__(other._array) return self.__class__._new(res) def __lt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __lt__. """ other = self._check_allowed_dtypes(other, "numeric", "__lt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lt__(other._array) return self.__class__._new(res) def __matmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __matmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__matmul__") if other is NotImplemented: return other res = self._array.__matmul__(other._array) return self.__class__._new(res) def __mod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mod__. """ other = self._check_allowed_dtypes(other, "numeric", "__mod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mod__(other._array) return self.__class__._new(res) def __mul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mul__. """ other = self._check_allowed_dtypes(other, "numeric", "__mul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mul__(other._array) return self.__class__._new(res) def __ne__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __ne__. """ other = self._check_allowed_dtypes(other, "all", "__ne__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ne__(other._array) return self.__class__._new(res) def __neg__(self: Array, /) -> Array: """ Performs the operation __neg__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __neg__") res = self._array.__neg__() return self.__class__._new(res) def __or__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __or__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__or__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__or__(other._array) return self.__class__._new(res) def __pos__(self: Array, /) -> Array: """ Performs the operation __pos__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __pos__") res = self._array.__pos__() return self.__class__._new(res) def __pow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __pow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__pow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow type promotion rules for 0-d # arrays, so we use pow() here instead. return pow(self, other) def __rshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rshift__(other._array) return self.__class__._new(res) def __setitem__( self, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], value: Union[int, float, bool, Array], /, ) -> None: """ Performs the operation __setitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array self._array.__setitem__(key, asarray(value)._array) def __sub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __sub__. """ other = self._check_allowed_dtypes(other, "numeric", "__sub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__sub__(other._array) return self.__class__._new(res) # PEP 484 requires int to be a subtype of float, but __truediv__ should # not accept int. def __truediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __truediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__truediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__truediv__(other._array) return self.__class__._new(res) def __xor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __xor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__xor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__xor__(other._array) return self.__class__._new(res) def __iadd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __iadd__. """ other = self._check_allowed_dtypes(other, "numeric", "__iadd__") if other is NotImplemented: return other self._array.__iadd__(other._array) return self def __radd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __radd__. """ other = self._check_allowed_dtypes(other, "numeric", "__radd__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__radd__(other._array) return self.__class__._new(res) def __iand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __iand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__iand__") if other is NotImplemented: return other self._array.__iand__(other._array) return self def __rand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rand__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rand__(other._array) return self.__class__._new(res) def __ifloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ifloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__ifloordiv__") if other is NotImplemented: return other self._array.__ifloordiv__(other._array) return self def __rfloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rfloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__rfloordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rfloordiv__(other._array) return self.__class__._new(res) def __ilshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __ilshift__. """ other = self._check_allowed_dtypes(other, "integer", "__ilshift__") if other is NotImplemented: return other self._array.__ilshift__(other._array) return self def __rlshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rlshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rlshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rlshift__(other._array) return self.__class__._new(res) def __imatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __imatmul__. """ # Note: NumPy does not implement __imatmul__. # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__imatmul__") if other is NotImplemented: return other # __imatmul__ can only be allowed when it would not change the shape # of self. other_shape = other.shape if self.shape == () or other_shape == (): raise ValueError("@= requires at least one dimension") if len(other_shape) == 1 or other_shape[-1] != other_shape[-2]: raise ValueError("@= cannot change the shape of the input array") self._array[:] = self._array.__matmul__(other._array) return self def __rmatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __rmatmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__rmatmul__") if other is NotImplemented: return other res = self._array.__rmatmul__(other._array) return self.__class__._new(res) def __imod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imod__. """ other = self._check_allowed_dtypes(other, "numeric", "__imod__") if other is NotImplemented: return other self._array.__imod__(other._array) return self def __rmod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmod__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmod__(other._array) return self.__class__._new(res) def __imul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imul__. """ other = self._check_allowed_dtypes(other, "numeric", "__imul__") if other is NotImplemented: return other self._array.__imul__(other._array) return self def __rmul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmul__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmul__(other._array) return self.__class__._new(res) def __ior__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ior__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ior__") if other is NotImplemented: return other self._array.__ior__(other._array) return self def __ror__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ror__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ror__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ror__(other._array) return self.__class__._new(res) def __ipow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ipow__. """ other = self._check_allowed_dtypes(other, "numeric", "__ipow__") if other is NotImplemented: return other self._array.__ipow__(other._array) return self def __rpow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rpow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__rpow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow the spec type promotion rules # for 0-d arrays, so we use pow() here instead. return pow(other, self) def __irshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __irshift__. """ other = self._check_allowed_dtypes(other, "integer", "__irshift__") if other is NotImplemented: return other self._array.__irshift__(other._array) return self def __rrshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rrshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rrshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rrshift__(other._array) return self.__class__._new(res) def __isub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __isub__. """ other = self._check_allowed_dtypes(other, "numeric", "__isub__") if other is NotImplemented: return other self._array.__isub__(other._array) return self def __rsub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rsub__. """ other = self._check_allowed_dtypes(other, "numeric", "__rsub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rsub__(other._array) return self.__class__._new(res) def __itruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __itruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__itruediv__") if other is NotImplemented: return other self._array.__itruediv__(other._array) return self def __rtruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __rtruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__rtruediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rtruediv__(other._array) return self.__class__._new(res) def __ixor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ixor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ixor__") if other is NotImplemented: return other self._array.__ixor__(other._array) return self def __rxor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rxor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rxor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rxor__(other._array) return self.__class__._new(res) def to_device(self: Array, device: Device, /, stream: None = None) -> Array: if stream is not None: raise ValueError("The stream argument to to_device() is not supported") if device == 'cpu': return self raise ValueError(f"Unsupported device {device!r}") def dtype(self) -> Dtype: """ Array API compatible wrapper for :py:meth:`np.ndarray.dtype <numpy.ndarray.dtype>`. See its docstring for more information. """ return self._array.dtype def device(self) -> Device: return "cpu" # Note: mT is new in array API spec (see matrix_transpose) def mT(self) -> Array: from .linalg import matrix_transpose return matrix_transpose(self) def ndim(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.ndim <numpy.ndarray.ndim>`. See its docstring for more information. """ return self._array.ndim def shape(self) -> Tuple[int, ...]: """ Array API compatible wrapper for :py:meth:`np.ndarray.shape <numpy.ndarray.shape>`. See its docstring for more information. """ return self._array.shape def size(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.size <numpy.ndarray.size>`. See its docstring for more information. """ return self._array.size def T(self) -> Array: """ Array API compatible wrapper for :py:meth:`np.ndarray.T <numpy.ndarray.T>`. See its docstring for more information. """ # Note: T only works on 2-dimensional arrays. See the corresponding # note in the specification: # https://data-apis.org/array-api/latest/API_specification/array_object.html#t if self.ndim != 2: raise ValueError("x.T requires x to have 2 dimensions. Use x.mT to transpose stacks of matrices and permute_dims() to permute dimensions.") return self.__class__._new(self._array.T) The provided code snippet includes necessary dependencies for implementing the `sin` function. Write a Python function `def sin(x: Array, /) -> Array` to solve the following problem: Array API compatible wrapper for :py:func:`np.sin <numpy.sin>`. See its docstring for more information. Here is the function: def sin(x: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.sin <numpy.sin>`. See its docstring for more information. """ if x.dtype not in _floating_dtypes: raise TypeError("Only floating-point dtypes are allowed in sin") return Array._new(np.sin(x._array))
Array API compatible wrapper for :py:func:`np.sin <numpy.sin>`. See its docstring for more information.
170,068
from __future__ import annotations from ._dtypes import ( _boolean_dtypes, _floating_dtypes, _integer_dtypes, _integer_or_boolean_dtypes, _numeric_dtypes, _result_type, ) from ._array_object import Array import numpy as np _floating_dtypes = (float32, float64) class Array: """ n-d array object for the array API namespace. See the docstring of :py:obj:`np.ndarray <numpy.ndarray>` for more information. This is a wrapper around numpy.ndarray that restricts the usage to only those things that are required by the array API namespace. Note, attributes on this object that start with a single underscore are not part of the API specification and should only be used internally. This object should not be constructed directly. Rather, use one of the creation functions, such as asarray(). """ _array: np.ndarray # Use a custom constructor instead of __init__, as manually initializing # this class is not supported API. def _new(cls, x, /): """ This is a private method for initializing the array API Array object. Functions outside of the array_api submodule should not use this method. Use one of the creation functions instead, such as ``asarray``. """ obj = super().__new__(cls) # Note: The spec does not have array scalars, only 0-D arrays. if isinstance(x, np.generic): # Convert the array scalar to a 0-D array x = np.asarray(x) if x.dtype not in _all_dtypes: raise TypeError( f"The array_api namespace does not support the dtype '{x.dtype}'" ) obj._array = x return obj # Prevent Array() from working def __new__(cls, *args, **kwargs): raise TypeError( "The array_api Array object should not be instantiated directly. Use an array creation function, such as asarray(), instead." ) # These functions are not required by the spec, but are implemented for # the sake of usability. def __str__(self: Array, /) -> str: """ Performs the operation __str__. """ return self._array.__str__().replace("array", "Array") def __repr__(self: Array, /) -> str: """ Performs the operation __repr__. """ suffix = f", dtype={self.dtype.name})" if 0 in self.shape: prefix = "empty(" mid = str(self.shape) else: prefix = "Array(" mid = np.array2string(self._array, separator=', ', prefix=prefix, suffix=suffix) return prefix + mid + suffix # This function is not required by the spec, but we implement it here for # convenience so that np.asarray(np.array_api.Array) will work. def __array__(self, dtype: None | np.dtype[Any] = None) -> npt.NDArray[Any]: """ Warning: this method is NOT part of the array API spec. Implementers of other libraries need not include it, and users should not assume it will be present in other implementations. """ return np.asarray(self._array, dtype=dtype) # These are various helper functions to make the array behavior match the # spec in places where it either deviates from or is more strict than # NumPy behavior def _check_allowed_dtypes(self, other: bool | int | float | Array, dtype_category: str, op: str) -> Array: """ Helper function for operators to only allow specific input dtypes Use like other = self._check_allowed_dtypes(other, 'numeric', '__add__') if other is NotImplemented: return other """ if self.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") if isinstance(other, (int, float, bool)): other = self._promote_scalar(other) elif isinstance(other, Array): if other.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") else: return NotImplemented # This will raise TypeError for type combinations that are not allowed # to promote in the spec (even if the NumPy array operator would # promote them). res_dtype = _result_type(self.dtype, other.dtype) if op.startswith("__i"): # Note: NumPy will allow in-place operators in some cases where # the type promoted operator does not match the left-hand side # operand. For example, # >>> a = np.array(1, dtype=np.int8) # >>> a += np.array(1, dtype=np.int16) # The spec explicitly disallows this. if res_dtype != self.dtype: raise TypeError( f"Cannot perform {op} with dtypes {self.dtype} and {other.dtype}" ) return other # Helper function to match the type promotion rules in the spec def _promote_scalar(self, scalar): """ Returns a promoted version of a Python scalar appropriate for use with operations on self. This may raise an OverflowError in cases where the scalar is an integer that is too large to fit in a NumPy integer dtype, or TypeError when the scalar type is incompatible with the dtype of self. """ # Note: Only Python scalar types that match the array dtype are # allowed. if isinstance(scalar, bool): if self.dtype not in _boolean_dtypes: raise TypeError( "Python bool scalars can only be promoted with bool arrays" ) elif isinstance(scalar, int): if self.dtype in _boolean_dtypes: raise TypeError( "Python int scalars cannot be promoted with bool arrays" ) elif isinstance(scalar, float): if self.dtype not in _floating_dtypes: raise TypeError( "Python float scalars can only be promoted with floating-point arrays." ) else: raise TypeError("'scalar' must be a Python scalar") # Note: scalars are unconditionally cast to the same dtype as the # array. # Note: the spec only specifies integer-dtype/int promotion # behavior for integers within the bounds of the integer dtype. # Outside of those bounds we use the default NumPy behavior (either # cast or raise OverflowError). return Array._new(np.array(scalar, self.dtype)) def _normalize_two_args(x1, x2) -> Tuple[Array, Array]: """ Normalize inputs to two arg functions to fix type promotion rules NumPy deviates from the spec type promotion rules in cases where one argument is 0-dimensional and the other is not. For example: >>> import numpy as np >>> a = np.array([1.0], dtype=np.float32) >>> b = np.array(1.0, dtype=np.float64) >>> np.add(a, b) # The spec says this should be float64 array([2.], dtype=float32) To fix this, we add a dimension to the 0-dimension array before passing it through. This works because a dimension would be added anyway from broadcasting, so the resulting shape is the same, but this prevents NumPy from not promoting the dtype. """ # Another option would be to use signature=(x1.dtype, x2.dtype, None), # but that only works for ufuncs, so we would have to call the ufuncs # directly in the operator methods. One should also note that this # sort of trick wouldn't work for functions like searchsorted, which # don't do normal broadcasting, but there aren't any functions like # that in the array API namespace. if x1.ndim == 0 and x2.ndim != 0: # The _array[None] workaround was chosen because it is relatively # performant. broadcast_to(x1._array, x2.shape) is much slower. We # could also manually type promote x2, but that is more complicated # and about the same performance as this. x1 = Array._new(x1._array[None]) elif x2.ndim == 0 and x1.ndim != 0: x2 = Array._new(x2._array[None]) return (x1, x2) # Note: A large fraction of allowed indices are disallowed here (see the # docstring below) def _validate_index(self, key): """ Validate an index according to the array API. The array API specification only requires a subset of indices that are supported by NumPy. This function will reject any index that is allowed by NumPy but not required by the array API specification. We always raise ``IndexError`` on such indices (the spec does not require any specific behavior on them, but this makes the NumPy array API namespace a minimal implementation of the spec). See https://data-apis.org/array-api/latest/API_specification/indexing.html for the full list of required indexing behavior This function raises IndexError if the index ``key`` is invalid. It only raises ``IndexError`` on indices that are not already rejected by NumPy, as NumPy will already raise the appropriate error on such indices. ``shape`` may be None, in which case, only cases that are independent of the array shape are checked. The following cases are allowed by NumPy, but not specified by the array API specification: - Indices to not include an implicit ellipsis at the end. That is, every axis of an array must be explicitly indexed or an ellipsis included. This behaviour is sometimes referred to as flat indexing. - The start and stop of a slice may not be out of bounds. In particular, for a slice ``i:j:k`` on an axis of size ``n``, only the following are allowed: - ``i`` or ``j`` omitted (``None``). - ``-n <= i <= max(0, n - 1)``. - For ``k > 0`` or ``k`` omitted (``None``), ``-n <= j <= n``. - For ``k < 0``, ``-n - 1 <= j <= max(0, n - 1)``. - Boolean array indices are not allowed as part of a larger tuple index. - Integer array indices are not allowed (with the exception of 0-D arrays, which are treated the same as scalars). Additionally, it should be noted that indices that would return a scalar in NumPy will return a 0-D array. Array scalars are not allowed in the specification, only 0-D arrays. This is done in the ``Array._new`` constructor, not this function. """ _key = key if isinstance(key, tuple) else (key,) for i in _key: if isinstance(i, bool) or not ( isinstance(i, SupportsIndex) # i.e. ints or isinstance(i, slice) or i == Ellipsis or i is None or isinstance(i, Array) or isinstance(i, np.ndarray) ): raise IndexError( f"Single-axes index {i} has {type(i)=}, but only " "integers, slices (:), ellipsis (...), newaxis (None), " "zero-dimensional integer arrays and boolean arrays " "are specified in the Array API." ) nonexpanding_key = [] single_axes = [] n_ellipsis = 0 key_has_mask = False for i in _key: if i is not None: nonexpanding_key.append(i) if isinstance(i, Array) or isinstance(i, np.ndarray): if i.dtype in _boolean_dtypes: key_has_mask = True single_axes.append(i) else: # i must not be an array here, to avoid elementwise equals if i == Ellipsis: n_ellipsis += 1 else: single_axes.append(i) n_single_axes = len(single_axes) if n_ellipsis > 1: return # handled by ndarray elif n_ellipsis == 0: # Note boolean masks must be the sole index, which we check for # later on. if not key_has_mask and n_single_axes < self.ndim: raise IndexError( f"{self.ndim=}, but the multi-axes index only specifies " f"{n_single_axes} dimensions. If this was intentional, " "add a trailing ellipsis (...) which expands into as many " "slices (:) as necessary - this is what np.ndarray arrays " "implicitly do, but such flat indexing behaviour is not " "specified in the Array API." ) if n_ellipsis == 0: indexed_shape = self.shape else: ellipsis_start = None for pos, i in enumerate(nonexpanding_key): if not (isinstance(i, Array) or isinstance(i, np.ndarray)): if i == Ellipsis: ellipsis_start = pos break assert ellipsis_start is not None # sanity check ellipsis_end = self.ndim - (n_single_axes - ellipsis_start) indexed_shape = ( self.shape[:ellipsis_start] + self.shape[ellipsis_end:] ) for i, side in zip(single_axes, indexed_shape): if isinstance(i, slice): if side == 0: f_range = "0 (or None)" else: f_range = f"between -{side} and {side - 1} (or None)" if i.start is not None: try: start = operator.index(i.start) except TypeError: pass # handled by ndarray else: if not (-side <= start <= side): raise IndexError( f"Slice {i} contains {start=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds starts are not specified in " "the Array API)" ) if i.stop is not None: try: stop = operator.index(i.stop) except TypeError: pass # handled by ndarray else: if not (-side <= stop <= side): raise IndexError( f"Slice {i} contains {stop=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds stops are not specified in " "the Array API)" ) elif isinstance(i, Array): if i.dtype in _boolean_dtypes and len(_key) != 1: assert isinstance(key, tuple) # sanity check raise IndexError( f"Single-axes index {i} is a boolean array and " f"{len(key)=}, but masking is only specified in the " "Array API when the array is the sole index." ) elif i.dtype in _integer_dtypes and i.ndim != 0: raise IndexError( f"Single-axes index {i} is a non-zero-dimensional " "integer array, but advanced integer indexing is not " "specified in the Array API." ) elif isinstance(i, tuple): raise IndexError( f"Single-axes index {i} is a tuple, but nested tuple " "indices are not specified in the Array API." ) # Everything below this line is required by the spec. def __abs__(self: Array, /) -> Array: """ Performs the operation __abs__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __abs__") res = self._array.__abs__() return self.__class__._new(res) def __add__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __add__. """ other = self._check_allowed_dtypes(other, "numeric", "__add__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__add__(other._array) return self.__class__._new(res) def __and__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __and__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__and__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__and__(other._array) return self.__class__._new(res) def __array_namespace__( self: Array, /, *, api_version: Optional[str] = None ) -> types.ModuleType: if api_version is not None and not api_version.startswith("2021."): raise ValueError(f"Unrecognized array API version: {api_version!r}") return array_api def __bool__(self: Array, /) -> bool: """ Performs the operation __bool__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("bool is only allowed on arrays with 0 dimensions") if self.dtype not in _boolean_dtypes: raise ValueError("bool is only allowed on boolean arrays") res = self._array.__bool__() return res def __dlpack__(self: Array, /, *, stream: None = None) -> PyCapsule: """ Performs the operation __dlpack__. """ return self._array.__dlpack__(stream=stream) def __dlpack_device__(self: Array, /) -> Tuple[IntEnum, int]: """ Performs the operation __dlpack_device__. """ # Note: device support is required for this return self._array.__dlpack_device__() def __eq__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __eq__. """ # Even though "all" dtypes are allowed, we still require them to be # promotable with each other. other = self._check_allowed_dtypes(other, "all", "__eq__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__eq__(other._array) return self.__class__._new(res) def __float__(self: Array, /) -> float: """ Performs the operation __float__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("float is only allowed on arrays with 0 dimensions") if self.dtype not in _floating_dtypes: raise ValueError("float is only allowed on floating-point arrays") res = self._array.__float__() return res def __floordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __floordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__floordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__floordiv__(other._array) return self.__class__._new(res) def __ge__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ge__. """ other = self._check_allowed_dtypes(other, "numeric", "__ge__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ge__(other._array) return self.__class__._new(res) def __getitem__( self: Array, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], /, ) -> Array: """ Performs the operation __getitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array res = self._array.__getitem__(key) return self._new(res) def __gt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __gt__. """ other = self._check_allowed_dtypes(other, "numeric", "__gt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__gt__(other._array) return self.__class__._new(res) def __int__(self: Array, /) -> int: """ Performs the operation __int__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("int is only allowed on arrays with 0 dimensions") if self.dtype not in _integer_dtypes: raise ValueError("int is only allowed on integer arrays") res = self._array.__int__() return res def __index__(self: Array, /) -> int: """ Performs the operation __index__. """ res = self._array.__index__() return res def __invert__(self: Array, /) -> Array: """ Performs the operation __invert__. """ if self.dtype not in _integer_or_boolean_dtypes: raise TypeError("Only integer or boolean dtypes are allowed in __invert__") res = self._array.__invert__() return self.__class__._new(res) def __le__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __le__. """ other = self._check_allowed_dtypes(other, "numeric", "__le__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__le__(other._array) return self.__class__._new(res) def __lshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __lshift__. """ other = self._check_allowed_dtypes(other, "integer", "__lshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lshift__(other._array) return self.__class__._new(res) def __lt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __lt__. """ other = self._check_allowed_dtypes(other, "numeric", "__lt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lt__(other._array) return self.__class__._new(res) def __matmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __matmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__matmul__") if other is NotImplemented: return other res = self._array.__matmul__(other._array) return self.__class__._new(res) def __mod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mod__. """ other = self._check_allowed_dtypes(other, "numeric", "__mod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mod__(other._array) return self.__class__._new(res) def __mul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mul__. """ other = self._check_allowed_dtypes(other, "numeric", "__mul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mul__(other._array) return self.__class__._new(res) def __ne__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __ne__. """ other = self._check_allowed_dtypes(other, "all", "__ne__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ne__(other._array) return self.__class__._new(res) def __neg__(self: Array, /) -> Array: """ Performs the operation __neg__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __neg__") res = self._array.__neg__() return self.__class__._new(res) def __or__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __or__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__or__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__or__(other._array) return self.__class__._new(res) def __pos__(self: Array, /) -> Array: """ Performs the operation __pos__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __pos__") res = self._array.__pos__() return self.__class__._new(res) def __pow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __pow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__pow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow type promotion rules for 0-d # arrays, so we use pow() here instead. return pow(self, other) def __rshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rshift__(other._array) return self.__class__._new(res) def __setitem__( self, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], value: Union[int, float, bool, Array], /, ) -> None: """ Performs the operation __setitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array self._array.__setitem__(key, asarray(value)._array) def __sub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __sub__. """ other = self._check_allowed_dtypes(other, "numeric", "__sub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__sub__(other._array) return self.__class__._new(res) # PEP 484 requires int to be a subtype of float, but __truediv__ should # not accept int. def __truediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __truediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__truediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__truediv__(other._array) return self.__class__._new(res) def __xor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __xor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__xor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__xor__(other._array) return self.__class__._new(res) def __iadd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __iadd__. """ other = self._check_allowed_dtypes(other, "numeric", "__iadd__") if other is NotImplemented: return other self._array.__iadd__(other._array) return self def __radd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __radd__. """ other = self._check_allowed_dtypes(other, "numeric", "__radd__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__radd__(other._array) return self.__class__._new(res) def __iand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __iand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__iand__") if other is NotImplemented: return other self._array.__iand__(other._array) return self def __rand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rand__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rand__(other._array) return self.__class__._new(res) def __ifloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ifloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__ifloordiv__") if other is NotImplemented: return other self._array.__ifloordiv__(other._array) return self def __rfloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rfloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__rfloordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rfloordiv__(other._array) return self.__class__._new(res) def __ilshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __ilshift__. """ other = self._check_allowed_dtypes(other, "integer", "__ilshift__") if other is NotImplemented: return other self._array.__ilshift__(other._array) return self def __rlshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rlshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rlshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rlshift__(other._array) return self.__class__._new(res) def __imatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __imatmul__. """ # Note: NumPy does not implement __imatmul__. # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__imatmul__") if other is NotImplemented: return other # __imatmul__ can only be allowed when it would not change the shape # of self. other_shape = other.shape if self.shape == () or other_shape == (): raise ValueError("@= requires at least one dimension") if len(other_shape) == 1 or other_shape[-1] != other_shape[-2]: raise ValueError("@= cannot change the shape of the input array") self._array[:] = self._array.__matmul__(other._array) return self def __rmatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __rmatmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__rmatmul__") if other is NotImplemented: return other res = self._array.__rmatmul__(other._array) return self.__class__._new(res) def __imod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imod__. """ other = self._check_allowed_dtypes(other, "numeric", "__imod__") if other is NotImplemented: return other self._array.__imod__(other._array) return self def __rmod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmod__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmod__(other._array) return self.__class__._new(res) def __imul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imul__. """ other = self._check_allowed_dtypes(other, "numeric", "__imul__") if other is NotImplemented: return other self._array.__imul__(other._array) return self def __rmul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmul__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmul__(other._array) return self.__class__._new(res) def __ior__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ior__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ior__") if other is NotImplemented: return other self._array.__ior__(other._array) return self def __ror__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ror__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ror__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ror__(other._array) return self.__class__._new(res) def __ipow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ipow__. """ other = self._check_allowed_dtypes(other, "numeric", "__ipow__") if other is NotImplemented: return other self._array.__ipow__(other._array) return self def __rpow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rpow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__rpow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow the spec type promotion rules # for 0-d arrays, so we use pow() here instead. return pow(other, self) def __irshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __irshift__. """ other = self._check_allowed_dtypes(other, "integer", "__irshift__") if other is NotImplemented: return other self._array.__irshift__(other._array) return self def __rrshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rrshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rrshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rrshift__(other._array) return self.__class__._new(res) def __isub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __isub__. """ other = self._check_allowed_dtypes(other, "numeric", "__isub__") if other is NotImplemented: return other self._array.__isub__(other._array) return self def __rsub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rsub__. """ other = self._check_allowed_dtypes(other, "numeric", "__rsub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rsub__(other._array) return self.__class__._new(res) def __itruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __itruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__itruediv__") if other is NotImplemented: return other self._array.__itruediv__(other._array) return self def __rtruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __rtruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__rtruediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rtruediv__(other._array) return self.__class__._new(res) def __ixor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ixor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ixor__") if other is NotImplemented: return other self._array.__ixor__(other._array) return self def __rxor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rxor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rxor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rxor__(other._array) return self.__class__._new(res) def to_device(self: Array, device: Device, /, stream: None = None) -> Array: if stream is not None: raise ValueError("The stream argument to to_device() is not supported") if device == 'cpu': return self raise ValueError(f"Unsupported device {device!r}") def dtype(self) -> Dtype: """ Array API compatible wrapper for :py:meth:`np.ndarray.dtype <numpy.ndarray.dtype>`. See its docstring for more information. """ return self._array.dtype def device(self) -> Device: return "cpu" # Note: mT is new in array API spec (see matrix_transpose) def mT(self) -> Array: from .linalg import matrix_transpose return matrix_transpose(self) def ndim(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.ndim <numpy.ndarray.ndim>`. See its docstring for more information. """ return self._array.ndim def shape(self) -> Tuple[int, ...]: """ Array API compatible wrapper for :py:meth:`np.ndarray.shape <numpy.ndarray.shape>`. See its docstring for more information. """ return self._array.shape def size(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.size <numpy.ndarray.size>`. See its docstring for more information. """ return self._array.size def T(self) -> Array: """ Array API compatible wrapper for :py:meth:`np.ndarray.T <numpy.ndarray.T>`. See its docstring for more information. """ # Note: T only works on 2-dimensional arrays. See the corresponding # note in the specification: # https://data-apis.org/array-api/latest/API_specification/array_object.html#t if self.ndim != 2: raise ValueError("x.T requires x to have 2 dimensions. Use x.mT to transpose stacks of matrices and permute_dims() to permute dimensions.") return self.__class__._new(self._array.T) The provided code snippet includes necessary dependencies for implementing the `sinh` function. Write a Python function `def sinh(x: Array, /) -> Array` to solve the following problem: Array API compatible wrapper for :py:func:`np.sinh <numpy.sinh>`. See its docstring for more information. Here is the function: def sinh(x: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.sinh <numpy.sinh>`. See its docstring for more information. """ if x.dtype not in _floating_dtypes: raise TypeError("Only floating-point dtypes are allowed in sinh") return Array._new(np.sinh(x._array))
Array API compatible wrapper for :py:func:`np.sinh <numpy.sinh>`. See its docstring for more information.
170,069
from __future__ import annotations from ._dtypes import ( _boolean_dtypes, _floating_dtypes, _integer_dtypes, _integer_or_boolean_dtypes, _numeric_dtypes, _result_type, ) from ._array_object import Array import numpy as np _numeric_dtypes = ( float32, float64, int8, int16, int32, int64, uint8, uint16, uint32, uint64, ) class Array: """ n-d array object for the array API namespace. See the docstring of :py:obj:`np.ndarray <numpy.ndarray>` for more information. This is a wrapper around numpy.ndarray that restricts the usage to only those things that are required by the array API namespace. Note, attributes on this object that start with a single underscore are not part of the API specification and should only be used internally. This object should not be constructed directly. Rather, use one of the creation functions, such as asarray(). """ _array: np.ndarray # Use a custom constructor instead of __init__, as manually initializing # this class is not supported API. def _new(cls, x, /): """ This is a private method for initializing the array API Array object. Functions outside of the array_api submodule should not use this method. Use one of the creation functions instead, such as ``asarray``. """ obj = super().__new__(cls) # Note: The spec does not have array scalars, only 0-D arrays. if isinstance(x, np.generic): # Convert the array scalar to a 0-D array x = np.asarray(x) if x.dtype not in _all_dtypes: raise TypeError( f"The array_api namespace does not support the dtype '{x.dtype}'" ) obj._array = x return obj # Prevent Array() from working def __new__(cls, *args, **kwargs): raise TypeError( "The array_api Array object should not be instantiated directly. Use an array creation function, such as asarray(), instead." ) # These functions are not required by the spec, but are implemented for # the sake of usability. def __str__(self: Array, /) -> str: """ Performs the operation __str__. """ return self._array.__str__().replace("array", "Array") def __repr__(self: Array, /) -> str: """ Performs the operation __repr__. """ suffix = f", dtype={self.dtype.name})" if 0 in self.shape: prefix = "empty(" mid = str(self.shape) else: prefix = "Array(" mid = np.array2string(self._array, separator=', ', prefix=prefix, suffix=suffix) return prefix + mid + suffix # This function is not required by the spec, but we implement it here for # convenience so that np.asarray(np.array_api.Array) will work. def __array__(self, dtype: None | np.dtype[Any] = None) -> npt.NDArray[Any]: """ Warning: this method is NOT part of the array API spec. Implementers of other libraries need not include it, and users should not assume it will be present in other implementations. """ return np.asarray(self._array, dtype=dtype) # These are various helper functions to make the array behavior match the # spec in places where it either deviates from or is more strict than # NumPy behavior def _check_allowed_dtypes(self, other: bool | int | float | Array, dtype_category: str, op: str) -> Array: """ Helper function for operators to only allow specific input dtypes Use like other = self._check_allowed_dtypes(other, 'numeric', '__add__') if other is NotImplemented: return other """ if self.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") if isinstance(other, (int, float, bool)): other = self._promote_scalar(other) elif isinstance(other, Array): if other.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") else: return NotImplemented # This will raise TypeError for type combinations that are not allowed # to promote in the spec (even if the NumPy array operator would # promote them). res_dtype = _result_type(self.dtype, other.dtype) if op.startswith("__i"): # Note: NumPy will allow in-place operators in some cases where # the type promoted operator does not match the left-hand side # operand. For example, # >>> a = np.array(1, dtype=np.int8) # >>> a += np.array(1, dtype=np.int16) # The spec explicitly disallows this. if res_dtype != self.dtype: raise TypeError( f"Cannot perform {op} with dtypes {self.dtype} and {other.dtype}" ) return other # Helper function to match the type promotion rules in the spec def _promote_scalar(self, scalar): """ Returns a promoted version of a Python scalar appropriate for use with operations on self. This may raise an OverflowError in cases where the scalar is an integer that is too large to fit in a NumPy integer dtype, or TypeError when the scalar type is incompatible with the dtype of self. """ # Note: Only Python scalar types that match the array dtype are # allowed. if isinstance(scalar, bool): if self.dtype not in _boolean_dtypes: raise TypeError( "Python bool scalars can only be promoted with bool arrays" ) elif isinstance(scalar, int): if self.dtype in _boolean_dtypes: raise TypeError( "Python int scalars cannot be promoted with bool arrays" ) elif isinstance(scalar, float): if self.dtype not in _floating_dtypes: raise TypeError( "Python float scalars can only be promoted with floating-point arrays." ) else: raise TypeError("'scalar' must be a Python scalar") # Note: scalars are unconditionally cast to the same dtype as the # array. # Note: the spec only specifies integer-dtype/int promotion # behavior for integers within the bounds of the integer dtype. # Outside of those bounds we use the default NumPy behavior (either # cast or raise OverflowError). return Array._new(np.array(scalar, self.dtype)) def _normalize_two_args(x1, x2) -> Tuple[Array, Array]: """ Normalize inputs to two arg functions to fix type promotion rules NumPy deviates from the spec type promotion rules in cases where one argument is 0-dimensional and the other is not. For example: >>> import numpy as np >>> a = np.array([1.0], dtype=np.float32) >>> b = np.array(1.0, dtype=np.float64) >>> np.add(a, b) # The spec says this should be float64 array([2.], dtype=float32) To fix this, we add a dimension to the 0-dimension array before passing it through. This works because a dimension would be added anyway from broadcasting, so the resulting shape is the same, but this prevents NumPy from not promoting the dtype. """ # Another option would be to use signature=(x1.dtype, x2.dtype, None), # but that only works for ufuncs, so we would have to call the ufuncs # directly in the operator methods. One should also note that this # sort of trick wouldn't work for functions like searchsorted, which # don't do normal broadcasting, but there aren't any functions like # that in the array API namespace. if x1.ndim == 0 and x2.ndim != 0: # The _array[None] workaround was chosen because it is relatively # performant. broadcast_to(x1._array, x2.shape) is much slower. We # could also manually type promote x2, but that is more complicated # and about the same performance as this. x1 = Array._new(x1._array[None]) elif x2.ndim == 0 and x1.ndim != 0: x2 = Array._new(x2._array[None]) return (x1, x2) # Note: A large fraction of allowed indices are disallowed here (see the # docstring below) def _validate_index(self, key): """ Validate an index according to the array API. The array API specification only requires a subset of indices that are supported by NumPy. This function will reject any index that is allowed by NumPy but not required by the array API specification. We always raise ``IndexError`` on such indices (the spec does not require any specific behavior on them, but this makes the NumPy array API namespace a minimal implementation of the spec). See https://data-apis.org/array-api/latest/API_specification/indexing.html for the full list of required indexing behavior This function raises IndexError if the index ``key`` is invalid. It only raises ``IndexError`` on indices that are not already rejected by NumPy, as NumPy will already raise the appropriate error on such indices. ``shape`` may be None, in which case, only cases that are independent of the array shape are checked. The following cases are allowed by NumPy, but not specified by the array API specification: - Indices to not include an implicit ellipsis at the end. That is, every axis of an array must be explicitly indexed or an ellipsis included. This behaviour is sometimes referred to as flat indexing. - The start and stop of a slice may not be out of bounds. In particular, for a slice ``i:j:k`` on an axis of size ``n``, only the following are allowed: - ``i`` or ``j`` omitted (``None``). - ``-n <= i <= max(0, n - 1)``. - For ``k > 0`` or ``k`` omitted (``None``), ``-n <= j <= n``. - For ``k < 0``, ``-n - 1 <= j <= max(0, n - 1)``. - Boolean array indices are not allowed as part of a larger tuple index. - Integer array indices are not allowed (with the exception of 0-D arrays, which are treated the same as scalars). Additionally, it should be noted that indices that would return a scalar in NumPy will return a 0-D array. Array scalars are not allowed in the specification, only 0-D arrays. This is done in the ``Array._new`` constructor, not this function. """ _key = key if isinstance(key, tuple) else (key,) for i in _key: if isinstance(i, bool) or not ( isinstance(i, SupportsIndex) # i.e. ints or isinstance(i, slice) or i == Ellipsis or i is None or isinstance(i, Array) or isinstance(i, np.ndarray) ): raise IndexError( f"Single-axes index {i} has {type(i)=}, but only " "integers, slices (:), ellipsis (...), newaxis (None), " "zero-dimensional integer arrays and boolean arrays " "are specified in the Array API." ) nonexpanding_key = [] single_axes = [] n_ellipsis = 0 key_has_mask = False for i in _key: if i is not None: nonexpanding_key.append(i) if isinstance(i, Array) or isinstance(i, np.ndarray): if i.dtype in _boolean_dtypes: key_has_mask = True single_axes.append(i) else: # i must not be an array here, to avoid elementwise equals if i == Ellipsis: n_ellipsis += 1 else: single_axes.append(i) n_single_axes = len(single_axes) if n_ellipsis > 1: return # handled by ndarray elif n_ellipsis == 0: # Note boolean masks must be the sole index, which we check for # later on. if not key_has_mask and n_single_axes < self.ndim: raise IndexError( f"{self.ndim=}, but the multi-axes index only specifies " f"{n_single_axes} dimensions. If this was intentional, " "add a trailing ellipsis (...) which expands into as many " "slices (:) as necessary - this is what np.ndarray arrays " "implicitly do, but such flat indexing behaviour is not " "specified in the Array API." ) if n_ellipsis == 0: indexed_shape = self.shape else: ellipsis_start = None for pos, i in enumerate(nonexpanding_key): if not (isinstance(i, Array) or isinstance(i, np.ndarray)): if i == Ellipsis: ellipsis_start = pos break assert ellipsis_start is not None # sanity check ellipsis_end = self.ndim - (n_single_axes - ellipsis_start) indexed_shape = ( self.shape[:ellipsis_start] + self.shape[ellipsis_end:] ) for i, side in zip(single_axes, indexed_shape): if isinstance(i, slice): if side == 0: f_range = "0 (or None)" else: f_range = f"between -{side} and {side - 1} (or None)" if i.start is not None: try: start = operator.index(i.start) except TypeError: pass # handled by ndarray else: if not (-side <= start <= side): raise IndexError( f"Slice {i} contains {start=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds starts are not specified in " "the Array API)" ) if i.stop is not None: try: stop = operator.index(i.stop) except TypeError: pass # handled by ndarray else: if not (-side <= stop <= side): raise IndexError( f"Slice {i} contains {stop=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds stops are not specified in " "the Array API)" ) elif isinstance(i, Array): if i.dtype in _boolean_dtypes and len(_key) != 1: assert isinstance(key, tuple) # sanity check raise IndexError( f"Single-axes index {i} is a boolean array and " f"{len(key)=}, but masking is only specified in the " "Array API when the array is the sole index." ) elif i.dtype in _integer_dtypes and i.ndim != 0: raise IndexError( f"Single-axes index {i} is a non-zero-dimensional " "integer array, but advanced integer indexing is not " "specified in the Array API." ) elif isinstance(i, tuple): raise IndexError( f"Single-axes index {i} is a tuple, but nested tuple " "indices are not specified in the Array API." ) # Everything below this line is required by the spec. def __abs__(self: Array, /) -> Array: """ Performs the operation __abs__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __abs__") res = self._array.__abs__() return self.__class__._new(res) def __add__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __add__. """ other = self._check_allowed_dtypes(other, "numeric", "__add__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__add__(other._array) return self.__class__._new(res) def __and__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __and__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__and__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__and__(other._array) return self.__class__._new(res) def __array_namespace__( self: Array, /, *, api_version: Optional[str] = None ) -> types.ModuleType: if api_version is not None and not api_version.startswith("2021."): raise ValueError(f"Unrecognized array API version: {api_version!r}") return array_api def __bool__(self: Array, /) -> bool: """ Performs the operation __bool__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("bool is only allowed on arrays with 0 dimensions") if self.dtype not in _boolean_dtypes: raise ValueError("bool is only allowed on boolean arrays") res = self._array.__bool__() return res def __dlpack__(self: Array, /, *, stream: None = None) -> PyCapsule: """ Performs the operation __dlpack__. """ return self._array.__dlpack__(stream=stream) def __dlpack_device__(self: Array, /) -> Tuple[IntEnum, int]: """ Performs the operation __dlpack_device__. """ # Note: device support is required for this return self._array.__dlpack_device__() def __eq__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __eq__. """ # Even though "all" dtypes are allowed, we still require them to be # promotable with each other. other = self._check_allowed_dtypes(other, "all", "__eq__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__eq__(other._array) return self.__class__._new(res) def __float__(self: Array, /) -> float: """ Performs the operation __float__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("float is only allowed on arrays with 0 dimensions") if self.dtype not in _floating_dtypes: raise ValueError("float is only allowed on floating-point arrays") res = self._array.__float__() return res def __floordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __floordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__floordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__floordiv__(other._array) return self.__class__._new(res) def __ge__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ge__. """ other = self._check_allowed_dtypes(other, "numeric", "__ge__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ge__(other._array) return self.__class__._new(res) def __getitem__( self: Array, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], /, ) -> Array: """ Performs the operation __getitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array res = self._array.__getitem__(key) return self._new(res) def __gt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __gt__. """ other = self._check_allowed_dtypes(other, "numeric", "__gt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__gt__(other._array) return self.__class__._new(res) def __int__(self: Array, /) -> int: """ Performs the operation __int__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("int is only allowed on arrays with 0 dimensions") if self.dtype not in _integer_dtypes: raise ValueError("int is only allowed on integer arrays") res = self._array.__int__() return res def __index__(self: Array, /) -> int: """ Performs the operation __index__. """ res = self._array.__index__() return res def __invert__(self: Array, /) -> Array: """ Performs the operation __invert__. """ if self.dtype not in _integer_or_boolean_dtypes: raise TypeError("Only integer or boolean dtypes are allowed in __invert__") res = self._array.__invert__() return self.__class__._new(res) def __le__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __le__. """ other = self._check_allowed_dtypes(other, "numeric", "__le__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__le__(other._array) return self.__class__._new(res) def __lshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __lshift__. """ other = self._check_allowed_dtypes(other, "integer", "__lshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lshift__(other._array) return self.__class__._new(res) def __lt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __lt__. """ other = self._check_allowed_dtypes(other, "numeric", "__lt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lt__(other._array) return self.__class__._new(res) def __matmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __matmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__matmul__") if other is NotImplemented: return other res = self._array.__matmul__(other._array) return self.__class__._new(res) def __mod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mod__. """ other = self._check_allowed_dtypes(other, "numeric", "__mod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mod__(other._array) return self.__class__._new(res) def __mul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mul__. """ other = self._check_allowed_dtypes(other, "numeric", "__mul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mul__(other._array) return self.__class__._new(res) def __ne__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __ne__. """ other = self._check_allowed_dtypes(other, "all", "__ne__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ne__(other._array) return self.__class__._new(res) def __neg__(self: Array, /) -> Array: """ Performs the operation __neg__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __neg__") res = self._array.__neg__() return self.__class__._new(res) def __or__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __or__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__or__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__or__(other._array) return self.__class__._new(res) def __pos__(self: Array, /) -> Array: """ Performs the operation __pos__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __pos__") res = self._array.__pos__() return self.__class__._new(res) def __pow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __pow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__pow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow type promotion rules for 0-d # arrays, so we use pow() here instead. return pow(self, other) def __rshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rshift__(other._array) return self.__class__._new(res) def __setitem__( self, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], value: Union[int, float, bool, Array], /, ) -> None: """ Performs the operation __setitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array self._array.__setitem__(key, asarray(value)._array) def __sub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __sub__. """ other = self._check_allowed_dtypes(other, "numeric", "__sub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__sub__(other._array) return self.__class__._new(res) # PEP 484 requires int to be a subtype of float, but __truediv__ should # not accept int. def __truediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __truediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__truediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__truediv__(other._array) return self.__class__._new(res) def __xor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __xor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__xor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__xor__(other._array) return self.__class__._new(res) def __iadd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __iadd__. """ other = self._check_allowed_dtypes(other, "numeric", "__iadd__") if other is NotImplemented: return other self._array.__iadd__(other._array) return self def __radd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __radd__. """ other = self._check_allowed_dtypes(other, "numeric", "__radd__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__radd__(other._array) return self.__class__._new(res) def __iand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __iand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__iand__") if other is NotImplemented: return other self._array.__iand__(other._array) return self def __rand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rand__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rand__(other._array) return self.__class__._new(res) def __ifloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ifloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__ifloordiv__") if other is NotImplemented: return other self._array.__ifloordiv__(other._array) return self def __rfloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rfloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__rfloordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rfloordiv__(other._array) return self.__class__._new(res) def __ilshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __ilshift__. """ other = self._check_allowed_dtypes(other, "integer", "__ilshift__") if other is NotImplemented: return other self._array.__ilshift__(other._array) return self def __rlshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rlshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rlshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rlshift__(other._array) return self.__class__._new(res) def __imatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __imatmul__. """ # Note: NumPy does not implement __imatmul__. # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__imatmul__") if other is NotImplemented: return other # __imatmul__ can only be allowed when it would not change the shape # of self. other_shape = other.shape if self.shape == () or other_shape == (): raise ValueError("@= requires at least one dimension") if len(other_shape) == 1 or other_shape[-1] != other_shape[-2]: raise ValueError("@= cannot change the shape of the input array") self._array[:] = self._array.__matmul__(other._array) return self def __rmatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __rmatmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__rmatmul__") if other is NotImplemented: return other res = self._array.__rmatmul__(other._array) return self.__class__._new(res) def __imod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imod__. """ other = self._check_allowed_dtypes(other, "numeric", "__imod__") if other is NotImplemented: return other self._array.__imod__(other._array) return self def __rmod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmod__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmod__(other._array) return self.__class__._new(res) def __imul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imul__. """ other = self._check_allowed_dtypes(other, "numeric", "__imul__") if other is NotImplemented: return other self._array.__imul__(other._array) return self def __rmul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmul__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmul__(other._array) return self.__class__._new(res) def __ior__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ior__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ior__") if other is NotImplemented: return other self._array.__ior__(other._array) return self def __ror__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ror__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ror__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ror__(other._array) return self.__class__._new(res) def __ipow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ipow__. """ other = self._check_allowed_dtypes(other, "numeric", "__ipow__") if other is NotImplemented: return other self._array.__ipow__(other._array) return self def __rpow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rpow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__rpow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow the spec type promotion rules # for 0-d arrays, so we use pow() here instead. return pow(other, self) def __irshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __irshift__. """ other = self._check_allowed_dtypes(other, "integer", "__irshift__") if other is NotImplemented: return other self._array.__irshift__(other._array) return self def __rrshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rrshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rrshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rrshift__(other._array) return self.__class__._new(res) def __isub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __isub__. """ other = self._check_allowed_dtypes(other, "numeric", "__isub__") if other is NotImplemented: return other self._array.__isub__(other._array) return self def __rsub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rsub__. """ other = self._check_allowed_dtypes(other, "numeric", "__rsub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rsub__(other._array) return self.__class__._new(res) def __itruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __itruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__itruediv__") if other is NotImplemented: return other self._array.__itruediv__(other._array) return self def __rtruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __rtruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__rtruediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rtruediv__(other._array) return self.__class__._new(res) def __ixor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ixor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ixor__") if other is NotImplemented: return other self._array.__ixor__(other._array) return self def __rxor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rxor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rxor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rxor__(other._array) return self.__class__._new(res) def to_device(self: Array, device: Device, /, stream: None = None) -> Array: if stream is not None: raise ValueError("The stream argument to to_device() is not supported") if device == 'cpu': return self raise ValueError(f"Unsupported device {device!r}") def dtype(self) -> Dtype: """ Array API compatible wrapper for :py:meth:`np.ndarray.dtype <numpy.ndarray.dtype>`. See its docstring for more information. """ return self._array.dtype def device(self) -> Device: return "cpu" # Note: mT is new in array API spec (see matrix_transpose) def mT(self) -> Array: from .linalg import matrix_transpose return matrix_transpose(self) def ndim(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.ndim <numpy.ndarray.ndim>`. See its docstring for more information. """ return self._array.ndim def shape(self) -> Tuple[int, ...]: """ Array API compatible wrapper for :py:meth:`np.ndarray.shape <numpy.ndarray.shape>`. See its docstring for more information. """ return self._array.shape def size(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.size <numpy.ndarray.size>`. See its docstring for more information. """ return self._array.size def T(self) -> Array: """ Array API compatible wrapper for :py:meth:`np.ndarray.T <numpy.ndarray.T>`. See its docstring for more information. """ # Note: T only works on 2-dimensional arrays. See the corresponding # note in the specification: # https://data-apis.org/array-api/latest/API_specification/array_object.html#t if self.ndim != 2: raise ValueError("x.T requires x to have 2 dimensions. Use x.mT to transpose stacks of matrices and permute_dims() to permute dimensions.") return self.__class__._new(self._array.T) The provided code snippet includes necessary dependencies for implementing the `square` function. Write a Python function `def square(x: Array, /) -> Array` to solve the following problem: Array API compatible wrapper for :py:func:`np.square <numpy.square>`. See its docstring for more information. Here is the function: def square(x: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.square <numpy.square>`. See its docstring for more information. """ if x.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in square") return Array._new(np.square(x._array))
Array API compatible wrapper for :py:func:`np.square <numpy.square>`. See its docstring for more information.
170,070
from __future__ import annotations from ._dtypes import ( _boolean_dtypes, _floating_dtypes, _integer_dtypes, _integer_or_boolean_dtypes, _numeric_dtypes, _result_type, ) from ._array_object import Array import numpy as np _floating_dtypes = (float32, float64) class Array: """ n-d array object for the array API namespace. See the docstring of :py:obj:`np.ndarray <numpy.ndarray>` for more information. This is a wrapper around numpy.ndarray that restricts the usage to only those things that are required by the array API namespace. Note, attributes on this object that start with a single underscore are not part of the API specification and should only be used internally. This object should not be constructed directly. Rather, use one of the creation functions, such as asarray(). """ _array: np.ndarray # Use a custom constructor instead of __init__, as manually initializing # this class is not supported API. def _new(cls, x, /): """ This is a private method for initializing the array API Array object. Functions outside of the array_api submodule should not use this method. Use one of the creation functions instead, such as ``asarray``. """ obj = super().__new__(cls) # Note: The spec does not have array scalars, only 0-D arrays. if isinstance(x, np.generic): # Convert the array scalar to a 0-D array x = np.asarray(x) if x.dtype not in _all_dtypes: raise TypeError( f"The array_api namespace does not support the dtype '{x.dtype}'" ) obj._array = x return obj # Prevent Array() from working def __new__(cls, *args, **kwargs): raise TypeError( "The array_api Array object should not be instantiated directly. Use an array creation function, such as asarray(), instead." ) # These functions are not required by the spec, but are implemented for # the sake of usability. def __str__(self: Array, /) -> str: """ Performs the operation __str__. """ return self._array.__str__().replace("array", "Array") def __repr__(self: Array, /) -> str: """ Performs the operation __repr__. """ suffix = f", dtype={self.dtype.name})" if 0 in self.shape: prefix = "empty(" mid = str(self.shape) else: prefix = "Array(" mid = np.array2string(self._array, separator=', ', prefix=prefix, suffix=suffix) return prefix + mid + suffix # This function is not required by the spec, but we implement it here for # convenience so that np.asarray(np.array_api.Array) will work. def __array__(self, dtype: None | np.dtype[Any] = None) -> npt.NDArray[Any]: """ Warning: this method is NOT part of the array API spec. Implementers of other libraries need not include it, and users should not assume it will be present in other implementations. """ return np.asarray(self._array, dtype=dtype) # These are various helper functions to make the array behavior match the # spec in places where it either deviates from or is more strict than # NumPy behavior def _check_allowed_dtypes(self, other: bool | int | float | Array, dtype_category: str, op: str) -> Array: """ Helper function for operators to only allow specific input dtypes Use like other = self._check_allowed_dtypes(other, 'numeric', '__add__') if other is NotImplemented: return other """ if self.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") if isinstance(other, (int, float, bool)): other = self._promote_scalar(other) elif isinstance(other, Array): if other.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") else: return NotImplemented # This will raise TypeError for type combinations that are not allowed # to promote in the spec (even if the NumPy array operator would # promote them). res_dtype = _result_type(self.dtype, other.dtype) if op.startswith("__i"): # Note: NumPy will allow in-place operators in some cases where # the type promoted operator does not match the left-hand side # operand. For example, # >>> a = np.array(1, dtype=np.int8) # >>> a += np.array(1, dtype=np.int16) # The spec explicitly disallows this. if res_dtype != self.dtype: raise TypeError( f"Cannot perform {op} with dtypes {self.dtype} and {other.dtype}" ) return other # Helper function to match the type promotion rules in the spec def _promote_scalar(self, scalar): """ Returns a promoted version of a Python scalar appropriate for use with operations on self. This may raise an OverflowError in cases where the scalar is an integer that is too large to fit in a NumPy integer dtype, or TypeError when the scalar type is incompatible with the dtype of self. """ # Note: Only Python scalar types that match the array dtype are # allowed. if isinstance(scalar, bool): if self.dtype not in _boolean_dtypes: raise TypeError( "Python bool scalars can only be promoted with bool arrays" ) elif isinstance(scalar, int): if self.dtype in _boolean_dtypes: raise TypeError( "Python int scalars cannot be promoted with bool arrays" ) elif isinstance(scalar, float): if self.dtype not in _floating_dtypes: raise TypeError( "Python float scalars can only be promoted with floating-point arrays." ) else: raise TypeError("'scalar' must be a Python scalar") # Note: scalars are unconditionally cast to the same dtype as the # array. # Note: the spec only specifies integer-dtype/int promotion # behavior for integers within the bounds of the integer dtype. # Outside of those bounds we use the default NumPy behavior (either # cast or raise OverflowError). return Array._new(np.array(scalar, self.dtype)) def _normalize_two_args(x1, x2) -> Tuple[Array, Array]: """ Normalize inputs to two arg functions to fix type promotion rules NumPy deviates from the spec type promotion rules in cases where one argument is 0-dimensional and the other is not. For example: >>> import numpy as np >>> a = np.array([1.0], dtype=np.float32) >>> b = np.array(1.0, dtype=np.float64) >>> np.add(a, b) # The spec says this should be float64 array([2.], dtype=float32) To fix this, we add a dimension to the 0-dimension array before passing it through. This works because a dimension would be added anyway from broadcasting, so the resulting shape is the same, but this prevents NumPy from not promoting the dtype. """ # Another option would be to use signature=(x1.dtype, x2.dtype, None), # but that only works for ufuncs, so we would have to call the ufuncs # directly in the operator methods. One should also note that this # sort of trick wouldn't work for functions like searchsorted, which # don't do normal broadcasting, but there aren't any functions like # that in the array API namespace. if x1.ndim == 0 and x2.ndim != 0: # The _array[None] workaround was chosen because it is relatively # performant. broadcast_to(x1._array, x2.shape) is much slower. We # could also manually type promote x2, but that is more complicated # and about the same performance as this. x1 = Array._new(x1._array[None]) elif x2.ndim == 0 and x1.ndim != 0: x2 = Array._new(x2._array[None]) return (x1, x2) # Note: A large fraction of allowed indices are disallowed here (see the # docstring below) def _validate_index(self, key): """ Validate an index according to the array API. The array API specification only requires a subset of indices that are supported by NumPy. This function will reject any index that is allowed by NumPy but not required by the array API specification. We always raise ``IndexError`` on such indices (the spec does not require any specific behavior on them, but this makes the NumPy array API namespace a minimal implementation of the spec). See https://data-apis.org/array-api/latest/API_specification/indexing.html for the full list of required indexing behavior This function raises IndexError if the index ``key`` is invalid. It only raises ``IndexError`` on indices that are not already rejected by NumPy, as NumPy will already raise the appropriate error on such indices. ``shape`` may be None, in which case, only cases that are independent of the array shape are checked. The following cases are allowed by NumPy, but not specified by the array API specification: - Indices to not include an implicit ellipsis at the end. That is, every axis of an array must be explicitly indexed or an ellipsis included. This behaviour is sometimes referred to as flat indexing. - The start and stop of a slice may not be out of bounds. In particular, for a slice ``i:j:k`` on an axis of size ``n``, only the following are allowed: - ``i`` or ``j`` omitted (``None``). - ``-n <= i <= max(0, n - 1)``. - For ``k > 0`` or ``k`` omitted (``None``), ``-n <= j <= n``. - For ``k < 0``, ``-n - 1 <= j <= max(0, n - 1)``. - Boolean array indices are not allowed as part of a larger tuple index. - Integer array indices are not allowed (with the exception of 0-D arrays, which are treated the same as scalars). Additionally, it should be noted that indices that would return a scalar in NumPy will return a 0-D array. Array scalars are not allowed in the specification, only 0-D arrays. This is done in the ``Array._new`` constructor, not this function. """ _key = key if isinstance(key, tuple) else (key,) for i in _key: if isinstance(i, bool) or not ( isinstance(i, SupportsIndex) # i.e. ints or isinstance(i, slice) or i == Ellipsis or i is None or isinstance(i, Array) or isinstance(i, np.ndarray) ): raise IndexError( f"Single-axes index {i} has {type(i)=}, but only " "integers, slices (:), ellipsis (...), newaxis (None), " "zero-dimensional integer arrays and boolean arrays " "are specified in the Array API." ) nonexpanding_key = [] single_axes = [] n_ellipsis = 0 key_has_mask = False for i in _key: if i is not None: nonexpanding_key.append(i) if isinstance(i, Array) or isinstance(i, np.ndarray): if i.dtype in _boolean_dtypes: key_has_mask = True single_axes.append(i) else: # i must not be an array here, to avoid elementwise equals if i == Ellipsis: n_ellipsis += 1 else: single_axes.append(i) n_single_axes = len(single_axes) if n_ellipsis > 1: return # handled by ndarray elif n_ellipsis == 0: # Note boolean masks must be the sole index, which we check for # later on. if not key_has_mask and n_single_axes < self.ndim: raise IndexError( f"{self.ndim=}, but the multi-axes index only specifies " f"{n_single_axes} dimensions. If this was intentional, " "add a trailing ellipsis (...) which expands into as many " "slices (:) as necessary - this is what np.ndarray arrays " "implicitly do, but such flat indexing behaviour is not " "specified in the Array API." ) if n_ellipsis == 0: indexed_shape = self.shape else: ellipsis_start = None for pos, i in enumerate(nonexpanding_key): if not (isinstance(i, Array) or isinstance(i, np.ndarray)): if i == Ellipsis: ellipsis_start = pos break assert ellipsis_start is not None # sanity check ellipsis_end = self.ndim - (n_single_axes - ellipsis_start) indexed_shape = ( self.shape[:ellipsis_start] + self.shape[ellipsis_end:] ) for i, side in zip(single_axes, indexed_shape): if isinstance(i, slice): if side == 0: f_range = "0 (or None)" else: f_range = f"between -{side} and {side - 1} (or None)" if i.start is not None: try: start = operator.index(i.start) except TypeError: pass # handled by ndarray else: if not (-side <= start <= side): raise IndexError( f"Slice {i} contains {start=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds starts are not specified in " "the Array API)" ) if i.stop is not None: try: stop = operator.index(i.stop) except TypeError: pass # handled by ndarray else: if not (-side <= stop <= side): raise IndexError( f"Slice {i} contains {stop=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds stops are not specified in " "the Array API)" ) elif isinstance(i, Array): if i.dtype in _boolean_dtypes and len(_key) != 1: assert isinstance(key, tuple) # sanity check raise IndexError( f"Single-axes index {i} is a boolean array and " f"{len(key)=}, but masking is only specified in the " "Array API when the array is the sole index." ) elif i.dtype in _integer_dtypes and i.ndim != 0: raise IndexError( f"Single-axes index {i} is a non-zero-dimensional " "integer array, but advanced integer indexing is not " "specified in the Array API." ) elif isinstance(i, tuple): raise IndexError( f"Single-axes index {i} is a tuple, but nested tuple " "indices are not specified in the Array API." ) # Everything below this line is required by the spec. def __abs__(self: Array, /) -> Array: """ Performs the operation __abs__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __abs__") res = self._array.__abs__() return self.__class__._new(res) def __add__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __add__. """ other = self._check_allowed_dtypes(other, "numeric", "__add__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__add__(other._array) return self.__class__._new(res) def __and__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __and__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__and__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__and__(other._array) return self.__class__._new(res) def __array_namespace__( self: Array, /, *, api_version: Optional[str] = None ) -> types.ModuleType: if api_version is not None and not api_version.startswith("2021."): raise ValueError(f"Unrecognized array API version: {api_version!r}") return array_api def __bool__(self: Array, /) -> bool: """ Performs the operation __bool__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("bool is only allowed on arrays with 0 dimensions") if self.dtype not in _boolean_dtypes: raise ValueError("bool is only allowed on boolean arrays") res = self._array.__bool__() return res def __dlpack__(self: Array, /, *, stream: None = None) -> PyCapsule: """ Performs the operation __dlpack__. """ return self._array.__dlpack__(stream=stream) def __dlpack_device__(self: Array, /) -> Tuple[IntEnum, int]: """ Performs the operation __dlpack_device__. """ # Note: device support is required for this return self._array.__dlpack_device__() def __eq__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __eq__. """ # Even though "all" dtypes are allowed, we still require them to be # promotable with each other. other = self._check_allowed_dtypes(other, "all", "__eq__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__eq__(other._array) return self.__class__._new(res) def __float__(self: Array, /) -> float: """ Performs the operation __float__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("float is only allowed on arrays with 0 dimensions") if self.dtype not in _floating_dtypes: raise ValueError("float is only allowed on floating-point arrays") res = self._array.__float__() return res def __floordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __floordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__floordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__floordiv__(other._array) return self.__class__._new(res) def __ge__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ge__. """ other = self._check_allowed_dtypes(other, "numeric", "__ge__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ge__(other._array) return self.__class__._new(res) def __getitem__( self: Array, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], /, ) -> Array: """ Performs the operation __getitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array res = self._array.__getitem__(key) return self._new(res) def __gt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __gt__. """ other = self._check_allowed_dtypes(other, "numeric", "__gt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__gt__(other._array) return self.__class__._new(res) def __int__(self: Array, /) -> int: """ Performs the operation __int__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("int is only allowed on arrays with 0 dimensions") if self.dtype not in _integer_dtypes: raise ValueError("int is only allowed on integer arrays") res = self._array.__int__() return res def __index__(self: Array, /) -> int: """ Performs the operation __index__. """ res = self._array.__index__() return res def __invert__(self: Array, /) -> Array: """ Performs the operation __invert__. """ if self.dtype not in _integer_or_boolean_dtypes: raise TypeError("Only integer or boolean dtypes are allowed in __invert__") res = self._array.__invert__() return self.__class__._new(res) def __le__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __le__. """ other = self._check_allowed_dtypes(other, "numeric", "__le__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__le__(other._array) return self.__class__._new(res) def __lshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __lshift__. """ other = self._check_allowed_dtypes(other, "integer", "__lshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lshift__(other._array) return self.__class__._new(res) def __lt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __lt__. """ other = self._check_allowed_dtypes(other, "numeric", "__lt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lt__(other._array) return self.__class__._new(res) def __matmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __matmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__matmul__") if other is NotImplemented: return other res = self._array.__matmul__(other._array) return self.__class__._new(res) def __mod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mod__. """ other = self._check_allowed_dtypes(other, "numeric", "__mod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mod__(other._array) return self.__class__._new(res) def __mul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mul__. """ other = self._check_allowed_dtypes(other, "numeric", "__mul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mul__(other._array) return self.__class__._new(res) def __ne__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __ne__. """ other = self._check_allowed_dtypes(other, "all", "__ne__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ne__(other._array) return self.__class__._new(res) def __neg__(self: Array, /) -> Array: """ Performs the operation __neg__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __neg__") res = self._array.__neg__() return self.__class__._new(res) def __or__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __or__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__or__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__or__(other._array) return self.__class__._new(res) def __pos__(self: Array, /) -> Array: """ Performs the operation __pos__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __pos__") res = self._array.__pos__() return self.__class__._new(res) def __pow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __pow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__pow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow type promotion rules for 0-d # arrays, so we use pow() here instead. return pow(self, other) def __rshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rshift__(other._array) return self.__class__._new(res) def __setitem__( self, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], value: Union[int, float, bool, Array], /, ) -> None: """ Performs the operation __setitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array self._array.__setitem__(key, asarray(value)._array) def __sub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __sub__. """ other = self._check_allowed_dtypes(other, "numeric", "__sub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__sub__(other._array) return self.__class__._new(res) # PEP 484 requires int to be a subtype of float, but __truediv__ should # not accept int. def __truediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __truediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__truediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__truediv__(other._array) return self.__class__._new(res) def __xor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __xor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__xor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__xor__(other._array) return self.__class__._new(res) def __iadd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __iadd__. """ other = self._check_allowed_dtypes(other, "numeric", "__iadd__") if other is NotImplemented: return other self._array.__iadd__(other._array) return self def __radd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __radd__. """ other = self._check_allowed_dtypes(other, "numeric", "__radd__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__radd__(other._array) return self.__class__._new(res) def __iand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __iand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__iand__") if other is NotImplemented: return other self._array.__iand__(other._array) return self def __rand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rand__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rand__(other._array) return self.__class__._new(res) def __ifloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ifloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__ifloordiv__") if other is NotImplemented: return other self._array.__ifloordiv__(other._array) return self def __rfloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rfloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__rfloordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rfloordiv__(other._array) return self.__class__._new(res) def __ilshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __ilshift__. """ other = self._check_allowed_dtypes(other, "integer", "__ilshift__") if other is NotImplemented: return other self._array.__ilshift__(other._array) return self def __rlshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rlshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rlshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rlshift__(other._array) return self.__class__._new(res) def __imatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __imatmul__. """ # Note: NumPy does not implement __imatmul__. # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__imatmul__") if other is NotImplemented: return other # __imatmul__ can only be allowed when it would not change the shape # of self. other_shape = other.shape if self.shape == () or other_shape == (): raise ValueError("@= requires at least one dimension") if len(other_shape) == 1 or other_shape[-1] != other_shape[-2]: raise ValueError("@= cannot change the shape of the input array") self._array[:] = self._array.__matmul__(other._array) return self def __rmatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __rmatmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__rmatmul__") if other is NotImplemented: return other res = self._array.__rmatmul__(other._array) return self.__class__._new(res) def __imod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imod__. """ other = self._check_allowed_dtypes(other, "numeric", "__imod__") if other is NotImplemented: return other self._array.__imod__(other._array) return self def __rmod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmod__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmod__(other._array) return self.__class__._new(res) def __imul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imul__. """ other = self._check_allowed_dtypes(other, "numeric", "__imul__") if other is NotImplemented: return other self._array.__imul__(other._array) return self def __rmul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmul__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmul__(other._array) return self.__class__._new(res) def __ior__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ior__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ior__") if other is NotImplemented: return other self._array.__ior__(other._array) return self def __ror__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ror__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ror__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ror__(other._array) return self.__class__._new(res) def __ipow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ipow__. """ other = self._check_allowed_dtypes(other, "numeric", "__ipow__") if other is NotImplemented: return other self._array.__ipow__(other._array) return self def __rpow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rpow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__rpow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow the spec type promotion rules # for 0-d arrays, so we use pow() here instead. return pow(other, self) def __irshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __irshift__. """ other = self._check_allowed_dtypes(other, "integer", "__irshift__") if other is NotImplemented: return other self._array.__irshift__(other._array) return self def __rrshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rrshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rrshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rrshift__(other._array) return self.__class__._new(res) def __isub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __isub__. """ other = self._check_allowed_dtypes(other, "numeric", "__isub__") if other is NotImplemented: return other self._array.__isub__(other._array) return self def __rsub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rsub__. """ other = self._check_allowed_dtypes(other, "numeric", "__rsub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rsub__(other._array) return self.__class__._new(res) def __itruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __itruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__itruediv__") if other is NotImplemented: return other self._array.__itruediv__(other._array) return self def __rtruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __rtruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__rtruediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rtruediv__(other._array) return self.__class__._new(res) def __ixor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ixor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ixor__") if other is NotImplemented: return other self._array.__ixor__(other._array) return self def __rxor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rxor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rxor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rxor__(other._array) return self.__class__._new(res) def to_device(self: Array, device: Device, /, stream: None = None) -> Array: if stream is not None: raise ValueError("The stream argument to to_device() is not supported") if device == 'cpu': return self raise ValueError(f"Unsupported device {device!r}") def dtype(self) -> Dtype: """ Array API compatible wrapper for :py:meth:`np.ndarray.dtype <numpy.ndarray.dtype>`. See its docstring for more information. """ return self._array.dtype def device(self) -> Device: return "cpu" # Note: mT is new in array API spec (see matrix_transpose) def mT(self) -> Array: from .linalg import matrix_transpose return matrix_transpose(self) def ndim(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.ndim <numpy.ndarray.ndim>`. See its docstring for more information. """ return self._array.ndim def shape(self) -> Tuple[int, ...]: """ Array API compatible wrapper for :py:meth:`np.ndarray.shape <numpy.ndarray.shape>`. See its docstring for more information. """ return self._array.shape def size(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.size <numpy.ndarray.size>`. See its docstring for more information. """ return self._array.size def T(self) -> Array: """ Array API compatible wrapper for :py:meth:`np.ndarray.T <numpy.ndarray.T>`. See its docstring for more information. """ # Note: T only works on 2-dimensional arrays. See the corresponding # note in the specification: # https://data-apis.org/array-api/latest/API_specification/array_object.html#t if self.ndim != 2: raise ValueError("x.T requires x to have 2 dimensions. Use x.mT to transpose stacks of matrices and permute_dims() to permute dimensions.") return self.__class__._new(self._array.T) The provided code snippet includes necessary dependencies for implementing the `sqrt` function. Write a Python function `def sqrt(x: Array, /) -> Array` to solve the following problem: Array API compatible wrapper for :py:func:`np.sqrt <numpy.sqrt>`. See its docstring for more information. Here is the function: def sqrt(x: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.sqrt <numpy.sqrt>`. See its docstring for more information. """ if x.dtype not in _floating_dtypes: raise TypeError("Only floating-point dtypes are allowed in sqrt") return Array._new(np.sqrt(x._array))
Array API compatible wrapper for :py:func:`np.sqrt <numpy.sqrt>`. See its docstring for more information.
170,071
from __future__ import annotations from ._dtypes import ( _boolean_dtypes, _floating_dtypes, _integer_dtypes, _integer_or_boolean_dtypes, _numeric_dtypes, _result_type, ) from ._array_object import Array import numpy as np _numeric_dtypes = ( float32, float64, int8, int16, int32, int64, uint8, uint16, uint32, uint64, ) def _result_type(type1, type2): if (type1, type2) in _promotion_table: return _promotion_table[type1, type2] raise TypeError(f"{type1} and {type2} cannot be type promoted together") class Array: """ n-d array object for the array API namespace. See the docstring of :py:obj:`np.ndarray <numpy.ndarray>` for more information. This is a wrapper around numpy.ndarray that restricts the usage to only those things that are required by the array API namespace. Note, attributes on this object that start with a single underscore are not part of the API specification and should only be used internally. This object should not be constructed directly. Rather, use one of the creation functions, such as asarray(). """ _array: np.ndarray # Use a custom constructor instead of __init__, as manually initializing # this class is not supported API. def _new(cls, x, /): """ This is a private method for initializing the array API Array object. Functions outside of the array_api submodule should not use this method. Use one of the creation functions instead, such as ``asarray``. """ obj = super().__new__(cls) # Note: The spec does not have array scalars, only 0-D arrays. if isinstance(x, np.generic): # Convert the array scalar to a 0-D array x = np.asarray(x) if x.dtype not in _all_dtypes: raise TypeError( f"The array_api namespace does not support the dtype '{x.dtype}'" ) obj._array = x return obj # Prevent Array() from working def __new__(cls, *args, **kwargs): raise TypeError( "The array_api Array object should not be instantiated directly. Use an array creation function, such as asarray(), instead." ) # These functions are not required by the spec, but are implemented for # the sake of usability. def __str__(self: Array, /) -> str: """ Performs the operation __str__. """ return self._array.__str__().replace("array", "Array") def __repr__(self: Array, /) -> str: """ Performs the operation __repr__. """ suffix = f", dtype={self.dtype.name})" if 0 in self.shape: prefix = "empty(" mid = str(self.shape) else: prefix = "Array(" mid = np.array2string(self._array, separator=', ', prefix=prefix, suffix=suffix) return prefix + mid + suffix # This function is not required by the spec, but we implement it here for # convenience so that np.asarray(np.array_api.Array) will work. def __array__(self, dtype: None | np.dtype[Any] = None) -> npt.NDArray[Any]: """ Warning: this method is NOT part of the array API spec. Implementers of other libraries need not include it, and users should not assume it will be present in other implementations. """ return np.asarray(self._array, dtype=dtype) # These are various helper functions to make the array behavior match the # spec in places where it either deviates from or is more strict than # NumPy behavior def _check_allowed_dtypes(self, other: bool | int | float | Array, dtype_category: str, op: str) -> Array: """ Helper function for operators to only allow specific input dtypes Use like other = self._check_allowed_dtypes(other, 'numeric', '__add__') if other is NotImplemented: return other """ if self.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") if isinstance(other, (int, float, bool)): other = self._promote_scalar(other) elif isinstance(other, Array): if other.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") else: return NotImplemented # This will raise TypeError for type combinations that are not allowed # to promote in the spec (even if the NumPy array operator would # promote them). res_dtype = _result_type(self.dtype, other.dtype) if op.startswith("__i"): # Note: NumPy will allow in-place operators in some cases where # the type promoted operator does not match the left-hand side # operand. For example, # >>> a = np.array(1, dtype=np.int8) # >>> a += np.array(1, dtype=np.int16) # The spec explicitly disallows this. if res_dtype != self.dtype: raise TypeError( f"Cannot perform {op} with dtypes {self.dtype} and {other.dtype}" ) return other # Helper function to match the type promotion rules in the spec def _promote_scalar(self, scalar): """ Returns a promoted version of a Python scalar appropriate for use with operations on self. This may raise an OverflowError in cases where the scalar is an integer that is too large to fit in a NumPy integer dtype, or TypeError when the scalar type is incompatible with the dtype of self. """ # Note: Only Python scalar types that match the array dtype are # allowed. if isinstance(scalar, bool): if self.dtype not in _boolean_dtypes: raise TypeError( "Python bool scalars can only be promoted with bool arrays" ) elif isinstance(scalar, int): if self.dtype in _boolean_dtypes: raise TypeError( "Python int scalars cannot be promoted with bool arrays" ) elif isinstance(scalar, float): if self.dtype not in _floating_dtypes: raise TypeError( "Python float scalars can only be promoted with floating-point arrays." ) else: raise TypeError("'scalar' must be a Python scalar") # Note: scalars are unconditionally cast to the same dtype as the # array. # Note: the spec only specifies integer-dtype/int promotion # behavior for integers within the bounds of the integer dtype. # Outside of those bounds we use the default NumPy behavior (either # cast or raise OverflowError). return Array._new(np.array(scalar, self.dtype)) def _normalize_two_args(x1, x2) -> Tuple[Array, Array]: """ Normalize inputs to two arg functions to fix type promotion rules NumPy deviates from the spec type promotion rules in cases where one argument is 0-dimensional and the other is not. For example: >>> import numpy as np >>> a = np.array([1.0], dtype=np.float32) >>> b = np.array(1.0, dtype=np.float64) >>> np.add(a, b) # The spec says this should be float64 array([2.], dtype=float32) To fix this, we add a dimension to the 0-dimension array before passing it through. This works because a dimension would be added anyway from broadcasting, so the resulting shape is the same, but this prevents NumPy from not promoting the dtype. """ # Another option would be to use signature=(x1.dtype, x2.dtype, None), # but that only works for ufuncs, so we would have to call the ufuncs # directly in the operator methods. One should also note that this # sort of trick wouldn't work for functions like searchsorted, which # don't do normal broadcasting, but there aren't any functions like # that in the array API namespace. if x1.ndim == 0 and x2.ndim != 0: # The _array[None] workaround was chosen because it is relatively # performant. broadcast_to(x1._array, x2.shape) is much slower. We # could also manually type promote x2, but that is more complicated # and about the same performance as this. x1 = Array._new(x1._array[None]) elif x2.ndim == 0 and x1.ndim != 0: x2 = Array._new(x2._array[None]) return (x1, x2) # Note: A large fraction of allowed indices are disallowed here (see the # docstring below) def _validate_index(self, key): """ Validate an index according to the array API. The array API specification only requires a subset of indices that are supported by NumPy. This function will reject any index that is allowed by NumPy but not required by the array API specification. We always raise ``IndexError`` on such indices (the spec does not require any specific behavior on them, but this makes the NumPy array API namespace a minimal implementation of the spec). See https://data-apis.org/array-api/latest/API_specification/indexing.html for the full list of required indexing behavior This function raises IndexError if the index ``key`` is invalid. It only raises ``IndexError`` on indices that are not already rejected by NumPy, as NumPy will already raise the appropriate error on such indices. ``shape`` may be None, in which case, only cases that are independent of the array shape are checked. The following cases are allowed by NumPy, but not specified by the array API specification: - Indices to not include an implicit ellipsis at the end. That is, every axis of an array must be explicitly indexed or an ellipsis included. This behaviour is sometimes referred to as flat indexing. - The start and stop of a slice may not be out of bounds. In particular, for a slice ``i:j:k`` on an axis of size ``n``, only the following are allowed: - ``i`` or ``j`` omitted (``None``). - ``-n <= i <= max(0, n - 1)``. - For ``k > 0`` or ``k`` omitted (``None``), ``-n <= j <= n``. - For ``k < 0``, ``-n - 1 <= j <= max(0, n - 1)``. - Boolean array indices are not allowed as part of a larger tuple index. - Integer array indices are not allowed (with the exception of 0-D arrays, which are treated the same as scalars). Additionally, it should be noted that indices that would return a scalar in NumPy will return a 0-D array. Array scalars are not allowed in the specification, only 0-D arrays. This is done in the ``Array._new`` constructor, not this function. """ _key = key if isinstance(key, tuple) else (key,) for i in _key: if isinstance(i, bool) or not ( isinstance(i, SupportsIndex) # i.e. ints or isinstance(i, slice) or i == Ellipsis or i is None or isinstance(i, Array) or isinstance(i, np.ndarray) ): raise IndexError( f"Single-axes index {i} has {type(i)=}, but only " "integers, slices (:), ellipsis (...), newaxis (None), " "zero-dimensional integer arrays and boolean arrays " "are specified in the Array API." ) nonexpanding_key = [] single_axes = [] n_ellipsis = 0 key_has_mask = False for i in _key: if i is not None: nonexpanding_key.append(i) if isinstance(i, Array) or isinstance(i, np.ndarray): if i.dtype in _boolean_dtypes: key_has_mask = True single_axes.append(i) else: # i must not be an array here, to avoid elementwise equals if i == Ellipsis: n_ellipsis += 1 else: single_axes.append(i) n_single_axes = len(single_axes) if n_ellipsis > 1: return # handled by ndarray elif n_ellipsis == 0: # Note boolean masks must be the sole index, which we check for # later on. if not key_has_mask and n_single_axes < self.ndim: raise IndexError( f"{self.ndim=}, but the multi-axes index only specifies " f"{n_single_axes} dimensions. If this was intentional, " "add a trailing ellipsis (...) which expands into as many " "slices (:) as necessary - this is what np.ndarray arrays " "implicitly do, but such flat indexing behaviour is not " "specified in the Array API." ) if n_ellipsis == 0: indexed_shape = self.shape else: ellipsis_start = None for pos, i in enumerate(nonexpanding_key): if not (isinstance(i, Array) or isinstance(i, np.ndarray)): if i == Ellipsis: ellipsis_start = pos break assert ellipsis_start is not None # sanity check ellipsis_end = self.ndim - (n_single_axes - ellipsis_start) indexed_shape = ( self.shape[:ellipsis_start] + self.shape[ellipsis_end:] ) for i, side in zip(single_axes, indexed_shape): if isinstance(i, slice): if side == 0: f_range = "0 (or None)" else: f_range = f"between -{side} and {side - 1} (or None)" if i.start is not None: try: start = operator.index(i.start) except TypeError: pass # handled by ndarray else: if not (-side <= start <= side): raise IndexError( f"Slice {i} contains {start=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds starts are not specified in " "the Array API)" ) if i.stop is not None: try: stop = operator.index(i.stop) except TypeError: pass # handled by ndarray else: if not (-side <= stop <= side): raise IndexError( f"Slice {i} contains {stop=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds stops are not specified in " "the Array API)" ) elif isinstance(i, Array): if i.dtype in _boolean_dtypes and len(_key) != 1: assert isinstance(key, tuple) # sanity check raise IndexError( f"Single-axes index {i} is a boolean array and " f"{len(key)=}, but masking is only specified in the " "Array API when the array is the sole index." ) elif i.dtype in _integer_dtypes and i.ndim != 0: raise IndexError( f"Single-axes index {i} is a non-zero-dimensional " "integer array, but advanced integer indexing is not " "specified in the Array API." ) elif isinstance(i, tuple): raise IndexError( f"Single-axes index {i} is a tuple, but nested tuple " "indices are not specified in the Array API." ) # Everything below this line is required by the spec. def __abs__(self: Array, /) -> Array: """ Performs the operation __abs__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __abs__") res = self._array.__abs__() return self.__class__._new(res) def __add__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __add__. """ other = self._check_allowed_dtypes(other, "numeric", "__add__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__add__(other._array) return self.__class__._new(res) def __and__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __and__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__and__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__and__(other._array) return self.__class__._new(res) def __array_namespace__( self: Array, /, *, api_version: Optional[str] = None ) -> types.ModuleType: if api_version is not None and not api_version.startswith("2021."): raise ValueError(f"Unrecognized array API version: {api_version!r}") return array_api def __bool__(self: Array, /) -> bool: """ Performs the operation __bool__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("bool is only allowed on arrays with 0 dimensions") if self.dtype not in _boolean_dtypes: raise ValueError("bool is only allowed on boolean arrays") res = self._array.__bool__() return res def __dlpack__(self: Array, /, *, stream: None = None) -> PyCapsule: """ Performs the operation __dlpack__. """ return self._array.__dlpack__(stream=stream) def __dlpack_device__(self: Array, /) -> Tuple[IntEnum, int]: """ Performs the operation __dlpack_device__. """ # Note: device support is required for this return self._array.__dlpack_device__() def __eq__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __eq__. """ # Even though "all" dtypes are allowed, we still require them to be # promotable with each other. other = self._check_allowed_dtypes(other, "all", "__eq__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__eq__(other._array) return self.__class__._new(res) def __float__(self: Array, /) -> float: """ Performs the operation __float__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("float is only allowed on arrays with 0 dimensions") if self.dtype not in _floating_dtypes: raise ValueError("float is only allowed on floating-point arrays") res = self._array.__float__() return res def __floordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __floordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__floordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__floordiv__(other._array) return self.__class__._new(res) def __ge__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ge__. """ other = self._check_allowed_dtypes(other, "numeric", "__ge__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ge__(other._array) return self.__class__._new(res) def __getitem__( self: Array, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], /, ) -> Array: """ Performs the operation __getitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array res = self._array.__getitem__(key) return self._new(res) def __gt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __gt__. """ other = self._check_allowed_dtypes(other, "numeric", "__gt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__gt__(other._array) return self.__class__._new(res) def __int__(self: Array, /) -> int: """ Performs the operation __int__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("int is only allowed on arrays with 0 dimensions") if self.dtype not in _integer_dtypes: raise ValueError("int is only allowed on integer arrays") res = self._array.__int__() return res def __index__(self: Array, /) -> int: """ Performs the operation __index__. """ res = self._array.__index__() return res def __invert__(self: Array, /) -> Array: """ Performs the operation __invert__. """ if self.dtype not in _integer_or_boolean_dtypes: raise TypeError("Only integer or boolean dtypes are allowed in __invert__") res = self._array.__invert__() return self.__class__._new(res) def __le__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __le__. """ other = self._check_allowed_dtypes(other, "numeric", "__le__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__le__(other._array) return self.__class__._new(res) def __lshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __lshift__. """ other = self._check_allowed_dtypes(other, "integer", "__lshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lshift__(other._array) return self.__class__._new(res) def __lt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __lt__. """ other = self._check_allowed_dtypes(other, "numeric", "__lt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lt__(other._array) return self.__class__._new(res) def __matmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __matmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__matmul__") if other is NotImplemented: return other res = self._array.__matmul__(other._array) return self.__class__._new(res) def __mod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mod__. """ other = self._check_allowed_dtypes(other, "numeric", "__mod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mod__(other._array) return self.__class__._new(res) def __mul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mul__. """ other = self._check_allowed_dtypes(other, "numeric", "__mul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mul__(other._array) return self.__class__._new(res) def __ne__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __ne__. """ other = self._check_allowed_dtypes(other, "all", "__ne__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ne__(other._array) return self.__class__._new(res) def __neg__(self: Array, /) -> Array: """ Performs the operation __neg__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __neg__") res = self._array.__neg__() return self.__class__._new(res) def __or__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __or__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__or__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__or__(other._array) return self.__class__._new(res) def __pos__(self: Array, /) -> Array: """ Performs the operation __pos__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __pos__") res = self._array.__pos__() return self.__class__._new(res) def __pow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __pow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__pow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow type promotion rules for 0-d # arrays, so we use pow() here instead. return pow(self, other) def __rshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rshift__(other._array) return self.__class__._new(res) def __setitem__( self, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], value: Union[int, float, bool, Array], /, ) -> None: """ Performs the operation __setitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array self._array.__setitem__(key, asarray(value)._array) def __sub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __sub__. """ other = self._check_allowed_dtypes(other, "numeric", "__sub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__sub__(other._array) return self.__class__._new(res) # PEP 484 requires int to be a subtype of float, but __truediv__ should # not accept int. def __truediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __truediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__truediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__truediv__(other._array) return self.__class__._new(res) def __xor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __xor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__xor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__xor__(other._array) return self.__class__._new(res) def __iadd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __iadd__. """ other = self._check_allowed_dtypes(other, "numeric", "__iadd__") if other is NotImplemented: return other self._array.__iadd__(other._array) return self def __radd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __radd__. """ other = self._check_allowed_dtypes(other, "numeric", "__radd__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__radd__(other._array) return self.__class__._new(res) def __iand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __iand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__iand__") if other is NotImplemented: return other self._array.__iand__(other._array) return self def __rand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rand__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rand__(other._array) return self.__class__._new(res) def __ifloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ifloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__ifloordiv__") if other is NotImplemented: return other self._array.__ifloordiv__(other._array) return self def __rfloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rfloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__rfloordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rfloordiv__(other._array) return self.__class__._new(res) def __ilshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __ilshift__. """ other = self._check_allowed_dtypes(other, "integer", "__ilshift__") if other is NotImplemented: return other self._array.__ilshift__(other._array) return self def __rlshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rlshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rlshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rlshift__(other._array) return self.__class__._new(res) def __imatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __imatmul__. """ # Note: NumPy does not implement __imatmul__. # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__imatmul__") if other is NotImplemented: return other # __imatmul__ can only be allowed when it would not change the shape # of self. other_shape = other.shape if self.shape == () or other_shape == (): raise ValueError("@= requires at least one dimension") if len(other_shape) == 1 or other_shape[-1] != other_shape[-2]: raise ValueError("@= cannot change the shape of the input array") self._array[:] = self._array.__matmul__(other._array) return self def __rmatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __rmatmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__rmatmul__") if other is NotImplemented: return other res = self._array.__rmatmul__(other._array) return self.__class__._new(res) def __imod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imod__. """ other = self._check_allowed_dtypes(other, "numeric", "__imod__") if other is NotImplemented: return other self._array.__imod__(other._array) return self def __rmod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmod__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmod__(other._array) return self.__class__._new(res) def __imul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imul__. """ other = self._check_allowed_dtypes(other, "numeric", "__imul__") if other is NotImplemented: return other self._array.__imul__(other._array) return self def __rmul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmul__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmul__(other._array) return self.__class__._new(res) def __ior__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ior__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ior__") if other is NotImplemented: return other self._array.__ior__(other._array) return self def __ror__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ror__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ror__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ror__(other._array) return self.__class__._new(res) def __ipow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ipow__. """ other = self._check_allowed_dtypes(other, "numeric", "__ipow__") if other is NotImplemented: return other self._array.__ipow__(other._array) return self def __rpow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rpow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__rpow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow the spec type promotion rules # for 0-d arrays, so we use pow() here instead. return pow(other, self) def __irshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __irshift__. """ other = self._check_allowed_dtypes(other, "integer", "__irshift__") if other is NotImplemented: return other self._array.__irshift__(other._array) return self def __rrshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rrshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rrshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rrshift__(other._array) return self.__class__._new(res) def __isub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __isub__. """ other = self._check_allowed_dtypes(other, "numeric", "__isub__") if other is NotImplemented: return other self._array.__isub__(other._array) return self def __rsub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rsub__. """ other = self._check_allowed_dtypes(other, "numeric", "__rsub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rsub__(other._array) return self.__class__._new(res) def __itruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __itruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__itruediv__") if other is NotImplemented: return other self._array.__itruediv__(other._array) return self def __rtruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __rtruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__rtruediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rtruediv__(other._array) return self.__class__._new(res) def __ixor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ixor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ixor__") if other is NotImplemented: return other self._array.__ixor__(other._array) return self def __rxor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rxor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rxor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rxor__(other._array) return self.__class__._new(res) def to_device(self: Array, device: Device, /, stream: None = None) -> Array: if stream is not None: raise ValueError("The stream argument to to_device() is not supported") if device == 'cpu': return self raise ValueError(f"Unsupported device {device!r}") def dtype(self) -> Dtype: """ Array API compatible wrapper for :py:meth:`np.ndarray.dtype <numpy.ndarray.dtype>`. See its docstring for more information. """ return self._array.dtype def device(self) -> Device: return "cpu" # Note: mT is new in array API spec (see matrix_transpose) def mT(self) -> Array: from .linalg import matrix_transpose return matrix_transpose(self) def ndim(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.ndim <numpy.ndarray.ndim>`. See its docstring for more information. """ return self._array.ndim def shape(self) -> Tuple[int, ...]: """ Array API compatible wrapper for :py:meth:`np.ndarray.shape <numpy.ndarray.shape>`. See its docstring for more information. """ return self._array.shape def size(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.size <numpy.ndarray.size>`. See its docstring for more information. """ return self._array.size def T(self) -> Array: """ Array API compatible wrapper for :py:meth:`np.ndarray.T <numpy.ndarray.T>`. See its docstring for more information. """ # Note: T only works on 2-dimensional arrays. See the corresponding # note in the specification: # https://data-apis.org/array-api/latest/API_specification/array_object.html#t if self.ndim != 2: raise ValueError("x.T requires x to have 2 dimensions. Use x.mT to transpose stacks of matrices and permute_dims() to permute dimensions.") return self.__class__._new(self._array.T) The provided code snippet includes necessary dependencies for implementing the `subtract` function. Write a Python function `def subtract(x1: Array, x2: Array, /) -> Array` to solve the following problem: Array API compatible wrapper for :py:func:`np.subtract <numpy.subtract>`. See its docstring for more information. Here is the function: def subtract(x1: Array, x2: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.subtract <numpy.subtract>`. See its docstring for more information. """ if x1.dtype not in _numeric_dtypes or x2.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in subtract") # Call result type here just to raise on disallowed type combinations _result_type(x1.dtype, x2.dtype) x1, x2 = Array._normalize_two_args(x1, x2) return Array._new(np.subtract(x1._array, x2._array))
Array API compatible wrapper for :py:func:`np.subtract <numpy.subtract>`. See its docstring for more information.
170,072
from __future__ import annotations from ._dtypes import ( _boolean_dtypes, _floating_dtypes, _integer_dtypes, _integer_or_boolean_dtypes, _numeric_dtypes, _result_type, ) from ._array_object import Array import numpy as np _floating_dtypes = (float32, float64) class Array: """ n-d array object for the array API namespace. See the docstring of :py:obj:`np.ndarray <numpy.ndarray>` for more information. This is a wrapper around numpy.ndarray that restricts the usage to only those things that are required by the array API namespace. Note, attributes on this object that start with a single underscore are not part of the API specification and should only be used internally. This object should not be constructed directly. Rather, use one of the creation functions, such as asarray(). """ _array: np.ndarray # Use a custom constructor instead of __init__, as manually initializing # this class is not supported API. def _new(cls, x, /): """ This is a private method for initializing the array API Array object. Functions outside of the array_api submodule should not use this method. Use one of the creation functions instead, such as ``asarray``. """ obj = super().__new__(cls) # Note: The spec does not have array scalars, only 0-D arrays. if isinstance(x, np.generic): # Convert the array scalar to a 0-D array x = np.asarray(x) if x.dtype not in _all_dtypes: raise TypeError( f"The array_api namespace does not support the dtype '{x.dtype}'" ) obj._array = x return obj # Prevent Array() from working def __new__(cls, *args, **kwargs): raise TypeError( "The array_api Array object should not be instantiated directly. Use an array creation function, such as asarray(), instead." ) # These functions are not required by the spec, but are implemented for # the sake of usability. def __str__(self: Array, /) -> str: """ Performs the operation __str__. """ return self._array.__str__().replace("array", "Array") def __repr__(self: Array, /) -> str: """ Performs the operation __repr__. """ suffix = f", dtype={self.dtype.name})" if 0 in self.shape: prefix = "empty(" mid = str(self.shape) else: prefix = "Array(" mid = np.array2string(self._array, separator=', ', prefix=prefix, suffix=suffix) return prefix + mid + suffix # This function is not required by the spec, but we implement it here for # convenience so that np.asarray(np.array_api.Array) will work. def __array__(self, dtype: None | np.dtype[Any] = None) -> npt.NDArray[Any]: """ Warning: this method is NOT part of the array API spec. Implementers of other libraries need not include it, and users should not assume it will be present in other implementations. """ return np.asarray(self._array, dtype=dtype) # These are various helper functions to make the array behavior match the # spec in places where it either deviates from or is more strict than # NumPy behavior def _check_allowed_dtypes(self, other: bool | int | float | Array, dtype_category: str, op: str) -> Array: """ Helper function for operators to only allow specific input dtypes Use like other = self._check_allowed_dtypes(other, 'numeric', '__add__') if other is NotImplemented: return other """ if self.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") if isinstance(other, (int, float, bool)): other = self._promote_scalar(other) elif isinstance(other, Array): if other.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") else: return NotImplemented # This will raise TypeError for type combinations that are not allowed # to promote in the spec (even if the NumPy array operator would # promote them). res_dtype = _result_type(self.dtype, other.dtype) if op.startswith("__i"): # Note: NumPy will allow in-place operators in some cases where # the type promoted operator does not match the left-hand side # operand. For example, # >>> a = np.array(1, dtype=np.int8) # >>> a += np.array(1, dtype=np.int16) # The spec explicitly disallows this. if res_dtype != self.dtype: raise TypeError( f"Cannot perform {op} with dtypes {self.dtype} and {other.dtype}" ) return other # Helper function to match the type promotion rules in the spec def _promote_scalar(self, scalar): """ Returns a promoted version of a Python scalar appropriate for use with operations on self. This may raise an OverflowError in cases where the scalar is an integer that is too large to fit in a NumPy integer dtype, or TypeError when the scalar type is incompatible with the dtype of self. """ # Note: Only Python scalar types that match the array dtype are # allowed. if isinstance(scalar, bool): if self.dtype not in _boolean_dtypes: raise TypeError( "Python bool scalars can only be promoted with bool arrays" ) elif isinstance(scalar, int): if self.dtype in _boolean_dtypes: raise TypeError( "Python int scalars cannot be promoted with bool arrays" ) elif isinstance(scalar, float): if self.dtype not in _floating_dtypes: raise TypeError( "Python float scalars can only be promoted with floating-point arrays." ) else: raise TypeError("'scalar' must be a Python scalar") # Note: scalars are unconditionally cast to the same dtype as the # array. # Note: the spec only specifies integer-dtype/int promotion # behavior for integers within the bounds of the integer dtype. # Outside of those bounds we use the default NumPy behavior (either # cast or raise OverflowError). return Array._new(np.array(scalar, self.dtype)) def _normalize_two_args(x1, x2) -> Tuple[Array, Array]: """ Normalize inputs to two arg functions to fix type promotion rules NumPy deviates from the spec type promotion rules in cases where one argument is 0-dimensional and the other is not. For example: >>> import numpy as np >>> a = np.array([1.0], dtype=np.float32) >>> b = np.array(1.0, dtype=np.float64) >>> np.add(a, b) # The spec says this should be float64 array([2.], dtype=float32) To fix this, we add a dimension to the 0-dimension array before passing it through. This works because a dimension would be added anyway from broadcasting, so the resulting shape is the same, but this prevents NumPy from not promoting the dtype. """ # Another option would be to use signature=(x1.dtype, x2.dtype, None), # but that only works for ufuncs, so we would have to call the ufuncs # directly in the operator methods. One should also note that this # sort of trick wouldn't work for functions like searchsorted, which # don't do normal broadcasting, but there aren't any functions like # that in the array API namespace. if x1.ndim == 0 and x2.ndim != 0: # The _array[None] workaround was chosen because it is relatively # performant. broadcast_to(x1._array, x2.shape) is much slower. We # could also manually type promote x2, but that is more complicated # and about the same performance as this. x1 = Array._new(x1._array[None]) elif x2.ndim == 0 and x1.ndim != 0: x2 = Array._new(x2._array[None]) return (x1, x2) # Note: A large fraction of allowed indices are disallowed here (see the # docstring below) def _validate_index(self, key): """ Validate an index according to the array API. The array API specification only requires a subset of indices that are supported by NumPy. This function will reject any index that is allowed by NumPy but not required by the array API specification. We always raise ``IndexError`` on such indices (the spec does not require any specific behavior on them, but this makes the NumPy array API namespace a minimal implementation of the spec). See https://data-apis.org/array-api/latest/API_specification/indexing.html for the full list of required indexing behavior This function raises IndexError if the index ``key`` is invalid. It only raises ``IndexError`` on indices that are not already rejected by NumPy, as NumPy will already raise the appropriate error on such indices. ``shape`` may be None, in which case, only cases that are independent of the array shape are checked. The following cases are allowed by NumPy, but not specified by the array API specification: - Indices to not include an implicit ellipsis at the end. That is, every axis of an array must be explicitly indexed or an ellipsis included. This behaviour is sometimes referred to as flat indexing. - The start and stop of a slice may not be out of bounds. In particular, for a slice ``i:j:k`` on an axis of size ``n``, only the following are allowed: - ``i`` or ``j`` omitted (``None``). - ``-n <= i <= max(0, n - 1)``. - For ``k > 0`` or ``k`` omitted (``None``), ``-n <= j <= n``. - For ``k < 0``, ``-n - 1 <= j <= max(0, n - 1)``. - Boolean array indices are not allowed as part of a larger tuple index. - Integer array indices are not allowed (with the exception of 0-D arrays, which are treated the same as scalars). Additionally, it should be noted that indices that would return a scalar in NumPy will return a 0-D array. Array scalars are not allowed in the specification, only 0-D arrays. This is done in the ``Array._new`` constructor, not this function. """ _key = key if isinstance(key, tuple) else (key,) for i in _key: if isinstance(i, bool) or not ( isinstance(i, SupportsIndex) # i.e. ints or isinstance(i, slice) or i == Ellipsis or i is None or isinstance(i, Array) or isinstance(i, np.ndarray) ): raise IndexError( f"Single-axes index {i} has {type(i)=}, but only " "integers, slices (:), ellipsis (...), newaxis (None), " "zero-dimensional integer arrays and boolean arrays " "are specified in the Array API." ) nonexpanding_key = [] single_axes = [] n_ellipsis = 0 key_has_mask = False for i in _key: if i is not None: nonexpanding_key.append(i) if isinstance(i, Array) or isinstance(i, np.ndarray): if i.dtype in _boolean_dtypes: key_has_mask = True single_axes.append(i) else: # i must not be an array here, to avoid elementwise equals if i == Ellipsis: n_ellipsis += 1 else: single_axes.append(i) n_single_axes = len(single_axes) if n_ellipsis > 1: return # handled by ndarray elif n_ellipsis == 0: # Note boolean masks must be the sole index, which we check for # later on. if not key_has_mask and n_single_axes < self.ndim: raise IndexError( f"{self.ndim=}, but the multi-axes index only specifies " f"{n_single_axes} dimensions. If this was intentional, " "add a trailing ellipsis (...) which expands into as many " "slices (:) as necessary - this is what np.ndarray arrays " "implicitly do, but such flat indexing behaviour is not " "specified in the Array API." ) if n_ellipsis == 0: indexed_shape = self.shape else: ellipsis_start = None for pos, i in enumerate(nonexpanding_key): if not (isinstance(i, Array) or isinstance(i, np.ndarray)): if i == Ellipsis: ellipsis_start = pos break assert ellipsis_start is not None # sanity check ellipsis_end = self.ndim - (n_single_axes - ellipsis_start) indexed_shape = ( self.shape[:ellipsis_start] + self.shape[ellipsis_end:] ) for i, side in zip(single_axes, indexed_shape): if isinstance(i, slice): if side == 0: f_range = "0 (or None)" else: f_range = f"between -{side} and {side - 1} (or None)" if i.start is not None: try: start = operator.index(i.start) except TypeError: pass # handled by ndarray else: if not (-side <= start <= side): raise IndexError( f"Slice {i} contains {start=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds starts are not specified in " "the Array API)" ) if i.stop is not None: try: stop = operator.index(i.stop) except TypeError: pass # handled by ndarray else: if not (-side <= stop <= side): raise IndexError( f"Slice {i} contains {stop=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds stops are not specified in " "the Array API)" ) elif isinstance(i, Array): if i.dtype in _boolean_dtypes and len(_key) != 1: assert isinstance(key, tuple) # sanity check raise IndexError( f"Single-axes index {i} is a boolean array and " f"{len(key)=}, but masking is only specified in the " "Array API when the array is the sole index." ) elif i.dtype in _integer_dtypes and i.ndim != 0: raise IndexError( f"Single-axes index {i} is a non-zero-dimensional " "integer array, but advanced integer indexing is not " "specified in the Array API." ) elif isinstance(i, tuple): raise IndexError( f"Single-axes index {i} is a tuple, but nested tuple " "indices are not specified in the Array API." ) # Everything below this line is required by the spec. def __abs__(self: Array, /) -> Array: """ Performs the operation __abs__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __abs__") res = self._array.__abs__() return self.__class__._new(res) def __add__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __add__. """ other = self._check_allowed_dtypes(other, "numeric", "__add__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__add__(other._array) return self.__class__._new(res) def __and__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __and__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__and__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__and__(other._array) return self.__class__._new(res) def __array_namespace__( self: Array, /, *, api_version: Optional[str] = None ) -> types.ModuleType: if api_version is not None and not api_version.startswith("2021."): raise ValueError(f"Unrecognized array API version: {api_version!r}") return array_api def __bool__(self: Array, /) -> bool: """ Performs the operation __bool__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("bool is only allowed on arrays with 0 dimensions") if self.dtype not in _boolean_dtypes: raise ValueError("bool is only allowed on boolean arrays") res = self._array.__bool__() return res def __dlpack__(self: Array, /, *, stream: None = None) -> PyCapsule: """ Performs the operation __dlpack__. """ return self._array.__dlpack__(stream=stream) def __dlpack_device__(self: Array, /) -> Tuple[IntEnum, int]: """ Performs the operation __dlpack_device__. """ # Note: device support is required for this return self._array.__dlpack_device__() def __eq__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __eq__. """ # Even though "all" dtypes are allowed, we still require them to be # promotable with each other. other = self._check_allowed_dtypes(other, "all", "__eq__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__eq__(other._array) return self.__class__._new(res) def __float__(self: Array, /) -> float: """ Performs the operation __float__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("float is only allowed on arrays with 0 dimensions") if self.dtype not in _floating_dtypes: raise ValueError("float is only allowed on floating-point arrays") res = self._array.__float__() return res def __floordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __floordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__floordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__floordiv__(other._array) return self.__class__._new(res) def __ge__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ge__. """ other = self._check_allowed_dtypes(other, "numeric", "__ge__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ge__(other._array) return self.__class__._new(res) def __getitem__( self: Array, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], /, ) -> Array: """ Performs the operation __getitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array res = self._array.__getitem__(key) return self._new(res) def __gt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __gt__. """ other = self._check_allowed_dtypes(other, "numeric", "__gt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__gt__(other._array) return self.__class__._new(res) def __int__(self: Array, /) -> int: """ Performs the operation __int__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("int is only allowed on arrays with 0 dimensions") if self.dtype not in _integer_dtypes: raise ValueError("int is only allowed on integer arrays") res = self._array.__int__() return res def __index__(self: Array, /) -> int: """ Performs the operation __index__. """ res = self._array.__index__() return res def __invert__(self: Array, /) -> Array: """ Performs the operation __invert__. """ if self.dtype not in _integer_or_boolean_dtypes: raise TypeError("Only integer or boolean dtypes are allowed in __invert__") res = self._array.__invert__() return self.__class__._new(res) def __le__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __le__. """ other = self._check_allowed_dtypes(other, "numeric", "__le__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__le__(other._array) return self.__class__._new(res) def __lshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __lshift__. """ other = self._check_allowed_dtypes(other, "integer", "__lshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lshift__(other._array) return self.__class__._new(res) def __lt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __lt__. """ other = self._check_allowed_dtypes(other, "numeric", "__lt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lt__(other._array) return self.__class__._new(res) def __matmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __matmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__matmul__") if other is NotImplemented: return other res = self._array.__matmul__(other._array) return self.__class__._new(res) def __mod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mod__. """ other = self._check_allowed_dtypes(other, "numeric", "__mod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mod__(other._array) return self.__class__._new(res) def __mul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mul__. """ other = self._check_allowed_dtypes(other, "numeric", "__mul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mul__(other._array) return self.__class__._new(res) def __ne__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __ne__. """ other = self._check_allowed_dtypes(other, "all", "__ne__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ne__(other._array) return self.__class__._new(res) def __neg__(self: Array, /) -> Array: """ Performs the operation __neg__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __neg__") res = self._array.__neg__() return self.__class__._new(res) def __or__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __or__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__or__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__or__(other._array) return self.__class__._new(res) def __pos__(self: Array, /) -> Array: """ Performs the operation __pos__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __pos__") res = self._array.__pos__() return self.__class__._new(res) def __pow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __pow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__pow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow type promotion rules for 0-d # arrays, so we use pow() here instead. return pow(self, other) def __rshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rshift__(other._array) return self.__class__._new(res) def __setitem__( self, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], value: Union[int, float, bool, Array], /, ) -> None: """ Performs the operation __setitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array self._array.__setitem__(key, asarray(value)._array) def __sub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __sub__. """ other = self._check_allowed_dtypes(other, "numeric", "__sub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__sub__(other._array) return self.__class__._new(res) # PEP 484 requires int to be a subtype of float, but __truediv__ should # not accept int. def __truediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __truediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__truediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__truediv__(other._array) return self.__class__._new(res) def __xor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __xor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__xor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__xor__(other._array) return self.__class__._new(res) def __iadd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __iadd__. """ other = self._check_allowed_dtypes(other, "numeric", "__iadd__") if other is NotImplemented: return other self._array.__iadd__(other._array) return self def __radd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __radd__. """ other = self._check_allowed_dtypes(other, "numeric", "__radd__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__radd__(other._array) return self.__class__._new(res) def __iand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __iand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__iand__") if other is NotImplemented: return other self._array.__iand__(other._array) return self def __rand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rand__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rand__(other._array) return self.__class__._new(res) def __ifloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ifloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__ifloordiv__") if other is NotImplemented: return other self._array.__ifloordiv__(other._array) return self def __rfloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rfloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__rfloordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rfloordiv__(other._array) return self.__class__._new(res) def __ilshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __ilshift__. """ other = self._check_allowed_dtypes(other, "integer", "__ilshift__") if other is NotImplemented: return other self._array.__ilshift__(other._array) return self def __rlshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rlshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rlshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rlshift__(other._array) return self.__class__._new(res) def __imatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __imatmul__. """ # Note: NumPy does not implement __imatmul__. # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__imatmul__") if other is NotImplemented: return other # __imatmul__ can only be allowed when it would not change the shape # of self. other_shape = other.shape if self.shape == () or other_shape == (): raise ValueError("@= requires at least one dimension") if len(other_shape) == 1 or other_shape[-1] != other_shape[-2]: raise ValueError("@= cannot change the shape of the input array") self._array[:] = self._array.__matmul__(other._array) return self def __rmatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __rmatmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__rmatmul__") if other is NotImplemented: return other res = self._array.__rmatmul__(other._array) return self.__class__._new(res) def __imod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imod__. """ other = self._check_allowed_dtypes(other, "numeric", "__imod__") if other is NotImplemented: return other self._array.__imod__(other._array) return self def __rmod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmod__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmod__(other._array) return self.__class__._new(res) def __imul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imul__. """ other = self._check_allowed_dtypes(other, "numeric", "__imul__") if other is NotImplemented: return other self._array.__imul__(other._array) return self def __rmul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmul__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmul__(other._array) return self.__class__._new(res) def __ior__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ior__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ior__") if other is NotImplemented: return other self._array.__ior__(other._array) return self def __ror__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ror__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ror__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ror__(other._array) return self.__class__._new(res) def __ipow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ipow__. """ other = self._check_allowed_dtypes(other, "numeric", "__ipow__") if other is NotImplemented: return other self._array.__ipow__(other._array) return self def __rpow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rpow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__rpow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow the spec type promotion rules # for 0-d arrays, so we use pow() here instead. return pow(other, self) def __irshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __irshift__. """ other = self._check_allowed_dtypes(other, "integer", "__irshift__") if other is NotImplemented: return other self._array.__irshift__(other._array) return self def __rrshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rrshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rrshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rrshift__(other._array) return self.__class__._new(res) def __isub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __isub__. """ other = self._check_allowed_dtypes(other, "numeric", "__isub__") if other is NotImplemented: return other self._array.__isub__(other._array) return self def __rsub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rsub__. """ other = self._check_allowed_dtypes(other, "numeric", "__rsub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rsub__(other._array) return self.__class__._new(res) def __itruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __itruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__itruediv__") if other is NotImplemented: return other self._array.__itruediv__(other._array) return self def __rtruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __rtruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__rtruediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rtruediv__(other._array) return self.__class__._new(res) def __ixor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ixor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ixor__") if other is NotImplemented: return other self._array.__ixor__(other._array) return self def __rxor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rxor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rxor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rxor__(other._array) return self.__class__._new(res) def to_device(self: Array, device: Device, /, stream: None = None) -> Array: if stream is not None: raise ValueError("The stream argument to to_device() is not supported") if device == 'cpu': return self raise ValueError(f"Unsupported device {device!r}") def dtype(self) -> Dtype: """ Array API compatible wrapper for :py:meth:`np.ndarray.dtype <numpy.ndarray.dtype>`. See its docstring for more information. """ return self._array.dtype def device(self) -> Device: return "cpu" # Note: mT is new in array API spec (see matrix_transpose) def mT(self) -> Array: from .linalg import matrix_transpose return matrix_transpose(self) def ndim(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.ndim <numpy.ndarray.ndim>`. See its docstring for more information. """ return self._array.ndim def shape(self) -> Tuple[int, ...]: """ Array API compatible wrapper for :py:meth:`np.ndarray.shape <numpy.ndarray.shape>`. See its docstring for more information. """ return self._array.shape def size(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.size <numpy.ndarray.size>`. See its docstring for more information. """ return self._array.size def T(self) -> Array: """ Array API compatible wrapper for :py:meth:`np.ndarray.T <numpy.ndarray.T>`. See its docstring for more information. """ # Note: T only works on 2-dimensional arrays. See the corresponding # note in the specification: # https://data-apis.org/array-api/latest/API_specification/array_object.html#t if self.ndim != 2: raise ValueError("x.T requires x to have 2 dimensions. Use x.mT to transpose stacks of matrices and permute_dims() to permute dimensions.") return self.__class__._new(self._array.T) The provided code snippet includes necessary dependencies for implementing the `tan` function. Write a Python function `def tan(x: Array, /) -> Array` to solve the following problem: Array API compatible wrapper for :py:func:`np.tan <numpy.tan>`. See its docstring for more information. Here is the function: def tan(x: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.tan <numpy.tan>`. See its docstring for more information. """ if x.dtype not in _floating_dtypes: raise TypeError("Only floating-point dtypes are allowed in tan") return Array._new(np.tan(x._array))
Array API compatible wrapper for :py:func:`np.tan <numpy.tan>`. See its docstring for more information.
170,073
from __future__ import annotations from ._dtypes import ( _boolean_dtypes, _floating_dtypes, _integer_dtypes, _integer_or_boolean_dtypes, _numeric_dtypes, _result_type, ) from ._array_object import Array import numpy as np _floating_dtypes = (float32, float64) class Array: """ n-d array object for the array API namespace. See the docstring of :py:obj:`np.ndarray <numpy.ndarray>` for more information. This is a wrapper around numpy.ndarray that restricts the usage to only those things that are required by the array API namespace. Note, attributes on this object that start with a single underscore are not part of the API specification and should only be used internally. This object should not be constructed directly. Rather, use one of the creation functions, such as asarray(). """ _array: np.ndarray # Use a custom constructor instead of __init__, as manually initializing # this class is not supported API. def _new(cls, x, /): """ This is a private method for initializing the array API Array object. Functions outside of the array_api submodule should not use this method. Use one of the creation functions instead, such as ``asarray``. """ obj = super().__new__(cls) # Note: The spec does not have array scalars, only 0-D arrays. if isinstance(x, np.generic): # Convert the array scalar to a 0-D array x = np.asarray(x) if x.dtype not in _all_dtypes: raise TypeError( f"The array_api namespace does not support the dtype '{x.dtype}'" ) obj._array = x return obj # Prevent Array() from working def __new__(cls, *args, **kwargs): raise TypeError( "The array_api Array object should not be instantiated directly. Use an array creation function, such as asarray(), instead." ) # These functions are not required by the spec, but are implemented for # the sake of usability. def __str__(self: Array, /) -> str: """ Performs the operation __str__. """ return self._array.__str__().replace("array", "Array") def __repr__(self: Array, /) -> str: """ Performs the operation __repr__. """ suffix = f", dtype={self.dtype.name})" if 0 in self.shape: prefix = "empty(" mid = str(self.shape) else: prefix = "Array(" mid = np.array2string(self._array, separator=', ', prefix=prefix, suffix=suffix) return prefix + mid + suffix # This function is not required by the spec, but we implement it here for # convenience so that np.asarray(np.array_api.Array) will work. def __array__(self, dtype: None | np.dtype[Any] = None) -> npt.NDArray[Any]: """ Warning: this method is NOT part of the array API spec. Implementers of other libraries need not include it, and users should not assume it will be present in other implementations. """ return np.asarray(self._array, dtype=dtype) # These are various helper functions to make the array behavior match the # spec in places where it either deviates from or is more strict than # NumPy behavior def _check_allowed_dtypes(self, other: bool | int | float | Array, dtype_category: str, op: str) -> Array: """ Helper function for operators to only allow specific input dtypes Use like other = self._check_allowed_dtypes(other, 'numeric', '__add__') if other is NotImplemented: return other """ if self.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") if isinstance(other, (int, float, bool)): other = self._promote_scalar(other) elif isinstance(other, Array): if other.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") else: return NotImplemented # This will raise TypeError for type combinations that are not allowed # to promote in the spec (even if the NumPy array operator would # promote them). res_dtype = _result_type(self.dtype, other.dtype) if op.startswith("__i"): # Note: NumPy will allow in-place operators in some cases where # the type promoted operator does not match the left-hand side # operand. For example, # >>> a = np.array(1, dtype=np.int8) # >>> a += np.array(1, dtype=np.int16) # The spec explicitly disallows this. if res_dtype != self.dtype: raise TypeError( f"Cannot perform {op} with dtypes {self.dtype} and {other.dtype}" ) return other # Helper function to match the type promotion rules in the spec def _promote_scalar(self, scalar): """ Returns a promoted version of a Python scalar appropriate for use with operations on self. This may raise an OverflowError in cases where the scalar is an integer that is too large to fit in a NumPy integer dtype, or TypeError when the scalar type is incompatible with the dtype of self. """ # Note: Only Python scalar types that match the array dtype are # allowed. if isinstance(scalar, bool): if self.dtype not in _boolean_dtypes: raise TypeError( "Python bool scalars can only be promoted with bool arrays" ) elif isinstance(scalar, int): if self.dtype in _boolean_dtypes: raise TypeError( "Python int scalars cannot be promoted with bool arrays" ) elif isinstance(scalar, float): if self.dtype not in _floating_dtypes: raise TypeError( "Python float scalars can only be promoted with floating-point arrays." ) else: raise TypeError("'scalar' must be a Python scalar") # Note: scalars are unconditionally cast to the same dtype as the # array. # Note: the spec only specifies integer-dtype/int promotion # behavior for integers within the bounds of the integer dtype. # Outside of those bounds we use the default NumPy behavior (either # cast or raise OverflowError). return Array._new(np.array(scalar, self.dtype)) def _normalize_two_args(x1, x2) -> Tuple[Array, Array]: """ Normalize inputs to two arg functions to fix type promotion rules NumPy deviates from the spec type promotion rules in cases where one argument is 0-dimensional and the other is not. For example: >>> import numpy as np >>> a = np.array([1.0], dtype=np.float32) >>> b = np.array(1.0, dtype=np.float64) >>> np.add(a, b) # The spec says this should be float64 array([2.], dtype=float32) To fix this, we add a dimension to the 0-dimension array before passing it through. This works because a dimension would be added anyway from broadcasting, so the resulting shape is the same, but this prevents NumPy from not promoting the dtype. """ # Another option would be to use signature=(x1.dtype, x2.dtype, None), # but that only works for ufuncs, so we would have to call the ufuncs # directly in the operator methods. One should also note that this # sort of trick wouldn't work for functions like searchsorted, which # don't do normal broadcasting, but there aren't any functions like # that in the array API namespace. if x1.ndim == 0 and x2.ndim != 0: # The _array[None] workaround was chosen because it is relatively # performant. broadcast_to(x1._array, x2.shape) is much slower. We # could also manually type promote x2, but that is more complicated # and about the same performance as this. x1 = Array._new(x1._array[None]) elif x2.ndim == 0 and x1.ndim != 0: x2 = Array._new(x2._array[None]) return (x1, x2) # Note: A large fraction of allowed indices are disallowed here (see the # docstring below) def _validate_index(self, key): """ Validate an index according to the array API. The array API specification only requires a subset of indices that are supported by NumPy. This function will reject any index that is allowed by NumPy but not required by the array API specification. We always raise ``IndexError`` on such indices (the spec does not require any specific behavior on them, but this makes the NumPy array API namespace a minimal implementation of the spec). See https://data-apis.org/array-api/latest/API_specification/indexing.html for the full list of required indexing behavior This function raises IndexError if the index ``key`` is invalid. It only raises ``IndexError`` on indices that are not already rejected by NumPy, as NumPy will already raise the appropriate error on such indices. ``shape`` may be None, in which case, only cases that are independent of the array shape are checked. The following cases are allowed by NumPy, but not specified by the array API specification: - Indices to not include an implicit ellipsis at the end. That is, every axis of an array must be explicitly indexed or an ellipsis included. This behaviour is sometimes referred to as flat indexing. - The start and stop of a slice may not be out of bounds. In particular, for a slice ``i:j:k`` on an axis of size ``n``, only the following are allowed: - ``i`` or ``j`` omitted (``None``). - ``-n <= i <= max(0, n - 1)``. - For ``k > 0`` or ``k`` omitted (``None``), ``-n <= j <= n``. - For ``k < 0``, ``-n - 1 <= j <= max(0, n - 1)``. - Boolean array indices are not allowed as part of a larger tuple index. - Integer array indices are not allowed (with the exception of 0-D arrays, which are treated the same as scalars). Additionally, it should be noted that indices that would return a scalar in NumPy will return a 0-D array. Array scalars are not allowed in the specification, only 0-D arrays. This is done in the ``Array._new`` constructor, not this function. """ _key = key if isinstance(key, tuple) else (key,) for i in _key: if isinstance(i, bool) or not ( isinstance(i, SupportsIndex) # i.e. ints or isinstance(i, slice) or i == Ellipsis or i is None or isinstance(i, Array) or isinstance(i, np.ndarray) ): raise IndexError( f"Single-axes index {i} has {type(i)=}, but only " "integers, slices (:), ellipsis (...), newaxis (None), " "zero-dimensional integer arrays and boolean arrays " "are specified in the Array API." ) nonexpanding_key = [] single_axes = [] n_ellipsis = 0 key_has_mask = False for i in _key: if i is not None: nonexpanding_key.append(i) if isinstance(i, Array) or isinstance(i, np.ndarray): if i.dtype in _boolean_dtypes: key_has_mask = True single_axes.append(i) else: # i must not be an array here, to avoid elementwise equals if i == Ellipsis: n_ellipsis += 1 else: single_axes.append(i) n_single_axes = len(single_axes) if n_ellipsis > 1: return # handled by ndarray elif n_ellipsis == 0: # Note boolean masks must be the sole index, which we check for # later on. if not key_has_mask and n_single_axes < self.ndim: raise IndexError( f"{self.ndim=}, but the multi-axes index only specifies " f"{n_single_axes} dimensions. If this was intentional, " "add a trailing ellipsis (...) which expands into as many " "slices (:) as necessary - this is what np.ndarray arrays " "implicitly do, but such flat indexing behaviour is not " "specified in the Array API." ) if n_ellipsis == 0: indexed_shape = self.shape else: ellipsis_start = None for pos, i in enumerate(nonexpanding_key): if not (isinstance(i, Array) or isinstance(i, np.ndarray)): if i == Ellipsis: ellipsis_start = pos break assert ellipsis_start is not None # sanity check ellipsis_end = self.ndim - (n_single_axes - ellipsis_start) indexed_shape = ( self.shape[:ellipsis_start] + self.shape[ellipsis_end:] ) for i, side in zip(single_axes, indexed_shape): if isinstance(i, slice): if side == 0: f_range = "0 (or None)" else: f_range = f"between -{side} and {side - 1} (or None)" if i.start is not None: try: start = operator.index(i.start) except TypeError: pass # handled by ndarray else: if not (-side <= start <= side): raise IndexError( f"Slice {i} contains {start=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds starts are not specified in " "the Array API)" ) if i.stop is not None: try: stop = operator.index(i.stop) except TypeError: pass # handled by ndarray else: if not (-side <= stop <= side): raise IndexError( f"Slice {i} contains {stop=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds stops are not specified in " "the Array API)" ) elif isinstance(i, Array): if i.dtype in _boolean_dtypes and len(_key) != 1: assert isinstance(key, tuple) # sanity check raise IndexError( f"Single-axes index {i} is a boolean array and " f"{len(key)=}, but masking is only specified in the " "Array API when the array is the sole index." ) elif i.dtype in _integer_dtypes and i.ndim != 0: raise IndexError( f"Single-axes index {i} is a non-zero-dimensional " "integer array, but advanced integer indexing is not " "specified in the Array API." ) elif isinstance(i, tuple): raise IndexError( f"Single-axes index {i} is a tuple, but nested tuple " "indices are not specified in the Array API." ) # Everything below this line is required by the spec. def __abs__(self: Array, /) -> Array: """ Performs the operation __abs__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __abs__") res = self._array.__abs__() return self.__class__._new(res) def __add__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __add__. """ other = self._check_allowed_dtypes(other, "numeric", "__add__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__add__(other._array) return self.__class__._new(res) def __and__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __and__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__and__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__and__(other._array) return self.__class__._new(res) def __array_namespace__( self: Array, /, *, api_version: Optional[str] = None ) -> types.ModuleType: if api_version is not None and not api_version.startswith("2021."): raise ValueError(f"Unrecognized array API version: {api_version!r}") return array_api def __bool__(self: Array, /) -> bool: """ Performs the operation __bool__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("bool is only allowed on arrays with 0 dimensions") if self.dtype not in _boolean_dtypes: raise ValueError("bool is only allowed on boolean arrays") res = self._array.__bool__() return res def __dlpack__(self: Array, /, *, stream: None = None) -> PyCapsule: """ Performs the operation __dlpack__. """ return self._array.__dlpack__(stream=stream) def __dlpack_device__(self: Array, /) -> Tuple[IntEnum, int]: """ Performs the operation __dlpack_device__. """ # Note: device support is required for this return self._array.__dlpack_device__() def __eq__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __eq__. """ # Even though "all" dtypes are allowed, we still require them to be # promotable with each other. other = self._check_allowed_dtypes(other, "all", "__eq__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__eq__(other._array) return self.__class__._new(res) def __float__(self: Array, /) -> float: """ Performs the operation __float__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("float is only allowed on arrays with 0 dimensions") if self.dtype not in _floating_dtypes: raise ValueError("float is only allowed on floating-point arrays") res = self._array.__float__() return res def __floordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __floordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__floordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__floordiv__(other._array) return self.__class__._new(res) def __ge__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ge__. """ other = self._check_allowed_dtypes(other, "numeric", "__ge__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ge__(other._array) return self.__class__._new(res) def __getitem__( self: Array, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], /, ) -> Array: """ Performs the operation __getitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array res = self._array.__getitem__(key) return self._new(res) def __gt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __gt__. """ other = self._check_allowed_dtypes(other, "numeric", "__gt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__gt__(other._array) return self.__class__._new(res) def __int__(self: Array, /) -> int: """ Performs the operation __int__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("int is only allowed on arrays with 0 dimensions") if self.dtype not in _integer_dtypes: raise ValueError("int is only allowed on integer arrays") res = self._array.__int__() return res def __index__(self: Array, /) -> int: """ Performs the operation __index__. """ res = self._array.__index__() return res def __invert__(self: Array, /) -> Array: """ Performs the operation __invert__. """ if self.dtype not in _integer_or_boolean_dtypes: raise TypeError("Only integer or boolean dtypes are allowed in __invert__") res = self._array.__invert__() return self.__class__._new(res) def __le__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __le__. """ other = self._check_allowed_dtypes(other, "numeric", "__le__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__le__(other._array) return self.__class__._new(res) def __lshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __lshift__. """ other = self._check_allowed_dtypes(other, "integer", "__lshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lshift__(other._array) return self.__class__._new(res) def __lt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __lt__. """ other = self._check_allowed_dtypes(other, "numeric", "__lt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lt__(other._array) return self.__class__._new(res) def __matmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __matmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__matmul__") if other is NotImplemented: return other res = self._array.__matmul__(other._array) return self.__class__._new(res) def __mod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mod__. """ other = self._check_allowed_dtypes(other, "numeric", "__mod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mod__(other._array) return self.__class__._new(res) def __mul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mul__. """ other = self._check_allowed_dtypes(other, "numeric", "__mul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mul__(other._array) return self.__class__._new(res) def __ne__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __ne__. """ other = self._check_allowed_dtypes(other, "all", "__ne__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ne__(other._array) return self.__class__._new(res) def __neg__(self: Array, /) -> Array: """ Performs the operation __neg__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __neg__") res = self._array.__neg__() return self.__class__._new(res) def __or__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __or__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__or__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__or__(other._array) return self.__class__._new(res) def __pos__(self: Array, /) -> Array: """ Performs the operation __pos__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __pos__") res = self._array.__pos__() return self.__class__._new(res) def __pow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __pow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__pow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow type promotion rules for 0-d # arrays, so we use pow() here instead. return pow(self, other) def __rshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rshift__(other._array) return self.__class__._new(res) def __setitem__( self, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], value: Union[int, float, bool, Array], /, ) -> None: """ Performs the operation __setitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array self._array.__setitem__(key, asarray(value)._array) def __sub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __sub__. """ other = self._check_allowed_dtypes(other, "numeric", "__sub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__sub__(other._array) return self.__class__._new(res) # PEP 484 requires int to be a subtype of float, but __truediv__ should # not accept int. def __truediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __truediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__truediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__truediv__(other._array) return self.__class__._new(res) def __xor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __xor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__xor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__xor__(other._array) return self.__class__._new(res) def __iadd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __iadd__. """ other = self._check_allowed_dtypes(other, "numeric", "__iadd__") if other is NotImplemented: return other self._array.__iadd__(other._array) return self def __radd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __radd__. """ other = self._check_allowed_dtypes(other, "numeric", "__radd__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__radd__(other._array) return self.__class__._new(res) def __iand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __iand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__iand__") if other is NotImplemented: return other self._array.__iand__(other._array) return self def __rand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rand__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rand__(other._array) return self.__class__._new(res) def __ifloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ifloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__ifloordiv__") if other is NotImplemented: return other self._array.__ifloordiv__(other._array) return self def __rfloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rfloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__rfloordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rfloordiv__(other._array) return self.__class__._new(res) def __ilshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __ilshift__. """ other = self._check_allowed_dtypes(other, "integer", "__ilshift__") if other is NotImplemented: return other self._array.__ilshift__(other._array) return self def __rlshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rlshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rlshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rlshift__(other._array) return self.__class__._new(res) def __imatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __imatmul__. """ # Note: NumPy does not implement __imatmul__. # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__imatmul__") if other is NotImplemented: return other # __imatmul__ can only be allowed when it would not change the shape # of self. other_shape = other.shape if self.shape == () or other_shape == (): raise ValueError("@= requires at least one dimension") if len(other_shape) == 1 or other_shape[-1] != other_shape[-2]: raise ValueError("@= cannot change the shape of the input array") self._array[:] = self._array.__matmul__(other._array) return self def __rmatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __rmatmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__rmatmul__") if other is NotImplemented: return other res = self._array.__rmatmul__(other._array) return self.__class__._new(res) def __imod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imod__. """ other = self._check_allowed_dtypes(other, "numeric", "__imod__") if other is NotImplemented: return other self._array.__imod__(other._array) return self def __rmod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmod__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmod__(other._array) return self.__class__._new(res) def __imul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imul__. """ other = self._check_allowed_dtypes(other, "numeric", "__imul__") if other is NotImplemented: return other self._array.__imul__(other._array) return self def __rmul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmul__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmul__(other._array) return self.__class__._new(res) def __ior__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ior__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ior__") if other is NotImplemented: return other self._array.__ior__(other._array) return self def __ror__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ror__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ror__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ror__(other._array) return self.__class__._new(res) def __ipow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ipow__. """ other = self._check_allowed_dtypes(other, "numeric", "__ipow__") if other is NotImplemented: return other self._array.__ipow__(other._array) return self def __rpow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rpow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__rpow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow the spec type promotion rules # for 0-d arrays, so we use pow() here instead. return pow(other, self) def __irshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __irshift__. """ other = self._check_allowed_dtypes(other, "integer", "__irshift__") if other is NotImplemented: return other self._array.__irshift__(other._array) return self def __rrshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rrshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rrshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rrshift__(other._array) return self.__class__._new(res) def __isub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __isub__. """ other = self._check_allowed_dtypes(other, "numeric", "__isub__") if other is NotImplemented: return other self._array.__isub__(other._array) return self def __rsub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rsub__. """ other = self._check_allowed_dtypes(other, "numeric", "__rsub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rsub__(other._array) return self.__class__._new(res) def __itruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __itruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__itruediv__") if other is NotImplemented: return other self._array.__itruediv__(other._array) return self def __rtruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __rtruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__rtruediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rtruediv__(other._array) return self.__class__._new(res) def __ixor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ixor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ixor__") if other is NotImplemented: return other self._array.__ixor__(other._array) return self def __rxor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rxor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rxor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rxor__(other._array) return self.__class__._new(res) def to_device(self: Array, device: Device, /, stream: None = None) -> Array: if stream is not None: raise ValueError("The stream argument to to_device() is not supported") if device == 'cpu': return self raise ValueError(f"Unsupported device {device!r}") def dtype(self) -> Dtype: """ Array API compatible wrapper for :py:meth:`np.ndarray.dtype <numpy.ndarray.dtype>`. See its docstring for more information. """ return self._array.dtype def device(self) -> Device: return "cpu" # Note: mT is new in array API spec (see matrix_transpose) def mT(self) -> Array: from .linalg import matrix_transpose return matrix_transpose(self) def ndim(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.ndim <numpy.ndarray.ndim>`. See its docstring for more information. """ return self._array.ndim def shape(self) -> Tuple[int, ...]: """ Array API compatible wrapper for :py:meth:`np.ndarray.shape <numpy.ndarray.shape>`. See its docstring for more information. """ return self._array.shape def size(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.size <numpy.ndarray.size>`. See its docstring for more information. """ return self._array.size def T(self) -> Array: """ Array API compatible wrapper for :py:meth:`np.ndarray.T <numpy.ndarray.T>`. See its docstring for more information. """ # Note: T only works on 2-dimensional arrays. See the corresponding # note in the specification: # https://data-apis.org/array-api/latest/API_specification/array_object.html#t if self.ndim != 2: raise ValueError("x.T requires x to have 2 dimensions. Use x.mT to transpose stacks of matrices and permute_dims() to permute dimensions.") return self.__class__._new(self._array.T) The provided code snippet includes necessary dependencies for implementing the `tanh` function. Write a Python function `def tanh(x: Array, /) -> Array` to solve the following problem: Array API compatible wrapper for :py:func:`np.tanh <numpy.tanh>`. See its docstring for more information. Here is the function: def tanh(x: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.tanh <numpy.tanh>`. See its docstring for more information. """ if x.dtype not in _floating_dtypes: raise TypeError("Only floating-point dtypes are allowed in tanh") return Array._new(np.tanh(x._array))
Array API compatible wrapper for :py:func:`np.tanh <numpy.tanh>`. See its docstring for more information.
170,074
from __future__ import annotations from ._dtypes import ( _boolean_dtypes, _floating_dtypes, _integer_dtypes, _integer_or_boolean_dtypes, _numeric_dtypes, _result_type, ) from ._array_object import Array import numpy as np _integer_dtypes = (int8, int16, int32, int64, uint8, uint16, uint32, uint64) _numeric_dtypes = ( float32, float64, int8, int16, int32, int64, uint8, uint16, uint32, uint64, ) class Array: """ n-d array object for the array API namespace. See the docstring of :py:obj:`np.ndarray <numpy.ndarray>` for more information. This is a wrapper around numpy.ndarray that restricts the usage to only those things that are required by the array API namespace. Note, attributes on this object that start with a single underscore are not part of the API specification and should only be used internally. This object should not be constructed directly. Rather, use one of the creation functions, such as asarray(). """ _array: np.ndarray # Use a custom constructor instead of __init__, as manually initializing # this class is not supported API. def _new(cls, x, /): """ This is a private method for initializing the array API Array object. Functions outside of the array_api submodule should not use this method. Use one of the creation functions instead, such as ``asarray``. """ obj = super().__new__(cls) # Note: The spec does not have array scalars, only 0-D arrays. if isinstance(x, np.generic): # Convert the array scalar to a 0-D array x = np.asarray(x) if x.dtype not in _all_dtypes: raise TypeError( f"The array_api namespace does not support the dtype '{x.dtype}'" ) obj._array = x return obj # Prevent Array() from working def __new__(cls, *args, **kwargs): raise TypeError( "The array_api Array object should not be instantiated directly. Use an array creation function, such as asarray(), instead." ) # These functions are not required by the spec, but are implemented for # the sake of usability. def __str__(self: Array, /) -> str: """ Performs the operation __str__. """ return self._array.__str__().replace("array", "Array") def __repr__(self: Array, /) -> str: """ Performs the operation __repr__. """ suffix = f", dtype={self.dtype.name})" if 0 in self.shape: prefix = "empty(" mid = str(self.shape) else: prefix = "Array(" mid = np.array2string(self._array, separator=', ', prefix=prefix, suffix=suffix) return prefix + mid + suffix # This function is not required by the spec, but we implement it here for # convenience so that np.asarray(np.array_api.Array) will work. def __array__(self, dtype: None | np.dtype[Any] = None) -> npt.NDArray[Any]: """ Warning: this method is NOT part of the array API spec. Implementers of other libraries need not include it, and users should not assume it will be present in other implementations. """ return np.asarray(self._array, dtype=dtype) # These are various helper functions to make the array behavior match the # spec in places where it either deviates from or is more strict than # NumPy behavior def _check_allowed_dtypes(self, other: bool | int | float | Array, dtype_category: str, op: str) -> Array: """ Helper function for operators to only allow specific input dtypes Use like other = self._check_allowed_dtypes(other, 'numeric', '__add__') if other is NotImplemented: return other """ if self.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") if isinstance(other, (int, float, bool)): other = self._promote_scalar(other) elif isinstance(other, Array): if other.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") else: return NotImplemented # This will raise TypeError for type combinations that are not allowed # to promote in the spec (even if the NumPy array operator would # promote them). res_dtype = _result_type(self.dtype, other.dtype) if op.startswith("__i"): # Note: NumPy will allow in-place operators in some cases where # the type promoted operator does not match the left-hand side # operand. For example, # >>> a = np.array(1, dtype=np.int8) # >>> a += np.array(1, dtype=np.int16) # The spec explicitly disallows this. if res_dtype != self.dtype: raise TypeError( f"Cannot perform {op} with dtypes {self.dtype} and {other.dtype}" ) return other # Helper function to match the type promotion rules in the spec def _promote_scalar(self, scalar): """ Returns a promoted version of a Python scalar appropriate for use with operations on self. This may raise an OverflowError in cases where the scalar is an integer that is too large to fit in a NumPy integer dtype, or TypeError when the scalar type is incompatible with the dtype of self. """ # Note: Only Python scalar types that match the array dtype are # allowed. if isinstance(scalar, bool): if self.dtype not in _boolean_dtypes: raise TypeError( "Python bool scalars can only be promoted with bool arrays" ) elif isinstance(scalar, int): if self.dtype in _boolean_dtypes: raise TypeError( "Python int scalars cannot be promoted with bool arrays" ) elif isinstance(scalar, float): if self.dtype not in _floating_dtypes: raise TypeError( "Python float scalars can only be promoted with floating-point arrays." ) else: raise TypeError("'scalar' must be a Python scalar") # Note: scalars are unconditionally cast to the same dtype as the # array. # Note: the spec only specifies integer-dtype/int promotion # behavior for integers within the bounds of the integer dtype. # Outside of those bounds we use the default NumPy behavior (either # cast or raise OverflowError). return Array._new(np.array(scalar, self.dtype)) def _normalize_two_args(x1, x2) -> Tuple[Array, Array]: """ Normalize inputs to two arg functions to fix type promotion rules NumPy deviates from the spec type promotion rules in cases where one argument is 0-dimensional and the other is not. For example: >>> import numpy as np >>> a = np.array([1.0], dtype=np.float32) >>> b = np.array(1.0, dtype=np.float64) >>> np.add(a, b) # The spec says this should be float64 array([2.], dtype=float32) To fix this, we add a dimension to the 0-dimension array before passing it through. This works because a dimension would be added anyway from broadcasting, so the resulting shape is the same, but this prevents NumPy from not promoting the dtype. """ # Another option would be to use signature=(x1.dtype, x2.dtype, None), # but that only works for ufuncs, so we would have to call the ufuncs # directly in the operator methods. One should also note that this # sort of trick wouldn't work for functions like searchsorted, which # don't do normal broadcasting, but there aren't any functions like # that in the array API namespace. if x1.ndim == 0 and x2.ndim != 0: # The _array[None] workaround was chosen because it is relatively # performant. broadcast_to(x1._array, x2.shape) is much slower. We # could also manually type promote x2, but that is more complicated # and about the same performance as this. x1 = Array._new(x1._array[None]) elif x2.ndim == 0 and x1.ndim != 0: x2 = Array._new(x2._array[None]) return (x1, x2) # Note: A large fraction of allowed indices are disallowed here (see the # docstring below) def _validate_index(self, key): """ Validate an index according to the array API. The array API specification only requires a subset of indices that are supported by NumPy. This function will reject any index that is allowed by NumPy but not required by the array API specification. We always raise ``IndexError`` on such indices (the spec does not require any specific behavior on them, but this makes the NumPy array API namespace a minimal implementation of the spec). See https://data-apis.org/array-api/latest/API_specification/indexing.html for the full list of required indexing behavior This function raises IndexError if the index ``key`` is invalid. It only raises ``IndexError`` on indices that are not already rejected by NumPy, as NumPy will already raise the appropriate error on such indices. ``shape`` may be None, in which case, only cases that are independent of the array shape are checked. The following cases are allowed by NumPy, but not specified by the array API specification: - Indices to not include an implicit ellipsis at the end. That is, every axis of an array must be explicitly indexed or an ellipsis included. This behaviour is sometimes referred to as flat indexing. - The start and stop of a slice may not be out of bounds. In particular, for a slice ``i:j:k`` on an axis of size ``n``, only the following are allowed: - ``i`` or ``j`` omitted (``None``). - ``-n <= i <= max(0, n - 1)``. - For ``k > 0`` or ``k`` omitted (``None``), ``-n <= j <= n``. - For ``k < 0``, ``-n - 1 <= j <= max(0, n - 1)``. - Boolean array indices are not allowed as part of a larger tuple index. - Integer array indices are not allowed (with the exception of 0-D arrays, which are treated the same as scalars). Additionally, it should be noted that indices that would return a scalar in NumPy will return a 0-D array. Array scalars are not allowed in the specification, only 0-D arrays. This is done in the ``Array._new`` constructor, not this function. """ _key = key if isinstance(key, tuple) else (key,) for i in _key: if isinstance(i, bool) or not ( isinstance(i, SupportsIndex) # i.e. ints or isinstance(i, slice) or i == Ellipsis or i is None or isinstance(i, Array) or isinstance(i, np.ndarray) ): raise IndexError( f"Single-axes index {i} has {type(i)=}, but only " "integers, slices (:), ellipsis (...), newaxis (None), " "zero-dimensional integer arrays and boolean arrays " "are specified in the Array API." ) nonexpanding_key = [] single_axes = [] n_ellipsis = 0 key_has_mask = False for i in _key: if i is not None: nonexpanding_key.append(i) if isinstance(i, Array) or isinstance(i, np.ndarray): if i.dtype in _boolean_dtypes: key_has_mask = True single_axes.append(i) else: # i must not be an array here, to avoid elementwise equals if i == Ellipsis: n_ellipsis += 1 else: single_axes.append(i) n_single_axes = len(single_axes) if n_ellipsis > 1: return # handled by ndarray elif n_ellipsis == 0: # Note boolean masks must be the sole index, which we check for # later on. if not key_has_mask and n_single_axes < self.ndim: raise IndexError( f"{self.ndim=}, but the multi-axes index only specifies " f"{n_single_axes} dimensions. If this was intentional, " "add a trailing ellipsis (...) which expands into as many " "slices (:) as necessary - this is what np.ndarray arrays " "implicitly do, but such flat indexing behaviour is not " "specified in the Array API." ) if n_ellipsis == 0: indexed_shape = self.shape else: ellipsis_start = None for pos, i in enumerate(nonexpanding_key): if not (isinstance(i, Array) or isinstance(i, np.ndarray)): if i == Ellipsis: ellipsis_start = pos break assert ellipsis_start is not None # sanity check ellipsis_end = self.ndim - (n_single_axes - ellipsis_start) indexed_shape = ( self.shape[:ellipsis_start] + self.shape[ellipsis_end:] ) for i, side in zip(single_axes, indexed_shape): if isinstance(i, slice): if side == 0: f_range = "0 (or None)" else: f_range = f"between -{side} and {side - 1} (or None)" if i.start is not None: try: start = operator.index(i.start) except TypeError: pass # handled by ndarray else: if not (-side <= start <= side): raise IndexError( f"Slice {i} contains {start=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds starts are not specified in " "the Array API)" ) if i.stop is not None: try: stop = operator.index(i.stop) except TypeError: pass # handled by ndarray else: if not (-side <= stop <= side): raise IndexError( f"Slice {i} contains {stop=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds stops are not specified in " "the Array API)" ) elif isinstance(i, Array): if i.dtype in _boolean_dtypes and len(_key) != 1: assert isinstance(key, tuple) # sanity check raise IndexError( f"Single-axes index {i} is a boolean array and " f"{len(key)=}, but masking is only specified in the " "Array API when the array is the sole index." ) elif i.dtype in _integer_dtypes and i.ndim != 0: raise IndexError( f"Single-axes index {i} is a non-zero-dimensional " "integer array, but advanced integer indexing is not " "specified in the Array API." ) elif isinstance(i, tuple): raise IndexError( f"Single-axes index {i} is a tuple, but nested tuple " "indices are not specified in the Array API." ) # Everything below this line is required by the spec. def __abs__(self: Array, /) -> Array: """ Performs the operation __abs__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __abs__") res = self._array.__abs__() return self.__class__._new(res) def __add__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __add__. """ other = self._check_allowed_dtypes(other, "numeric", "__add__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__add__(other._array) return self.__class__._new(res) def __and__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __and__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__and__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__and__(other._array) return self.__class__._new(res) def __array_namespace__( self: Array, /, *, api_version: Optional[str] = None ) -> types.ModuleType: if api_version is not None and not api_version.startswith("2021."): raise ValueError(f"Unrecognized array API version: {api_version!r}") return array_api def __bool__(self: Array, /) -> bool: """ Performs the operation __bool__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("bool is only allowed on arrays with 0 dimensions") if self.dtype not in _boolean_dtypes: raise ValueError("bool is only allowed on boolean arrays") res = self._array.__bool__() return res def __dlpack__(self: Array, /, *, stream: None = None) -> PyCapsule: """ Performs the operation __dlpack__. """ return self._array.__dlpack__(stream=stream) def __dlpack_device__(self: Array, /) -> Tuple[IntEnum, int]: """ Performs the operation __dlpack_device__. """ # Note: device support is required for this return self._array.__dlpack_device__() def __eq__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __eq__. """ # Even though "all" dtypes are allowed, we still require them to be # promotable with each other. other = self._check_allowed_dtypes(other, "all", "__eq__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__eq__(other._array) return self.__class__._new(res) def __float__(self: Array, /) -> float: """ Performs the operation __float__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("float is only allowed on arrays with 0 dimensions") if self.dtype not in _floating_dtypes: raise ValueError("float is only allowed on floating-point arrays") res = self._array.__float__() return res def __floordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __floordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__floordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__floordiv__(other._array) return self.__class__._new(res) def __ge__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ge__. """ other = self._check_allowed_dtypes(other, "numeric", "__ge__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ge__(other._array) return self.__class__._new(res) def __getitem__( self: Array, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], /, ) -> Array: """ Performs the operation __getitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array res = self._array.__getitem__(key) return self._new(res) def __gt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __gt__. """ other = self._check_allowed_dtypes(other, "numeric", "__gt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__gt__(other._array) return self.__class__._new(res) def __int__(self: Array, /) -> int: """ Performs the operation __int__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("int is only allowed on arrays with 0 dimensions") if self.dtype not in _integer_dtypes: raise ValueError("int is only allowed on integer arrays") res = self._array.__int__() return res def __index__(self: Array, /) -> int: """ Performs the operation __index__. """ res = self._array.__index__() return res def __invert__(self: Array, /) -> Array: """ Performs the operation __invert__. """ if self.dtype not in _integer_or_boolean_dtypes: raise TypeError("Only integer or boolean dtypes are allowed in __invert__") res = self._array.__invert__() return self.__class__._new(res) def __le__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __le__. """ other = self._check_allowed_dtypes(other, "numeric", "__le__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__le__(other._array) return self.__class__._new(res) def __lshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __lshift__. """ other = self._check_allowed_dtypes(other, "integer", "__lshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lshift__(other._array) return self.__class__._new(res) def __lt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __lt__. """ other = self._check_allowed_dtypes(other, "numeric", "__lt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lt__(other._array) return self.__class__._new(res) def __matmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __matmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__matmul__") if other is NotImplemented: return other res = self._array.__matmul__(other._array) return self.__class__._new(res) def __mod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mod__. """ other = self._check_allowed_dtypes(other, "numeric", "__mod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mod__(other._array) return self.__class__._new(res) def __mul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mul__. """ other = self._check_allowed_dtypes(other, "numeric", "__mul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mul__(other._array) return self.__class__._new(res) def __ne__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __ne__. """ other = self._check_allowed_dtypes(other, "all", "__ne__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ne__(other._array) return self.__class__._new(res) def __neg__(self: Array, /) -> Array: """ Performs the operation __neg__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __neg__") res = self._array.__neg__() return self.__class__._new(res) def __or__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __or__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__or__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__or__(other._array) return self.__class__._new(res) def __pos__(self: Array, /) -> Array: """ Performs the operation __pos__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __pos__") res = self._array.__pos__() return self.__class__._new(res) def __pow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __pow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__pow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow type promotion rules for 0-d # arrays, so we use pow() here instead. return pow(self, other) def __rshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rshift__(other._array) return self.__class__._new(res) def __setitem__( self, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], value: Union[int, float, bool, Array], /, ) -> None: """ Performs the operation __setitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array self._array.__setitem__(key, asarray(value)._array) def __sub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __sub__. """ other = self._check_allowed_dtypes(other, "numeric", "__sub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__sub__(other._array) return self.__class__._new(res) # PEP 484 requires int to be a subtype of float, but __truediv__ should # not accept int. def __truediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __truediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__truediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__truediv__(other._array) return self.__class__._new(res) def __xor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __xor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__xor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__xor__(other._array) return self.__class__._new(res) def __iadd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __iadd__. """ other = self._check_allowed_dtypes(other, "numeric", "__iadd__") if other is NotImplemented: return other self._array.__iadd__(other._array) return self def __radd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __radd__. """ other = self._check_allowed_dtypes(other, "numeric", "__radd__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__radd__(other._array) return self.__class__._new(res) def __iand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __iand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__iand__") if other is NotImplemented: return other self._array.__iand__(other._array) return self def __rand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rand__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rand__(other._array) return self.__class__._new(res) def __ifloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ifloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__ifloordiv__") if other is NotImplemented: return other self._array.__ifloordiv__(other._array) return self def __rfloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rfloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__rfloordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rfloordiv__(other._array) return self.__class__._new(res) def __ilshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __ilshift__. """ other = self._check_allowed_dtypes(other, "integer", "__ilshift__") if other is NotImplemented: return other self._array.__ilshift__(other._array) return self def __rlshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rlshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rlshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rlshift__(other._array) return self.__class__._new(res) def __imatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __imatmul__. """ # Note: NumPy does not implement __imatmul__. # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__imatmul__") if other is NotImplemented: return other # __imatmul__ can only be allowed when it would not change the shape # of self. other_shape = other.shape if self.shape == () or other_shape == (): raise ValueError("@= requires at least one dimension") if len(other_shape) == 1 or other_shape[-1] != other_shape[-2]: raise ValueError("@= cannot change the shape of the input array") self._array[:] = self._array.__matmul__(other._array) return self def __rmatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __rmatmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__rmatmul__") if other is NotImplemented: return other res = self._array.__rmatmul__(other._array) return self.__class__._new(res) def __imod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imod__. """ other = self._check_allowed_dtypes(other, "numeric", "__imod__") if other is NotImplemented: return other self._array.__imod__(other._array) return self def __rmod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmod__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmod__(other._array) return self.__class__._new(res) def __imul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imul__. """ other = self._check_allowed_dtypes(other, "numeric", "__imul__") if other is NotImplemented: return other self._array.__imul__(other._array) return self def __rmul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmul__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmul__(other._array) return self.__class__._new(res) def __ior__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ior__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ior__") if other is NotImplemented: return other self._array.__ior__(other._array) return self def __ror__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ror__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ror__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ror__(other._array) return self.__class__._new(res) def __ipow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ipow__. """ other = self._check_allowed_dtypes(other, "numeric", "__ipow__") if other is NotImplemented: return other self._array.__ipow__(other._array) return self def __rpow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rpow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__rpow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow the spec type promotion rules # for 0-d arrays, so we use pow() here instead. return pow(other, self) def __irshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __irshift__. """ other = self._check_allowed_dtypes(other, "integer", "__irshift__") if other is NotImplemented: return other self._array.__irshift__(other._array) return self def __rrshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rrshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rrshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rrshift__(other._array) return self.__class__._new(res) def __isub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __isub__. """ other = self._check_allowed_dtypes(other, "numeric", "__isub__") if other is NotImplemented: return other self._array.__isub__(other._array) return self def __rsub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rsub__. """ other = self._check_allowed_dtypes(other, "numeric", "__rsub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rsub__(other._array) return self.__class__._new(res) def __itruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __itruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__itruediv__") if other is NotImplemented: return other self._array.__itruediv__(other._array) return self def __rtruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __rtruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__rtruediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rtruediv__(other._array) return self.__class__._new(res) def __ixor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ixor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ixor__") if other is NotImplemented: return other self._array.__ixor__(other._array) return self def __rxor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rxor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rxor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rxor__(other._array) return self.__class__._new(res) def to_device(self: Array, device: Device, /, stream: None = None) -> Array: if stream is not None: raise ValueError("The stream argument to to_device() is not supported") if device == 'cpu': return self raise ValueError(f"Unsupported device {device!r}") def dtype(self) -> Dtype: """ Array API compatible wrapper for :py:meth:`np.ndarray.dtype <numpy.ndarray.dtype>`. See its docstring for more information. """ return self._array.dtype def device(self) -> Device: return "cpu" # Note: mT is new in array API spec (see matrix_transpose) def mT(self) -> Array: from .linalg import matrix_transpose return matrix_transpose(self) def ndim(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.ndim <numpy.ndarray.ndim>`. See its docstring for more information. """ return self._array.ndim def shape(self) -> Tuple[int, ...]: """ Array API compatible wrapper for :py:meth:`np.ndarray.shape <numpy.ndarray.shape>`. See its docstring for more information. """ return self._array.shape def size(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.size <numpy.ndarray.size>`. See its docstring for more information. """ return self._array.size def T(self) -> Array: """ Array API compatible wrapper for :py:meth:`np.ndarray.T <numpy.ndarray.T>`. See its docstring for more information. """ # Note: T only works on 2-dimensional arrays. See the corresponding # note in the specification: # https://data-apis.org/array-api/latest/API_specification/array_object.html#t if self.ndim != 2: raise ValueError("x.T requires x to have 2 dimensions. Use x.mT to transpose stacks of matrices and permute_dims() to permute dimensions.") return self.__class__._new(self._array.T) The provided code snippet includes necessary dependencies for implementing the `trunc` function. Write a Python function `def trunc(x: Array, /) -> Array` to solve the following problem: Array API compatible wrapper for :py:func:`np.trunc <numpy.trunc>`. See its docstring for more information. Here is the function: def trunc(x: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.trunc <numpy.trunc>`. See its docstring for more information. """ if x.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in trunc") if x.dtype in _integer_dtypes: # Note: The return dtype of trunc is the same as the input return x return Array._new(np.trunc(x._array))
Array API compatible wrapper for :py:func:`np.trunc <numpy.trunc>`. See its docstring for more information.
170,075
from __future__ import annotations from ._array_object import Array from typing import Optional, Tuple, Union import numpy as np class Array: """ n-d array object for the array API namespace. See the docstring of :py:obj:`np.ndarray <numpy.ndarray>` for more information. This is a wrapper around numpy.ndarray that restricts the usage to only those things that are required by the array API namespace. Note, attributes on this object that start with a single underscore are not part of the API specification and should only be used internally. This object should not be constructed directly. Rather, use one of the creation functions, such as asarray(). """ _array: np.ndarray # Use a custom constructor instead of __init__, as manually initializing # this class is not supported API. def _new(cls, x, /): """ This is a private method for initializing the array API Array object. Functions outside of the array_api submodule should not use this method. Use one of the creation functions instead, such as ``asarray``. """ obj = super().__new__(cls) # Note: The spec does not have array scalars, only 0-D arrays. if isinstance(x, np.generic): # Convert the array scalar to a 0-D array x = np.asarray(x) if x.dtype not in _all_dtypes: raise TypeError( f"The array_api namespace does not support the dtype '{x.dtype}'" ) obj._array = x return obj # Prevent Array() from working def __new__(cls, *args, **kwargs): raise TypeError( "The array_api Array object should not be instantiated directly. Use an array creation function, such as asarray(), instead." ) # These functions are not required by the spec, but are implemented for # the sake of usability. def __str__(self: Array, /) -> str: """ Performs the operation __str__. """ return self._array.__str__().replace("array", "Array") def __repr__(self: Array, /) -> str: """ Performs the operation __repr__. """ suffix = f", dtype={self.dtype.name})" if 0 in self.shape: prefix = "empty(" mid = str(self.shape) else: prefix = "Array(" mid = np.array2string(self._array, separator=', ', prefix=prefix, suffix=suffix) return prefix + mid + suffix # This function is not required by the spec, but we implement it here for # convenience so that np.asarray(np.array_api.Array) will work. def __array__(self, dtype: None | np.dtype[Any] = None) -> npt.NDArray[Any]: """ Warning: this method is NOT part of the array API spec. Implementers of other libraries need not include it, and users should not assume it will be present in other implementations. """ return np.asarray(self._array, dtype=dtype) # These are various helper functions to make the array behavior match the # spec in places where it either deviates from or is more strict than # NumPy behavior def _check_allowed_dtypes(self, other: bool | int | float | Array, dtype_category: str, op: str) -> Array: """ Helper function for operators to only allow specific input dtypes Use like other = self._check_allowed_dtypes(other, 'numeric', '__add__') if other is NotImplemented: return other """ if self.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") if isinstance(other, (int, float, bool)): other = self._promote_scalar(other) elif isinstance(other, Array): if other.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") else: return NotImplemented # This will raise TypeError for type combinations that are not allowed # to promote in the spec (even if the NumPy array operator would # promote them). res_dtype = _result_type(self.dtype, other.dtype) if op.startswith("__i"): # Note: NumPy will allow in-place operators in some cases where # the type promoted operator does not match the left-hand side # operand. For example, # >>> a = np.array(1, dtype=np.int8) # >>> a += np.array(1, dtype=np.int16) # The spec explicitly disallows this. if res_dtype != self.dtype: raise TypeError( f"Cannot perform {op} with dtypes {self.dtype} and {other.dtype}" ) return other # Helper function to match the type promotion rules in the spec def _promote_scalar(self, scalar): """ Returns a promoted version of a Python scalar appropriate for use with operations on self. This may raise an OverflowError in cases where the scalar is an integer that is too large to fit in a NumPy integer dtype, or TypeError when the scalar type is incompatible with the dtype of self. """ # Note: Only Python scalar types that match the array dtype are # allowed. if isinstance(scalar, bool): if self.dtype not in _boolean_dtypes: raise TypeError( "Python bool scalars can only be promoted with bool arrays" ) elif isinstance(scalar, int): if self.dtype in _boolean_dtypes: raise TypeError( "Python int scalars cannot be promoted with bool arrays" ) elif isinstance(scalar, float): if self.dtype not in _floating_dtypes: raise TypeError( "Python float scalars can only be promoted with floating-point arrays." ) else: raise TypeError("'scalar' must be a Python scalar") # Note: scalars are unconditionally cast to the same dtype as the # array. # Note: the spec only specifies integer-dtype/int promotion # behavior for integers within the bounds of the integer dtype. # Outside of those bounds we use the default NumPy behavior (either # cast or raise OverflowError). return Array._new(np.array(scalar, self.dtype)) def _normalize_two_args(x1, x2) -> Tuple[Array, Array]: """ Normalize inputs to two arg functions to fix type promotion rules NumPy deviates from the spec type promotion rules in cases where one argument is 0-dimensional and the other is not. For example: >>> import numpy as np >>> a = np.array([1.0], dtype=np.float32) >>> b = np.array(1.0, dtype=np.float64) >>> np.add(a, b) # The spec says this should be float64 array([2.], dtype=float32) To fix this, we add a dimension to the 0-dimension array before passing it through. This works because a dimension would be added anyway from broadcasting, so the resulting shape is the same, but this prevents NumPy from not promoting the dtype. """ # Another option would be to use signature=(x1.dtype, x2.dtype, None), # but that only works for ufuncs, so we would have to call the ufuncs # directly in the operator methods. One should also note that this # sort of trick wouldn't work for functions like searchsorted, which # don't do normal broadcasting, but there aren't any functions like # that in the array API namespace. if x1.ndim == 0 and x2.ndim != 0: # The _array[None] workaround was chosen because it is relatively # performant. broadcast_to(x1._array, x2.shape) is much slower. We # could also manually type promote x2, but that is more complicated # and about the same performance as this. x1 = Array._new(x1._array[None]) elif x2.ndim == 0 and x1.ndim != 0: x2 = Array._new(x2._array[None]) return (x1, x2) # Note: A large fraction of allowed indices are disallowed here (see the # docstring below) def _validate_index(self, key): """ Validate an index according to the array API. The array API specification only requires a subset of indices that are supported by NumPy. This function will reject any index that is allowed by NumPy but not required by the array API specification. We always raise ``IndexError`` on such indices (the spec does not require any specific behavior on them, but this makes the NumPy array API namespace a minimal implementation of the spec). See https://data-apis.org/array-api/latest/API_specification/indexing.html for the full list of required indexing behavior This function raises IndexError if the index ``key`` is invalid. It only raises ``IndexError`` on indices that are not already rejected by NumPy, as NumPy will already raise the appropriate error on such indices. ``shape`` may be None, in which case, only cases that are independent of the array shape are checked. The following cases are allowed by NumPy, but not specified by the array API specification: - Indices to not include an implicit ellipsis at the end. That is, every axis of an array must be explicitly indexed or an ellipsis included. This behaviour is sometimes referred to as flat indexing. - The start and stop of a slice may not be out of bounds. In particular, for a slice ``i:j:k`` on an axis of size ``n``, only the following are allowed: - ``i`` or ``j`` omitted (``None``). - ``-n <= i <= max(0, n - 1)``. - For ``k > 0`` or ``k`` omitted (``None``), ``-n <= j <= n``. - For ``k < 0``, ``-n - 1 <= j <= max(0, n - 1)``. - Boolean array indices are not allowed as part of a larger tuple index. - Integer array indices are not allowed (with the exception of 0-D arrays, which are treated the same as scalars). Additionally, it should be noted that indices that would return a scalar in NumPy will return a 0-D array. Array scalars are not allowed in the specification, only 0-D arrays. This is done in the ``Array._new`` constructor, not this function. """ _key = key if isinstance(key, tuple) else (key,) for i in _key: if isinstance(i, bool) or not ( isinstance(i, SupportsIndex) # i.e. ints or isinstance(i, slice) or i == Ellipsis or i is None or isinstance(i, Array) or isinstance(i, np.ndarray) ): raise IndexError( f"Single-axes index {i} has {type(i)=}, but only " "integers, slices (:), ellipsis (...), newaxis (None), " "zero-dimensional integer arrays and boolean arrays " "are specified in the Array API." ) nonexpanding_key = [] single_axes = [] n_ellipsis = 0 key_has_mask = False for i in _key: if i is not None: nonexpanding_key.append(i) if isinstance(i, Array) or isinstance(i, np.ndarray): if i.dtype in _boolean_dtypes: key_has_mask = True single_axes.append(i) else: # i must not be an array here, to avoid elementwise equals if i == Ellipsis: n_ellipsis += 1 else: single_axes.append(i) n_single_axes = len(single_axes) if n_ellipsis > 1: return # handled by ndarray elif n_ellipsis == 0: # Note boolean masks must be the sole index, which we check for # later on. if not key_has_mask and n_single_axes < self.ndim: raise IndexError( f"{self.ndim=}, but the multi-axes index only specifies " f"{n_single_axes} dimensions. If this was intentional, " "add a trailing ellipsis (...) which expands into as many " "slices (:) as necessary - this is what np.ndarray arrays " "implicitly do, but such flat indexing behaviour is not " "specified in the Array API." ) if n_ellipsis == 0: indexed_shape = self.shape else: ellipsis_start = None for pos, i in enumerate(nonexpanding_key): if not (isinstance(i, Array) or isinstance(i, np.ndarray)): if i == Ellipsis: ellipsis_start = pos break assert ellipsis_start is not None # sanity check ellipsis_end = self.ndim - (n_single_axes - ellipsis_start) indexed_shape = ( self.shape[:ellipsis_start] + self.shape[ellipsis_end:] ) for i, side in zip(single_axes, indexed_shape): if isinstance(i, slice): if side == 0: f_range = "0 (or None)" else: f_range = f"between -{side} and {side - 1} (or None)" if i.start is not None: try: start = operator.index(i.start) except TypeError: pass # handled by ndarray else: if not (-side <= start <= side): raise IndexError( f"Slice {i} contains {start=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds starts are not specified in " "the Array API)" ) if i.stop is not None: try: stop = operator.index(i.stop) except TypeError: pass # handled by ndarray else: if not (-side <= stop <= side): raise IndexError( f"Slice {i} contains {stop=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds stops are not specified in " "the Array API)" ) elif isinstance(i, Array): if i.dtype in _boolean_dtypes and len(_key) != 1: assert isinstance(key, tuple) # sanity check raise IndexError( f"Single-axes index {i} is a boolean array and " f"{len(key)=}, but masking is only specified in the " "Array API when the array is the sole index." ) elif i.dtype in _integer_dtypes and i.ndim != 0: raise IndexError( f"Single-axes index {i} is a non-zero-dimensional " "integer array, but advanced integer indexing is not " "specified in the Array API." ) elif isinstance(i, tuple): raise IndexError( f"Single-axes index {i} is a tuple, but nested tuple " "indices are not specified in the Array API." ) # Everything below this line is required by the spec. def __abs__(self: Array, /) -> Array: """ Performs the operation __abs__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __abs__") res = self._array.__abs__() return self.__class__._new(res) def __add__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __add__. """ other = self._check_allowed_dtypes(other, "numeric", "__add__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__add__(other._array) return self.__class__._new(res) def __and__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __and__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__and__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__and__(other._array) return self.__class__._new(res) def __array_namespace__( self: Array, /, *, api_version: Optional[str] = None ) -> types.ModuleType: if api_version is not None and not api_version.startswith("2021."): raise ValueError(f"Unrecognized array API version: {api_version!r}") return array_api def __bool__(self: Array, /) -> bool: """ Performs the operation __bool__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("bool is only allowed on arrays with 0 dimensions") if self.dtype not in _boolean_dtypes: raise ValueError("bool is only allowed on boolean arrays") res = self._array.__bool__() return res def __dlpack__(self: Array, /, *, stream: None = None) -> PyCapsule: """ Performs the operation __dlpack__. """ return self._array.__dlpack__(stream=stream) def __dlpack_device__(self: Array, /) -> Tuple[IntEnum, int]: """ Performs the operation __dlpack_device__. """ # Note: device support is required for this return self._array.__dlpack_device__() def __eq__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __eq__. """ # Even though "all" dtypes are allowed, we still require them to be # promotable with each other. other = self._check_allowed_dtypes(other, "all", "__eq__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__eq__(other._array) return self.__class__._new(res) def __float__(self: Array, /) -> float: """ Performs the operation __float__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("float is only allowed on arrays with 0 dimensions") if self.dtype not in _floating_dtypes: raise ValueError("float is only allowed on floating-point arrays") res = self._array.__float__() return res def __floordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __floordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__floordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__floordiv__(other._array) return self.__class__._new(res) def __ge__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ge__. """ other = self._check_allowed_dtypes(other, "numeric", "__ge__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ge__(other._array) return self.__class__._new(res) def __getitem__( self: Array, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], /, ) -> Array: """ Performs the operation __getitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array res = self._array.__getitem__(key) return self._new(res) def __gt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __gt__. """ other = self._check_allowed_dtypes(other, "numeric", "__gt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__gt__(other._array) return self.__class__._new(res) def __int__(self: Array, /) -> int: """ Performs the operation __int__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("int is only allowed on arrays with 0 dimensions") if self.dtype not in _integer_dtypes: raise ValueError("int is only allowed on integer arrays") res = self._array.__int__() return res def __index__(self: Array, /) -> int: """ Performs the operation __index__. """ res = self._array.__index__() return res def __invert__(self: Array, /) -> Array: """ Performs the operation __invert__. """ if self.dtype not in _integer_or_boolean_dtypes: raise TypeError("Only integer or boolean dtypes are allowed in __invert__") res = self._array.__invert__() return self.__class__._new(res) def __le__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __le__. """ other = self._check_allowed_dtypes(other, "numeric", "__le__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__le__(other._array) return self.__class__._new(res) def __lshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __lshift__. """ other = self._check_allowed_dtypes(other, "integer", "__lshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lshift__(other._array) return self.__class__._new(res) def __lt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __lt__. """ other = self._check_allowed_dtypes(other, "numeric", "__lt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lt__(other._array) return self.__class__._new(res) def __matmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __matmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__matmul__") if other is NotImplemented: return other res = self._array.__matmul__(other._array) return self.__class__._new(res) def __mod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mod__. """ other = self._check_allowed_dtypes(other, "numeric", "__mod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mod__(other._array) return self.__class__._new(res) def __mul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mul__. """ other = self._check_allowed_dtypes(other, "numeric", "__mul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mul__(other._array) return self.__class__._new(res) def __ne__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __ne__. """ other = self._check_allowed_dtypes(other, "all", "__ne__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ne__(other._array) return self.__class__._new(res) def __neg__(self: Array, /) -> Array: """ Performs the operation __neg__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __neg__") res = self._array.__neg__() return self.__class__._new(res) def __or__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __or__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__or__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__or__(other._array) return self.__class__._new(res) def __pos__(self: Array, /) -> Array: """ Performs the operation __pos__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __pos__") res = self._array.__pos__() return self.__class__._new(res) def __pow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __pow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__pow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow type promotion rules for 0-d # arrays, so we use pow() here instead. return pow(self, other) def __rshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rshift__(other._array) return self.__class__._new(res) def __setitem__( self, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], value: Union[int, float, bool, Array], /, ) -> None: """ Performs the operation __setitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array self._array.__setitem__(key, asarray(value)._array) def __sub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __sub__. """ other = self._check_allowed_dtypes(other, "numeric", "__sub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__sub__(other._array) return self.__class__._new(res) # PEP 484 requires int to be a subtype of float, but __truediv__ should # not accept int. def __truediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __truediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__truediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__truediv__(other._array) return self.__class__._new(res) def __xor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __xor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__xor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__xor__(other._array) return self.__class__._new(res) def __iadd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __iadd__. """ other = self._check_allowed_dtypes(other, "numeric", "__iadd__") if other is NotImplemented: return other self._array.__iadd__(other._array) return self def __radd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __radd__. """ other = self._check_allowed_dtypes(other, "numeric", "__radd__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__radd__(other._array) return self.__class__._new(res) def __iand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __iand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__iand__") if other is NotImplemented: return other self._array.__iand__(other._array) return self def __rand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rand__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rand__(other._array) return self.__class__._new(res) def __ifloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ifloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__ifloordiv__") if other is NotImplemented: return other self._array.__ifloordiv__(other._array) return self def __rfloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rfloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__rfloordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rfloordiv__(other._array) return self.__class__._new(res) def __ilshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __ilshift__. """ other = self._check_allowed_dtypes(other, "integer", "__ilshift__") if other is NotImplemented: return other self._array.__ilshift__(other._array) return self def __rlshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rlshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rlshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rlshift__(other._array) return self.__class__._new(res) def __imatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __imatmul__. """ # Note: NumPy does not implement __imatmul__. # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__imatmul__") if other is NotImplemented: return other # __imatmul__ can only be allowed when it would not change the shape # of self. other_shape = other.shape if self.shape == () or other_shape == (): raise ValueError("@= requires at least one dimension") if len(other_shape) == 1 or other_shape[-1] != other_shape[-2]: raise ValueError("@= cannot change the shape of the input array") self._array[:] = self._array.__matmul__(other._array) return self def __rmatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __rmatmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__rmatmul__") if other is NotImplemented: return other res = self._array.__rmatmul__(other._array) return self.__class__._new(res) def __imod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imod__. """ other = self._check_allowed_dtypes(other, "numeric", "__imod__") if other is NotImplemented: return other self._array.__imod__(other._array) return self def __rmod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmod__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmod__(other._array) return self.__class__._new(res) def __imul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imul__. """ other = self._check_allowed_dtypes(other, "numeric", "__imul__") if other is NotImplemented: return other self._array.__imul__(other._array) return self def __rmul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmul__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmul__(other._array) return self.__class__._new(res) def __ior__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ior__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ior__") if other is NotImplemented: return other self._array.__ior__(other._array) return self def __ror__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ror__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ror__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ror__(other._array) return self.__class__._new(res) def __ipow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ipow__. """ other = self._check_allowed_dtypes(other, "numeric", "__ipow__") if other is NotImplemented: return other self._array.__ipow__(other._array) return self def __rpow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rpow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__rpow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow the spec type promotion rules # for 0-d arrays, so we use pow() here instead. return pow(other, self) def __irshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __irshift__. """ other = self._check_allowed_dtypes(other, "integer", "__irshift__") if other is NotImplemented: return other self._array.__irshift__(other._array) return self def __rrshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rrshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rrshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rrshift__(other._array) return self.__class__._new(res) def __isub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __isub__. """ other = self._check_allowed_dtypes(other, "numeric", "__isub__") if other is NotImplemented: return other self._array.__isub__(other._array) return self def __rsub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rsub__. """ other = self._check_allowed_dtypes(other, "numeric", "__rsub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rsub__(other._array) return self.__class__._new(res) def __itruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __itruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__itruediv__") if other is NotImplemented: return other self._array.__itruediv__(other._array) return self def __rtruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __rtruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__rtruediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rtruediv__(other._array) return self.__class__._new(res) def __ixor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ixor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ixor__") if other is NotImplemented: return other self._array.__ixor__(other._array) return self def __rxor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rxor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rxor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rxor__(other._array) return self.__class__._new(res) def to_device(self: Array, device: Device, /, stream: None = None) -> Array: if stream is not None: raise ValueError("The stream argument to to_device() is not supported") if device == 'cpu': return self raise ValueError(f"Unsupported device {device!r}") def dtype(self) -> Dtype: """ Array API compatible wrapper for :py:meth:`np.ndarray.dtype <numpy.ndarray.dtype>`. See its docstring for more information. """ return self._array.dtype def device(self) -> Device: return "cpu" # Note: mT is new in array API spec (see matrix_transpose) def mT(self) -> Array: from .linalg import matrix_transpose return matrix_transpose(self) def ndim(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.ndim <numpy.ndarray.ndim>`. See its docstring for more information. """ return self._array.ndim def shape(self) -> Tuple[int, ...]: """ Array API compatible wrapper for :py:meth:`np.ndarray.shape <numpy.ndarray.shape>`. See its docstring for more information. """ return self._array.shape def size(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.size <numpy.ndarray.size>`. See its docstring for more information. """ return self._array.size def T(self) -> Array: """ Array API compatible wrapper for :py:meth:`np.ndarray.T <numpy.ndarray.T>`. See its docstring for more information. """ # Note: T only works on 2-dimensional arrays. See the corresponding # note in the specification: # https://data-apis.org/array-api/latest/API_specification/array_object.html#t if self.ndim != 2: raise ValueError("x.T requires x to have 2 dimensions. Use x.mT to transpose stacks of matrices and permute_dims() to permute dimensions.") return self.__class__._new(self._array.T) Union: _SpecialForm = ... Optional: _SpecialForm = ... class Tuple(BaseTypingInstance): def _is_homogenous(self): # To specify a variable-length tuple of homogeneous type, Tuple[T, ...] # is used. return self._generics_manager.is_homogenous_tuple() def py__simple_getitem__(self, index): if self._is_homogenous(): return self._generics_manager.get_index_and_execute(0) else: if isinstance(index, int): return self._generics_manager.get_index_and_execute(index) debug.dbg('The getitem type on Tuple was %s' % index) return NO_VALUES def py__iter__(self, contextualized_node=None): if self._is_homogenous(): yield LazyKnownValues(self._generics_manager.get_index_and_execute(0)) else: for v in self._generics_manager.to_tuple(): yield LazyKnownValues(v.execute_annotation()) def py__getitem__(self, index_value_set, contextualized_node): if self._is_homogenous(): return self._generics_manager.get_index_and_execute(0) return ValueSet.from_sets( self._generics_manager.to_tuple() ).execute_annotation() def _get_wrapped_value(self): tuple_, = self.inference_state.builtins_module \ .py__getattribute__('tuple').execute_annotation() return tuple_ def name(self): return self._wrapped_value.name def infer_type_vars(self, value_set): # Circular from jedi.inference.gradual.annotation import merge_pairwise_generics, merge_type_var_dicts value_set = value_set.filter( lambda x: x.py__name__().lower() == 'tuple', ) if self._is_homogenous(): # The parameter annotation is of the form `Tuple[T, ...]`, # so we treat the incoming tuple like a iterable sequence # rather than a positional container of elements. return self._class_value.get_generics()[0].infer_type_vars( value_set.merge_types_of_iterate(), ) else: # The parameter annotation has only explicit type parameters # (e.g: `Tuple[T]`, `Tuple[T, U]`, `Tuple[T, U, V]`, etc.) so we # treat the incoming values as needing to match the annotation # exactly, just as we would for non-tuple annotations. type_var_dict = {} for element in value_set: try: method = element.get_annotated_class_object except AttributeError: # This might still happen, because the tuple name matching # above is not 100% correct, so just catch the remaining # cases here. continue py_class = method() merge_type_var_dicts( type_var_dict, merge_pairwise_generics(self._class_value, py_class), ) return type_var_dict The provided code snippet includes necessary dependencies for implementing the `all` function. Write a Python function `def all( x: Array, /, *, axis: Optional[Union[int, Tuple[int, ...]]] = None, keepdims: bool = False, ) -> Array` to solve the following problem: Array API compatible wrapper for :py:func:`np.all <numpy.all>`. See its docstring for more information. Here is the function: def all( x: Array, /, *, axis: Optional[Union[int, Tuple[int, ...]]] = None, keepdims: bool = False, ) -> Array: """ Array API compatible wrapper for :py:func:`np.all <numpy.all>`. See its docstring for more information. """ return Array._new(np.asarray(np.all(x._array, axis=axis, keepdims=keepdims)))
Array API compatible wrapper for :py:func:`np.all <numpy.all>`. See its docstring for more information.
170,076
from __future__ import annotations from ._array_object import Array from typing import Optional, Tuple, Union import numpy as np class Array: """ n-d array object for the array API namespace. See the docstring of :py:obj:`np.ndarray <numpy.ndarray>` for more information. This is a wrapper around numpy.ndarray that restricts the usage to only those things that are required by the array API namespace. Note, attributes on this object that start with a single underscore are not part of the API specification and should only be used internally. This object should not be constructed directly. Rather, use one of the creation functions, such as asarray(). """ _array: np.ndarray # Use a custom constructor instead of __init__, as manually initializing # this class is not supported API. def _new(cls, x, /): """ This is a private method for initializing the array API Array object. Functions outside of the array_api submodule should not use this method. Use one of the creation functions instead, such as ``asarray``. """ obj = super().__new__(cls) # Note: The spec does not have array scalars, only 0-D arrays. if isinstance(x, np.generic): # Convert the array scalar to a 0-D array x = np.asarray(x) if x.dtype not in _all_dtypes: raise TypeError( f"The array_api namespace does not support the dtype '{x.dtype}'" ) obj._array = x return obj # Prevent Array() from working def __new__(cls, *args, **kwargs): raise TypeError( "The array_api Array object should not be instantiated directly. Use an array creation function, such as asarray(), instead." ) # These functions are not required by the spec, but are implemented for # the sake of usability. def __str__(self: Array, /) -> str: """ Performs the operation __str__. """ return self._array.__str__().replace("array", "Array") def __repr__(self: Array, /) -> str: """ Performs the operation __repr__. """ suffix = f", dtype={self.dtype.name})" if 0 in self.shape: prefix = "empty(" mid = str(self.shape) else: prefix = "Array(" mid = np.array2string(self._array, separator=', ', prefix=prefix, suffix=suffix) return prefix + mid + suffix # This function is not required by the spec, but we implement it here for # convenience so that np.asarray(np.array_api.Array) will work. def __array__(self, dtype: None | np.dtype[Any] = None) -> npt.NDArray[Any]: """ Warning: this method is NOT part of the array API spec. Implementers of other libraries need not include it, and users should not assume it will be present in other implementations. """ return np.asarray(self._array, dtype=dtype) # These are various helper functions to make the array behavior match the # spec in places where it either deviates from or is more strict than # NumPy behavior def _check_allowed_dtypes(self, other: bool | int | float | Array, dtype_category: str, op: str) -> Array: """ Helper function for operators to only allow specific input dtypes Use like other = self._check_allowed_dtypes(other, 'numeric', '__add__') if other is NotImplemented: return other """ if self.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") if isinstance(other, (int, float, bool)): other = self._promote_scalar(other) elif isinstance(other, Array): if other.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") else: return NotImplemented # This will raise TypeError for type combinations that are not allowed # to promote in the spec (even if the NumPy array operator would # promote them). res_dtype = _result_type(self.dtype, other.dtype) if op.startswith("__i"): # Note: NumPy will allow in-place operators in some cases where # the type promoted operator does not match the left-hand side # operand. For example, # >>> a = np.array(1, dtype=np.int8) # >>> a += np.array(1, dtype=np.int16) # The spec explicitly disallows this. if res_dtype != self.dtype: raise TypeError( f"Cannot perform {op} with dtypes {self.dtype} and {other.dtype}" ) return other # Helper function to match the type promotion rules in the spec def _promote_scalar(self, scalar): """ Returns a promoted version of a Python scalar appropriate for use with operations on self. This may raise an OverflowError in cases where the scalar is an integer that is too large to fit in a NumPy integer dtype, or TypeError when the scalar type is incompatible with the dtype of self. """ # Note: Only Python scalar types that match the array dtype are # allowed. if isinstance(scalar, bool): if self.dtype not in _boolean_dtypes: raise TypeError( "Python bool scalars can only be promoted with bool arrays" ) elif isinstance(scalar, int): if self.dtype in _boolean_dtypes: raise TypeError( "Python int scalars cannot be promoted with bool arrays" ) elif isinstance(scalar, float): if self.dtype not in _floating_dtypes: raise TypeError( "Python float scalars can only be promoted with floating-point arrays." ) else: raise TypeError("'scalar' must be a Python scalar") # Note: scalars are unconditionally cast to the same dtype as the # array. # Note: the spec only specifies integer-dtype/int promotion # behavior for integers within the bounds of the integer dtype. # Outside of those bounds we use the default NumPy behavior (either # cast or raise OverflowError). return Array._new(np.array(scalar, self.dtype)) def _normalize_two_args(x1, x2) -> Tuple[Array, Array]: """ Normalize inputs to two arg functions to fix type promotion rules NumPy deviates from the spec type promotion rules in cases where one argument is 0-dimensional and the other is not. For example: >>> import numpy as np >>> a = np.array([1.0], dtype=np.float32) >>> b = np.array(1.0, dtype=np.float64) >>> np.add(a, b) # The spec says this should be float64 array([2.], dtype=float32) To fix this, we add a dimension to the 0-dimension array before passing it through. This works because a dimension would be added anyway from broadcasting, so the resulting shape is the same, but this prevents NumPy from not promoting the dtype. """ # Another option would be to use signature=(x1.dtype, x2.dtype, None), # but that only works for ufuncs, so we would have to call the ufuncs # directly in the operator methods. One should also note that this # sort of trick wouldn't work for functions like searchsorted, which # don't do normal broadcasting, but there aren't any functions like # that in the array API namespace. if x1.ndim == 0 and x2.ndim != 0: # The _array[None] workaround was chosen because it is relatively # performant. broadcast_to(x1._array, x2.shape) is much slower. We # could also manually type promote x2, but that is more complicated # and about the same performance as this. x1 = Array._new(x1._array[None]) elif x2.ndim == 0 and x1.ndim != 0: x2 = Array._new(x2._array[None]) return (x1, x2) # Note: A large fraction of allowed indices are disallowed here (see the # docstring below) def _validate_index(self, key): """ Validate an index according to the array API. The array API specification only requires a subset of indices that are supported by NumPy. This function will reject any index that is allowed by NumPy but not required by the array API specification. We always raise ``IndexError`` on such indices (the spec does not require any specific behavior on them, but this makes the NumPy array API namespace a minimal implementation of the spec). See https://data-apis.org/array-api/latest/API_specification/indexing.html for the full list of required indexing behavior This function raises IndexError if the index ``key`` is invalid. It only raises ``IndexError`` on indices that are not already rejected by NumPy, as NumPy will already raise the appropriate error on such indices. ``shape`` may be None, in which case, only cases that are independent of the array shape are checked. The following cases are allowed by NumPy, but not specified by the array API specification: - Indices to not include an implicit ellipsis at the end. That is, every axis of an array must be explicitly indexed or an ellipsis included. This behaviour is sometimes referred to as flat indexing. - The start and stop of a slice may not be out of bounds. In particular, for a slice ``i:j:k`` on an axis of size ``n``, only the following are allowed: - ``i`` or ``j`` omitted (``None``). - ``-n <= i <= max(0, n - 1)``. - For ``k > 0`` or ``k`` omitted (``None``), ``-n <= j <= n``. - For ``k < 0``, ``-n - 1 <= j <= max(0, n - 1)``. - Boolean array indices are not allowed as part of a larger tuple index. - Integer array indices are not allowed (with the exception of 0-D arrays, which are treated the same as scalars). Additionally, it should be noted that indices that would return a scalar in NumPy will return a 0-D array. Array scalars are not allowed in the specification, only 0-D arrays. This is done in the ``Array._new`` constructor, not this function. """ _key = key if isinstance(key, tuple) else (key,) for i in _key: if isinstance(i, bool) or not ( isinstance(i, SupportsIndex) # i.e. ints or isinstance(i, slice) or i == Ellipsis or i is None or isinstance(i, Array) or isinstance(i, np.ndarray) ): raise IndexError( f"Single-axes index {i} has {type(i)=}, but only " "integers, slices (:), ellipsis (...), newaxis (None), " "zero-dimensional integer arrays and boolean arrays " "are specified in the Array API." ) nonexpanding_key = [] single_axes = [] n_ellipsis = 0 key_has_mask = False for i in _key: if i is not None: nonexpanding_key.append(i) if isinstance(i, Array) or isinstance(i, np.ndarray): if i.dtype in _boolean_dtypes: key_has_mask = True single_axes.append(i) else: # i must not be an array here, to avoid elementwise equals if i == Ellipsis: n_ellipsis += 1 else: single_axes.append(i) n_single_axes = len(single_axes) if n_ellipsis > 1: return # handled by ndarray elif n_ellipsis == 0: # Note boolean masks must be the sole index, which we check for # later on. if not key_has_mask and n_single_axes < self.ndim: raise IndexError( f"{self.ndim=}, but the multi-axes index only specifies " f"{n_single_axes} dimensions. If this was intentional, " "add a trailing ellipsis (...) which expands into as many " "slices (:) as necessary - this is what np.ndarray arrays " "implicitly do, but such flat indexing behaviour is not " "specified in the Array API." ) if n_ellipsis == 0: indexed_shape = self.shape else: ellipsis_start = None for pos, i in enumerate(nonexpanding_key): if not (isinstance(i, Array) or isinstance(i, np.ndarray)): if i == Ellipsis: ellipsis_start = pos break assert ellipsis_start is not None # sanity check ellipsis_end = self.ndim - (n_single_axes - ellipsis_start) indexed_shape = ( self.shape[:ellipsis_start] + self.shape[ellipsis_end:] ) for i, side in zip(single_axes, indexed_shape): if isinstance(i, slice): if side == 0: f_range = "0 (or None)" else: f_range = f"between -{side} and {side - 1} (or None)" if i.start is not None: try: start = operator.index(i.start) except TypeError: pass # handled by ndarray else: if not (-side <= start <= side): raise IndexError( f"Slice {i} contains {start=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds starts are not specified in " "the Array API)" ) if i.stop is not None: try: stop = operator.index(i.stop) except TypeError: pass # handled by ndarray else: if not (-side <= stop <= side): raise IndexError( f"Slice {i} contains {stop=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds stops are not specified in " "the Array API)" ) elif isinstance(i, Array): if i.dtype in _boolean_dtypes and len(_key) != 1: assert isinstance(key, tuple) # sanity check raise IndexError( f"Single-axes index {i} is a boolean array and " f"{len(key)=}, but masking is only specified in the " "Array API when the array is the sole index." ) elif i.dtype in _integer_dtypes and i.ndim != 0: raise IndexError( f"Single-axes index {i} is a non-zero-dimensional " "integer array, but advanced integer indexing is not " "specified in the Array API." ) elif isinstance(i, tuple): raise IndexError( f"Single-axes index {i} is a tuple, but nested tuple " "indices are not specified in the Array API." ) # Everything below this line is required by the spec. def __abs__(self: Array, /) -> Array: """ Performs the operation __abs__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __abs__") res = self._array.__abs__() return self.__class__._new(res) def __add__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __add__. """ other = self._check_allowed_dtypes(other, "numeric", "__add__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__add__(other._array) return self.__class__._new(res) def __and__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __and__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__and__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__and__(other._array) return self.__class__._new(res) def __array_namespace__( self: Array, /, *, api_version: Optional[str] = None ) -> types.ModuleType: if api_version is not None and not api_version.startswith("2021."): raise ValueError(f"Unrecognized array API version: {api_version!r}") return array_api def __bool__(self: Array, /) -> bool: """ Performs the operation __bool__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("bool is only allowed on arrays with 0 dimensions") if self.dtype not in _boolean_dtypes: raise ValueError("bool is only allowed on boolean arrays") res = self._array.__bool__() return res def __dlpack__(self: Array, /, *, stream: None = None) -> PyCapsule: """ Performs the operation __dlpack__. """ return self._array.__dlpack__(stream=stream) def __dlpack_device__(self: Array, /) -> Tuple[IntEnum, int]: """ Performs the operation __dlpack_device__. """ # Note: device support is required for this return self._array.__dlpack_device__() def __eq__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __eq__. """ # Even though "all" dtypes are allowed, we still require them to be # promotable with each other. other = self._check_allowed_dtypes(other, "all", "__eq__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__eq__(other._array) return self.__class__._new(res) def __float__(self: Array, /) -> float: """ Performs the operation __float__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("float is only allowed on arrays with 0 dimensions") if self.dtype not in _floating_dtypes: raise ValueError("float is only allowed on floating-point arrays") res = self._array.__float__() return res def __floordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __floordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__floordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__floordiv__(other._array) return self.__class__._new(res) def __ge__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ge__. """ other = self._check_allowed_dtypes(other, "numeric", "__ge__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ge__(other._array) return self.__class__._new(res) def __getitem__( self: Array, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], /, ) -> Array: """ Performs the operation __getitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array res = self._array.__getitem__(key) return self._new(res) def __gt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __gt__. """ other = self._check_allowed_dtypes(other, "numeric", "__gt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__gt__(other._array) return self.__class__._new(res) def __int__(self: Array, /) -> int: """ Performs the operation __int__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("int is only allowed on arrays with 0 dimensions") if self.dtype not in _integer_dtypes: raise ValueError("int is only allowed on integer arrays") res = self._array.__int__() return res def __index__(self: Array, /) -> int: """ Performs the operation __index__. """ res = self._array.__index__() return res def __invert__(self: Array, /) -> Array: """ Performs the operation __invert__. """ if self.dtype not in _integer_or_boolean_dtypes: raise TypeError("Only integer or boolean dtypes are allowed in __invert__") res = self._array.__invert__() return self.__class__._new(res) def __le__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __le__. """ other = self._check_allowed_dtypes(other, "numeric", "__le__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__le__(other._array) return self.__class__._new(res) def __lshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __lshift__. """ other = self._check_allowed_dtypes(other, "integer", "__lshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lshift__(other._array) return self.__class__._new(res) def __lt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __lt__. """ other = self._check_allowed_dtypes(other, "numeric", "__lt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lt__(other._array) return self.__class__._new(res) def __matmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __matmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__matmul__") if other is NotImplemented: return other res = self._array.__matmul__(other._array) return self.__class__._new(res) def __mod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mod__. """ other = self._check_allowed_dtypes(other, "numeric", "__mod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mod__(other._array) return self.__class__._new(res) def __mul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mul__. """ other = self._check_allowed_dtypes(other, "numeric", "__mul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mul__(other._array) return self.__class__._new(res) def __ne__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __ne__. """ other = self._check_allowed_dtypes(other, "all", "__ne__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ne__(other._array) return self.__class__._new(res) def __neg__(self: Array, /) -> Array: """ Performs the operation __neg__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __neg__") res = self._array.__neg__() return self.__class__._new(res) def __or__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __or__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__or__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__or__(other._array) return self.__class__._new(res) def __pos__(self: Array, /) -> Array: """ Performs the operation __pos__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __pos__") res = self._array.__pos__() return self.__class__._new(res) def __pow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __pow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__pow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow type promotion rules for 0-d # arrays, so we use pow() here instead. return pow(self, other) def __rshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rshift__(other._array) return self.__class__._new(res) def __setitem__( self, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], value: Union[int, float, bool, Array], /, ) -> None: """ Performs the operation __setitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array self._array.__setitem__(key, asarray(value)._array) def __sub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __sub__. """ other = self._check_allowed_dtypes(other, "numeric", "__sub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__sub__(other._array) return self.__class__._new(res) # PEP 484 requires int to be a subtype of float, but __truediv__ should # not accept int. def __truediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __truediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__truediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__truediv__(other._array) return self.__class__._new(res) def __xor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __xor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__xor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__xor__(other._array) return self.__class__._new(res) def __iadd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __iadd__. """ other = self._check_allowed_dtypes(other, "numeric", "__iadd__") if other is NotImplemented: return other self._array.__iadd__(other._array) return self def __radd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __radd__. """ other = self._check_allowed_dtypes(other, "numeric", "__radd__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__radd__(other._array) return self.__class__._new(res) def __iand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __iand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__iand__") if other is NotImplemented: return other self._array.__iand__(other._array) return self def __rand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rand__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rand__(other._array) return self.__class__._new(res) def __ifloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ifloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__ifloordiv__") if other is NotImplemented: return other self._array.__ifloordiv__(other._array) return self def __rfloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rfloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__rfloordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rfloordiv__(other._array) return self.__class__._new(res) def __ilshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __ilshift__. """ other = self._check_allowed_dtypes(other, "integer", "__ilshift__") if other is NotImplemented: return other self._array.__ilshift__(other._array) return self def __rlshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rlshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rlshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rlshift__(other._array) return self.__class__._new(res) def __imatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __imatmul__. """ # Note: NumPy does not implement __imatmul__. # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__imatmul__") if other is NotImplemented: return other # __imatmul__ can only be allowed when it would not change the shape # of self. other_shape = other.shape if self.shape == () or other_shape == (): raise ValueError("@= requires at least one dimension") if len(other_shape) == 1 or other_shape[-1] != other_shape[-2]: raise ValueError("@= cannot change the shape of the input array") self._array[:] = self._array.__matmul__(other._array) return self def __rmatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __rmatmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__rmatmul__") if other is NotImplemented: return other res = self._array.__rmatmul__(other._array) return self.__class__._new(res) def __imod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imod__. """ other = self._check_allowed_dtypes(other, "numeric", "__imod__") if other is NotImplemented: return other self._array.__imod__(other._array) return self def __rmod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmod__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmod__(other._array) return self.__class__._new(res) def __imul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imul__. """ other = self._check_allowed_dtypes(other, "numeric", "__imul__") if other is NotImplemented: return other self._array.__imul__(other._array) return self def __rmul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmul__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmul__(other._array) return self.__class__._new(res) def __ior__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ior__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ior__") if other is NotImplemented: return other self._array.__ior__(other._array) return self def __ror__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ror__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ror__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ror__(other._array) return self.__class__._new(res) def __ipow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ipow__. """ other = self._check_allowed_dtypes(other, "numeric", "__ipow__") if other is NotImplemented: return other self._array.__ipow__(other._array) return self def __rpow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rpow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__rpow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow the spec type promotion rules # for 0-d arrays, so we use pow() here instead. return pow(other, self) def __irshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __irshift__. """ other = self._check_allowed_dtypes(other, "integer", "__irshift__") if other is NotImplemented: return other self._array.__irshift__(other._array) return self def __rrshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rrshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rrshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rrshift__(other._array) return self.__class__._new(res) def __isub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __isub__. """ other = self._check_allowed_dtypes(other, "numeric", "__isub__") if other is NotImplemented: return other self._array.__isub__(other._array) return self def __rsub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rsub__. """ other = self._check_allowed_dtypes(other, "numeric", "__rsub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rsub__(other._array) return self.__class__._new(res) def __itruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __itruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__itruediv__") if other is NotImplemented: return other self._array.__itruediv__(other._array) return self def __rtruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __rtruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__rtruediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rtruediv__(other._array) return self.__class__._new(res) def __ixor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ixor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ixor__") if other is NotImplemented: return other self._array.__ixor__(other._array) return self def __rxor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rxor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rxor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rxor__(other._array) return self.__class__._new(res) def to_device(self: Array, device: Device, /, stream: None = None) -> Array: if stream is not None: raise ValueError("The stream argument to to_device() is not supported") if device == 'cpu': return self raise ValueError(f"Unsupported device {device!r}") def dtype(self) -> Dtype: """ Array API compatible wrapper for :py:meth:`np.ndarray.dtype <numpy.ndarray.dtype>`. See its docstring for more information. """ return self._array.dtype def device(self) -> Device: return "cpu" # Note: mT is new in array API spec (see matrix_transpose) def mT(self) -> Array: from .linalg import matrix_transpose return matrix_transpose(self) def ndim(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.ndim <numpy.ndarray.ndim>`. See its docstring for more information. """ return self._array.ndim def shape(self) -> Tuple[int, ...]: """ Array API compatible wrapper for :py:meth:`np.ndarray.shape <numpy.ndarray.shape>`. See its docstring for more information. """ return self._array.shape def size(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.size <numpy.ndarray.size>`. See its docstring for more information. """ return self._array.size def T(self) -> Array: """ Array API compatible wrapper for :py:meth:`np.ndarray.T <numpy.ndarray.T>`. See its docstring for more information. """ # Note: T only works on 2-dimensional arrays. See the corresponding # note in the specification: # https://data-apis.org/array-api/latest/API_specification/array_object.html#t if self.ndim != 2: raise ValueError("x.T requires x to have 2 dimensions. Use x.mT to transpose stacks of matrices and permute_dims() to permute dimensions.") return self.__class__._new(self._array.T) Union: _SpecialForm = ... Optional: _SpecialForm = ... class Tuple(BaseTypingInstance): def _is_homogenous(self): # To specify a variable-length tuple of homogeneous type, Tuple[T, ...] # is used. return self._generics_manager.is_homogenous_tuple() def py__simple_getitem__(self, index): if self._is_homogenous(): return self._generics_manager.get_index_and_execute(0) else: if isinstance(index, int): return self._generics_manager.get_index_and_execute(index) debug.dbg('The getitem type on Tuple was %s' % index) return NO_VALUES def py__iter__(self, contextualized_node=None): if self._is_homogenous(): yield LazyKnownValues(self._generics_manager.get_index_and_execute(0)) else: for v in self._generics_manager.to_tuple(): yield LazyKnownValues(v.execute_annotation()) def py__getitem__(self, index_value_set, contextualized_node): if self._is_homogenous(): return self._generics_manager.get_index_and_execute(0) return ValueSet.from_sets( self._generics_manager.to_tuple() ).execute_annotation() def _get_wrapped_value(self): tuple_, = self.inference_state.builtins_module \ .py__getattribute__('tuple').execute_annotation() return tuple_ def name(self): return self._wrapped_value.name def infer_type_vars(self, value_set): # Circular from jedi.inference.gradual.annotation import merge_pairwise_generics, merge_type_var_dicts value_set = value_set.filter( lambda x: x.py__name__().lower() == 'tuple', ) if self._is_homogenous(): # The parameter annotation is of the form `Tuple[T, ...]`, # so we treat the incoming tuple like a iterable sequence # rather than a positional container of elements. return self._class_value.get_generics()[0].infer_type_vars( value_set.merge_types_of_iterate(), ) else: # The parameter annotation has only explicit type parameters # (e.g: `Tuple[T]`, `Tuple[T, U]`, `Tuple[T, U, V]`, etc.) so we # treat the incoming values as needing to match the annotation # exactly, just as we would for non-tuple annotations. type_var_dict = {} for element in value_set: try: method = element.get_annotated_class_object except AttributeError: # This might still happen, because the tuple name matching # above is not 100% correct, so just catch the remaining # cases here. continue py_class = method() merge_type_var_dicts( type_var_dict, merge_pairwise_generics(self._class_value, py_class), ) return type_var_dict The provided code snippet includes necessary dependencies for implementing the `any` function. Write a Python function `def any( x: Array, /, *, axis: Optional[Union[int, Tuple[int, ...]]] = None, keepdims: bool = False, ) -> Array` to solve the following problem: Array API compatible wrapper for :py:func:`np.any <numpy.any>`. See its docstring for more information. Here is the function: def any( x: Array, /, *, axis: Optional[Union[int, Tuple[int, ...]]] = None, keepdims: bool = False, ) -> Array: """ Array API compatible wrapper for :py:func:`np.any <numpy.any>`. See its docstring for more information. """ return Array._new(np.asarray(np.any(x._array, axis=axis, keepdims=keepdims)))
Array API compatible wrapper for :py:func:`np.any <numpy.any>`. See its docstring for more information.
170,077
from __future__ import annotations from ._array_object import Array import numpy as np class Array: """ n-d array object for the array API namespace. See the docstring of :py:obj:`np.ndarray <numpy.ndarray>` for more information. This is a wrapper around numpy.ndarray that restricts the usage to only those things that are required by the array API namespace. Note, attributes on this object that start with a single underscore are not part of the API specification and should only be used internally. This object should not be constructed directly. Rather, use one of the creation functions, such as asarray(). """ _array: np.ndarray # Use a custom constructor instead of __init__, as manually initializing # this class is not supported API. def _new(cls, x, /): """ This is a private method for initializing the array API Array object. Functions outside of the array_api submodule should not use this method. Use one of the creation functions instead, such as ``asarray``. """ obj = super().__new__(cls) # Note: The spec does not have array scalars, only 0-D arrays. if isinstance(x, np.generic): # Convert the array scalar to a 0-D array x = np.asarray(x) if x.dtype not in _all_dtypes: raise TypeError( f"The array_api namespace does not support the dtype '{x.dtype}'" ) obj._array = x return obj # Prevent Array() from working def __new__(cls, *args, **kwargs): raise TypeError( "The array_api Array object should not be instantiated directly. Use an array creation function, such as asarray(), instead." ) # These functions are not required by the spec, but are implemented for # the sake of usability. def __str__(self: Array, /) -> str: """ Performs the operation __str__. """ return self._array.__str__().replace("array", "Array") def __repr__(self: Array, /) -> str: """ Performs the operation __repr__. """ suffix = f", dtype={self.dtype.name})" if 0 in self.shape: prefix = "empty(" mid = str(self.shape) else: prefix = "Array(" mid = np.array2string(self._array, separator=', ', prefix=prefix, suffix=suffix) return prefix + mid + suffix # This function is not required by the spec, but we implement it here for # convenience so that np.asarray(np.array_api.Array) will work. def __array__(self, dtype: None | np.dtype[Any] = None) -> npt.NDArray[Any]: """ Warning: this method is NOT part of the array API spec. Implementers of other libraries need not include it, and users should not assume it will be present in other implementations. """ return np.asarray(self._array, dtype=dtype) # These are various helper functions to make the array behavior match the # spec in places where it either deviates from or is more strict than # NumPy behavior def _check_allowed_dtypes(self, other: bool | int | float | Array, dtype_category: str, op: str) -> Array: """ Helper function for operators to only allow specific input dtypes Use like other = self._check_allowed_dtypes(other, 'numeric', '__add__') if other is NotImplemented: return other """ if self.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") if isinstance(other, (int, float, bool)): other = self._promote_scalar(other) elif isinstance(other, Array): if other.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") else: return NotImplemented # This will raise TypeError for type combinations that are not allowed # to promote in the spec (even if the NumPy array operator would # promote them). res_dtype = _result_type(self.dtype, other.dtype) if op.startswith("__i"): # Note: NumPy will allow in-place operators in some cases where # the type promoted operator does not match the left-hand side # operand. For example, # >>> a = np.array(1, dtype=np.int8) # >>> a += np.array(1, dtype=np.int16) # The spec explicitly disallows this. if res_dtype != self.dtype: raise TypeError( f"Cannot perform {op} with dtypes {self.dtype} and {other.dtype}" ) return other # Helper function to match the type promotion rules in the spec def _promote_scalar(self, scalar): """ Returns a promoted version of a Python scalar appropriate for use with operations on self. This may raise an OverflowError in cases where the scalar is an integer that is too large to fit in a NumPy integer dtype, or TypeError when the scalar type is incompatible with the dtype of self. """ # Note: Only Python scalar types that match the array dtype are # allowed. if isinstance(scalar, bool): if self.dtype not in _boolean_dtypes: raise TypeError( "Python bool scalars can only be promoted with bool arrays" ) elif isinstance(scalar, int): if self.dtype in _boolean_dtypes: raise TypeError( "Python int scalars cannot be promoted with bool arrays" ) elif isinstance(scalar, float): if self.dtype not in _floating_dtypes: raise TypeError( "Python float scalars can only be promoted with floating-point arrays." ) else: raise TypeError("'scalar' must be a Python scalar") # Note: scalars are unconditionally cast to the same dtype as the # array. # Note: the spec only specifies integer-dtype/int promotion # behavior for integers within the bounds of the integer dtype. # Outside of those bounds we use the default NumPy behavior (either # cast or raise OverflowError). return Array._new(np.array(scalar, self.dtype)) def _normalize_two_args(x1, x2) -> Tuple[Array, Array]: """ Normalize inputs to two arg functions to fix type promotion rules NumPy deviates from the spec type promotion rules in cases where one argument is 0-dimensional and the other is not. For example: >>> import numpy as np >>> a = np.array([1.0], dtype=np.float32) >>> b = np.array(1.0, dtype=np.float64) >>> np.add(a, b) # The spec says this should be float64 array([2.], dtype=float32) To fix this, we add a dimension to the 0-dimension array before passing it through. This works because a dimension would be added anyway from broadcasting, so the resulting shape is the same, but this prevents NumPy from not promoting the dtype. """ # Another option would be to use signature=(x1.dtype, x2.dtype, None), # but that only works for ufuncs, so we would have to call the ufuncs # directly in the operator methods. One should also note that this # sort of trick wouldn't work for functions like searchsorted, which # don't do normal broadcasting, but there aren't any functions like # that in the array API namespace. if x1.ndim == 0 and x2.ndim != 0: # The _array[None] workaround was chosen because it is relatively # performant. broadcast_to(x1._array, x2.shape) is much slower. We # could also manually type promote x2, but that is more complicated # and about the same performance as this. x1 = Array._new(x1._array[None]) elif x2.ndim == 0 and x1.ndim != 0: x2 = Array._new(x2._array[None]) return (x1, x2) # Note: A large fraction of allowed indices are disallowed here (see the # docstring below) def _validate_index(self, key): """ Validate an index according to the array API. The array API specification only requires a subset of indices that are supported by NumPy. This function will reject any index that is allowed by NumPy but not required by the array API specification. We always raise ``IndexError`` on such indices (the spec does not require any specific behavior on them, but this makes the NumPy array API namespace a minimal implementation of the spec). See https://data-apis.org/array-api/latest/API_specification/indexing.html for the full list of required indexing behavior This function raises IndexError if the index ``key`` is invalid. It only raises ``IndexError`` on indices that are not already rejected by NumPy, as NumPy will already raise the appropriate error on such indices. ``shape`` may be None, in which case, only cases that are independent of the array shape are checked. The following cases are allowed by NumPy, but not specified by the array API specification: - Indices to not include an implicit ellipsis at the end. That is, every axis of an array must be explicitly indexed or an ellipsis included. This behaviour is sometimes referred to as flat indexing. - The start and stop of a slice may not be out of bounds. In particular, for a slice ``i:j:k`` on an axis of size ``n``, only the following are allowed: - ``i`` or ``j`` omitted (``None``). - ``-n <= i <= max(0, n - 1)``. - For ``k > 0`` or ``k`` omitted (``None``), ``-n <= j <= n``. - For ``k < 0``, ``-n - 1 <= j <= max(0, n - 1)``. - Boolean array indices are not allowed as part of a larger tuple index. - Integer array indices are not allowed (with the exception of 0-D arrays, which are treated the same as scalars). Additionally, it should be noted that indices that would return a scalar in NumPy will return a 0-D array. Array scalars are not allowed in the specification, only 0-D arrays. This is done in the ``Array._new`` constructor, not this function. """ _key = key if isinstance(key, tuple) else (key,) for i in _key: if isinstance(i, bool) or not ( isinstance(i, SupportsIndex) # i.e. ints or isinstance(i, slice) or i == Ellipsis or i is None or isinstance(i, Array) or isinstance(i, np.ndarray) ): raise IndexError( f"Single-axes index {i} has {type(i)=}, but only " "integers, slices (:), ellipsis (...), newaxis (None), " "zero-dimensional integer arrays and boolean arrays " "are specified in the Array API." ) nonexpanding_key = [] single_axes = [] n_ellipsis = 0 key_has_mask = False for i in _key: if i is not None: nonexpanding_key.append(i) if isinstance(i, Array) or isinstance(i, np.ndarray): if i.dtype in _boolean_dtypes: key_has_mask = True single_axes.append(i) else: # i must not be an array here, to avoid elementwise equals if i == Ellipsis: n_ellipsis += 1 else: single_axes.append(i) n_single_axes = len(single_axes) if n_ellipsis > 1: return # handled by ndarray elif n_ellipsis == 0: # Note boolean masks must be the sole index, which we check for # later on. if not key_has_mask and n_single_axes < self.ndim: raise IndexError( f"{self.ndim=}, but the multi-axes index only specifies " f"{n_single_axes} dimensions. If this was intentional, " "add a trailing ellipsis (...) which expands into as many " "slices (:) as necessary - this is what np.ndarray arrays " "implicitly do, but such flat indexing behaviour is not " "specified in the Array API." ) if n_ellipsis == 0: indexed_shape = self.shape else: ellipsis_start = None for pos, i in enumerate(nonexpanding_key): if not (isinstance(i, Array) or isinstance(i, np.ndarray)): if i == Ellipsis: ellipsis_start = pos break assert ellipsis_start is not None # sanity check ellipsis_end = self.ndim - (n_single_axes - ellipsis_start) indexed_shape = ( self.shape[:ellipsis_start] + self.shape[ellipsis_end:] ) for i, side in zip(single_axes, indexed_shape): if isinstance(i, slice): if side == 0: f_range = "0 (or None)" else: f_range = f"between -{side} and {side - 1} (or None)" if i.start is not None: try: start = operator.index(i.start) except TypeError: pass # handled by ndarray else: if not (-side <= start <= side): raise IndexError( f"Slice {i} contains {start=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds starts are not specified in " "the Array API)" ) if i.stop is not None: try: stop = operator.index(i.stop) except TypeError: pass # handled by ndarray else: if not (-side <= stop <= side): raise IndexError( f"Slice {i} contains {stop=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds stops are not specified in " "the Array API)" ) elif isinstance(i, Array): if i.dtype in _boolean_dtypes and len(_key) != 1: assert isinstance(key, tuple) # sanity check raise IndexError( f"Single-axes index {i} is a boolean array and " f"{len(key)=}, but masking is only specified in the " "Array API when the array is the sole index." ) elif i.dtype in _integer_dtypes and i.ndim != 0: raise IndexError( f"Single-axes index {i} is a non-zero-dimensional " "integer array, but advanced integer indexing is not " "specified in the Array API." ) elif isinstance(i, tuple): raise IndexError( f"Single-axes index {i} is a tuple, but nested tuple " "indices are not specified in the Array API." ) # Everything below this line is required by the spec. def __abs__(self: Array, /) -> Array: """ Performs the operation __abs__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __abs__") res = self._array.__abs__() return self.__class__._new(res) def __add__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __add__. """ other = self._check_allowed_dtypes(other, "numeric", "__add__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__add__(other._array) return self.__class__._new(res) def __and__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __and__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__and__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__and__(other._array) return self.__class__._new(res) def __array_namespace__( self: Array, /, *, api_version: Optional[str] = None ) -> types.ModuleType: if api_version is not None and not api_version.startswith("2021."): raise ValueError(f"Unrecognized array API version: {api_version!r}") return array_api def __bool__(self: Array, /) -> bool: """ Performs the operation __bool__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("bool is only allowed on arrays with 0 dimensions") if self.dtype not in _boolean_dtypes: raise ValueError("bool is only allowed on boolean arrays") res = self._array.__bool__() return res def __dlpack__(self: Array, /, *, stream: None = None) -> PyCapsule: """ Performs the operation __dlpack__. """ return self._array.__dlpack__(stream=stream) def __dlpack_device__(self: Array, /) -> Tuple[IntEnum, int]: """ Performs the operation __dlpack_device__. """ # Note: device support is required for this return self._array.__dlpack_device__() def __eq__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __eq__. """ # Even though "all" dtypes are allowed, we still require them to be # promotable with each other. other = self._check_allowed_dtypes(other, "all", "__eq__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__eq__(other._array) return self.__class__._new(res) def __float__(self: Array, /) -> float: """ Performs the operation __float__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("float is only allowed on arrays with 0 dimensions") if self.dtype not in _floating_dtypes: raise ValueError("float is only allowed on floating-point arrays") res = self._array.__float__() return res def __floordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __floordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__floordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__floordiv__(other._array) return self.__class__._new(res) def __ge__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ge__. """ other = self._check_allowed_dtypes(other, "numeric", "__ge__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ge__(other._array) return self.__class__._new(res) def __getitem__( self: Array, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], /, ) -> Array: """ Performs the operation __getitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array res = self._array.__getitem__(key) return self._new(res) def __gt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __gt__. """ other = self._check_allowed_dtypes(other, "numeric", "__gt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__gt__(other._array) return self.__class__._new(res) def __int__(self: Array, /) -> int: """ Performs the operation __int__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("int is only allowed on arrays with 0 dimensions") if self.dtype not in _integer_dtypes: raise ValueError("int is only allowed on integer arrays") res = self._array.__int__() return res def __index__(self: Array, /) -> int: """ Performs the operation __index__. """ res = self._array.__index__() return res def __invert__(self: Array, /) -> Array: """ Performs the operation __invert__. """ if self.dtype not in _integer_or_boolean_dtypes: raise TypeError("Only integer or boolean dtypes are allowed in __invert__") res = self._array.__invert__() return self.__class__._new(res) def __le__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __le__. """ other = self._check_allowed_dtypes(other, "numeric", "__le__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__le__(other._array) return self.__class__._new(res) def __lshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __lshift__. """ other = self._check_allowed_dtypes(other, "integer", "__lshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lshift__(other._array) return self.__class__._new(res) def __lt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __lt__. """ other = self._check_allowed_dtypes(other, "numeric", "__lt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lt__(other._array) return self.__class__._new(res) def __matmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __matmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__matmul__") if other is NotImplemented: return other res = self._array.__matmul__(other._array) return self.__class__._new(res) def __mod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mod__. """ other = self._check_allowed_dtypes(other, "numeric", "__mod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mod__(other._array) return self.__class__._new(res) def __mul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mul__. """ other = self._check_allowed_dtypes(other, "numeric", "__mul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mul__(other._array) return self.__class__._new(res) def __ne__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __ne__. """ other = self._check_allowed_dtypes(other, "all", "__ne__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ne__(other._array) return self.__class__._new(res) def __neg__(self: Array, /) -> Array: """ Performs the operation __neg__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __neg__") res = self._array.__neg__() return self.__class__._new(res) def __or__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __or__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__or__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__or__(other._array) return self.__class__._new(res) def __pos__(self: Array, /) -> Array: """ Performs the operation __pos__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __pos__") res = self._array.__pos__() return self.__class__._new(res) def __pow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __pow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__pow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow type promotion rules for 0-d # arrays, so we use pow() here instead. return pow(self, other) def __rshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rshift__(other._array) return self.__class__._new(res) def __setitem__( self, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], value: Union[int, float, bool, Array], /, ) -> None: """ Performs the operation __setitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array self._array.__setitem__(key, asarray(value)._array) def __sub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __sub__. """ other = self._check_allowed_dtypes(other, "numeric", "__sub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__sub__(other._array) return self.__class__._new(res) # PEP 484 requires int to be a subtype of float, but __truediv__ should # not accept int. def __truediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __truediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__truediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__truediv__(other._array) return self.__class__._new(res) def __xor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __xor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__xor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__xor__(other._array) return self.__class__._new(res) def __iadd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __iadd__. """ other = self._check_allowed_dtypes(other, "numeric", "__iadd__") if other is NotImplemented: return other self._array.__iadd__(other._array) return self def __radd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __radd__. """ other = self._check_allowed_dtypes(other, "numeric", "__radd__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__radd__(other._array) return self.__class__._new(res) def __iand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __iand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__iand__") if other is NotImplemented: return other self._array.__iand__(other._array) return self def __rand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rand__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rand__(other._array) return self.__class__._new(res) def __ifloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ifloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__ifloordiv__") if other is NotImplemented: return other self._array.__ifloordiv__(other._array) return self def __rfloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rfloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__rfloordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rfloordiv__(other._array) return self.__class__._new(res) def __ilshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __ilshift__. """ other = self._check_allowed_dtypes(other, "integer", "__ilshift__") if other is NotImplemented: return other self._array.__ilshift__(other._array) return self def __rlshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rlshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rlshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rlshift__(other._array) return self.__class__._new(res) def __imatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __imatmul__. """ # Note: NumPy does not implement __imatmul__. # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__imatmul__") if other is NotImplemented: return other # __imatmul__ can only be allowed when it would not change the shape # of self. other_shape = other.shape if self.shape == () or other_shape == (): raise ValueError("@= requires at least one dimension") if len(other_shape) == 1 or other_shape[-1] != other_shape[-2]: raise ValueError("@= cannot change the shape of the input array") self._array[:] = self._array.__matmul__(other._array) return self def __rmatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __rmatmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__rmatmul__") if other is NotImplemented: return other res = self._array.__rmatmul__(other._array) return self.__class__._new(res) def __imod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imod__. """ other = self._check_allowed_dtypes(other, "numeric", "__imod__") if other is NotImplemented: return other self._array.__imod__(other._array) return self def __rmod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmod__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmod__(other._array) return self.__class__._new(res) def __imul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imul__. """ other = self._check_allowed_dtypes(other, "numeric", "__imul__") if other is NotImplemented: return other self._array.__imul__(other._array) return self def __rmul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmul__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmul__(other._array) return self.__class__._new(res) def __ior__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ior__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ior__") if other is NotImplemented: return other self._array.__ior__(other._array) return self def __ror__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ror__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ror__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ror__(other._array) return self.__class__._new(res) def __ipow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ipow__. """ other = self._check_allowed_dtypes(other, "numeric", "__ipow__") if other is NotImplemented: return other self._array.__ipow__(other._array) return self def __rpow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rpow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__rpow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow the spec type promotion rules # for 0-d arrays, so we use pow() here instead. return pow(other, self) def __irshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __irshift__. """ other = self._check_allowed_dtypes(other, "integer", "__irshift__") if other is NotImplemented: return other self._array.__irshift__(other._array) return self def __rrshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rrshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rrshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rrshift__(other._array) return self.__class__._new(res) def __isub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __isub__. """ other = self._check_allowed_dtypes(other, "numeric", "__isub__") if other is NotImplemented: return other self._array.__isub__(other._array) return self def __rsub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rsub__. """ other = self._check_allowed_dtypes(other, "numeric", "__rsub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rsub__(other._array) return self.__class__._new(res) def __itruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __itruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__itruediv__") if other is NotImplemented: return other self._array.__itruediv__(other._array) return self def __rtruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __rtruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__rtruediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rtruediv__(other._array) return self.__class__._new(res) def __ixor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ixor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ixor__") if other is NotImplemented: return other self._array.__ixor__(other._array) return self def __rxor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rxor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rxor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rxor__(other._array) return self.__class__._new(res) def to_device(self: Array, device: Device, /, stream: None = None) -> Array: if stream is not None: raise ValueError("The stream argument to to_device() is not supported") if device == 'cpu': return self raise ValueError(f"Unsupported device {device!r}") def dtype(self) -> Dtype: """ Array API compatible wrapper for :py:meth:`np.ndarray.dtype <numpy.ndarray.dtype>`. See its docstring for more information. """ return self._array.dtype def device(self) -> Device: return "cpu" # Note: mT is new in array API spec (see matrix_transpose) def mT(self) -> Array: from .linalg import matrix_transpose return matrix_transpose(self) def ndim(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.ndim <numpy.ndarray.ndim>`. See its docstring for more information. """ return self._array.ndim def shape(self) -> Tuple[int, ...]: """ Array API compatible wrapper for :py:meth:`np.ndarray.shape <numpy.ndarray.shape>`. See its docstring for more information. """ return self._array.shape def size(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.size <numpy.ndarray.size>`. See its docstring for more information. """ return self._array.size def T(self) -> Array: """ Array API compatible wrapper for :py:meth:`np.ndarray.T <numpy.ndarray.T>`. See its docstring for more information. """ # Note: T only works on 2-dimensional arrays. See the corresponding # note in the specification: # https://data-apis.org/array-api/latest/API_specification/array_object.html#t if self.ndim != 2: raise ValueError("x.T requires x to have 2 dimensions. Use x.mT to transpose stacks of matrices and permute_dims() to permute dimensions.") return self.__class__._new(self._array.T) The provided code snippet includes necessary dependencies for implementing the `argsort` function. Write a Python function `def argsort( x: Array, /, *, axis: int = -1, descending: bool = False, stable: bool = True ) -> Array` to solve the following problem: Array API compatible wrapper for :py:func:`np.argsort <numpy.argsort>`. See its docstring for more information. Here is the function: def argsort( x: Array, /, *, axis: int = -1, descending: bool = False, stable: bool = True ) -> Array: """ Array API compatible wrapper for :py:func:`np.argsort <numpy.argsort>`. See its docstring for more information. """ # Note: this keyword argument is different, and the default is different. kind = "stable" if stable else "quicksort" if not descending: res = np.argsort(x._array, axis=axis, kind=kind) else: # As NumPy has no native descending sort, we imitate it here. Note that # simply flipping the results of np.argsort(x._array, ...) would not # respect the relative order like it would in native descending sorts. res = np.flip( np.argsort(np.flip(x._array, axis=axis), axis=axis, kind=kind), axis=axis, ) # Rely on flip()/argsort() to validate axis normalised_axis = axis if axis >= 0 else x.ndim + axis max_i = x.shape[normalised_axis] - 1 res = max_i - res return Array._new(res)
Array API compatible wrapper for :py:func:`np.argsort <numpy.argsort>`. See its docstring for more information.
170,078
from __future__ import annotations from ._array_object import Array import numpy as np class Array: """ n-d array object for the array API namespace. See the docstring of :py:obj:`np.ndarray <numpy.ndarray>` for more information. This is a wrapper around numpy.ndarray that restricts the usage to only those things that are required by the array API namespace. Note, attributes on this object that start with a single underscore are not part of the API specification and should only be used internally. This object should not be constructed directly. Rather, use one of the creation functions, such as asarray(). """ _array: np.ndarray # Use a custom constructor instead of __init__, as manually initializing # this class is not supported API. def _new(cls, x, /): """ This is a private method for initializing the array API Array object. Functions outside of the array_api submodule should not use this method. Use one of the creation functions instead, such as ``asarray``. """ obj = super().__new__(cls) # Note: The spec does not have array scalars, only 0-D arrays. if isinstance(x, np.generic): # Convert the array scalar to a 0-D array x = np.asarray(x) if x.dtype not in _all_dtypes: raise TypeError( f"The array_api namespace does not support the dtype '{x.dtype}'" ) obj._array = x return obj # Prevent Array() from working def __new__(cls, *args, **kwargs): raise TypeError( "The array_api Array object should not be instantiated directly. Use an array creation function, such as asarray(), instead." ) # These functions are not required by the spec, but are implemented for # the sake of usability. def __str__(self: Array, /) -> str: """ Performs the operation __str__. """ return self._array.__str__().replace("array", "Array") def __repr__(self: Array, /) -> str: """ Performs the operation __repr__. """ suffix = f", dtype={self.dtype.name})" if 0 in self.shape: prefix = "empty(" mid = str(self.shape) else: prefix = "Array(" mid = np.array2string(self._array, separator=', ', prefix=prefix, suffix=suffix) return prefix + mid + suffix # This function is not required by the spec, but we implement it here for # convenience so that np.asarray(np.array_api.Array) will work. def __array__(self, dtype: None | np.dtype[Any] = None) -> npt.NDArray[Any]: """ Warning: this method is NOT part of the array API spec. Implementers of other libraries need not include it, and users should not assume it will be present in other implementations. """ return np.asarray(self._array, dtype=dtype) # These are various helper functions to make the array behavior match the # spec in places where it either deviates from or is more strict than # NumPy behavior def _check_allowed_dtypes(self, other: bool | int | float | Array, dtype_category: str, op: str) -> Array: """ Helper function for operators to only allow specific input dtypes Use like other = self._check_allowed_dtypes(other, 'numeric', '__add__') if other is NotImplemented: return other """ if self.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") if isinstance(other, (int, float, bool)): other = self._promote_scalar(other) elif isinstance(other, Array): if other.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") else: return NotImplemented # This will raise TypeError for type combinations that are not allowed # to promote in the spec (even if the NumPy array operator would # promote them). res_dtype = _result_type(self.dtype, other.dtype) if op.startswith("__i"): # Note: NumPy will allow in-place operators in some cases where # the type promoted operator does not match the left-hand side # operand. For example, # >>> a = np.array(1, dtype=np.int8) # >>> a += np.array(1, dtype=np.int16) # The spec explicitly disallows this. if res_dtype != self.dtype: raise TypeError( f"Cannot perform {op} with dtypes {self.dtype} and {other.dtype}" ) return other # Helper function to match the type promotion rules in the spec def _promote_scalar(self, scalar): """ Returns a promoted version of a Python scalar appropriate for use with operations on self. This may raise an OverflowError in cases where the scalar is an integer that is too large to fit in a NumPy integer dtype, or TypeError when the scalar type is incompatible with the dtype of self. """ # Note: Only Python scalar types that match the array dtype are # allowed. if isinstance(scalar, bool): if self.dtype not in _boolean_dtypes: raise TypeError( "Python bool scalars can only be promoted with bool arrays" ) elif isinstance(scalar, int): if self.dtype in _boolean_dtypes: raise TypeError( "Python int scalars cannot be promoted with bool arrays" ) elif isinstance(scalar, float): if self.dtype not in _floating_dtypes: raise TypeError( "Python float scalars can only be promoted with floating-point arrays." ) else: raise TypeError("'scalar' must be a Python scalar") # Note: scalars are unconditionally cast to the same dtype as the # array. # Note: the spec only specifies integer-dtype/int promotion # behavior for integers within the bounds of the integer dtype. # Outside of those bounds we use the default NumPy behavior (either # cast or raise OverflowError). return Array._new(np.array(scalar, self.dtype)) def _normalize_two_args(x1, x2) -> Tuple[Array, Array]: """ Normalize inputs to two arg functions to fix type promotion rules NumPy deviates from the spec type promotion rules in cases where one argument is 0-dimensional and the other is not. For example: >>> import numpy as np >>> a = np.array([1.0], dtype=np.float32) >>> b = np.array(1.0, dtype=np.float64) >>> np.add(a, b) # The spec says this should be float64 array([2.], dtype=float32) To fix this, we add a dimension to the 0-dimension array before passing it through. This works because a dimension would be added anyway from broadcasting, so the resulting shape is the same, but this prevents NumPy from not promoting the dtype. """ # Another option would be to use signature=(x1.dtype, x2.dtype, None), # but that only works for ufuncs, so we would have to call the ufuncs # directly in the operator methods. One should also note that this # sort of trick wouldn't work for functions like searchsorted, which # don't do normal broadcasting, but there aren't any functions like # that in the array API namespace. if x1.ndim == 0 and x2.ndim != 0: # The _array[None] workaround was chosen because it is relatively # performant. broadcast_to(x1._array, x2.shape) is much slower. We # could also manually type promote x2, but that is more complicated # and about the same performance as this. x1 = Array._new(x1._array[None]) elif x2.ndim == 0 and x1.ndim != 0: x2 = Array._new(x2._array[None]) return (x1, x2) # Note: A large fraction of allowed indices are disallowed here (see the # docstring below) def _validate_index(self, key): """ Validate an index according to the array API. The array API specification only requires a subset of indices that are supported by NumPy. This function will reject any index that is allowed by NumPy but not required by the array API specification. We always raise ``IndexError`` on such indices (the spec does not require any specific behavior on them, but this makes the NumPy array API namespace a minimal implementation of the spec). See https://data-apis.org/array-api/latest/API_specification/indexing.html for the full list of required indexing behavior This function raises IndexError if the index ``key`` is invalid. It only raises ``IndexError`` on indices that are not already rejected by NumPy, as NumPy will already raise the appropriate error on such indices. ``shape`` may be None, in which case, only cases that are independent of the array shape are checked. The following cases are allowed by NumPy, but not specified by the array API specification: - Indices to not include an implicit ellipsis at the end. That is, every axis of an array must be explicitly indexed or an ellipsis included. This behaviour is sometimes referred to as flat indexing. - The start and stop of a slice may not be out of bounds. In particular, for a slice ``i:j:k`` on an axis of size ``n``, only the following are allowed: - ``i`` or ``j`` omitted (``None``). - ``-n <= i <= max(0, n - 1)``. - For ``k > 0`` or ``k`` omitted (``None``), ``-n <= j <= n``. - For ``k < 0``, ``-n - 1 <= j <= max(0, n - 1)``. - Boolean array indices are not allowed as part of a larger tuple index. - Integer array indices are not allowed (with the exception of 0-D arrays, which are treated the same as scalars). Additionally, it should be noted that indices that would return a scalar in NumPy will return a 0-D array. Array scalars are not allowed in the specification, only 0-D arrays. This is done in the ``Array._new`` constructor, not this function. """ _key = key if isinstance(key, tuple) else (key,) for i in _key: if isinstance(i, bool) or not ( isinstance(i, SupportsIndex) # i.e. ints or isinstance(i, slice) or i == Ellipsis or i is None or isinstance(i, Array) or isinstance(i, np.ndarray) ): raise IndexError( f"Single-axes index {i} has {type(i)=}, but only " "integers, slices (:), ellipsis (...), newaxis (None), " "zero-dimensional integer arrays and boolean arrays " "are specified in the Array API." ) nonexpanding_key = [] single_axes = [] n_ellipsis = 0 key_has_mask = False for i in _key: if i is not None: nonexpanding_key.append(i) if isinstance(i, Array) or isinstance(i, np.ndarray): if i.dtype in _boolean_dtypes: key_has_mask = True single_axes.append(i) else: # i must not be an array here, to avoid elementwise equals if i == Ellipsis: n_ellipsis += 1 else: single_axes.append(i) n_single_axes = len(single_axes) if n_ellipsis > 1: return # handled by ndarray elif n_ellipsis == 0: # Note boolean masks must be the sole index, which we check for # later on. if not key_has_mask and n_single_axes < self.ndim: raise IndexError( f"{self.ndim=}, but the multi-axes index only specifies " f"{n_single_axes} dimensions. If this was intentional, " "add a trailing ellipsis (...) which expands into as many " "slices (:) as necessary - this is what np.ndarray arrays " "implicitly do, but such flat indexing behaviour is not " "specified in the Array API." ) if n_ellipsis == 0: indexed_shape = self.shape else: ellipsis_start = None for pos, i in enumerate(nonexpanding_key): if not (isinstance(i, Array) or isinstance(i, np.ndarray)): if i == Ellipsis: ellipsis_start = pos break assert ellipsis_start is not None # sanity check ellipsis_end = self.ndim - (n_single_axes - ellipsis_start) indexed_shape = ( self.shape[:ellipsis_start] + self.shape[ellipsis_end:] ) for i, side in zip(single_axes, indexed_shape): if isinstance(i, slice): if side == 0: f_range = "0 (or None)" else: f_range = f"between -{side} and {side - 1} (or None)" if i.start is not None: try: start = operator.index(i.start) except TypeError: pass # handled by ndarray else: if not (-side <= start <= side): raise IndexError( f"Slice {i} contains {start=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds starts are not specified in " "the Array API)" ) if i.stop is not None: try: stop = operator.index(i.stop) except TypeError: pass # handled by ndarray else: if not (-side <= stop <= side): raise IndexError( f"Slice {i} contains {stop=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds stops are not specified in " "the Array API)" ) elif isinstance(i, Array): if i.dtype in _boolean_dtypes and len(_key) != 1: assert isinstance(key, tuple) # sanity check raise IndexError( f"Single-axes index {i} is a boolean array and " f"{len(key)=}, but masking is only specified in the " "Array API when the array is the sole index." ) elif i.dtype in _integer_dtypes and i.ndim != 0: raise IndexError( f"Single-axes index {i} is a non-zero-dimensional " "integer array, but advanced integer indexing is not " "specified in the Array API." ) elif isinstance(i, tuple): raise IndexError( f"Single-axes index {i} is a tuple, but nested tuple " "indices are not specified in the Array API." ) # Everything below this line is required by the spec. def __abs__(self: Array, /) -> Array: """ Performs the operation __abs__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __abs__") res = self._array.__abs__() return self.__class__._new(res) def __add__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __add__. """ other = self._check_allowed_dtypes(other, "numeric", "__add__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__add__(other._array) return self.__class__._new(res) def __and__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __and__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__and__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__and__(other._array) return self.__class__._new(res) def __array_namespace__( self: Array, /, *, api_version: Optional[str] = None ) -> types.ModuleType: if api_version is not None and not api_version.startswith("2021."): raise ValueError(f"Unrecognized array API version: {api_version!r}") return array_api def __bool__(self: Array, /) -> bool: """ Performs the operation __bool__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("bool is only allowed on arrays with 0 dimensions") if self.dtype not in _boolean_dtypes: raise ValueError("bool is only allowed on boolean arrays") res = self._array.__bool__() return res def __dlpack__(self: Array, /, *, stream: None = None) -> PyCapsule: """ Performs the operation __dlpack__. """ return self._array.__dlpack__(stream=stream) def __dlpack_device__(self: Array, /) -> Tuple[IntEnum, int]: """ Performs the operation __dlpack_device__. """ # Note: device support is required for this return self._array.__dlpack_device__() def __eq__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __eq__. """ # Even though "all" dtypes are allowed, we still require them to be # promotable with each other. other = self._check_allowed_dtypes(other, "all", "__eq__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__eq__(other._array) return self.__class__._new(res) def __float__(self: Array, /) -> float: """ Performs the operation __float__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("float is only allowed on arrays with 0 dimensions") if self.dtype not in _floating_dtypes: raise ValueError("float is only allowed on floating-point arrays") res = self._array.__float__() return res def __floordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __floordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__floordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__floordiv__(other._array) return self.__class__._new(res) def __ge__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ge__. """ other = self._check_allowed_dtypes(other, "numeric", "__ge__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ge__(other._array) return self.__class__._new(res) def __getitem__( self: Array, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], /, ) -> Array: """ Performs the operation __getitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array res = self._array.__getitem__(key) return self._new(res) def __gt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __gt__. """ other = self._check_allowed_dtypes(other, "numeric", "__gt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__gt__(other._array) return self.__class__._new(res) def __int__(self: Array, /) -> int: """ Performs the operation __int__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("int is only allowed on arrays with 0 dimensions") if self.dtype not in _integer_dtypes: raise ValueError("int is only allowed on integer arrays") res = self._array.__int__() return res def __index__(self: Array, /) -> int: """ Performs the operation __index__. """ res = self._array.__index__() return res def __invert__(self: Array, /) -> Array: """ Performs the operation __invert__. """ if self.dtype not in _integer_or_boolean_dtypes: raise TypeError("Only integer or boolean dtypes are allowed in __invert__") res = self._array.__invert__() return self.__class__._new(res) def __le__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __le__. """ other = self._check_allowed_dtypes(other, "numeric", "__le__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__le__(other._array) return self.__class__._new(res) def __lshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __lshift__. """ other = self._check_allowed_dtypes(other, "integer", "__lshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lshift__(other._array) return self.__class__._new(res) def __lt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __lt__. """ other = self._check_allowed_dtypes(other, "numeric", "__lt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lt__(other._array) return self.__class__._new(res) def __matmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __matmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__matmul__") if other is NotImplemented: return other res = self._array.__matmul__(other._array) return self.__class__._new(res) def __mod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mod__. """ other = self._check_allowed_dtypes(other, "numeric", "__mod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mod__(other._array) return self.__class__._new(res) def __mul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mul__. """ other = self._check_allowed_dtypes(other, "numeric", "__mul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mul__(other._array) return self.__class__._new(res) def __ne__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __ne__. """ other = self._check_allowed_dtypes(other, "all", "__ne__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ne__(other._array) return self.__class__._new(res) def __neg__(self: Array, /) -> Array: """ Performs the operation __neg__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __neg__") res = self._array.__neg__() return self.__class__._new(res) def __or__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __or__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__or__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__or__(other._array) return self.__class__._new(res) def __pos__(self: Array, /) -> Array: """ Performs the operation __pos__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __pos__") res = self._array.__pos__() return self.__class__._new(res) def __pow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __pow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__pow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow type promotion rules for 0-d # arrays, so we use pow() here instead. return pow(self, other) def __rshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rshift__(other._array) return self.__class__._new(res) def __setitem__( self, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], value: Union[int, float, bool, Array], /, ) -> None: """ Performs the operation __setitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array self._array.__setitem__(key, asarray(value)._array) def __sub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __sub__. """ other = self._check_allowed_dtypes(other, "numeric", "__sub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__sub__(other._array) return self.__class__._new(res) # PEP 484 requires int to be a subtype of float, but __truediv__ should # not accept int. def __truediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __truediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__truediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__truediv__(other._array) return self.__class__._new(res) def __xor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __xor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__xor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__xor__(other._array) return self.__class__._new(res) def __iadd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __iadd__. """ other = self._check_allowed_dtypes(other, "numeric", "__iadd__") if other is NotImplemented: return other self._array.__iadd__(other._array) return self def __radd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __radd__. """ other = self._check_allowed_dtypes(other, "numeric", "__radd__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__radd__(other._array) return self.__class__._new(res) def __iand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __iand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__iand__") if other is NotImplemented: return other self._array.__iand__(other._array) return self def __rand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rand__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rand__(other._array) return self.__class__._new(res) def __ifloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ifloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__ifloordiv__") if other is NotImplemented: return other self._array.__ifloordiv__(other._array) return self def __rfloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rfloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__rfloordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rfloordiv__(other._array) return self.__class__._new(res) def __ilshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __ilshift__. """ other = self._check_allowed_dtypes(other, "integer", "__ilshift__") if other is NotImplemented: return other self._array.__ilshift__(other._array) return self def __rlshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rlshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rlshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rlshift__(other._array) return self.__class__._new(res) def __imatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __imatmul__. """ # Note: NumPy does not implement __imatmul__. # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__imatmul__") if other is NotImplemented: return other # __imatmul__ can only be allowed when it would not change the shape # of self. other_shape = other.shape if self.shape == () or other_shape == (): raise ValueError("@= requires at least one dimension") if len(other_shape) == 1 or other_shape[-1] != other_shape[-2]: raise ValueError("@= cannot change the shape of the input array") self._array[:] = self._array.__matmul__(other._array) return self def __rmatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __rmatmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__rmatmul__") if other is NotImplemented: return other res = self._array.__rmatmul__(other._array) return self.__class__._new(res) def __imod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imod__. """ other = self._check_allowed_dtypes(other, "numeric", "__imod__") if other is NotImplemented: return other self._array.__imod__(other._array) return self def __rmod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmod__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmod__(other._array) return self.__class__._new(res) def __imul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imul__. """ other = self._check_allowed_dtypes(other, "numeric", "__imul__") if other is NotImplemented: return other self._array.__imul__(other._array) return self def __rmul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmul__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmul__(other._array) return self.__class__._new(res) def __ior__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ior__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ior__") if other is NotImplemented: return other self._array.__ior__(other._array) return self def __ror__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ror__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ror__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ror__(other._array) return self.__class__._new(res) def __ipow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ipow__. """ other = self._check_allowed_dtypes(other, "numeric", "__ipow__") if other is NotImplemented: return other self._array.__ipow__(other._array) return self def __rpow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rpow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__rpow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow the spec type promotion rules # for 0-d arrays, so we use pow() here instead. return pow(other, self) def __irshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __irshift__. """ other = self._check_allowed_dtypes(other, "integer", "__irshift__") if other is NotImplemented: return other self._array.__irshift__(other._array) return self def __rrshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rrshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rrshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rrshift__(other._array) return self.__class__._new(res) def __isub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __isub__. """ other = self._check_allowed_dtypes(other, "numeric", "__isub__") if other is NotImplemented: return other self._array.__isub__(other._array) return self def __rsub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rsub__. """ other = self._check_allowed_dtypes(other, "numeric", "__rsub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rsub__(other._array) return self.__class__._new(res) def __itruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __itruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__itruediv__") if other is NotImplemented: return other self._array.__itruediv__(other._array) return self def __rtruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __rtruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__rtruediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rtruediv__(other._array) return self.__class__._new(res) def __ixor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ixor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ixor__") if other is NotImplemented: return other self._array.__ixor__(other._array) return self def __rxor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rxor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rxor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rxor__(other._array) return self.__class__._new(res) def to_device(self: Array, device: Device, /, stream: None = None) -> Array: if stream is not None: raise ValueError("The stream argument to to_device() is not supported") if device == 'cpu': return self raise ValueError(f"Unsupported device {device!r}") def dtype(self) -> Dtype: """ Array API compatible wrapper for :py:meth:`np.ndarray.dtype <numpy.ndarray.dtype>`. See its docstring for more information. """ return self._array.dtype def device(self) -> Device: return "cpu" # Note: mT is new in array API spec (see matrix_transpose) def mT(self) -> Array: from .linalg import matrix_transpose return matrix_transpose(self) def ndim(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.ndim <numpy.ndarray.ndim>`. See its docstring for more information. """ return self._array.ndim def shape(self) -> Tuple[int, ...]: """ Array API compatible wrapper for :py:meth:`np.ndarray.shape <numpy.ndarray.shape>`. See its docstring for more information. """ return self._array.shape def size(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.size <numpy.ndarray.size>`. See its docstring for more information. """ return self._array.size def T(self) -> Array: """ Array API compatible wrapper for :py:meth:`np.ndarray.T <numpy.ndarray.T>`. See its docstring for more information. """ # Note: T only works on 2-dimensional arrays. See the corresponding # note in the specification: # https://data-apis.org/array-api/latest/API_specification/array_object.html#t if self.ndim != 2: raise ValueError("x.T requires x to have 2 dimensions. Use x.mT to transpose stacks of matrices and permute_dims() to permute dimensions.") return self.__class__._new(self._array.T) The provided code snippet includes necessary dependencies for implementing the `sort` function. Write a Python function `def sort( x: Array, /, *, axis: int = -1, descending: bool = False, stable: bool = True ) -> Array` to solve the following problem: Array API compatible wrapper for :py:func:`np.sort <numpy.sort>`. See its docstring for more information. Here is the function: def sort( x: Array, /, *, axis: int = -1, descending: bool = False, stable: bool = True ) -> Array: """ Array API compatible wrapper for :py:func:`np.sort <numpy.sort>`. See its docstring for more information. """ # Note: this keyword argument is different, and the default is different. kind = "stable" if stable else "quicksort" res = np.sort(x._array, axis=axis, kind=kind) if descending: res = np.flip(res, axis=axis) return Array._new(res)
Array API compatible wrapper for :py:func:`np.sort <numpy.sort>`. See its docstring for more information.
170,079
from __future__ import annotations from ._array_object import Array from ._data_type_functions import result_type from typing import List, Optional, Tuple, Union import numpy as np class Array: """ n-d array object for the array API namespace. See the docstring of :py:obj:`np.ndarray <numpy.ndarray>` for more information. This is a wrapper around numpy.ndarray that restricts the usage to only those things that are required by the array API namespace. Note, attributes on this object that start with a single underscore are not part of the API specification and should only be used internally. This object should not be constructed directly. Rather, use one of the creation functions, such as asarray(). """ _array: np.ndarray # Use a custom constructor instead of __init__, as manually initializing # this class is not supported API. def _new(cls, x, /): """ This is a private method for initializing the array API Array object. Functions outside of the array_api submodule should not use this method. Use one of the creation functions instead, such as ``asarray``. """ obj = super().__new__(cls) # Note: The spec does not have array scalars, only 0-D arrays. if isinstance(x, np.generic): # Convert the array scalar to a 0-D array x = np.asarray(x) if x.dtype not in _all_dtypes: raise TypeError( f"The array_api namespace does not support the dtype '{x.dtype}'" ) obj._array = x return obj # Prevent Array() from working def __new__(cls, *args, **kwargs): raise TypeError( "The array_api Array object should not be instantiated directly. Use an array creation function, such as asarray(), instead." ) # These functions are not required by the spec, but are implemented for # the sake of usability. def __str__(self: Array, /) -> str: """ Performs the operation __str__. """ return self._array.__str__().replace("array", "Array") def __repr__(self: Array, /) -> str: """ Performs the operation __repr__. """ suffix = f", dtype={self.dtype.name})" if 0 in self.shape: prefix = "empty(" mid = str(self.shape) else: prefix = "Array(" mid = np.array2string(self._array, separator=', ', prefix=prefix, suffix=suffix) return prefix + mid + suffix # This function is not required by the spec, but we implement it here for # convenience so that np.asarray(np.array_api.Array) will work. def __array__(self, dtype: None | np.dtype[Any] = None) -> npt.NDArray[Any]: """ Warning: this method is NOT part of the array API spec. Implementers of other libraries need not include it, and users should not assume it will be present in other implementations. """ return np.asarray(self._array, dtype=dtype) # These are various helper functions to make the array behavior match the # spec in places where it either deviates from or is more strict than # NumPy behavior def _check_allowed_dtypes(self, other: bool | int | float | Array, dtype_category: str, op: str) -> Array: """ Helper function for operators to only allow specific input dtypes Use like other = self._check_allowed_dtypes(other, 'numeric', '__add__') if other is NotImplemented: return other """ if self.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") if isinstance(other, (int, float, bool)): other = self._promote_scalar(other) elif isinstance(other, Array): if other.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") else: return NotImplemented # This will raise TypeError for type combinations that are not allowed # to promote in the spec (even if the NumPy array operator would # promote them). res_dtype = _result_type(self.dtype, other.dtype) if op.startswith("__i"): # Note: NumPy will allow in-place operators in some cases where # the type promoted operator does not match the left-hand side # operand. For example, # >>> a = np.array(1, dtype=np.int8) # >>> a += np.array(1, dtype=np.int16) # The spec explicitly disallows this. if res_dtype != self.dtype: raise TypeError( f"Cannot perform {op} with dtypes {self.dtype} and {other.dtype}" ) return other # Helper function to match the type promotion rules in the spec def _promote_scalar(self, scalar): """ Returns a promoted version of a Python scalar appropriate for use with operations on self. This may raise an OverflowError in cases where the scalar is an integer that is too large to fit in a NumPy integer dtype, or TypeError when the scalar type is incompatible with the dtype of self. """ # Note: Only Python scalar types that match the array dtype are # allowed. if isinstance(scalar, bool): if self.dtype not in _boolean_dtypes: raise TypeError( "Python bool scalars can only be promoted with bool arrays" ) elif isinstance(scalar, int): if self.dtype in _boolean_dtypes: raise TypeError( "Python int scalars cannot be promoted with bool arrays" ) elif isinstance(scalar, float): if self.dtype not in _floating_dtypes: raise TypeError( "Python float scalars can only be promoted with floating-point arrays." ) else: raise TypeError("'scalar' must be a Python scalar") # Note: scalars are unconditionally cast to the same dtype as the # array. # Note: the spec only specifies integer-dtype/int promotion # behavior for integers within the bounds of the integer dtype. # Outside of those bounds we use the default NumPy behavior (either # cast or raise OverflowError). return Array._new(np.array(scalar, self.dtype)) def _normalize_two_args(x1, x2) -> Tuple[Array, Array]: """ Normalize inputs to two arg functions to fix type promotion rules NumPy deviates from the spec type promotion rules in cases where one argument is 0-dimensional and the other is not. For example: >>> import numpy as np >>> a = np.array([1.0], dtype=np.float32) >>> b = np.array(1.0, dtype=np.float64) >>> np.add(a, b) # The spec says this should be float64 array([2.], dtype=float32) To fix this, we add a dimension to the 0-dimension array before passing it through. This works because a dimension would be added anyway from broadcasting, so the resulting shape is the same, but this prevents NumPy from not promoting the dtype. """ # Another option would be to use signature=(x1.dtype, x2.dtype, None), # but that only works for ufuncs, so we would have to call the ufuncs # directly in the operator methods. One should also note that this # sort of trick wouldn't work for functions like searchsorted, which # don't do normal broadcasting, but there aren't any functions like # that in the array API namespace. if x1.ndim == 0 and x2.ndim != 0: # The _array[None] workaround was chosen because it is relatively # performant. broadcast_to(x1._array, x2.shape) is much slower. We # could also manually type promote x2, but that is more complicated # and about the same performance as this. x1 = Array._new(x1._array[None]) elif x2.ndim == 0 and x1.ndim != 0: x2 = Array._new(x2._array[None]) return (x1, x2) # Note: A large fraction of allowed indices are disallowed here (see the # docstring below) def _validate_index(self, key): """ Validate an index according to the array API. The array API specification only requires a subset of indices that are supported by NumPy. This function will reject any index that is allowed by NumPy but not required by the array API specification. We always raise ``IndexError`` on such indices (the spec does not require any specific behavior on them, but this makes the NumPy array API namespace a minimal implementation of the spec). See https://data-apis.org/array-api/latest/API_specification/indexing.html for the full list of required indexing behavior This function raises IndexError if the index ``key`` is invalid. It only raises ``IndexError`` on indices that are not already rejected by NumPy, as NumPy will already raise the appropriate error on such indices. ``shape`` may be None, in which case, only cases that are independent of the array shape are checked. The following cases are allowed by NumPy, but not specified by the array API specification: - Indices to not include an implicit ellipsis at the end. That is, every axis of an array must be explicitly indexed or an ellipsis included. This behaviour is sometimes referred to as flat indexing. - The start and stop of a slice may not be out of bounds. In particular, for a slice ``i:j:k`` on an axis of size ``n``, only the following are allowed: - ``i`` or ``j`` omitted (``None``). - ``-n <= i <= max(0, n - 1)``. - For ``k > 0`` or ``k`` omitted (``None``), ``-n <= j <= n``. - For ``k < 0``, ``-n - 1 <= j <= max(0, n - 1)``. - Boolean array indices are not allowed as part of a larger tuple index. - Integer array indices are not allowed (with the exception of 0-D arrays, which are treated the same as scalars). Additionally, it should be noted that indices that would return a scalar in NumPy will return a 0-D array. Array scalars are not allowed in the specification, only 0-D arrays. This is done in the ``Array._new`` constructor, not this function. """ _key = key if isinstance(key, tuple) else (key,) for i in _key: if isinstance(i, bool) or not ( isinstance(i, SupportsIndex) # i.e. ints or isinstance(i, slice) or i == Ellipsis or i is None or isinstance(i, Array) or isinstance(i, np.ndarray) ): raise IndexError( f"Single-axes index {i} has {type(i)=}, but only " "integers, slices (:), ellipsis (...), newaxis (None), " "zero-dimensional integer arrays and boolean arrays " "are specified in the Array API." ) nonexpanding_key = [] single_axes = [] n_ellipsis = 0 key_has_mask = False for i in _key: if i is not None: nonexpanding_key.append(i) if isinstance(i, Array) or isinstance(i, np.ndarray): if i.dtype in _boolean_dtypes: key_has_mask = True single_axes.append(i) else: # i must not be an array here, to avoid elementwise equals if i == Ellipsis: n_ellipsis += 1 else: single_axes.append(i) n_single_axes = len(single_axes) if n_ellipsis > 1: return # handled by ndarray elif n_ellipsis == 0: # Note boolean masks must be the sole index, which we check for # later on. if not key_has_mask and n_single_axes < self.ndim: raise IndexError( f"{self.ndim=}, but the multi-axes index only specifies " f"{n_single_axes} dimensions. If this was intentional, " "add a trailing ellipsis (...) which expands into as many " "slices (:) as necessary - this is what np.ndarray arrays " "implicitly do, but such flat indexing behaviour is not " "specified in the Array API." ) if n_ellipsis == 0: indexed_shape = self.shape else: ellipsis_start = None for pos, i in enumerate(nonexpanding_key): if not (isinstance(i, Array) or isinstance(i, np.ndarray)): if i == Ellipsis: ellipsis_start = pos break assert ellipsis_start is not None # sanity check ellipsis_end = self.ndim - (n_single_axes - ellipsis_start) indexed_shape = ( self.shape[:ellipsis_start] + self.shape[ellipsis_end:] ) for i, side in zip(single_axes, indexed_shape): if isinstance(i, slice): if side == 0: f_range = "0 (or None)" else: f_range = f"between -{side} and {side - 1} (or None)" if i.start is not None: try: start = operator.index(i.start) except TypeError: pass # handled by ndarray else: if not (-side <= start <= side): raise IndexError( f"Slice {i} contains {start=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds starts are not specified in " "the Array API)" ) if i.stop is not None: try: stop = operator.index(i.stop) except TypeError: pass # handled by ndarray else: if not (-side <= stop <= side): raise IndexError( f"Slice {i} contains {stop=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds stops are not specified in " "the Array API)" ) elif isinstance(i, Array): if i.dtype in _boolean_dtypes and len(_key) != 1: assert isinstance(key, tuple) # sanity check raise IndexError( f"Single-axes index {i} is a boolean array and " f"{len(key)=}, but masking is only specified in the " "Array API when the array is the sole index." ) elif i.dtype in _integer_dtypes and i.ndim != 0: raise IndexError( f"Single-axes index {i} is a non-zero-dimensional " "integer array, but advanced integer indexing is not " "specified in the Array API." ) elif isinstance(i, tuple): raise IndexError( f"Single-axes index {i} is a tuple, but nested tuple " "indices are not specified in the Array API." ) # Everything below this line is required by the spec. def __abs__(self: Array, /) -> Array: """ Performs the operation __abs__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __abs__") res = self._array.__abs__() return self.__class__._new(res) def __add__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __add__. """ other = self._check_allowed_dtypes(other, "numeric", "__add__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__add__(other._array) return self.__class__._new(res) def __and__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __and__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__and__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__and__(other._array) return self.__class__._new(res) def __array_namespace__( self: Array, /, *, api_version: Optional[str] = None ) -> types.ModuleType: if api_version is not None and not api_version.startswith("2021."): raise ValueError(f"Unrecognized array API version: {api_version!r}") return array_api def __bool__(self: Array, /) -> bool: """ Performs the operation __bool__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("bool is only allowed on arrays with 0 dimensions") if self.dtype not in _boolean_dtypes: raise ValueError("bool is only allowed on boolean arrays") res = self._array.__bool__() return res def __dlpack__(self: Array, /, *, stream: None = None) -> PyCapsule: """ Performs the operation __dlpack__. """ return self._array.__dlpack__(stream=stream) def __dlpack_device__(self: Array, /) -> Tuple[IntEnum, int]: """ Performs the operation __dlpack_device__. """ # Note: device support is required for this return self._array.__dlpack_device__() def __eq__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __eq__. """ # Even though "all" dtypes are allowed, we still require them to be # promotable with each other. other = self._check_allowed_dtypes(other, "all", "__eq__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__eq__(other._array) return self.__class__._new(res) def __float__(self: Array, /) -> float: """ Performs the operation __float__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("float is only allowed on arrays with 0 dimensions") if self.dtype not in _floating_dtypes: raise ValueError("float is only allowed on floating-point arrays") res = self._array.__float__() return res def __floordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __floordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__floordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__floordiv__(other._array) return self.__class__._new(res) def __ge__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ge__. """ other = self._check_allowed_dtypes(other, "numeric", "__ge__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ge__(other._array) return self.__class__._new(res) def __getitem__( self: Array, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], /, ) -> Array: """ Performs the operation __getitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array res = self._array.__getitem__(key) return self._new(res) def __gt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __gt__. """ other = self._check_allowed_dtypes(other, "numeric", "__gt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__gt__(other._array) return self.__class__._new(res) def __int__(self: Array, /) -> int: """ Performs the operation __int__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("int is only allowed on arrays with 0 dimensions") if self.dtype not in _integer_dtypes: raise ValueError("int is only allowed on integer arrays") res = self._array.__int__() return res def __index__(self: Array, /) -> int: """ Performs the operation __index__. """ res = self._array.__index__() return res def __invert__(self: Array, /) -> Array: """ Performs the operation __invert__. """ if self.dtype not in _integer_or_boolean_dtypes: raise TypeError("Only integer or boolean dtypes are allowed in __invert__") res = self._array.__invert__() return self.__class__._new(res) def __le__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __le__. """ other = self._check_allowed_dtypes(other, "numeric", "__le__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__le__(other._array) return self.__class__._new(res) def __lshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __lshift__. """ other = self._check_allowed_dtypes(other, "integer", "__lshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lshift__(other._array) return self.__class__._new(res) def __lt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __lt__. """ other = self._check_allowed_dtypes(other, "numeric", "__lt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lt__(other._array) return self.__class__._new(res) def __matmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __matmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__matmul__") if other is NotImplemented: return other res = self._array.__matmul__(other._array) return self.__class__._new(res) def __mod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mod__. """ other = self._check_allowed_dtypes(other, "numeric", "__mod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mod__(other._array) return self.__class__._new(res) def __mul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mul__. """ other = self._check_allowed_dtypes(other, "numeric", "__mul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mul__(other._array) return self.__class__._new(res) def __ne__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __ne__. """ other = self._check_allowed_dtypes(other, "all", "__ne__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ne__(other._array) return self.__class__._new(res) def __neg__(self: Array, /) -> Array: """ Performs the operation __neg__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __neg__") res = self._array.__neg__() return self.__class__._new(res) def __or__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __or__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__or__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__or__(other._array) return self.__class__._new(res) def __pos__(self: Array, /) -> Array: """ Performs the operation __pos__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __pos__") res = self._array.__pos__() return self.__class__._new(res) def __pow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __pow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__pow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow type promotion rules for 0-d # arrays, so we use pow() here instead. return pow(self, other) def __rshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rshift__(other._array) return self.__class__._new(res) def __setitem__( self, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], value: Union[int, float, bool, Array], /, ) -> None: """ Performs the operation __setitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array self._array.__setitem__(key, asarray(value)._array) def __sub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __sub__. """ other = self._check_allowed_dtypes(other, "numeric", "__sub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__sub__(other._array) return self.__class__._new(res) # PEP 484 requires int to be a subtype of float, but __truediv__ should # not accept int. def __truediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __truediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__truediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__truediv__(other._array) return self.__class__._new(res) def __xor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __xor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__xor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__xor__(other._array) return self.__class__._new(res) def __iadd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __iadd__. """ other = self._check_allowed_dtypes(other, "numeric", "__iadd__") if other is NotImplemented: return other self._array.__iadd__(other._array) return self def __radd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __radd__. """ other = self._check_allowed_dtypes(other, "numeric", "__radd__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__radd__(other._array) return self.__class__._new(res) def __iand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __iand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__iand__") if other is NotImplemented: return other self._array.__iand__(other._array) return self def __rand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rand__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rand__(other._array) return self.__class__._new(res) def __ifloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ifloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__ifloordiv__") if other is NotImplemented: return other self._array.__ifloordiv__(other._array) return self def __rfloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rfloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__rfloordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rfloordiv__(other._array) return self.__class__._new(res) def __ilshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __ilshift__. """ other = self._check_allowed_dtypes(other, "integer", "__ilshift__") if other is NotImplemented: return other self._array.__ilshift__(other._array) return self def __rlshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rlshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rlshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rlshift__(other._array) return self.__class__._new(res) def __imatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __imatmul__. """ # Note: NumPy does not implement __imatmul__. # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__imatmul__") if other is NotImplemented: return other # __imatmul__ can only be allowed when it would not change the shape # of self. other_shape = other.shape if self.shape == () or other_shape == (): raise ValueError("@= requires at least one dimension") if len(other_shape) == 1 or other_shape[-1] != other_shape[-2]: raise ValueError("@= cannot change the shape of the input array") self._array[:] = self._array.__matmul__(other._array) return self def __rmatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __rmatmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__rmatmul__") if other is NotImplemented: return other res = self._array.__rmatmul__(other._array) return self.__class__._new(res) def __imod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imod__. """ other = self._check_allowed_dtypes(other, "numeric", "__imod__") if other is NotImplemented: return other self._array.__imod__(other._array) return self def __rmod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmod__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmod__(other._array) return self.__class__._new(res) def __imul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imul__. """ other = self._check_allowed_dtypes(other, "numeric", "__imul__") if other is NotImplemented: return other self._array.__imul__(other._array) return self def __rmul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmul__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmul__(other._array) return self.__class__._new(res) def __ior__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ior__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ior__") if other is NotImplemented: return other self._array.__ior__(other._array) return self def __ror__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ror__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ror__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ror__(other._array) return self.__class__._new(res) def __ipow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ipow__. """ other = self._check_allowed_dtypes(other, "numeric", "__ipow__") if other is NotImplemented: return other self._array.__ipow__(other._array) return self def __rpow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rpow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__rpow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow the spec type promotion rules # for 0-d arrays, so we use pow() here instead. return pow(other, self) def __irshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __irshift__. """ other = self._check_allowed_dtypes(other, "integer", "__irshift__") if other is NotImplemented: return other self._array.__irshift__(other._array) return self def __rrshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rrshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rrshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rrshift__(other._array) return self.__class__._new(res) def __isub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __isub__. """ other = self._check_allowed_dtypes(other, "numeric", "__isub__") if other is NotImplemented: return other self._array.__isub__(other._array) return self def __rsub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rsub__. """ other = self._check_allowed_dtypes(other, "numeric", "__rsub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rsub__(other._array) return self.__class__._new(res) def __itruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __itruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__itruediv__") if other is NotImplemented: return other self._array.__itruediv__(other._array) return self def __rtruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __rtruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__rtruediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rtruediv__(other._array) return self.__class__._new(res) def __ixor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ixor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ixor__") if other is NotImplemented: return other self._array.__ixor__(other._array) return self def __rxor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rxor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rxor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rxor__(other._array) return self.__class__._new(res) def to_device(self: Array, device: Device, /, stream: None = None) -> Array: if stream is not None: raise ValueError("The stream argument to to_device() is not supported") if device == 'cpu': return self raise ValueError(f"Unsupported device {device!r}") def dtype(self) -> Dtype: """ Array API compatible wrapper for :py:meth:`np.ndarray.dtype <numpy.ndarray.dtype>`. See its docstring for more information. """ return self._array.dtype def device(self) -> Device: return "cpu" # Note: mT is new in array API spec (see matrix_transpose) def mT(self) -> Array: from .linalg import matrix_transpose return matrix_transpose(self) def ndim(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.ndim <numpy.ndarray.ndim>`. See its docstring for more information. """ return self._array.ndim def shape(self) -> Tuple[int, ...]: """ Array API compatible wrapper for :py:meth:`np.ndarray.shape <numpy.ndarray.shape>`. See its docstring for more information. """ return self._array.shape def size(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.size <numpy.ndarray.size>`. See its docstring for more information. """ return self._array.size def T(self) -> Array: """ Array API compatible wrapper for :py:meth:`np.ndarray.T <numpy.ndarray.T>`. See its docstring for more information. """ # Note: T only works on 2-dimensional arrays. See the corresponding # note in the specification: # https://data-apis.org/array-api/latest/API_specification/array_object.html#t if self.ndim != 2: raise ValueError("x.T requires x to have 2 dimensions. Use x.mT to transpose stacks of matrices and permute_dims() to permute dimensions.") return self.__class__._new(self._array.T) def result_type(*arrays_and_dtypes: Union[Array, Dtype]) -> Dtype: """ Array API compatible wrapper for :py:func:`np.result_type <numpy.result_type>`. See its docstring for more information. """ # Note: we use a custom implementation that gives only the type promotions # required by the spec rather than using np.result_type. NumPy implements # too many extra type promotions like int64 + uint64 -> float64, and does # value-based casting on scalar arrays. A = [] for a in arrays_and_dtypes: if isinstance(a, Array): a = a.dtype elif isinstance(a, np.ndarray) or a not in _all_dtypes: raise TypeError("result_type() inputs must be array_api arrays or dtypes") A.append(a) if len(A) == 0: raise ValueError("at least one array or dtype is required") elif len(A) == 1: return A[0] else: t = A[0] for t2 in A[1:]: t = _result_type(t, t2) return t Union: _SpecialForm = ... Optional: _SpecialForm = ... List = _Alias() class Tuple(BaseTypingInstance): def _is_homogenous(self): # To specify a variable-length tuple of homogeneous type, Tuple[T, ...] # is used. return self._generics_manager.is_homogenous_tuple() def py__simple_getitem__(self, index): if self._is_homogenous(): return self._generics_manager.get_index_and_execute(0) else: if isinstance(index, int): return self._generics_manager.get_index_and_execute(index) debug.dbg('The getitem type on Tuple was %s' % index) return NO_VALUES def py__iter__(self, contextualized_node=None): if self._is_homogenous(): yield LazyKnownValues(self._generics_manager.get_index_and_execute(0)) else: for v in self._generics_manager.to_tuple(): yield LazyKnownValues(v.execute_annotation()) def py__getitem__(self, index_value_set, contextualized_node): if self._is_homogenous(): return self._generics_manager.get_index_and_execute(0) return ValueSet.from_sets( self._generics_manager.to_tuple() ).execute_annotation() def _get_wrapped_value(self): tuple_, = self.inference_state.builtins_module \ .py__getattribute__('tuple').execute_annotation() return tuple_ def name(self): return self._wrapped_value.name def infer_type_vars(self, value_set): # Circular from jedi.inference.gradual.annotation import merge_pairwise_generics, merge_type_var_dicts value_set = value_set.filter( lambda x: x.py__name__().lower() == 'tuple', ) if self._is_homogenous(): # The parameter annotation is of the form `Tuple[T, ...]`, # so we treat the incoming tuple like a iterable sequence # rather than a positional container of elements. return self._class_value.get_generics()[0].infer_type_vars( value_set.merge_types_of_iterate(), ) else: # The parameter annotation has only explicit type parameters # (e.g: `Tuple[T]`, `Tuple[T, U]`, `Tuple[T, U, V]`, etc.) so we # treat the incoming values as needing to match the annotation # exactly, just as we would for non-tuple annotations. type_var_dict = {} for element in value_set: try: method = element.get_annotated_class_object except AttributeError: # This might still happen, because the tuple name matching # above is not 100% correct, so just catch the remaining # cases here. continue py_class = method() merge_type_var_dicts( type_var_dict, merge_pairwise_generics(self._class_value, py_class), ) return type_var_dict The provided code snippet includes necessary dependencies for implementing the `concat` function. Write a Python function `def concat( arrays: Union[Tuple[Array, ...], List[Array]], /, *, axis: Optional[int] = 0 ) -> Array` to solve the following problem: Array API compatible wrapper for :py:func:`np.concatenate <numpy.concatenate>`. See its docstring for more information. Here is the function: def concat( arrays: Union[Tuple[Array, ...], List[Array]], /, *, axis: Optional[int] = 0 ) -> Array: """ Array API compatible wrapper for :py:func:`np.concatenate <numpy.concatenate>`. See its docstring for more information. """ # Note: Casting rules here are different from the np.concatenate default # (no for scalars with axis=None, no cross-kind casting) dtype = result_type(*arrays) arrays = tuple(a._array for a in arrays) return Array._new(np.concatenate(arrays, axis=axis, dtype=dtype))
Array API compatible wrapper for :py:func:`np.concatenate <numpy.concatenate>`. See its docstring for more information.
170,080
from __future__ import annotations from ._array_object import Array from ._data_type_functions import result_type from typing import List, Optional, Tuple, Union import numpy as np class Array: """ n-d array object for the array API namespace. See the docstring of :py:obj:`np.ndarray <numpy.ndarray>` for more information. This is a wrapper around numpy.ndarray that restricts the usage to only those things that are required by the array API namespace. Note, attributes on this object that start with a single underscore are not part of the API specification and should only be used internally. This object should not be constructed directly. Rather, use one of the creation functions, such as asarray(). """ _array: np.ndarray # Use a custom constructor instead of __init__, as manually initializing # this class is not supported API. def _new(cls, x, /): """ This is a private method for initializing the array API Array object. Functions outside of the array_api submodule should not use this method. Use one of the creation functions instead, such as ``asarray``. """ obj = super().__new__(cls) # Note: The spec does not have array scalars, only 0-D arrays. if isinstance(x, np.generic): # Convert the array scalar to a 0-D array x = np.asarray(x) if x.dtype not in _all_dtypes: raise TypeError( f"The array_api namespace does not support the dtype '{x.dtype}'" ) obj._array = x return obj # Prevent Array() from working def __new__(cls, *args, **kwargs): raise TypeError( "The array_api Array object should not be instantiated directly. Use an array creation function, such as asarray(), instead." ) # These functions are not required by the spec, but are implemented for # the sake of usability. def __str__(self: Array, /) -> str: """ Performs the operation __str__. """ return self._array.__str__().replace("array", "Array") def __repr__(self: Array, /) -> str: """ Performs the operation __repr__. """ suffix = f", dtype={self.dtype.name})" if 0 in self.shape: prefix = "empty(" mid = str(self.shape) else: prefix = "Array(" mid = np.array2string(self._array, separator=', ', prefix=prefix, suffix=suffix) return prefix + mid + suffix # This function is not required by the spec, but we implement it here for # convenience so that np.asarray(np.array_api.Array) will work. def __array__(self, dtype: None | np.dtype[Any] = None) -> npt.NDArray[Any]: """ Warning: this method is NOT part of the array API spec. Implementers of other libraries need not include it, and users should not assume it will be present in other implementations. """ return np.asarray(self._array, dtype=dtype) # These are various helper functions to make the array behavior match the # spec in places where it either deviates from or is more strict than # NumPy behavior def _check_allowed_dtypes(self, other: bool | int | float | Array, dtype_category: str, op: str) -> Array: """ Helper function for operators to only allow specific input dtypes Use like other = self._check_allowed_dtypes(other, 'numeric', '__add__') if other is NotImplemented: return other """ if self.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") if isinstance(other, (int, float, bool)): other = self._promote_scalar(other) elif isinstance(other, Array): if other.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") else: return NotImplemented # This will raise TypeError for type combinations that are not allowed # to promote in the spec (even if the NumPy array operator would # promote them). res_dtype = _result_type(self.dtype, other.dtype) if op.startswith("__i"): # Note: NumPy will allow in-place operators in some cases where # the type promoted operator does not match the left-hand side # operand. For example, # >>> a = np.array(1, dtype=np.int8) # >>> a += np.array(1, dtype=np.int16) # The spec explicitly disallows this. if res_dtype != self.dtype: raise TypeError( f"Cannot perform {op} with dtypes {self.dtype} and {other.dtype}" ) return other # Helper function to match the type promotion rules in the spec def _promote_scalar(self, scalar): """ Returns a promoted version of a Python scalar appropriate for use with operations on self. This may raise an OverflowError in cases where the scalar is an integer that is too large to fit in a NumPy integer dtype, or TypeError when the scalar type is incompatible with the dtype of self. """ # Note: Only Python scalar types that match the array dtype are # allowed. if isinstance(scalar, bool): if self.dtype not in _boolean_dtypes: raise TypeError( "Python bool scalars can only be promoted with bool arrays" ) elif isinstance(scalar, int): if self.dtype in _boolean_dtypes: raise TypeError( "Python int scalars cannot be promoted with bool arrays" ) elif isinstance(scalar, float): if self.dtype not in _floating_dtypes: raise TypeError( "Python float scalars can only be promoted with floating-point arrays." ) else: raise TypeError("'scalar' must be a Python scalar") # Note: scalars are unconditionally cast to the same dtype as the # array. # Note: the spec only specifies integer-dtype/int promotion # behavior for integers within the bounds of the integer dtype. # Outside of those bounds we use the default NumPy behavior (either # cast or raise OverflowError). return Array._new(np.array(scalar, self.dtype)) def _normalize_two_args(x1, x2) -> Tuple[Array, Array]: """ Normalize inputs to two arg functions to fix type promotion rules NumPy deviates from the spec type promotion rules in cases where one argument is 0-dimensional and the other is not. For example: >>> import numpy as np >>> a = np.array([1.0], dtype=np.float32) >>> b = np.array(1.0, dtype=np.float64) >>> np.add(a, b) # The spec says this should be float64 array([2.], dtype=float32) To fix this, we add a dimension to the 0-dimension array before passing it through. This works because a dimension would be added anyway from broadcasting, so the resulting shape is the same, but this prevents NumPy from not promoting the dtype. """ # Another option would be to use signature=(x1.dtype, x2.dtype, None), # but that only works for ufuncs, so we would have to call the ufuncs # directly in the operator methods. One should also note that this # sort of trick wouldn't work for functions like searchsorted, which # don't do normal broadcasting, but there aren't any functions like # that in the array API namespace. if x1.ndim == 0 and x2.ndim != 0: # The _array[None] workaround was chosen because it is relatively # performant. broadcast_to(x1._array, x2.shape) is much slower. We # could also manually type promote x2, but that is more complicated # and about the same performance as this. x1 = Array._new(x1._array[None]) elif x2.ndim == 0 and x1.ndim != 0: x2 = Array._new(x2._array[None]) return (x1, x2) # Note: A large fraction of allowed indices are disallowed here (see the # docstring below) def _validate_index(self, key): """ Validate an index according to the array API. The array API specification only requires a subset of indices that are supported by NumPy. This function will reject any index that is allowed by NumPy but not required by the array API specification. We always raise ``IndexError`` on such indices (the spec does not require any specific behavior on them, but this makes the NumPy array API namespace a minimal implementation of the spec). See https://data-apis.org/array-api/latest/API_specification/indexing.html for the full list of required indexing behavior This function raises IndexError if the index ``key`` is invalid. It only raises ``IndexError`` on indices that are not already rejected by NumPy, as NumPy will already raise the appropriate error on such indices. ``shape`` may be None, in which case, only cases that are independent of the array shape are checked. The following cases are allowed by NumPy, but not specified by the array API specification: - Indices to not include an implicit ellipsis at the end. That is, every axis of an array must be explicitly indexed or an ellipsis included. This behaviour is sometimes referred to as flat indexing. - The start and stop of a slice may not be out of bounds. In particular, for a slice ``i:j:k`` on an axis of size ``n``, only the following are allowed: - ``i`` or ``j`` omitted (``None``). - ``-n <= i <= max(0, n - 1)``. - For ``k > 0`` or ``k`` omitted (``None``), ``-n <= j <= n``. - For ``k < 0``, ``-n - 1 <= j <= max(0, n - 1)``. - Boolean array indices are not allowed as part of a larger tuple index. - Integer array indices are not allowed (with the exception of 0-D arrays, which are treated the same as scalars). Additionally, it should be noted that indices that would return a scalar in NumPy will return a 0-D array. Array scalars are not allowed in the specification, only 0-D arrays. This is done in the ``Array._new`` constructor, not this function. """ _key = key if isinstance(key, tuple) else (key,) for i in _key: if isinstance(i, bool) or not ( isinstance(i, SupportsIndex) # i.e. ints or isinstance(i, slice) or i == Ellipsis or i is None or isinstance(i, Array) or isinstance(i, np.ndarray) ): raise IndexError( f"Single-axes index {i} has {type(i)=}, but only " "integers, slices (:), ellipsis (...), newaxis (None), " "zero-dimensional integer arrays and boolean arrays " "are specified in the Array API." ) nonexpanding_key = [] single_axes = [] n_ellipsis = 0 key_has_mask = False for i in _key: if i is not None: nonexpanding_key.append(i) if isinstance(i, Array) or isinstance(i, np.ndarray): if i.dtype in _boolean_dtypes: key_has_mask = True single_axes.append(i) else: # i must not be an array here, to avoid elementwise equals if i == Ellipsis: n_ellipsis += 1 else: single_axes.append(i) n_single_axes = len(single_axes) if n_ellipsis > 1: return # handled by ndarray elif n_ellipsis == 0: # Note boolean masks must be the sole index, which we check for # later on. if not key_has_mask and n_single_axes < self.ndim: raise IndexError( f"{self.ndim=}, but the multi-axes index only specifies " f"{n_single_axes} dimensions. If this was intentional, " "add a trailing ellipsis (...) which expands into as many " "slices (:) as necessary - this is what np.ndarray arrays " "implicitly do, but such flat indexing behaviour is not " "specified in the Array API." ) if n_ellipsis == 0: indexed_shape = self.shape else: ellipsis_start = None for pos, i in enumerate(nonexpanding_key): if not (isinstance(i, Array) or isinstance(i, np.ndarray)): if i == Ellipsis: ellipsis_start = pos break assert ellipsis_start is not None # sanity check ellipsis_end = self.ndim - (n_single_axes - ellipsis_start) indexed_shape = ( self.shape[:ellipsis_start] + self.shape[ellipsis_end:] ) for i, side in zip(single_axes, indexed_shape): if isinstance(i, slice): if side == 0: f_range = "0 (or None)" else: f_range = f"between -{side} and {side - 1} (or None)" if i.start is not None: try: start = operator.index(i.start) except TypeError: pass # handled by ndarray else: if not (-side <= start <= side): raise IndexError( f"Slice {i} contains {start=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds starts are not specified in " "the Array API)" ) if i.stop is not None: try: stop = operator.index(i.stop) except TypeError: pass # handled by ndarray else: if not (-side <= stop <= side): raise IndexError( f"Slice {i} contains {stop=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds stops are not specified in " "the Array API)" ) elif isinstance(i, Array): if i.dtype in _boolean_dtypes and len(_key) != 1: assert isinstance(key, tuple) # sanity check raise IndexError( f"Single-axes index {i} is a boolean array and " f"{len(key)=}, but masking is only specified in the " "Array API when the array is the sole index." ) elif i.dtype in _integer_dtypes and i.ndim != 0: raise IndexError( f"Single-axes index {i} is a non-zero-dimensional " "integer array, but advanced integer indexing is not " "specified in the Array API." ) elif isinstance(i, tuple): raise IndexError( f"Single-axes index {i} is a tuple, but nested tuple " "indices are not specified in the Array API." ) # Everything below this line is required by the spec. def __abs__(self: Array, /) -> Array: """ Performs the operation __abs__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __abs__") res = self._array.__abs__() return self.__class__._new(res) def __add__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __add__. """ other = self._check_allowed_dtypes(other, "numeric", "__add__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__add__(other._array) return self.__class__._new(res) def __and__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __and__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__and__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__and__(other._array) return self.__class__._new(res) def __array_namespace__( self: Array, /, *, api_version: Optional[str] = None ) -> types.ModuleType: if api_version is not None and not api_version.startswith("2021."): raise ValueError(f"Unrecognized array API version: {api_version!r}") return array_api def __bool__(self: Array, /) -> bool: """ Performs the operation __bool__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("bool is only allowed on arrays with 0 dimensions") if self.dtype not in _boolean_dtypes: raise ValueError("bool is only allowed on boolean arrays") res = self._array.__bool__() return res def __dlpack__(self: Array, /, *, stream: None = None) -> PyCapsule: """ Performs the operation __dlpack__. """ return self._array.__dlpack__(stream=stream) def __dlpack_device__(self: Array, /) -> Tuple[IntEnum, int]: """ Performs the operation __dlpack_device__. """ # Note: device support is required for this return self._array.__dlpack_device__() def __eq__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __eq__. """ # Even though "all" dtypes are allowed, we still require them to be # promotable with each other. other = self._check_allowed_dtypes(other, "all", "__eq__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__eq__(other._array) return self.__class__._new(res) def __float__(self: Array, /) -> float: """ Performs the operation __float__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("float is only allowed on arrays with 0 dimensions") if self.dtype not in _floating_dtypes: raise ValueError("float is only allowed on floating-point arrays") res = self._array.__float__() return res def __floordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __floordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__floordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__floordiv__(other._array) return self.__class__._new(res) def __ge__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ge__. """ other = self._check_allowed_dtypes(other, "numeric", "__ge__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ge__(other._array) return self.__class__._new(res) def __getitem__( self: Array, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], /, ) -> Array: """ Performs the operation __getitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array res = self._array.__getitem__(key) return self._new(res) def __gt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __gt__. """ other = self._check_allowed_dtypes(other, "numeric", "__gt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__gt__(other._array) return self.__class__._new(res) def __int__(self: Array, /) -> int: """ Performs the operation __int__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("int is only allowed on arrays with 0 dimensions") if self.dtype not in _integer_dtypes: raise ValueError("int is only allowed on integer arrays") res = self._array.__int__() return res def __index__(self: Array, /) -> int: """ Performs the operation __index__. """ res = self._array.__index__() return res def __invert__(self: Array, /) -> Array: """ Performs the operation __invert__. """ if self.dtype not in _integer_or_boolean_dtypes: raise TypeError("Only integer or boolean dtypes are allowed in __invert__") res = self._array.__invert__() return self.__class__._new(res) def __le__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __le__. """ other = self._check_allowed_dtypes(other, "numeric", "__le__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__le__(other._array) return self.__class__._new(res) def __lshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __lshift__. """ other = self._check_allowed_dtypes(other, "integer", "__lshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lshift__(other._array) return self.__class__._new(res) def __lt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __lt__. """ other = self._check_allowed_dtypes(other, "numeric", "__lt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lt__(other._array) return self.__class__._new(res) def __matmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __matmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__matmul__") if other is NotImplemented: return other res = self._array.__matmul__(other._array) return self.__class__._new(res) def __mod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mod__. """ other = self._check_allowed_dtypes(other, "numeric", "__mod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mod__(other._array) return self.__class__._new(res) def __mul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mul__. """ other = self._check_allowed_dtypes(other, "numeric", "__mul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mul__(other._array) return self.__class__._new(res) def __ne__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __ne__. """ other = self._check_allowed_dtypes(other, "all", "__ne__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ne__(other._array) return self.__class__._new(res) def __neg__(self: Array, /) -> Array: """ Performs the operation __neg__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __neg__") res = self._array.__neg__() return self.__class__._new(res) def __or__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __or__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__or__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__or__(other._array) return self.__class__._new(res) def __pos__(self: Array, /) -> Array: """ Performs the operation __pos__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __pos__") res = self._array.__pos__() return self.__class__._new(res) def __pow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __pow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__pow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow type promotion rules for 0-d # arrays, so we use pow() here instead. return pow(self, other) def __rshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rshift__(other._array) return self.__class__._new(res) def __setitem__( self, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], value: Union[int, float, bool, Array], /, ) -> None: """ Performs the operation __setitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array self._array.__setitem__(key, asarray(value)._array) def __sub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __sub__. """ other = self._check_allowed_dtypes(other, "numeric", "__sub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__sub__(other._array) return self.__class__._new(res) # PEP 484 requires int to be a subtype of float, but __truediv__ should # not accept int. def __truediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __truediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__truediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__truediv__(other._array) return self.__class__._new(res) def __xor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __xor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__xor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__xor__(other._array) return self.__class__._new(res) def __iadd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __iadd__. """ other = self._check_allowed_dtypes(other, "numeric", "__iadd__") if other is NotImplemented: return other self._array.__iadd__(other._array) return self def __radd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __radd__. """ other = self._check_allowed_dtypes(other, "numeric", "__radd__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__radd__(other._array) return self.__class__._new(res) def __iand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __iand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__iand__") if other is NotImplemented: return other self._array.__iand__(other._array) return self def __rand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rand__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rand__(other._array) return self.__class__._new(res) def __ifloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ifloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__ifloordiv__") if other is NotImplemented: return other self._array.__ifloordiv__(other._array) return self def __rfloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rfloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__rfloordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rfloordiv__(other._array) return self.__class__._new(res) def __ilshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __ilshift__. """ other = self._check_allowed_dtypes(other, "integer", "__ilshift__") if other is NotImplemented: return other self._array.__ilshift__(other._array) return self def __rlshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rlshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rlshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rlshift__(other._array) return self.__class__._new(res) def __imatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __imatmul__. """ # Note: NumPy does not implement __imatmul__. # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__imatmul__") if other is NotImplemented: return other # __imatmul__ can only be allowed when it would not change the shape # of self. other_shape = other.shape if self.shape == () or other_shape == (): raise ValueError("@= requires at least one dimension") if len(other_shape) == 1 or other_shape[-1] != other_shape[-2]: raise ValueError("@= cannot change the shape of the input array") self._array[:] = self._array.__matmul__(other._array) return self def __rmatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __rmatmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__rmatmul__") if other is NotImplemented: return other res = self._array.__rmatmul__(other._array) return self.__class__._new(res) def __imod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imod__. """ other = self._check_allowed_dtypes(other, "numeric", "__imod__") if other is NotImplemented: return other self._array.__imod__(other._array) return self def __rmod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmod__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmod__(other._array) return self.__class__._new(res) def __imul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imul__. """ other = self._check_allowed_dtypes(other, "numeric", "__imul__") if other is NotImplemented: return other self._array.__imul__(other._array) return self def __rmul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmul__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmul__(other._array) return self.__class__._new(res) def __ior__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ior__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ior__") if other is NotImplemented: return other self._array.__ior__(other._array) return self def __ror__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ror__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ror__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ror__(other._array) return self.__class__._new(res) def __ipow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ipow__. """ other = self._check_allowed_dtypes(other, "numeric", "__ipow__") if other is NotImplemented: return other self._array.__ipow__(other._array) return self def __rpow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rpow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__rpow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow the spec type promotion rules # for 0-d arrays, so we use pow() here instead. return pow(other, self) def __irshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __irshift__. """ other = self._check_allowed_dtypes(other, "integer", "__irshift__") if other is NotImplemented: return other self._array.__irshift__(other._array) return self def __rrshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rrshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rrshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rrshift__(other._array) return self.__class__._new(res) def __isub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __isub__. """ other = self._check_allowed_dtypes(other, "numeric", "__isub__") if other is NotImplemented: return other self._array.__isub__(other._array) return self def __rsub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rsub__. """ other = self._check_allowed_dtypes(other, "numeric", "__rsub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rsub__(other._array) return self.__class__._new(res) def __itruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __itruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__itruediv__") if other is NotImplemented: return other self._array.__itruediv__(other._array) return self def __rtruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __rtruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__rtruediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rtruediv__(other._array) return self.__class__._new(res) def __ixor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ixor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ixor__") if other is NotImplemented: return other self._array.__ixor__(other._array) return self def __rxor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rxor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rxor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rxor__(other._array) return self.__class__._new(res) def to_device(self: Array, device: Device, /, stream: None = None) -> Array: if stream is not None: raise ValueError("The stream argument to to_device() is not supported") if device == 'cpu': return self raise ValueError(f"Unsupported device {device!r}") def dtype(self) -> Dtype: """ Array API compatible wrapper for :py:meth:`np.ndarray.dtype <numpy.ndarray.dtype>`. See its docstring for more information. """ return self._array.dtype def device(self) -> Device: return "cpu" # Note: mT is new in array API spec (see matrix_transpose) def mT(self) -> Array: from .linalg import matrix_transpose return matrix_transpose(self) def ndim(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.ndim <numpy.ndarray.ndim>`. See its docstring for more information. """ return self._array.ndim def shape(self) -> Tuple[int, ...]: """ Array API compatible wrapper for :py:meth:`np.ndarray.shape <numpy.ndarray.shape>`. See its docstring for more information. """ return self._array.shape def size(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.size <numpy.ndarray.size>`. See its docstring for more information. """ return self._array.size def T(self) -> Array: """ Array API compatible wrapper for :py:meth:`np.ndarray.T <numpy.ndarray.T>`. See its docstring for more information. """ # Note: T only works on 2-dimensional arrays. See the corresponding # note in the specification: # https://data-apis.org/array-api/latest/API_specification/array_object.html#t if self.ndim != 2: raise ValueError("x.T requires x to have 2 dimensions. Use x.mT to transpose stacks of matrices and permute_dims() to permute dimensions.") return self.__class__._new(self._array.T) The provided code snippet includes necessary dependencies for implementing the `expand_dims` function. Write a Python function `def expand_dims(x: Array, /, *, axis: int) -> Array` to solve the following problem: Array API compatible wrapper for :py:func:`np.expand_dims <numpy.expand_dims>`. See its docstring for more information. Here is the function: def expand_dims(x: Array, /, *, axis: int) -> Array: """ Array API compatible wrapper for :py:func:`np.expand_dims <numpy.expand_dims>`. See its docstring for more information. """ return Array._new(np.expand_dims(x._array, axis))
Array API compatible wrapper for :py:func:`np.expand_dims <numpy.expand_dims>`. See its docstring for more information.
170,081
from __future__ import annotations from ._array_object import Array from ._data_type_functions import result_type from typing import List, Optional, Tuple, Union import numpy as np class Array: """ n-d array object for the array API namespace. See the docstring of :py:obj:`np.ndarray <numpy.ndarray>` for more information. This is a wrapper around numpy.ndarray that restricts the usage to only those things that are required by the array API namespace. Note, attributes on this object that start with a single underscore are not part of the API specification and should only be used internally. This object should not be constructed directly. Rather, use one of the creation functions, such as asarray(). """ _array: np.ndarray # Use a custom constructor instead of __init__, as manually initializing # this class is not supported API. def _new(cls, x, /): """ This is a private method for initializing the array API Array object. Functions outside of the array_api submodule should not use this method. Use one of the creation functions instead, such as ``asarray``. """ obj = super().__new__(cls) # Note: The spec does not have array scalars, only 0-D arrays. if isinstance(x, np.generic): # Convert the array scalar to a 0-D array x = np.asarray(x) if x.dtype not in _all_dtypes: raise TypeError( f"The array_api namespace does not support the dtype '{x.dtype}'" ) obj._array = x return obj # Prevent Array() from working def __new__(cls, *args, **kwargs): raise TypeError( "The array_api Array object should not be instantiated directly. Use an array creation function, such as asarray(), instead." ) # These functions are not required by the spec, but are implemented for # the sake of usability. def __str__(self: Array, /) -> str: """ Performs the operation __str__. """ return self._array.__str__().replace("array", "Array") def __repr__(self: Array, /) -> str: """ Performs the operation __repr__. """ suffix = f", dtype={self.dtype.name})" if 0 in self.shape: prefix = "empty(" mid = str(self.shape) else: prefix = "Array(" mid = np.array2string(self._array, separator=', ', prefix=prefix, suffix=suffix) return prefix + mid + suffix # This function is not required by the spec, but we implement it here for # convenience so that np.asarray(np.array_api.Array) will work. def __array__(self, dtype: None | np.dtype[Any] = None) -> npt.NDArray[Any]: """ Warning: this method is NOT part of the array API spec. Implementers of other libraries need not include it, and users should not assume it will be present in other implementations. """ return np.asarray(self._array, dtype=dtype) # These are various helper functions to make the array behavior match the # spec in places where it either deviates from or is more strict than # NumPy behavior def _check_allowed_dtypes(self, other: bool | int | float | Array, dtype_category: str, op: str) -> Array: """ Helper function for operators to only allow specific input dtypes Use like other = self._check_allowed_dtypes(other, 'numeric', '__add__') if other is NotImplemented: return other """ if self.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") if isinstance(other, (int, float, bool)): other = self._promote_scalar(other) elif isinstance(other, Array): if other.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") else: return NotImplemented # This will raise TypeError for type combinations that are not allowed # to promote in the spec (even if the NumPy array operator would # promote them). res_dtype = _result_type(self.dtype, other.dtype) if op.startswith("__i"): # Note: NumPy will allow in-place operators in some cases where # the type promoted operator does not match the left-hand side # operand. For example, # >>> a = np.array(1, dtype=np.int8) # >>> a += np.array(1, dtype=np.int16) # The spec explicitly disallows this. if res_dtype != self.dtype: raise TypeError( f"Cannot perform {op} with dtypes {self.dtype} and {other.dtype}" ) return other # Helper function to match the type promotion rules in the spec def _promote_scalar(self, scalar): """ Returns a promoted version of a Python scalar appropriate for use with operations on self. This may raise an OverflowError in cases where the scalar is an integer that is too large to fit in a NumPy integer dtype, or TypeError when the scalar type is incompatible with the dtype of self. """ # Note: Only Python scalar types that match the array dtype are # allowed. if isinstance(scalar, bool): if self.dtype not in _boolean_dtypes: raise TypeError( "Python bool scalars can only be promoted with bool arrays" ) elif isinstance(scalar, int): if self.dtype in _boolean_dtypes: raise TypeError( "Python int scalars cannot be promoted with bool arrays" ) elif isinstance(scalar, float): if self.dtype not in _floating_dtypes: raise TypeError( "Python float scalars can only be promoted with floating-point arrays." ) else: raise TypeError("'scalar' must be a Python scalar") # Note: scalars are unconditionally cast to the same dtype as the # array. # Note: the spec only specifies integer-dtype/int promotion # behavior for integers within the bounds of the integer dtype. # Outside of those bounds we use the default NumPy behavior (either # cast or raise OverflowError). return Array._new(np.array(scalar, self.dtype)) def _normalize_two_args(x1, x2) -> Tuple[Array, Array]: """ Normalize inputs to two arg functions to fix type promotion rules NumPy deviates from the spec type promotion rules in cases where one argument is 0-dimensional and the other is not. For example: >>> import numpy as np >>> a = np.array([1.0], dtype=np.float32) >>> b = np.array(1.0, dtype=np.float64) >>> np.add(a, b) # The spec says this should be float64 array([2.], dtype=float32) To fix this, we add a dimension to the 0-dimension array before passing it through. This works because a dimension would be added anyway from broadcasting, so the resulting shape is the same, but this prevents NumPy from not promoting the dtype. """ # Another option would be to use signature=(x1.dtype, x2.dtype, None), # but that only works for ufuncs, so we would have to call the ufuncs # directly in the operator methods. One should also note that this # sort of trick wouldn't work for functions like searchsorted, which # don't do normal broadcasting, but there aren't any functions like # that in the array API namespace. if x1.ndim == 0 and x2.ndim != 0: # The _array[None] workaround was chosen because it is relatively # performant. broadcast_to(x1._array, x2.shape) is much slower. We # could also manually type promote x2, but that is more complicated # and about the same performance as this. x1 = Array._new(x1._array[None]) elif x2.ndim == 0 and x1.ndim != 0: x2 = Array._new(x2._array[None]) return (x1, x2) # Note: A large fraction of allowed indices are disallowed here (see the # docstring below) def _validate_index(self, key): """ Validate an index according to the array API. The array API specification only requires a subset of indices that are supported by NumPy. This function will reject any index that is allowed by NumPy but not required by the array API specification. We always raise ``IndexError`` on such indices (the spec does not require any specific behavior on them, but this makes the NumPy array API namespace a minimal implementation of the spec). See https://data-apis.org/array-api/latest/API_specification/indexing.html for the full list of required indexing behavior This function raises IndexError if the index ``key`` is invalid. It only raises ``IndexError`` on indices that are not already rejected by NumPy, as NumPy will already raise the appropriate error on such indices. ``shape`` may be None, in which case, only cases that are independent of the array shape are checked. The following cases are allowed by NumPy, but not specified by the array API specification: - Indices to not include an implicit ellipsis at the end. That is, every axis of an array must be explicitly indexed or an ellipsis included. This behaviour is sometimes referred to as flat indexing. - The start and stop of a slice may not be out of bounds. In particular, for a slice ``i:j:k`` on an axis of size ``n``, only the following are allowed: - ``i`` or ``j`` omitted (``None``). - ``-n <= i <= max(0, n - 1)``. - For ``k > 0`` or ``k`` omitted (``None``), ``-n <= j <= n``. - For ``k < 0``, ``-n - 1 <= j <= max(0, n - 1)``. - Boolean array indices are not allowed as part of a larger tuple index. - Integer array indices are not allowed (with the exception of 0-D arrays, which are treated the same as scalars). Additionally, it should be noted that indices that would return a scalar in NumPy will return a 0-D array. Array scalars are not allowed in the specification, only 0-D arrays. This is done in the ``Array._new`` constructor, not this function. """ _key = key if isinstance(key, tuple) else (key,) for i in _key: if isinstance(i, bool) or not ( isinstance(i, SupportsIndex) # i.e. ints or isinstance(i, slice) or i == Ellipsis or i is None or isinstance(i, Array) or isinstance(i, np.ndarray) ): raise IndexError( f"Single-axes index {i} has {type(i)=}, but only " "integers, slices (:), ellipsis (...), newaxis (None), " "zero-dimensional integer arrays and boolean arrays " "are specified in the Array API." ) nonexpanding_key = [] single_axes = [] n_ellipsis = 0 key_has_mask = False for i in _key: if i is not None: nonexpanding_key.append(i) if isinstance(i, Array) or isinstance(i, np.ndarray): if i.dtype in _boolean_dtypes: key_has_mask = True single_axes.append(i) else: # i must not be an array here, to avoid elementwise equals if i == Ellipsis: n_ellipsis += 1 else: single_axes.append(i) n_single_axes = len(single_axes) if n_ellipsis > 1: return # handled by ndarray elif n_ellipsis == 0: # Note boolean masks must be the sole index, which we check for # later on. if not key_has_mask and n_single_axes < self.ndim: raise IndexError( f"{self.ndim=}, but the multi-axes index only specifies " f"{n_single_axes} dimensions. If this was intentional, " "add a trailing ellipsis (...) which expands into as many " "slices (:) as necessary - this is what np.ndarray arrays " "implicitly do, but such flat indexing behaviour is not " "specified in the Array API." ) if n_ellipsis == 0: indexed_shape = self.shape else: ellipsis_start = None for pos, i in enumerate(nonexpanding_key): if not (isinstance(i, Array) or isinstance(i, np.ndarray)): if i == Ellipsis: ellipsis_start = pos break assert ellipsis_start is not None # sanity check ellipsis_end = self.ndim - (n_single_axes - ellipsis_start) indexed_shape = ( self.shape[:ellipsis_start] + self.shape[ellipsis_end:] ) for i, side in zip(single_axes, indexed_shape): if isinstance(i, slice): if side == 0: f_range = "0 (or None)" else: f_range = f"between -{side} and {side - 1} (or None)" if i.start is not None: try: start = operator.index(i.start) except TypeError: pass # handled by ndarray else: if not (-side <= start <= side): raise IndexError( f"Slice {i} contains {start=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds starts are not specified in " "the Array API)" ) if i.stop is not None: try: stop = operator.index(i.stop) except TypeError: pass # handled by ndarray else: if not (-side <= stop <= side): raise IndexError( f"Slice {i} contains {stop=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds stops are not specified in " "the Array API)" ) elif isinstance(i, Array): if i.dtype in _boolean_dtypes and len(_key) != 1: assert isinstance(key, tuple) # sanity check raise IndexError( f"Single-axes index {i} is a boolean array and " f"{len(key)=}, but masking is only specified in the " "Array API when the array is the sole index." ) elif i.dtype in _integer_dtypes and i.ndim != 0: raise IndexError( f"Single-axes index {i} is a non-zero-dimensional " "integer array, but advanced integer indexing is not " "specified in the Array API." ) elif isinstance(i, tuple): raise IndexError( f"Single-axes index {i} is a tuple, but nested tuple " "indices are not specified in the Array API." ) # Everything below this line is required by the spec. def __abs__(self: Array, /) -> Array: """ Performs the operation __abs__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __abs__") res = self._array.__abs__() return self.__class__._new(res) def __add__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __add__. """ other = self._check_allowed_dtypes(other, "numeric", "__add__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__add__(other._array) return self.__class__._new(res) def __and__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __and__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__and__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__and__(other._array) return self.__class__._new(res) def __array_namespace__( self: Array, /, *, api_version: Optional[str] = None ) -> types.ModuleType: if api_version is not None and not api_version.startswith("2021."): raise ValueError(f"Unrecognized array API version: {api_version!r}") return array_api def __bool__(self: Array, /) -> bool: """ Performs the operation __bool__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("bool is only allowed on arrays with 0 dimensions") if self.dtype not in _boolean_dtypes: raise ValueError("bool is only allowed on boolean arrays") res = self._array.__bool__() return res def __dlpack__(self: Array, /, *, stream: None = None) -> PyCapsule: """ Performs the operation __dlpack__. """ return self._array.__dlpack__(stream=stream) def __dlpack_device__(self: Array, /) -> Tuple[IntEnum, int]: """ Performs the operation __dlpack_device__. """ # Note: device support is required for this return self._array.__dlpack_device__() def __eq__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __eq__. """ # Even though "all" dtypes are allowed, we still require them to be # promotable with each other. other = self._check_allowed_dtypes(other, "all", "__eq__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__eq__(other._array) return self.__class__._new(res) def __float__(self: Array, /) -> float: """ Performs the operation __float__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("float is only allowed on arrays with 0 dimensions") if self.dtype not in _floating_dtypes: raise ValueError("float is only allowed on floating-point arrays") res = self._array.__float__() return res def __floordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __floordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__floordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__floordiv__(other._array) return self.__class__._new(res) def __ge__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ge__. """ other = self._check_allowed_dtypes(other, "numeric", "__ge__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ge__(other._array) return self.__class__._new(res) def __getitem__( self: Array, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], /, ) -> Array: """ Performs the operation __getitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array res = self._array.__getitem__(key) return self._new(res) def __gt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __gt__. """ other = self._check_allowed_dtypes(other, "numeric", "__gt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__gt__(other._array) return self.__class__._new(res) def __int__(self: Array, /) -> int: """ Performs the operation __int__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("int is only allowed on arrays with 0 dimensions") if self.dtype not in _integer_dtypes: raise ValueError("int is only allowed on integer arrays") res = self._array.__int__() return res def __index__(self: Array, /) -> int: """ Performs the operation __index__. """ res = self._array.__index__() return res def __invert__(self: Array, /) -> Array: """ Performs the operation __invert__. """ if self.dtype not in _integer_or_boolean_dtypes: raise TypeError("Only integer or boolean dtypes are allowed in __invert__") res = self._array.__invert__() return self.__class__._new(res) def __le__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __le__. """ other = self._check_allowed_dtypes(other, "numeric", "__le__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__le__(other._array) return self.__class__._new(res) def __lshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __lshift__. """ other = self._check_allowed_dtypes(other, "integer", "__lshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lshift__(other._array) return self.__class__._new(res) def __lt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __lt__. """ other = self._check_allowed_dtypes(other, "numeric", "__lt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lt__(other._array) return self.__class__._new(res) def __matmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __matmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__matmul__") if other is NotImplemented: return other res = self._array.__matmul__(other._array) return self.__class__._new(res) def __mod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mod__. """ other = self._check_allowed_dtypes(other, "numeric", "__mod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mod__(other._array) return self.__class__._new(res) def __mul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mul__. """ other = self._check_allowed_dtypes(other, "numeric", "__mul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mul__(other._array) return self.__class__._new(res) def __ne__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __ne__. """ other = self._check_allowed_dtypes(other, "all", "__ne__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ne__(other._array) return self.__class__._new(res) def __neg__(self: Array, /) -> Array: """ Performs the operation __neg__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __neg__") res = self._array.__neg__() return self.__class__._new(res) def __or__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __or__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__or__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__or__(other._array) return self.__class__._new(res) def __pos__(self: Array, /) -> Array: """ Performs the operation __pos__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __pos__") res = self._array.__pos__() return self.__class__._new(res) def __pow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __pow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__pow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow type promotion rules for 0-d # arrays, so we use pow() here instead. return pow(self, other) def __rshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rshift__(other._array) return self.__class__._new(res) def __setitem__( self, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], value: Union[int, float, bool, Array], /, ) -> None: """ Performs the operation __setitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array self._array.__setitem__(key, asarray(value)._array) def __sub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __sub__. """ other = self._check_allowed_dtypes(other, "numeric", "__sub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__sub__(other._array) return self.__class__._new(res) # PEP 484 requires int to be a subtype of float, but __truediv__ should # not accept int. def __truediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __truediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__truediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__truediv__(other._array) return self.__class__._new(res) def __xor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __xor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__xor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__xor__(other._array) return self.__class__._new(res) def __iadd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __iadd__. """ other = self._check_allowed_dtypes(other, "numeric", "__iadd__") if other is NotImplemented: return other self._array.__iadd__(other._array) return self def __radd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __radd__. """ other = self._check_allowed_dtypes(other, "numeric", "__radd__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__radd__(other._array) return self.__class__._new(res) def __iand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __iand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__iand__") if other is NotImplemented: return other self._array.__iand__(other._array) return self def __rand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rand__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rand__(other._array) return self.__class__._new(res) def __ifloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ifloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__ifloordiv__") if other is NotImplemented: return other self._array.__ifloordiv__(other._array) return self def __rfloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rfloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__rfloordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rfloordiv__(other._array) return self.__class__._new(res) def __ilshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __ilshift__. """ other = self._check_allowed_dtypes(other, "integer", "__ilshift__") if other is NotImplemented: return other self._array.__ilshift__(other._array) return self def __rlshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rlshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rlshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rlshift__(other._array) return self.__class__._new(res) def __imatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __imatmul__. """ # Note: NumPy does not implement __imatmul__. # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__imatmul__") if other is NotImplemented: return other # __imatmul__ can only be allowed when it would not change the shape # of self. other_shape = other.shape if self.shape == () or other_shape == (): raise ValueError("@= requires at least one dimension") if len(other_shape) == 1 or other_shape[-1] != other_shape[-2]: raise ValueError("@= cannot change the shape of the input array") self._array[:] = self._array.__matmul__(other._array) return self def __rmatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __rmatmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__rmatmul__") if other is NotImplemented: return other res = self._array.__rmatmul__(other._array) return self.__class__._new(res) def __imod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imod__. """ other = self._check_allowed_dtypes(other, "numeric", "__imod__") if other is NotImplemented: return other self._array.__imod__(other._array) return self def __rmod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmod__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmod__(other._array) return self.__class__._new(res) def __imul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imul__. """ other = self._check_allowed_dtypes(other, "numeric", "__imul__") if other is NotImplemented: return other self._array.__imul__(other._array) return self def __rmul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmul__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmul__(other._array) return self.__class__._new(res) def __ior__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ior__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ior__") if other is NotImplemented: return other self._array.__ior__(other._array) return self def __ror__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ror__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ror__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ror__(other._array) return self.__class__._new(res) def __ipow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ipow__. """ other = self._check_allowed_dtypes(other, "numeric", "__ipow__") if other is NotImplemented: return other self._array.__ipow__(other._array) return self def __rpow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rpow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__rpow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow the spec type promotion rules # for 0-d arrays, so we use pow() here instead. return pow(other, self) def __irshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __irshift__. """ other = self._check_allowed_dtypes(other, "integer", "__irshift__") if other is NotImplemented: return other self._array.__irshift__(other._array) return self def __rrshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rrshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rrshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rrshift__(other._array) return self.__class__._new(res) def __isub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __isub__. """ other = self._check_allowed_dtypes(other, "numeric", "__isub__") if other is NotImplemented: return other self._array.__isub__(other._array) return self def __rsub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rsub__. """ other = self._check_allowed_dtypes(other, "numeric", "__rsub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rsub__(other._array) return self.__class__._new(res) def __itruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __itruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__itruediv__") if other is NotImplemented: return other self._array.__itruediv__(other._array) return self def __rtruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __rtruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__rtruediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rtruediv__(other._array) return self.__class__._new(res) def __ixor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ixor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ixor__") if other is NotImplemented: return other self._array.__ixor__(other._array) return self def __rxor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rxor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rxor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rxor__(other._array) return self.__class__._new(res) def to_device(self: Array, device: Device, /, stream: None = None) -> Array: if stream is not None: raise ValueError("The stream argument to to_device() is not supported") if device == 'cpu': return self raise ValueError(f"Unsupported device {device!r}") def dtype(self) -> Dtype: """ Array API compatible wrapper for :py:meth:`np.ndarray.dtype <numpy.ndarray.dtype>`. See its docstring for more information. """ return self._array.dtype def device(self) -> Device: return "cpu" # Note: mT is new in array API spec (see matrix_transpose) def mT(self) -> Array: from .linalg import matrix_transpose return matrix_transpose(self) def ndim(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.ndim <numpy.ndarray.ndim>`. See its docstring for more information. """ return self._array.ndim def shape(self) -> Tuple[int, ...]: """ Array API compatible wrapper for :py:meth:`np.ndarray.shape <numpy.ndarray.shape>`. See its docstring for more information. """ return self._array.shape def size(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.size <numpy.ndarray.size>`. See its docstring for more information. """ return self._array.size def T(self) -> Array: """ Array API compatible wrapper for :py:meth:`np.ndarray.T <numpy.ndarray.T>`. See its docstring for more information. """ # Note: T only works on 2-dimensional arrays. See the corresponding # note in the specification: # https://data-apis.org/array-api/latest/API_specification/array_object.html#t if self.ndim != 2: raise ValueError("x.T requires x to have 2 dimensions. Use x.mT to transpose stacks of matrices and permute_dims() to permute dimensions.") return self.__class__._new(self._array.T) Union: _SpecialForm = ... Optional: _SpecialForm = ... class Tuple(BaseTypingInstance): def _is_homogenous(self): # To specify a variable-length tuple of homogeneous type, Tuple[T, ...] # is used. return self._generics_manager.is_homogenous_tuple() def py__simple_getitem__(self, index): if self._is_homogenous(): return self._generics_manager.get_index_and_execute(0) else: if isinstance(index, int): return self._generics_manager.get_index_and_execute(index) debug.dbg('The getitem type on Tuple was %s' % index) return NO_VALUES def py__iter__(self, contextualized_node=None): if self._is_homogenous(): yield LazyKnownValues(self._generics_manager.get_index_and_execute(0)) else: for v in self._generics_manager.to_tuple(): yield LazyKnownValues(v.execute_annotation()) def py__getitem__(self, index_value_set, contextualized_node): if self._is_homogenous(): return self._generics_manager.get_index_and_execute(0) return ValueSet.from_sets( self._generics_manager.to_tuple() ).execute_annotation() def _get_wrapped_value(self): tuple_, = self.inference_state.builtins_module \ .py__getattribute__('tuple').execute_annotation() return tuple_ def name(self): return self._wrapped_value.name def infer_type_vars(self, value_set): # Circular from jedi.inference.gradual.annotation import merge_pairwise_generics, merge_type_var_dicts value_set = value_set.filter( lambda x: x.py__name__().lower() == 'tuple', ) if self._is_homogenous(): # The parameter annotation is of the form `Tuple[T, ...]`, # so we treat the incoming tuple like a iterable sequence # rather than a positional container of elements. return self._class_value.get_generics()[0].infer_type_vars( value_set.merge_types_of_iterate(), ) else: # The parameter annotation has only explicit type parameters # (e.g: `Tuple[T]`, `Tuple[T, U]`, `Tuple[T, U, V]`, etc.) so we # treat the incoming values as needing to match the annotation # exactly, just as we would for non-tuple annotations. type_var_dict = {} for element in value_set: try: method = element.get_annotated_class_object except AttributeError: # This might still happen, because the tuple name matching # above is not 100% correct, so just catch the remaining # cases here. continue py_class = method() merge_type_var_dicts( type_var_dict, merge_pairwise_generics(self._class_value, py_class), ) return type_var_dict The provided code snippet includes necessary dependencies for implementing the `flip` function. Write a Python function `def flip(x: Array, /, *, axis: Optional[Union[int, Tuple[int, ...]]] = None) -> Array` to solve the following problem: Array API compatible wrapper for :py:func:`np.flip <numpy.flip>`. See its docstring for more information. Here is the function: def flip(x: Array, /, *, axis: Optional[Union[int, Tuple[int, ...]]] = None) -> Array: """ Array API compatible wrapper for :py:func:`np.flip <numpy.flip>`. See its docstring for more information. """ return Array._new(np.flip(x._array, axis=axis))
Array API compatible wrapper for :py:func:`np.flip <numpy.flip>`. See its docstring for more information.
170,082
from __future__ import annotations from ._array_object import Array from ._data_type_functions import result_type from typing import List, Optional, Tuple, Union import numpy as np class Array: """ n-d array object for the array API namespace. See the docstring of :py:obj:`np.ndarray <numpy.ndarray>` for more information. This is a wrapper around numpy.ndarray that restricts the usage to only those things that are required by the array API namespace. Note, attributes on this object that start with a single underscore are not part of the API specification and should only be used internally. This object should not be constructed directly. Rather, use one of the creation functions, such as asarray(). """ _array: np.ndarray # Use a custom constructor instead of __init__, as manually initializing # this class is not supported API. def _new(cls, x, /): """ This is a private method for initializing the array API Array object. Functions outside of the array_api submodule should not use this method. Use one of the creation functions instead, such as ``asarray``. """ obj = super().__new__(cls) # Note: The spec does not have array scalars, only 0-D arrays. if isinstance(x, np.generic): # Convert the array scalar to a 0-D array x = np.asarray(x) if x.dtype not in _all_dtypes: raise TypeError( f"The array_api namespace does not support the dtype '{x.dtype}'" ) obj._array = x return obj # Prevent Array() from working def __new__(cls, *args, **kwargs): raise TypeError( "The array_api Array object should not be instantiated directly. Use an array creation function, such as asarray(), instead." ) # These functions are not required by the spec, but are implemented for # the sake of usability. def __str__(self: Array, /) -> str: """ Performs the operation __str__. """ return self._array.__str__().replace("array", "Array") def __repr__(self: Array, /) -> str: """ Performs the operation __repr__. """ suffix = f", dtype={self.dtype.name})" if 0 in self.shape: prefix = "empty(" mid = str(self.shape) else: prefix = "Array(" mid = np.array2string(self._array, separator=', ', prefix=prefix, suffix=suffix) return prefix + mid + suffix # This function is not required by the spec, but we implement it here for # convenience so that np.asarray(np.array_api.Array) will work. def __array__(self, dtype: None | np.dtype[Any] = None) -> npt.NDArray[Any]: """ Warning: this method is NOT part of the array API spec. Implementers of other libraries need not include it, and users should not assume it will be present in other implementations. """ return np.asarray(self._array, dtype=dtype) # These are various helper functions to make the array behavior match the # spec in places where it either deviates from or is more strict than # NumPy behavior def _check_allowed_dtypes(self, other: bool | int | float | Array, dtype_category: str, op: str) -> Array: """ Helper function for operators to only allow specific input dtypes Use like other = self._check_allowed_dtypes(other, 'numeric', '__add__') if other is NotImplemented: return other """ if self.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") if isinstance(other, (int, float, bool)): other = self._promote_scalar(other) elif isinstance(other, Array): if other.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") else: return NotImplemented # This will raise TypeError for type combinations that are not allowed # to promote in the spec (even if the NumPy array operator would # promote them). res_dtype = _result_type(self.dtype, other.dtype) if op.startswith("__i"): # Note: NumPy will allow in-place operators in some cases where # the type promoted operator does not match the left-hand side # operand. For example, # >>> a = np.array(1, dtype=np.int8) # >>> a += np.array(1, dtype=np.int16) # The spec explicitly disallows this. if res_dtype != self.dtype: raise TypeError( f"Cannot perform {op} with dtypes {self.dtype} and {other.dtype}" ) return other # Helper function to match the type promotion rules in the spec def _promote_scalar(self, scalar): """ Returns a promoted version of a Python scalar appropriate for use with operations on self. This may raise an OverflowError in cases where the scalar is an integer that is too large to fit in a NumPy integer dtype, or TypeError when the scalar type is incompatible with the dtype of self. """ # Note: Only Python scalar types that match the array dtype are # allowed. if isinstance(scalar, bool): if self.dtype not in _boolean_dtypes: raise TypeError( "Python bool scalars can only be promoted with bool arrays" ) elif isinstance(scalar, int): if self.dtype in _boolean_dtypes: raise TypeError( "Python int scalars cannot be promoted with bool arrays" ) elif isinstance(scalar, float): if self.dtype not in _floating_dtypes: raise TypeError( "Python float scalars can only be promoted with floating-point arrays." ) else: raise TypeError("'scalar' must be a Python scalar") # Note: scalars are unconditionally cast to the same dtype as the # array. # Note: the spec only specifies integer-dtype/int promotion # behavior for integers within the bounds of the integer dtype. # Outside of those bounds we use the default NumPy behavior (either # cast or raise OverflowError). return Array._new(np.array(scalar, self.dtype)) def _normalize_two_args(x1, x2) -> Tuple[Array, Array]: """ Normalize inputs to two arg functions to fix type promotion rules NumPy deviates from the spec type promotion rules in cases where one argument is 0-dimensional and the other is not. For example: >>> import numpy as np >>> a = np.array([1.0], dtype=np.float32) >>> b = np.array(1.0, dtype=np.float64) >>> np.add(a, b) # The spec says this should be float64 array([2.], dtype=float32) To fix this, we add a dimension to the 0-dimension array before passing it through. This works because a dimension would be added anyway from broadcasting, so the resulting shape is the same, but this prevents NumPy from not promoting the dtype. """ # Another option would be to use signature=(x1.dtype, x2.dtype, None), # but that only works for ufuncs, so we would have to call the ufuncs # directly in the operator methods. One should also note that this # sort of trick wouldn't work for functions like searchsorted, which # don't do normal broadcasting, but there aren't any functions like # that in the array API namespace. if x1.ndim == 0 and x2.ndim != 0: # The _array[None] workaround was chosen because it is relatively # performant. broadcast_to(x1._array, x2.shape) is much slower. We # could also manually type promote x2, but that is more complicated # and about the same performance as this. x1 = Array._new(x1._array[None]) elif x2.ndim == 0 and x1.ndim != 0: x2 = Array._new(x2._array[None]) return (x1, x2) # Note: A large fraction of allowed indices are disallowed here (see the # docstring below) def _validate_index(self, key): """ Validate an index according to the array API. The array API specification only requires a subset of indices that are supported by NumPy. This function will reject any index that is allowed by NumPy but not required by the array API specification. We always raise ``IndexError`` on such indices (the spec does not require any specific behavior on them, but this makes the NumPy array API namespace a minimal implementation of the spec). See https://data-apis.org/array-api/latest/API_specification/indexing.html for the full list of required indexing behavior This function raises IndexError if the index ``key`` is invalid. It only raises ``IndexError`` on indices that are not already rejected by NumPy, as NumPy will already raise the appropriate error on such indices. ``shape`` may be None, in which case, only cases that are independent of the array shape are checked. The following cases are allowed by NumPy, but not specified by the array API specification: - Indices to not include an implicit ellipsis at the end. That is, every axis of an array must be explicitly indexed or an ellipsis included. This behaviour is sometimes referred to as flat indexing. - The start and stop of a slice may not be out of bounds. In particular, for a slice ``i:j:k`` on an axis of size ``n``, only the following are allowed: - ``i`` or ``j`` omitted (``None``). - ``-n <= i <= max(0, n - 1)``. - For ``k > 0`` or ``k`` omitted (``None``), ``-n <= j <= n``. - For ``k < 0``, ``-n - 1 <= j <= max(0, n - 1)``. - Boolean array indices are not allowed as part of a larger tuple index. - Integer array indices are not allowed (with the exception of 0-D arrays, which are treated the same as scalars). Additionally, it should be noted that indices that would return a scalar in NumPy will return a 0-D array. Array scalars are not allowed in the specification, only 0-D arrays. This is done in the ``Array._new`` constructor, not this function. """ _key = key if isinstance(key, tuple) else (key,) for i in _key: if isinstance(i, bool) or not ( isinstance(i, SupportsIndex) # i.e. ints or isinstance(i, slice) or i == Ellipsis or i is None or isinstance(i, Array) or isinstance(i, np.ndarray) ): raise IndexError( f"Single-axes index {i} has {type(i)=}, but only " "integers, slices (:), ellipsis (...), newaxis (None), " "zero-dimensional integer arrays and boolean arrays " "are specified in the Array API." ) nonexpanding_key = [] single_axes = [] n_ellipsis = 0 key_has_mask = False for i in _key: if i is not None: nonexpanding_key.append(i) if isinstance(i, Array) or isinstance(i, np.ndarray): if i.dtype in _boolean_dtypes: key_has_mask = True single_axes.append(i) else: # i must not be an array here, to avoid elementwise equals if i == Ellipsis: n_ellipsis += 1 else: single_axes.append(i) n_single_axes = len(single_axes) if n_ellipsis > 1: return # handled by ndarray elif n_ellipsis == 0: # Note boolean masks must be the sole index, which we check for # later on. if not key_has_mask and n_single_axes < self.ndim: raise IndexError( f"{self.ndim=}, but the multi-axes index only specifies " f"{n_single_axes} dimensions. If this was intentional, " "add a trailing ellipsis (...) which expands into as many " "slices (:) as necessary - this is what np.ndarray arrays " "implicitly do, but such flat indexing behaviour is not " "specified in the Array API." ) if n_ellipsis == 0: indexed_shape = self.shape else: ellipsis_start = None for pos, i in enumerate(nonexpanding_key): if not (isinstance(i, Array) or isinstance(i, np.ndarray)): if i == Ellipsis: ellipsis_start = pos break assert ellipsis_start is not None # sanity check ellipsis_end = self.ndim - (n_single_axes - ellipsis_start) indexed_shape = ( self.shape[:ellipsis_start] + self.shape[ellipsis_end:] ) for i, side in zip(single_axes, indexed_shape): if isinstance(i, slice): if side == 0: f_range = "0 (or None)" else: f_range = f"between -{side} and {side - 1} (or None)" if i.start is not None: try: start = operator.index(i.start) except TypeError: pass # handled by ndarray else: if not (-side <= start <= side): raise IndexError( f"Slice {i} contains {start=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds starts are not specified in " "the Array API)" ) if i.stop is not None: try: stop = operator.index(i.stop) except TypeError: pass # handled by ndarray else: if not (-side <= stop <= side): raise IndexError( f"Slice {i} contains {stop=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds stops are not specified in " "the Array API)" ) elif isinstance(i, Array): if i.dtype in _boolean_dtypes and len(_key) != 1: assert isinstance(key, tuple) # sanity check raise IndexError( f"Single-axes index {i} is a boolean array and " f"{len(key)=}, but masking is only specified in the " "Array API when the array is the sole index." ) elif i.dtype in _integer_dtypes and i.ndim != 0: raise IndexError( f"Single-axes index {i} is a non-zero-dimensional " "integer array, but advanced integer indexing is not " "specified in the Array API." ) elif isinstance(i, tuple): raise IndexError( f"Single-axes index {i} is a tuple, but nested tuple " "indices are not specified in the Array API." ) # Everything below this line is required by the spec. def __abs__(self: Array, /) -> Array: """ Performs the operation __abs__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __abs__") res = self._array.__abs__() return self.__class__._new(res) def __add__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __add__. """ other = self._check_allowed_dtypes(other, "numeric", "__add__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__add__(other._array) return self.__class__._new(res) def __and__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __and__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__and__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__and__(other._array) return self.__class__._new(res) def __array_namespace__( self: Array, /, *, api_version: Optional[str] = None ) -> types.ModuleType: if api_version is not None and not api_version.startswith("2021."): raise ValueError(f"Unrecognized array API version: {api_version!r}") return array_api def __bool__(self: Array, /) -> bool: """ Performs the operation __bool__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("bool is only allowed on arrays with 0 dimensions") if self.dtype not in _boolean_dtypes: raise ValueError("bool is only allowed on boolean arrays") res = self._array.__bool__() return res def __dlpack__(self: Array, /, *, stream: None = None) -> PyCapsule: """ Performs the operation __dlpack__. """ return self._array.__dlpack__(stream=stream) def __dlpack_device__(self: Array, /) -> Tuple[IntEnum, int]: """ Performs the operation __dlpack_device__. """ # Note: device support is required for this return self._array.__dlpack_device__() def __eq__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __eq__. """ # Even though "all" dtypes are allowed, we still require them to be # promotable with each other. other = self._check_allowed_dtypes(other, "all", "__eq__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__eq__(other._array) return self.__class__._new(res) def __float__(self: Array, /) -> float: """ Performs the operation __float__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("float is only allowed on arrays with 0 dimensions") if self.dtype not in _floating_dtypes: raise ValueError("float is only allowed on floating-point arrays") res = self._array.__float__() return res def __floordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __floordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__floordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__floordiv__(other._array) return self.__class__._new(res) def __ge__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ge__. """ other = self._check_allowed_dtypes(other, "numeric", "__ge__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ge__(other._array) return self.__class__._new(res) def __getitem__( self: Array, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], /, ) -> Array: """ Performs the operation __getitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array res = self._array.__getitem__(key) return self._new(res) def __gt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __gt__. """ other = self._check_allowed_dtypes(other, "numeric", "__gt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__gt__(other._array) return self.__class__._new(res) def __int__(self: Array, /) -> int: """ Performs the operation __int__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("int is only allowed on arrays with 0 dimensions") if self.dtype not in _integer_dtypes: raise ValueError("int is only allowed on integer arrays") res = self._array.__int__() return res def __index__(self: Array, /) -> int: """ Performs the operation __index__. """ res = self._array.__index__() return res def __invert__(self: Array, /) -> Array: """ Performs the operation __invert__. """ if self.dtype not in _integer_or_boolean_dtypes: raise TypeError("Only integer or boolean dtypes are allowed in __invert__") res = self._array.__invert__() return self.__class__._new(res) def __le__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __le__. """ other = self._check_allowed_dtypes(other, "numeric", "__le__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__le__(other._array) return self.__class__._new(res) def __lshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __lshift__. """ other = self._check_allowed_dtypes(other, "integer", "__lshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lshift__(other._array) return self.__class__._new(res) def __lt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __lt__. """ other = self._check_allowed_dtypes(other, "numeric", "__lt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lt__(other._array) return self.__class__._new(res) def __matmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __matmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__matmul__") if other is NotImplemented: return other res = self._array.__matmul__(other._array) return self.__class__._new(res) def __mod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mod__. """ other = self._check_allowed_dtypes(other, "numeric", "__mod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mod__(other._array) return self.__class__._new(res) def __mul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mul__. """ other = self._check_allowed_dtypes(other, "numeric", "__mul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mul__(other._array) return self.__class__._new(res) def __ne__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __ne__. """ other = self._check_allowed_dtypes(other, "all", "__ne__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ne__(other._array) return self.__class__._new(res) def __neg__(self: Array, /) -> Array: """ Performs the operation __neg__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __neg__") res = self._array.__neg__() return self.__class__._new(res) def __or__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __or__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__or__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__or__(other._array) return self.__class__._new(res) def __pos__(self: Array, /) -> Array: """ Performs the operation __pos__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __pos__") res = self._array.__pos__() return self.__class__._new(res) def __pow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __pow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__pow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow type promotion rules for 0-d # arrays, so we use pow() here instead. return pow(self, other) def __rshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rshift__(other._array) return self.__class__._new(res) def __setitem__( self, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], value: Union[int, float, bool, Array], /, ) -> None: """ Performs the operation __setitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array self._array.__setitem__(key, asarray(value)._array) def __sub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __sub__. """ other = self._check_allowed_dtypes(other, "numeric", "__sub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__sub__(other._array) return self.__class__._new(res) # PEP 484 requires int to be a subtype of float, but __truediv__ should # not accept int. def __truediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __truediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__truediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__truediv__(other._array) return self.__class__._new(res) def __xor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __xor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__xor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__xor__(other._array) return self.__class__._new(res) def __iadd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __iadd__. """ other = self._check_allowed_dtypes(other, "numeric", "__iadd__") if other is NotImplemented: return other self._array.__iadd__(other._array) return self def __radd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __radd__. """ other = self._check_allowed_dtypes(other, "numeric", "__radd__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__radd__(other._array) return self.__class__._new(res) def __iand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __iand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__iand__") if other is NotImplemented: return other self._array.__iand__(other._array) return self def __rand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rand__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rand__(other._array) return self.__class__._new(res) def __ifloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ifloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__ifloordiv__") if other is NotImplemented: return other self._array.__ifloordiv__(other._array) return self def __rfloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rfloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__rfloordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rfloordiv__(other._array) return self.__class__._new(res) def __ilshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __ilshift__. """ other = self._check_allowed_dtypes(other, "integer", "__ilshift__") if other is NotImplemented: return other self._array.__ilshift__(other._array) return self def __rlshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rlshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rlshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rlshift__(other._array) return self.__class__._new(res) def __imatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __imatmul__. """ # Note: NumPy does not implement __imatmul__. # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__imatmul__") if other is NotImplemented: return other # __imatmul__ can only be allowed when it would not change the shape # of self. other_shape = other.shape if self.shape == () or other_shape == (): raise ValueError("@= requires at least one dimension") if len(other_shape) == 1 or other_shape[-1] != other_shape[-2]: raise ValueError("@= cannot change the shape of the input array") self._array[:] = self._array.__matmul__(other._array) return self def __rmatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __rmatmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__rmatmul__") if other is NotImplemented: return other res = self._array.__rmatmul__(other._array) return self.__class__._new(res) def __imod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imod__. """ other = self._check_allowed_dtypes(other, "numeric", "__imod__") if other is NotImplemented: return other self._array.__imod__(other._array) return self def __rmod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmod__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmod__(other._array) return self.__class__._new(res) def __imul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imul__. """ other = self._check_allowed_dtypes(other, "numeric", "__imul__") if other is NotImplemented: return other self._array.__imul__(other._array) return self def __rmul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmul__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmul__(other._array) return self.__class__._new(res) def __ior__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ior__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ior__") if other is NotImplemented: return other self._array.__ior__(other._array) return self def __ror__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ror__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ror__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ror__(other._array) return self.__class__._new(res) def __ipow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ipow__. """ other = self._check_allowed_dtypes(other, "numeric", "__ipow__") if other is NotImplemented: return other self._array.__ipow__(other._array) return self def __rpow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rpow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__rpow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow the spec type promotion rules # for 0-d arrays, so we use pow() here instead. return pow(other, self) def __irshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __irshift__. """ other = self._check_allowed_dtypes(other, "integer", "__irshift__") if other is NotImplemented: return other self._array.__irshift__(other._array) return self def __rrshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rrshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rrshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rrshift__(other._array) return self.__class__._new(res) def __isub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __isub__. """ other = self._check_allowed_dtypes(other, "numeric", "__isub__") if other is NotImplemented: return other self._array.__isub__(other._array) return self def __rsub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rsub__. """ other = self._check_allowed_dtypes(other, "numeric", "__rsub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rsub__(other._array) return self.__class__._new(res) def __itruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __itruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__itruediv__") if other is NotImplemented: return other self._array.__itruediv__(other._array) return self def __rtruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __rtruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__rtruediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rtruediv__(other._array) return self.__class__._new(res) def __ixor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ixor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ixor__") if other is NotImplemented: return other self._array.__ixor__(other._array) return self def __rxor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rxor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rxor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rxor__(other._array) return self.__class__._new(res) def to_device(self: Array, device: Device, /, stream: None = None) -> Array: if stream is not None: raise ValueError("The stream argument to to_device() is not supported") if device == 'cpu': return self raise ValueError(f"Unsupported device {device!r}") def dtype(self) -> Dtype: """ Array API compatible wrapper for :py:meth:`np.ndarray.dtype <numpy.ndarray.dtype>`. See its docstring for more information. """ return self._array.dtype def device(self) -> Device: return "cpu" # Note: mT is new in array API spec (see matrix_transpose) def mT(self) -> Array: from .linalg import matrix_transpose return matrix_transpose(self) def ndim(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.ndim <numpy.ndarray.ndim>`. See its docstring for more information. """ return self._array.ndim def shape(self) -> Tuple[int, ...]: """ Array API compatible wrapper for :py:meth:`np.ndarray.shape <numpy.ndarray.shape>`. See its docstring for more information. """ return self._array.shape def size(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.size <numpy.ndarray.size>`. See its docstring for more information. """ return self._array.size def T(self) -> Array: """ Array API compatible wrapper for :py:meth:`np.ndarray.T <numpy.ndarray.T>`. See its docstring for more information. """ # Note: T only works on 2-dimensional arrays. See the corresponding # note in the specification: # https://data-apis.org/array-api/latest/API_specification/array_object.html#t if self.ndim != 2: raise ValueError("x.T requires x to have 2 dimensions. Use x.mT to transpose stacks of matrices and permute_dims() to permute dimensions.") return self.__class__._new(self._array.T) class Tuple(BaseTypingInstance): def _is_homogenous(self): # To specify a variable-length tuple of homogeneous type, Tuple[T, ...] # is used. return self._generics_manager.is_homogenous_tuple() def py__simple_getitem__(self, index): if self._is_homogenous(): return self._generics_manager.get_index_and_execute(0) else: if isinstance(index, int): return self._generics_manager.get_index_and_execute(index) debug.dbg('The getitem type on Tuple was %s' % index) return NO_VALUES def py__iter__(self, contextualized_node=None): if self._is_homogenous(): yield LazyKnownValues(self._generics_manager.get_index_and_execute(0)) else: for v in self._generics_manager.to_tuple(): yield LazyKnownValues(v.execute_annotation()) def py__getitem__(self, index_value_set, contextualized_node): if self._is_homogenous(): return self._generics_manager.get_index_and_execute(0) return ValueSet.from_sets( self._generics_manager.to_tuple() ).execute_annotation() def _get_wrapped_value(self): tuple_, = self.inference_state.builtins_module \ .py__getattribute__('tuple').execute_annotation() return tuple_ def name(self): return self._wrapped_value.name def infer_type_vars(self, value_set): # Circular from jedi.inference.gradual.annotation import merge_pairwise_generics, merge_type_var_dicts value_set = value_set.filter( lambda x: x.py__name__().lower() == 'tuple', ) if self._is_homogenous(): # The parameter annotation is of the form `Tuple[T, ...]`, # so we treat the incoming tuple like a iterable sequence # rather than a positional container of elements. return self._class_value.get_generics()[0].infer_type_vars( value_set.merge_types_of_iterate(), ) else: # The parameter annotation has only explicit type parameters # (e.g: `Tuple[T]`, `Tuple[T, U]`, `Tuple[T, U, V]`, etc.) so we # treat the incoming values as needing to match the annotation # exactly, just as we would for non-tuple annotations. type_var_dict = {} for element in value_set: try: method = element.get_annotated_class_object except AttributeError: # This might still happen, because the tuple name matching # above is not 100% correct, so just catch the remaining # cases here. continue py_class = method() merge_type_var_dicts( type_var_dict, merge_pairwise_generics(self._class_value, py_class), ) return type_var_dict The provided code snippet includes necessary dependencies for implementing the `permute_dims` function. Write a Python function `def permute_dims(x: Array, /, axes: Tuple[int, ...]) -> Array` to solve the following problem: Array API compatible wrapper for :py:func:`np.transpose <numpy.transpose>`. See its docstring for more information. Here is the function: def permute_dims(x: Array, /, axes: Tuple[int, ...]) -> Array: """ Array API compatible wrapper for :py:func:`np.transpose <numpy.transpose>`. See its docstring for more information. """ return Array._new(np.transpose(x._array, axes))
Array API compatible wrapper for :py:func:`np.transpose <numpy.transpose>`. See its docstring for more information.
170,083
from __future__ import annotations from ._array_object import Array from ._data_type_functions import result_type from typing import List, Optional, Tuple, Union import numpy as np class Array: """ n-d array object for the array API namespace. See the docstring of :py:obj:`np.ndarray <numpy.ndarray>` for more information. This is a wrapper around numpy.ndarray that restricts the usage to only those things that are required by the array API namespace. Note, attributes on this object that start with a single underscore are not part of the API specification and should only be used internally. This object should not be constructed directly. Rather, use one of the creation functions, such as asarray(). """ _array: np.ndarray # Use a custom constructor instead of __init__, as manually initializing # this class is not supported API. def _new(cls, x, /): """ This is a private method for initializing the array API Array object. Functions outside of the array_api submodule should not use this method. Use one of the creation functions instead, such as ``asarray``. """ obj = super().__new__(cls) # Note: The spec does not have array scalars, only 0-D arrays. if isinstance(x, np.generic): # Convert the array scalar to a 0-D array x = np.asarray(x) if x.dtype not in _all_dtypes: raise TypeError( f"The array_api namespace does not support the dtype '{x.dtype}'" ) obj._array = x return obj # Prevent Array() from working def __new__(cls, *args, **kwargs): raise TypeError( "The array_api Array object should not be instantiated directly. Use an array creation function, such as asarray(), instead." ) # These functions are not required by the spec, but are implemented for # the sake of usability. def __str__(self: Array, /) -> str: """ Performs the operation __str__. """ return self._array.__str__().replace("array", "Array") def __repr__(self: Array, /) -> str: """ Performs the operation __repr__. """ suffix = f", dtype={self.dtype.name})" if 0 in self.shape: prefix = "empty(" mid = str(self.shape) else: prefix = "Array(" mid = np.array2string(self._array, separator=', ', prefix=prefix, suffix=suffix) return prefix + mid + suffix # This function is not required by the spec, but we implement it here for # convenience so that np.asarray(np.array_api.Array) will work. def __array__(self, dtype: None | np.dtype[Any] = None) -> npt.NDArray[Any]: """ Warning: this method is NOT part of the array API spec. Implementers of other libraries need not include it, and users should not assume it will be present in other implementations. """ return np.asarray(self._array, dtype=dtype) # These are various helper functions to make the array behavior match the # spec in places where it either deviates from or is more strict than # NumPy behavior def _check_allowed_dtypes(self, other: bool | int | float | Array, dtype_category: str, op: str) -> Array: """ Helper function for operators to only allow specific input dtypes Use like other = self._check_allowed_dtypes(other, 'numeric', '__add__') if other is NotImplemented: return other """ if self.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") if isinstance(other, (int, float, bool)): other = self._promote_scalar(other) elif isinstance(other, Array): if other.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") else: return NotImplemented # This will raise TypeError for type combinations that are not allowed # to promote in the spec (even if the NumPy array operator would # promote them). res_dtype = _result_type(self.dtype, other.dtype) if op.startswith("__i"): # Note: NumPy will allow in-place operators in some cases where # the type promoted operator does not match the left-hand side # operand. For example, # >>> a = np.array(1, dtype=np.int8) # >>> a += np.array(1, dtype=np.int16) # The spec explicitly disallows this. if res_dtype != self.dtype: raise TypeError( f"Cannot perform {op} with dtypes {self.dtype} and {other.dtype}" ) return other # Helper function to match the type promotion rules in the spec def _promote_scalar(self, scalar): """ Returns a promoted version of a Python scalar appropriate for use with operations on self. This may raise an OverflowError in cases where the scalar is an integer that is too large to fit in a NumPy integer dtype, or TypeError when the scalar type is incompatible with the dtype of self. """ # Note: Only Python scalar types that match the array dtype are # allowed. if isinstance(scalar, bool): if self.dtype not in _boolean_dtypes: raise TypeError( "Python bool scalars can only be promoted with bool arrays" ) elif isinstance(scalar, int): if self.dtype in _boolean_dtypes: raise TypeError( "Python int scalars cannot be promoted with bool arrays" ) elif isinstance(scalar, float): if self.dtype not in _floating_dtypes: raise TypeError( "Python float scalars can only be promoted with floating-point arrays." ) else: raise TypeError("'scalar' must be a Python scalar") # Note: scalars are unconditionally cast to the same dtype as the # array. # Note: the spec only specifies integer-dtype/int promotion # behavior for integers within the bounds of the integer dtype. # Outside of those bounds we use the default NumPy behavior (either # cast or raise OverflowError). return Array._new(np.array(scalar, self.dtype)) def _normalize_two_args(x1, x2) -> Tuple[Array, Array]: """ Normalize inputs to two arg functions to fix type promotion rules NumPy deviates from the spec type promotion rules in cases where one argument is 0-dimensional and the other is not. For example: >>> import numpy as np >>> a = np.array([1.0], dtype=np.float32) >>> b = np.array(1.0, dtype=np.float64) >>> np.add(a, b) # The spec says this should be float64 array([2.], dtype=float32) To fix this, we add a dimension to the 0-dimension array before passing it through. This works because a dimension would be added anyway from broadcasting, so the resulting shape is the same, but this prevents NumPy from not promoting the dtype. """ # Another option would be to use signature=(x1.dtype, x2.dtype, None), # but that only works for ufuncs, so we would have to call the ufuncs # directly in the operator methods. One should also note that this # sort of trick wouldn't work for functions like searchsorted, which # don't do normal broadcasting, but there aren't any functions like # that in the array API namespace. if x1.ndim == 0 and x2.ndim != 0: # The _array[None] workaround was chosen because it is relatively # performant. broadcast_to(x1._array, x2.shape) is much slower. We # could also manually type promote x2, but that is more complicated # and about the same performance as this. x1 = Array._new(x1._array[None]) elif x2.ndim == 0 and x1.ndim != 0: x2 = Array._new(x2._array[None]) return (x1, x2) # Note: A large fraction of allowed indices are disallowed here (see the # docstring below) def _validate_index(self, key): """ Validate an index according to the array API. The array API specification only requires a subset of indices that are supported by NumPy. This function will reject any index that is allowed by NumPy but not required by the array API specification. We always raise ``IndexError`` on such indices (the spec does not require any specific behavior on them, but this makes the NumPy array API namespace a minimal implementation of the spec). See https://data-apis.org/array-api/latest/API_specification/indexing.html for the full list of required indexing behavior This function raises IndexError if the index ``key`` is invalid. It only raises ``IndexError`` on indices that are not already rejected by NumPy, as NumPy will already raise the appropriate error on such indices. ``shape`` may be None, in which case, only cases that are independent of the array shape are checked. The following cases are allowed by NumPy, but not specified by the array API specification: - Indices to not include an implicit ellipsis at the end. That is, every axis of an array must be explicitly indexed or an ellipsis included. This behaviour is sometimes referred to as flat indexing. - The start and stop of a slice may not be out of bounds. In particular, for a slice ``i:j:k`` on an axis of size ``n``, only the following are allowed: - ``i`` or ``j`` omitted (``None``). - ``-n <= i <= max(0, n - 1)``. - For ``k > 0`` or ``k`` omitted (``None``), ``-n <= j <= n``. - For ``k < 0``, ``-n - 1 <= j <= max(0, n - 1)``. - Boolean array indices are not allowed as part of a larger tuple index. - Integer array indices are not allowed (with the exception of 0-D arrays, which are treated the same as scalars). Additionally, it should be noted that indices that would return a scalar in NumPy will return a 0-D array. Array scalars are not allowed in the specification, only 0-D arrays. This is done in the ``Array._new`` constructor, not this function. """ _key = key if isinstance(key, tuple) else (key,) for i in _key: if isinstance(i, bool) or not ( isinstance(i, SupportsIndex) # i.e. ints or isinstance(i, slice) or i == Ellipsis or i is None or isinstance(i, Array) or isinstance(i, np.ndarray) ): raise IndexError( f"Single-axes index {i} has {type(i)=}, but only " "integers, slices (:), ellipsis (...), newaxis (None), " "zero-dimensional integer arrays and boolean arrays " "are specified in the Array API." ) nonexpanding_key = [] single_axes = [] n_ellipsis = 0 key_has_mask = False for i in _key: if i is not None: nonexpanding_key.append(i) if isinstance(i, Array) or isinstance(i, np.ndarray): if i.dtype in _boolean_dtypes: key_has_mask = True single_axes.append(i) else: # i must not be an array here, to avoid elementwise equals if i == Ellipsis: n_ellipsis += 1 else: single_axes.append(i) n_single_axes = len(single_axes) if n_ellipsis > 1: return # handled by ndarray elif n_ellipsis == 0: # Note boolean masks must be the sole index, which we check for # later on. if not key_has_mask and n_single_axes < self.ndim: raise IndexError( f"{self.ndim=}, but the multi-axes index only specifies " f"{n_single_axes} dimensions. If this was intentional, " "add a trailing ellipsis (...) which expands into as many " "slices (:) as necessary - this is what np.ndarray arrays " "implicitly do, but such flat indexing behaviour is not " "specified in the Array API." ) if n_ellipsis == 0: indexed_shape = self.shape else: ellipsis_start = None for pos, i in enumerate(nonexpanding_key): if not (isinstance(i, Array) or isinstance(i, np.ndarray)): if i == Ellipsis: ellipsis_start = pos break assert ellipsis_start is not None # sanity check ellipsis_end = self.ndim - (n_single_axes - ellipsis_start) indexed_shape = ( self.shape[:ellipsis_start] + self.shape[ellipsis_end:] ) for i, side in zip(single_axes, indexed_shape): if isinstance(i, slice): if side == 0: f_range = "0 (or None)" else: f_range = f"between -{side} and {side - 1} (or None)" if i.start is not None: try: start = operator.index(i.start) except TypeError: pass # handled by ndarray else: if not (-side <= start <= side): raise IndexError( f"Slice {i} contains {start=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds starts are not specified in " "the Array API)" ) if i.stop is not None: try: stop = operator.index(i.stop) except TypeError: pass # handled by ndarray else: if not (-side <= stop <= side): raise IndexError( f"Slice {i} contains {stop=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds stops are not specified in " "the Array API)" ) elif isinstance(i, Array): if i.dtype in _boolean_dtypes and len(_key) != 1: assert isinstance(key, tuple) # sanity check raise IndexError( f"Single-axes index {i} is a boolean array and " f"{len(key)=}, but masking is only specified in the " "Array API when the array is the sole index." ) elif i.dtype in _integer_dtypes and i.ndim != 0: raise IndexError( f"Single-axes index {i} is a non-zero-dimensional " "integer array, but advanced integer indexing is not " "specified in the Array API." ) elif isinstance(i, tuple): raise IndexError( f"Single-axes index {i} is a tuple, but nested tuple " "indices are not specified in the Array API." ) # Everything below this line is required by the spec. def __abs__(self: Array, /) -> Array: """ Performs the operation __abs__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __abs__") res = self._array.__abs__() return self.__class__._new(res) def __add__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __add__. """ other = self._check_allowed_dtypes(other, "numeric", "__add__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__add__(other._array) return self.__class__._new(res) def __and__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __and__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__and__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__and__(other._array) return self.__class__._new(res) def __array_namespace__( self: Array, /, *, api_version: Optional[str] = None ) -> types.ModuleType: if api_version is not None and not api_version.startswith("2021."): raise ValueError(f"Unrecognized array API version: {api_version!r}") return array_api def __bool__(self: Array, /) -> bool: """ Performs the operation __bool__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("bool is only allowed on arrays with 0 dimensions") if self.dtype not in _boolean_dtypes: raise ValueError("bool is only allowed on boolean arrays") res = self._array.__bool__() return res def __dlpack__(self: Array, /, *, stream: None = None) -> PyCapsule: """ Performs the operation __dlpack__. """ return self._array.__dlpack__(stream=stream) def __dlpack_device__(self: Array, /) -> Tuple[IntEnum, int]: """ Performs the operation __dlpack_device__. """ # Note: device support is required for this return self._array.__dlpack_device__() def __eq__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __eq__. """ # Even though "all" dtypes are allowed, we still require them to be # promotable with each other. other = self._check_allowed_dtypes(other, "all", "__eq__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__eq__(other._array) return self.__class__._new(res) def __float__(self: Array, /) -> float: """ Performs the operation __float__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("float is only allowed on arrays with 0 dimensions") if self.dtype not in _floating_dtypes: raise ValueError("float is only allowed on floating-point arrays") res = self._array.__float__() return res def __floordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __floordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__floordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__floordiv__(other._array) return self.__class__._new(res) def __ge__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ge__. """ other = self._check_allowed_dtypes(other, "numeric", "__ge__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ge__(other._array) return self.__class__._new(res) def __getitem__( self: Array, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], /, ) -> Array: """ Performs the operation __getitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array res = self._array.__getitem__(key) return self._new(res) def __gt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __gt__. """ other = self._check_allowed_dtypes(other, "numeric", "__gt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__gt__(other._array) return self.__class__._new(res) def __int__(self: Array, /) -> int: """ Performs the operation __int__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("int is only allowed on arrays with 0 dimensions") if self.dtype not in _integer_dtypes: raise ValueError("int is only allowed on integer arrays") res = self._array.__int__() return res def __index__(self: Array, /) -> int: """ Performs the operation __index__. """ res = self._array.__index__() return res def __invert__(self: Array, /) -> Array: """ Performs the operation __invert__. """ if self.dtype not in _integer_or_boolean_dtypes: raise TypeError("Only integer or boolean dtypes are allowed in __invert__") res = self._array.__invert__() return self.__class__._new(res) def __le__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __le__. """ other = self._check_allowed_dtypes(other, "numeric", "__le__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__le__(other._array) return self.__class__._new(res) def __lshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __lshift__. """ other = self._check_allowed_dtypes(other, "integer", "__lshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lshift__(other._array) return self.__class__._new(res) def __lt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __lt__. """ other = self._check_allowed_dtypes(other, "numeric", "__lt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lt__(other._array) return self.__class__._new(res) def __matmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __matmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__matmul__") if other is NotImplemented: return other res = self._array.__matmul__(other._array) return self.__class__._new(res) def __mod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mod__. """ other = self._check_allowed_dtypes(other, "numeric", "__mod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mod__(other._array) return self.__class__._new(res) def __mul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mul__. """ other = self._check_allowed_dtypes(other, "numeric", "__mul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mul__(other._array) return self.__class__._new(res) def __ne__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __ne__. """ other = self._check_allowed_dtypes(other, "all", "__ne__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ne__(other._array) return self.__class__._new(res) def __neg__(self: Array, /) -> Array: """ Performs the operation __neg__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __neg__") res = self._array.__neg__() return self.__class__._new(res) def __or__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __or__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__or__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__or__(other._array) return self.__class__._new(res) def __pos__(self: Array, /) -> Array: """ Performs the operation __pos__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __pos__") res = self._array.__pos__() return self.__class__._new(res) def __pow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __pow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__pow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow type promotion rules for 0-d # arrays, so we use pow() here instead. return pow(self, other) def __rshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rshift__(other._array) return self.__class__._new(res) def __setitem__( self, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], value: Union[int, float, bool, Array], /, ) -> None: """ Performs the operation __setitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array self._array.__setitem__(key, asarray(value)._array) def __sub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __sub__. """ other = self._check_allowed_dtypes(other, "numeric", "__sub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__sub__(other._array) return self.__class__._new(res) # PEP 484 requires int to be a subtype of float, but __truediv__ should # not accept int. def __truediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __truediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__truediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__truediv__(other._array) return self.__class__._new(res) def __xor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __xor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__xor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__xor__(other._array) return self.__class__._new(res) def __iadd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __iadd__. """ other = self._check_allowed_dtypes(other, "numeric", "__iadd__") if other is NotImplemented: return other self._array.__iadd__(other._array) return self def __radd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __radd__. """ other = self._check_allowed_dtypes(other, "numeric", "__radd__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__radd__(other._array) return self.__class__._new(res) def __iand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __iand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__iand__") if other is NotImplemented: return other self._array.__iand__(other._array) return self def __rand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rand__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rand__(other._array) return self.__class__._new(res) def __ifloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ifloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__ifloordiv__") if other is NotImplemented: return other self._array.__ifloordiv__(other._array) return self def __rfloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rfloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__rfloordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rfloordiv__(other._array) return self.__class__._new(res) def __ilshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __ilshift__. """ other = self._check_allowed_dtypes(other, "integer", "__ilshift__") if other is NotImplemented: return other self._array.__ilshift__(other._array) return self def __rlshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rlshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rlshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rlshift__(other._array) return self.__class__._new(res) def __imatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __imatmul__. """ # Note: NumPy does not implement __imatmul__. # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__imatmul__") if other is NotImplemented: return other # __imatmul__ can only be allowed when it would not change the shape # of self. other_shape = other.shape if self.shape == () or other_shape == (): raise ValueError("@= requires at least one dimension") if len(other_shape) == 1 or other_shape[-1] != other_shape[-2]: raise ValueError("@= cannot change the shape of the input array") self._array[:] = self._array.__matmul__(other._array) return self def __rmatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __rmatmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__rmatmul__") if other is NotImplemented: return other res = self._array.__rmatmul__(other._array) return self.__class__._new(res) def __imod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imod__. """ other = self._check_allowed_dtypes(other, "numeric", "__imod__") if other is NotImplemented: return other self._array.__imod__(other._array) return self def __rmod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmod__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmod__(other._array) return self.__class__._new(res) def __imul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imul__. """ other = self._check_allowed_dtypes(other, "numeric", "__imul__") if other is NotImplemented: return other self._array.__imul__(other._array) return self def __rmul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmul__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmul__(other._array) return self.__class__._new(res) def __ior__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ior__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ior__") if other is NotImplemented: return other self._array.__ior__(other._array) return self def __ror__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ror__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ror__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ror__(other._array) return self.__class__._new(res) def __ipow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ipow__. """ other = self._check_allowed_dtypes(other, "numeric", "__ipow__") if other is NotImplemented: return other self._array.__ipow__(other._array) return self def __rpow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rpow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__rpow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow the spec type promotion rules # for 0-d arrays, so we use pow() here instead. return pow(other, self) def __irshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __irshift__. """ other = self._check_allowed_dtypes(other, "integer", "__irshift__") if other is NotImplemented: return other self._array.__irshift__(other._array) return self def __rrshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rrshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rrshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rrshift__(other._array) return self.__class__._new(res) def __isub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __isub__. """ other = self._check_allowed_dtypes(other, "numeric", "__isub__") if other is NotImplemented: return other self._array.__isub__(other._array) return self def __rsub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rsub__. """ other = self._check_allowed_dtypes(other, "numeric", "__rsub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rsub__(other._array) return self.__class__._new(res) def __itruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __itruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__itruediv__") if other is NotImplemented: return other self._array.__itruediv__(other._array) return self def __rtruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __rtruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__rtruediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rtruediv__(other._array) return self.__class__._new(res) def __ixor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ixor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ixor__") if other is NotImplemented: return other self._array.__ixor__(other._array) return self def __rxor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rxor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rxor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rxor__(other._array) return self.__class__._new(res) def to_device(self: Array, device: Device, /, stream: None = None) -> Array: if stream is not None: raise ValueError("The stream argument to to_device() is not supported") if device == 'cpu': return self raise ValueError(f"Unsupported device {device!r}") def dtype(self) -> Dtype: """ Array API compatible wrapper for :py:meth:`np.ndarray.dtype <numpy.ndarray.dtype>`. See its docstring for more information. """ return self._array.dtype def device(self) -> Device: return "cpu" # Note: mT is new in array API spec (see matrix_transpose) def mT(self) -> Array: from .linalg import matrix_transpose return matrix_transpose(self) def ndim(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.ndim <numpy.ndarray.ndim>`. See its docstring for more information. """ return self._array.ndim def shape(self) -> Tuple[int, ...]: """ Array API compatible wrapper for :py:meth:`np.ndarray.shape <numpy.ndarray.shape>`. See its docstring for more information. """ return self._array.shape def size(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.size <numpy.ndarray.size>`. See its docstring for more information. """ return self._array.size def T(self) -> Array: """ Array API compatible wrapper for :py:meth:`np.ndarray.T <numpy.ndarray.T>`. See its docstring for more information. """ # Note: T only works on 2-dimensional arrays. See the corresponding # note in the specification: # https://data-apis.org/array-api/latest/API_specification/array_object.html#t if self.ndim != 2: raise ValueError("x.T requires x to have 2 dimensions. Use x.mT to transpose stacks of matrices and permute_dims() to permute dimensions.") return self.__class__._new(self._array.T) Union: _SpecialForm = ... Optional: _SpecialForm = ... class Tuple(BaseTypingInstance): def _is_homogenous(self): # To specify a variable-length tuple of homogeneous type, Tuple[T, ...] # is used. return self._generics_manager.is_homogenous_tuple() def py__simple_getitem__(self, index): if self._is_homogenous(): return self._generics_manager.get_index_and_execute(0) else: if isinstance(index, int): return self._generics_manager.get_index_and_execute(index) debug.dbg('The getitem type on Tuple was %s' % index) return NO_VALUES def py__iter__(self, contextualized_node=None): if self._is_homogenous(): yield LazyKnownValues(self._generics_manager.get_index_and_execute(0)) else: for v in self._generics_manager.to_tuple(): yield LazyKnownValues(v.execute_annotation()) def py__getitem__(self, index_value_set, contextualized_node): if self._is_homogenous(): return self._generics_manager.get_index_and_execute(0) return ValueSet.from_sets( self._generics_manager.to_tuple() ).execute_annotation() def _get_wrapped_value(self): tuple_, = self.inference_state.builtins_module \ .py__getattribute__('tuple').execute_annotation() return tuple_ def name(self): return self._wrapped_value.name def infer_type_vars(self, value_set): # Circular from jedi.inference.gradual.annotation import merge_pairwise_generics, merge_type_var_dicts value_set = value_set.filter( lambda x: x.py__name__().lower() == 'tuple', ) if self._is_homogenous(): # The parameter annotation is of the form `Tuple[T, ...]`, # so we treat the incoming tuple like a iterable sequence # rather than a positional container of elements. return self._class_value.get_generics()[0].infer_type_vars( value_set.merge_types_of_iterate(), ) else: # The parameter annotation has only explicit type parameters # (e.g: `Tuple[T]`, `Tuple[T, U]`, `Tuple[T, U, V]`, etc.) so we # treat the incoming values as needing to match the annotation # exactly, just as we would for non-tuple annotations. type_var_dict = {} for element in value_set: try: method = element.get_annotated_class_object except AttributeError: # This might still happen, because the tuple name matching # above is not 100% correct, so just catch the remaining # cases here. continue py_class = method() merge_type_var_dicts( type_var_dict, merge_pairwise_generics(self._class_value, py_class), ) return type_var_dict The provided code snippet includes necessary dependencies for implementing the `roll` function. Write a Python function `def roll( x: Array, /, shift: Union[int, Tuple[int, ...]], *, axis: Optional[Union[int, Tuple[int, ...]]] = None, ) -> Array` to solve the following problem: Array API compatible wrapper for :py:func:`np.roll <numpy.roll>`. See its docstring for more information. Here is the function: def roll( x: Array, /, shift: Union[int, Tuple[int, ...]], *, axis: Optional[Union[int, Tuple[int, ...]]] = None, ) -> Array: """ Array API compatible wrapper for :py:func:`np.roll <numpy.roll>`. See its docstring for more information. """ return Array._new(np.roll(x._array, shift, axis=axis))
Array API compatible wrapper for :py:func:`np.roll <numpy.roll>`. See its docstring for more information.
170,084
from __future__ import annotations from ._array_object import Array from ._data_type_functions import result_type from typing import List, Optional, Tuple, Union import numpy as np class Array: """ n-d array object for the array API namespace. See the docstring of :py:obj:`np.ndarray <numpy.ndarray>` for more information. This is a wrapper around numpy.ndarray that restricts the usage to only those things that are required by the array API namespace. Note, attributes on this object that start with a single underscore are not part of the API specification and should only be used internally. This object should not be constructed directly. Rather, use one of the creation functions, such as asarray(). """ _array: np.ndarray # Use a custom constructor instead of __init__, as manually initializing # this class is not supported API. def _new(cls, x, /): """ This is a private method for initializing the array API Array object. Functions outside of the array_api submodule should not use this method. Use one of the creation functions instead, such as ``asarray``. """ obj = super().__new__(cls) # Note: The spec does not have array scalars, only 0-D arrays. if isinstance(x, np.generic): # Convert the array scalar to a 0-D array x = np.asarray(x) if x.dtype not in _all_dtypes: raise TypeError( f"The array_api namespace does not support the dtype '{x.dtype}'" ) obj._array = x return obj # Prevent Array() from working def __new__(cls, *args, **kwargs): raise TypeError( "The array_api Array object should not be instantiated directly. Use an array creation function, such as asarray(), instead." ) # These functions are not required by the spec, but are implemented for # the sake of usability. def __str__(self: Array, /) -> str: """ Performs the operation __str__. """ return self._array.__str__().replace("array", "Array") def __repr__(self: Array, /) -> str: """ Performs the operation __repr__. """ suffix = f", dtype={self.dtype.name})" if 0 in self.shape: prefix = "empty(" mid = str(self.shape) else: prefix = "Array(" mid = np.array2string(self._array, separator=', ', prefix=prefix, suffix=suffix) return prefix + mid + suffix # This function is not required by the spec, but we implement it here for # convenience so that np.asarray(np.array_api.Array) will work. def __array__(self, dtype: None | np.dtype[Any] = None) -> npt.NDArray[Any]: """ Warning: this method is NOT part of the array API spec. Implementers of other libraries need not include it, and users should not assume it will be present in other implementations. """ return np.asarray(self._array, dtype=dtype) # These are various helper functions to make the array behavior match the # spec in places where it either deviates from or is more strict than # NumPy behavior def _check_allowed_dtypes(self, other: bool | int | float | Array, dtype_category: str, op: str) -> Array: """ Helper function for operators to only allow specific input dtypes Use like other = self._check_allowed_dtypes(other, 'numeric', '__add__') if other is NotImplemented: return other """ if self.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") if isinstance(other, (int, float, bool)): other = self._promote_scalar(other) elif isinstance(other, Array): if other.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") else: return NotImplemented # This will raise TypeError for type combinations that are not allowed # to promote in the spec (even if the NumPy array operator would # promote them). res_dtype = _result_type(self.dtype, other.dtype) if op.startswith("__i"): # Note: NumPy will allow in-place operators in some cases where # the type promoted operator does not match the left-hand side # operand. For example, # >>> a = np.array(1, dtype=np.int8) # >>> a += np.array(1, dtype=np.int16) # The spec explicitly disallows this. if res_dtype != self.dtype: raise TypeError( f"Cannot perform {op} with dtypes {self.dtype} and {other.dtype}" ) return other # Helper function to match the type promotion rules in the spec def _promote_scalar(self, scalar): """ Returns a promoted version of a Python scalar appropriate for use with operations on self. This may raise an OverflowError in cases where the scalar is an integer that is too large to fit in a NumPy integer dtype, or TypeError when the scalar type is incompatible with the dtype of self. """ # Note: Only Python scalar types that match the array dtype are # allowed. if isinstance(scalar, bool): if self.dtype not in _boolean_dtypes: raise TypeError( "Python bool scalars can only be promoted with bool arrays" ) elif isinstance(scalar, int): if self.dtype in _boolean_dtypes: raise TypeError( "Python int scalars cannot be promoted with bool arrays" ) elif isinstance(scalar, float): if self.dtype not in _floating_dtypes: raise TypeError( "Python float scalars can only be promoted with floating-point arrays." ) else: raise TypeError("'scalar' must be a Python scalar") # Note: scalars are unconditionally cast to the same dtype as the # array. # Note: the spec only specifies integer-dtype/int promotion # behavior for integers within the bounds of the integer dtype. # Outside of those bounds we use the default NumPy behavior (either # cast or raise OverflowError). return Array._new(np.array(scalar, self.dtype)) def _normalize_two_args(x1, x2) -> Tuple[Array, Array]: """ Normalize inputs to two arg functions to fix type promotion rules NumPy deviates from the spec type promotion rules in cases where one argument is 0-dimensional and the other is not. For example: >>> import numpy as np >>> a = np.array([1.0], dtype=np.float32) >>> b = np.array(1.0, dtype=np.float64) >>> np.add(a, b) # The spec says this should be float64 array([2.], dtype=float32) To fix this, we add a dimension to the 0-dimension array before passing it through. This works because a dimension would be added anyway from broadcasting, so the resulting shape is the same, but this prevents NumPy from not promoting the dtype. """ # Another option would be to use signature=(x1.dtype, x2.dtype, None), # but that only works for ufuncs, so we would have to call the ufuncs # directly in the operator methods. One should also note that this # sort of trick wouldn't work for functions like searchsorted, which # don't do normal broadcasting, but there aren't any functions like # that in the array API namespace. if x1.ndim == 0 and x2.ndim != 0: # The _array[None] workaround was chosen because it is relatively # performant. broadcast_to(x1._array, x2.shape) is much slower. We # could also manually type promote x2, but that is more complicated # and about the same performance as this. x1 = Array._new(x1._array[None]) elif x2.ndim == 0 and x1.ndim != 0: x2 = Array._new(x2._array[None]) return (x1, x2) # Note: A large fraction of allowed indices are disallowed here (see the # docstring below) def _validate_index(self, key): """ Validate an index according to the array API. The array API specification only requires a subset of indices that are supported by NumPy. This function will reject any index that is allowed by NumPy but not required by the array API specification. We always raise ``IndexError`` on such indices (the spec does not require any specific behavior on them, but this makes the NumPy array API namespace a minimal implementation of the spec). See https://data-apis.org/array-api/latest/API_specification/indexing.html for the full list of required indexing behavior This function raises IndexError if the index ``key`` is invalid. It only raises ``IndexError`` on indices that are not already rejected by NumPy, as NumPy will already raise the appropriate error on such indices. ``shape`` may be None, in which case, only cases that are independent of the array shape are checked. The following cases are allowed by NumPy, but not specified by the array API specification: - Indices to not include an implicit ellipsis at the end. That is, every axis of an array must be explicitly indexed or an ellipsis included. This behaviour is sometimes referred to as flat indexing. - The start and stop of a slice may not be out of bounds. In particular, for a slice ``i:j:k`` on an axis of size ``n``, only the following are allowed: - ``i`` or ``j`` omitted (``None``). - ``-n <= i <= max(0, n - 1)``. - For ``k > 0`` or ``k`` omitted (``None``), ``-n <= j <= n``. - For ``k < 0``, ``-n - 1 <= j <= max(0, n - 1)``. - Boolean array indices are not allowed as part of a larger tuple index. - Integer array indices are not allowed (with the exception of 0-D arrays, which are treated the same as scalars). Additionally, it should be noted that indices that would return a scalar in NumPy will return a 0-D array. Array scalars are not allowed in the specification, only 0-D arrays. This is done in the ``Array._new`` constructor, not this function. """ _key = key if isinstance(key, tuple) else (key,) for i in _key: if isinstance(i, bool) or not ( isinstance(i, SupportsIndex) # i.e. ints or isinstance(i, slice) or i == Ellipsis or i is None or isinstance(i, Array) or isinstance(i, np.ndarray) ): raise IndexError( f"Single-axes index {i} has {type(i)=}, but only " "integers, slices (:), ellipsis (...), newaxis (None), " "zero-dimensional integer arrays and boolean arrays " "are specified in the Array API." ) nonexpanding_key = [] single_axes = [] n_ellipsis = 0 key_has_mask = False for i in _key: if i is not None: nonexpanding_key.append(i) if isinstance(i, Array) or isinstance(i, np.ndarray): if i.dtype in _boolean_dtypes: key_has_mask = True single_axes.append(i) else: # i must not be an array here, to avoid elementwise equals if i == Ellipsis: n_ellipsis += 1 else: single_axes.append(i) n_single_axes = len(single_axes) if n_ellipsis > 1: return # handled by ndarray elif n_ellipsis == 0: # Note boolean masks must be the sole index, which we check for # later on. if not key_has_mask and n_single_axes < self.ndim: raise IndexError( f"{self.ndim=}, but the multi-axes index only specifies " f"{n_single_axes} dimensions. If this was intentional, " "add a trailing ellipsis (...) which expands into as many " "slices (:) as necessary - this is what np.ndarray arrays " "implicitly do, but such flat indexing behaviour is not " "specified in the Array API." ) if n_ellipsis == 0: indexed_shape = self.shape else: ellipsis_start = None for pos, i in enumerate(nonexpanding_key): if not (isinstance(i, Array) or isinstance(i, np.ndarray)): if i == Ellipsis: ellipsis_start = pos break assert ellipsis_start is not None # sanity check ellipsis_end = self.ndim - (n_single_axes - ellipsis_start) indexed_shape = ( self.shape[:ellipsis_start] + self.shape[ellipsis_end:] ) for i, side in zip(single_axes, indexed_shape): if isinstance(i, slice): if side == 0: f_range = "0 (or None)" else: f_range = f"between -{side} and {side - 1} (or None)" if i.start is not None: try: start = operator.index(i.start) except TypeError: pass # handled by ndarray else: if not (-side <= start <= side): raise IndexError( f"Slice {i} contains {start=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds starts are not specified in " "the Array API)" ) if i.stop is not None: try: stop = operator.index(i.stop) except TypeError: pass # handled by ndarray else: if not (-side <= stop <= side): raise IndexError( f"Slice {i} contains {stop=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds stops are not specified in " "the Array API)" ) elif isinstance(i, Array): if i.dtype in _boolean_dtypes and len(_key) != 1: assert isinstance(key, tuple) # sanity check raise IndexError( f"Single-axes index {i} is a boolean array and " f"{len(key)=}, but masking is only specified in the " "Array API when the array is the sole index." ) elif i.dtype in _integer_dtypes and i.ndim != 0: raise IndexError( f"Single-axes index {i} is a non-zero-dimensional " "integer array, but advanced integer indexing is not " "specified in the Array API." ) elif isinstance(i, tuple): raise IndexError( f"Single-axes index {i} is a tuple, but nested tuple " "indices are not specified in the Array API." ) # Everything below this line is required by the spec. def __abs__(self: Array, /) -> Array: """ Performs the operation __abs__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __abs__") res = self._array.__abs__() return self.__class__._new(res) def __add__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __add__. """ other = self._check_allowed_dtypes(other, "numeric", "__add__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__add__(other._array) return self.__class__._new(res) def __and__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __and__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__and__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__and__(other._array) return self.__class__._new(res) def __array_namespace__( self: Array, /, *, api_version: Optional[str] = None ) -> types.ModuleType: if api_version is not None and not api_version.startswith("2021."): raise ValueError(f"Unrecognized array API version: {api_version!r}") return array_api def __bool__(self: Array, /) -> bool: """ Performs the operation __bool__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("bool is only allowed on arrays with 0 dimensions") if self.dtype not in _boolean_dtypes: raise ValueError("bool is only allowed on boolean arrays") res = self._array.__bool__() return res def __dlpack__(self: Array, /, *, stream: None = None) -> PyCapsule: """ Performs the operation __dlpack__. """ return self._array.__dlpack__(stream=stream) def __dlpack_device__(self: Array, /) -> Tuple[IntEnum, int]: """ Performs the operation __dlpack_device__. """ # Note: device support is required for this return self._array.__dlpack_device__() def __eq__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __eq__. """ # Even though "all" dtypes are allowed, we still require them to be # promotable with each other. other = self._check_allowed_dtypes(other, "all", "__eq__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__eq__(other._array) return self.__class__._new(res) def __float__(self: Array, /) -> float: """ Performs the operation __float__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("float is only allowed on arrays with 0 dimensions") if self.dtype not in _floating_dtypes: raise ValueError("float is only allowed on floating-point arrays") res = self._array.__float__() return res def __floordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __floordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__floordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__floordiv__(other._array) return self.__class__._new(res) def __ge__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ge__. """ other = self._check_allowed_dtypes(other, "numeric", "__ge__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ge__(other._array) return self.__class__._new(res) def __getitem__( self: Array, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], /, ) -> Array: """ Performs the operation __getitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array res = self._array.__getitem__(key) return self._new(res) def __gt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __gt__. """ other = self._check_allowed_dtypes(other, "numeric", "__gt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__gt__(other._array) return self.__class__._new(res) def __int__(self: Array, /) -> int: """ Performs the operation __int__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("int is only allowed on arrays with 0 dimensions") if self.dtype not in _integer_dtypes: raise ValueError("int is only allowed on integer arrays") res = self._array.__int__() return res def __index__(self: Array, /) -> int: """ Performs the operation __index__. """ res = self._array.__index__() return res def __invert__(self: Array, /) -> Array: """ Performs the operation __invert__. """ if self.dtype not in _integer_or_boolean_dtypes: raise TypeError("Only integer or boolean dtypes are allowed in __invert__") res = self._array.__invert__() return self.__class__._new(res) def __le__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __le__. """ other = self._check_allowed_dtypes(other, "numeric", "__le__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__le__(other._array) return self.__class__._new(res) def __lshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __lshift__. """ other = self._check_allowed_dtypes(other, "integer", "__lshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lshift__(other._array) return self.__class__._new(res) def __lt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __lt__. """ other = self._check_allowed_dtypes(other, "numeric", "__lt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lt__(other._array) return self.__class__._new(res) def __matmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __matmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__matmul__") if other is NotImplemented: return other res = self._array.__matmul__(other._array) return self.__class__._new(res) def __mod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mod__. """ other = self._check_allowed_dtypes(other, "numeric", "__mod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mod__(other._array) return self.__class__._new(res) def __mul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mul__. """ other = self._check_allowed_dtypes(other, "numeric", "__mul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mul__(other._array) return self.__class__._new(res) def __ne__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __ne__. """ other = self._check_allowed_dtypes(other, "all", "__ne__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ne__(other._array) return self.__class__._new(res) def __neg__(self: Array, /) -> Array: """ Performs the operation __neg__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __neg__") res = self._array.__neg__() return self.__class__._new(res) def __or__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __or__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__or__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__or__(other._array) return self.__class__._new(res) def __pos__(self: Array, /) -> Array: """ Performs the operation __pos__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __pos__") res = self._array.__pos__() return self.__class__._new(res) def __pow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __pow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__pow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow type promotion rules for 0-d # arrays, so we use pow() here instead. return pow(self, other) def __rshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rshift__(other._array) return self.__class__._new(res) def __setitem__( self, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], value: Union[int, float, bool, Array], /, ) -> None: """ Performs the operation __setitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array self._array.__setitem__(key, asarray(value)._array) def __sub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __sub__. """ other = self._check_allowed_dtypes(other, "numeric", "__sub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__sub__(other._array) return self.__class__._new(res) # PEP 484 requires int to be a subtype of float, but __truediv__ should # not accept int. def __truediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __truediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__truediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__truediv__(other._array) return self.__class__._new(res) def __xor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __xor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__xor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__xor__(other._array) return self.__class__._new(res) def __iadd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __iadd__. """ other = self._check_allowed_dtypes(other, "numeric", "__iadd__") if other is NotImplemented: return other self._array.__iadd__(other._array) return self def __radd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __radd__. """ other = self._check_allowed_dtypes(other, "numeric", "__radd__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__radd__(other._array) return self.__class__._new(res) def __iand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __iand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__iand__") if other is NotImplemented: return other self._array.__iand__(other._array) return self def __rand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rand__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rand__(other._array) return self.__class__._new(res) def __ifloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ifloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__ifloordiv__") if other is NotImplemented: return other self._array.__ifloordiv__(other._array) return self def __rfloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rfloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__rfloordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rfloordiv__(other._array) return self.__class__._new(res) def __ilshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __ilshift__. """ other = self._check_allowed_dtypes(other, "integer", "__ilshift__") if other is NotImplemented: return other self._array.__ilshift__(other._array) return self def __rlshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rlshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rlshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rlshift__(other._array) return self.__class__._new(res) def __imatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __imatmul__. """ # Note: NumPy does not implement __imatmul__. # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__imatmul__") if other is NotImplemented: return other # __imatmul__ can only be allowed when it would not change the shape # of self. other_shape = other.shape if self.shape == () or other_shape == (): raise ValueError("@= requires at least one dimension") if len(other_shape) == 1 or other_shape[-1] != other_shape[-2]: raise ValueError("@= cannot change the shape of the input array") self._array[:] = self._array.__matmul__(other._array) return self def __rmatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __rmatmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__rmatmul__") if other is NotImplemented: return other res = self._array.__rmatmul__(other._array) return self.__class__._new(res) def __imod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imod__. """ other = self._check_allowed_dtypes(other, "numeric", "__imod__") if other is NotImplemented: return other self._array.__imod__(other._array) return self def __rmod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmod__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmod__(other._array) return self.__class__._new(res) def __imul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imul__. """ other = self._check_allowed_dtypes(other, "numeric", "__imul__") if other is NotImplemented: return other self._array.__imul__(other._array) return self def __rmul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmul__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmul__(other._array) return self.__class__._new(res) def __ior__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ior__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ior__") if other is NotImplemented: return other self._array.__ior__(other._array) return self def __ror__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ror__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ror__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ror__(other._array) return self.__class__._new(res) def __ipow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ipow__. """ other = self._check_allowed_dtypes(other, "numeric", "__ipow__") if other is NotImplemented: return other self._array.__ipow__(other._array) return self def __rpow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rpow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__rpow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow the spec type promotion rules # for 0-d arrays, so we use pow() here instead. return pow(other, self) def __irshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __irshift__. """ other = self._check_allowed_dtypes(other, "integer", "__irshift__") if other is NotImplemented: return other self._array.__irshift__(other._array) return self def __rrshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rrshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rrshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rrshift__(other._array) return self.__class__._new(res) def __isub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __isub__. """ other = self._check_allowed_dtypes(other, "numeric", "__isub__") if other is NotImplemented: return other self._array.__isub__(other._array) return self def __rsub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rsub__. """ other = self._check_allowed_dtypes(other, "numeric", "__rsub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rsub__(other._array) return self.__class__._new(res) def __itruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __itruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__itruediv__") if other is NotImplemented: return other self._array.__itruediv__(other._array) return self def __rtruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __rtruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__rtruediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rtruediv__(other._array) return self.__class__._new(res) def __ixor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ixor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ixor__") if other is NotImplemented: return other self._array.__ixor__(other._array) return self def __rxor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rxor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rxor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rxor__(other._array) return self.__class__._new(res) def to_device(self: Array, device: Device, /, stream: None = None) -> Array: if stream is not None: raise ValueError("The stream argument to to_device() is not supported") if device == 'cpu': return self raise ValueError(f"Unsupported device {device!r}") def dtype(self) -> Dtype: """ Array API compatible wrapper for :py:meth:`np.ndarray.dtype <numpy.ndarray.dtype>`. See its docstring for more information. """ return self._array.dtype def device(self) -> Device: return "cpu" # Note: mT is new in array API spec (see matrix_transpose) def mT(self) -> Array: from .linalg import matrix_transpose return matrix_transpose(self) def ndim(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.ndim <numpy.ndarray.ndim>`. See its docstring for more information. """ return self._array.ndim def shape(self) -> Tuple[int, ...]: """ Array API compatible wrapper for :py:meth:`np.ndarray.shape <numpy.ndarray.shape>`. See its docstring for more information. """ return self._array.shape def size(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.size <numpy.ndarray.size>`. See its docstring for more information. """ return self._array.size def T(self) -> Array: """ Array API compatible wrapper for :py:meth:`np.ndarray.T <numpy.ndarray.T>`. See its docstring for more information. """ # Note: T only works on 2-dimensional arrays. See the corresponding # note in the specification: # https://data-apis.org/array-api/latest/API_specification/array_object.html#t if self.ndim != 2: raise ValueError("x.T requires x to have 2 dimensions. Use x.mT to transpose stacks of matrices and permute_dims() to permute dimensions.") return self.__class__._new(self._array.T) class Tuple(BaseTypingInstance): def _is_homogenous(self): # To specify a variable-length tuple of homogeneous type, Tuple[T, ...] # is used. return self._generics_manager.is_homogenous_tuple() def py__simple_getitem__(self, index): if self._is_homogenous(): return self._generics_manager.get_index_and_execute(0) else: if isinstance(index, int): return self._generics_manager.get_index_and_execute(index) debug.dbg('The getitem type on Tuple was %s' % index) return NO_VALUES def py__iter__(self, contextualized_node=None): if self._is_homogenous(): yield LazyKnownValues(self._generics_manager.get_index_and_execute(0)) else: for v in self._generics_manager.to_tuple(): yield LazyKnownValues(v.execute_annotation()) def py__getitem__(self, index_value_set, contextualized_node): if self._is_homogenous(): return self._generics_manager.get_index_and_execute(0) return ValueSet.from_sets( self._generics_manager.to_tuple() ).execute_annotation() def _get_wrapped_value(self): tuple_, = self.inference_state.builtins_module \ .py__getattribute__('tuple').execute_annotation() return tuple_ def name(self): return self._wrapped_value.name def infer_type_vars(self, value_set): # Circular from jedi.inference.gradual.annotation import merge_pairwise_generics, merge_type_var_dicts value_set = value_set.filter( lambda x: x.py__name__().lower() == 'tuple', ) if self._is_homogenous(): # The parameter annotation is of the form `Tuple[T, ...]`, # so we treat the incoming tuple like a iterable sequence # rather than a positional container of elements. return self._class_value.get_generics()[0].infer_type_vars( value_set.merge_types_of_iterate(), ) else: # The parameter annotation has only explicit type parameters # (e.g: `Tuple[T]`, `Tuple[T, U]`, `Tuple[T, U, V]`, etc.) so we # treat the incoming values as needing to match the annotation # exactly, just as we would for non-tuple annotations. type_var_dict = {} for element in value_set: try: method = element.get_annotated_class_object except AttributeError: # This might still happen, because the tuple name matching # above is not 100% correct, so just catch the remaining # cases here. continue py_class = method() merge_type_var_dicts( type_var_dict, merge_pairwise_generics(self._class_value, py_class), ) return type_var_dict Union: _SpecialForm = ... The provided code snippet includes necessary dependencies for implementing the `squeeze` function. Write a Python function `def squeeze(x: Array, /, axis: Union[int, Tuple[int, ...]]) -> Array` to solve the following problem: Array API compatible wrapper for :py:func:`np.squeeze <numpy.squeeze>`. See its docstring for more information. Here is the function: def squeeze(x: Array, /, axis: Union[int, Tuple[int, ...]]) -> Array: """ Array API compatible wrapper for :py:func:`np.squeeze <numpy.squeeze>`. See its docstring for more information. """ return Array._new(np.squeeze(x._array, axis=axis))
Array API compatible wrapper for :py:func:`np.squeeze <numpy.squeeze>`. See its docstring for more information.
170,085
from __future__ import annotations from ._array_object import Array from ._data_type_functions import result_type from typing import List, Optional, Tuple, Union import numpy as np class Array: """ n-d array object for the array API namespace. See the docstring of :py:obj:`np.ndarray <numpy.ndarray>` for more information. This is a wrapper around numpy.ndarray that restricts the usage to only those things that are required by the array API namespace. Note, attributes on this object that start with a single underscore are not part of the API specification and should only be used internally. This object should not be constructed directly. Rather, use one of the creation functions, such as asarray(). """ _array: np.ndarray # Use a custom constructor instead of __init__, as manually initializing # this class is not supported API. def _new(cls, x, /): """ This is a private method for initializing the array API Array object. Functions outside of the array_api submodule should not use this method. Use one of the creation functions instead, such as ``asarray``. """ obj = super().__new__(cls) # Note: The spec does not have array scalars, only 0-D arrays. if isinstance(x, np.generic): # Convert the array scalar to a 0-D array x = np.asarray(x) if x.dtype not in _all_dtypes: raise TypeError( f"The array_api namespace does not support the dtype '{x.dtype}'" ) obj._array = x return obj # Prevent Array() from working def __new__(cls, *args, **kwargs): raise TypeError( "The array_api Array object should not be instantiated directly. Use an array creation function, such as asarray(), instead." ) # These functions are not required by the spec, but are implemented for # the sake of usability. def __str__(self: Array, /) -> str: """ Performs the operation __str__. """ return self._array.__str__().replace("array", "Array") def __repr__(self: Array, /) -> str: """ Performs the operation __repr__. """ suffix = f", dtype={self.dtype.name})" if 0 in self.shape: prefix = "empty(" mid = str(self.shape) else: prefix = "Array(" mid = np.array2string(self._array, separator=', ', prefix=prefix, suffix=suffix) return prefix + mid + suffix # This function is not required by the spec, but we implement it here for # convenience so that np.asarray(np.array_api.Array) will work. def __array__(self, dtype: None | np.dtype[Any] = None) -> npt.NDArray[Any]: """ Warning: this method is NOT part of the array API spec. Implementers of other libraries need not include it, and users should not assume it will be present in other implementations. """ return np.asarray(self._array, dtype=dtype) # These are various helper functions to make the array behavior match the # spec in places where it either deviates from or is more strict than # NumPy behavior def _check_allowed_dtypes(self, other: bool | int | float | Array, dtype_category: str, op: str) -> Array: """ Helper function for operators to only allow specific input dtypes Use like other = self._check_allowed_dtypes(other, 'numeric', '__add__') if other is NotImplemented: return other """ if self.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") if isinstance(other, (int, float, bool)): other = self._promote_scalar(other) elif isinstance(other, Array): if other.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") else: return NotImplemented # This will raise TypeError for type combinations that are not allowed # to promote in the spec (even if the NumPy array operator would # promote them). res_dtype = _result_type(self.dtype, other.dtype) if op.startswith("__i"): # Note: NumPy will allow in-place operators in some cases where # the type promoted operator does not match the left-hand side # operand. For example, # >>> a = np.array(1, dtype=np.int8) # >>> a += np.array(1, dtype=np.int16) # The spec explicitly disallows this. if res_dtype != self.dtype: raise TypeError( f"Cannot perform {op} with dtypes {self.dtype} and {other.dtype}" ) return other # Helper function to match the type promotion rules in the spec def _promote_scalar(self, scalar): """ Returns a promoted version of a Python scalar appropriate for use with operations on self. This may raise an OverflowError in cases where the scalar is an integer that is too large to fit in a NumPy integer dtype, or TypeError when the scalar type is incompatible with the dtype of self. """ # Note: Only Python scalar types that match the array dtype are # allowed. if isinstance(scalar, bool): if self.dtype not in _boolean_dtypes: raise TypeError( "Python bool scalars can only be promoted with bool arrays" ) elif isinstance(scalar, int): if self.dtype in _boolean_dtypes: raise TypeError( "Python int scalars cannot be promoted with bool arrays" ) elif isinstance(scalar, float): if self.dtype not in _floating_dtypes: raise TypeError( "Python float scalars can only be promoted with floating-point arrays." ) else: raise TypeError("'scalar' must be a Python scalar") # Note: scalars are unconditionally cast to the same dtype as the # array. # Note: the spec only specifies integer-dtype/int promotion # behavior for integers within the bounds of the integer dtype. # Outside of those bounds we use the default NumPy behavior (either # cast or raise OverflowError). return Array._new(np.array(scalar, self.dtype)) def _normalize_two_args(x1, x2) -> Tuple[Array, Array]: """ Normalize inputs to two arg functions to fix type promotion rules NumPy deviates from the spec type promotion rules in cases where one argument is 0-dimensional and the other is not. For example: >>> import numpy as np >>> a = np.array([1.0], dtype=np.float32) >>> b = np.array(1.0, dtype=np.float64) >>> np.add(a, b) # The spec says this should be float64 array([2.], dtype=float32) To fix this, we add a dimension to the 0-dimension array before passing it through. This works because a dimension would be added anyway from broadcasting, so the resulting shape is the same, but this prevents NumPy from not promoting the dtype. """ # Another option would be to use signature=(x1.dtype, x2.dtype, None), # but that only works for ufuncs, so we would have to call the ufuncs # directly in the operator methods. One should also note that this # sort of trick wouldn't work for functions like searchsorted, which # don't do normal broadcasting, but there aren't any functions like # that in the array API namespace. if x1.ndim == 0 and x2.ndim != 0: # The _array[None] workaround was chosen because it is relatively # performant. broadcast_to(x1._array, x2.shape) is much slower. We # could also manually type promote x2, but that is more complicated # and about the same performance as this. x1 = Array._new(x1._array[None]) elif x2.ndim == 0 and x1.ndim != 0: x2 = Array._new(x2._array[None]) return (x1, x2) # Note: A large fraction of allowed indices are disallowed here (see the # docstring below) def _validate_index(self, key): """ Validate an index according to the array API. The array API specification only requires a subset of indices that are supported by NumPy. This function will reject any index that is allowed by NumPy but not required by the array API specification. We always raise ``IndexError`` on such indices (the spec does not require any specific behavior on them, but this makes the NumPy array API namespace a minimal implementation of the spec). See https://data-apis.org/array-api/latest/API_specification/indexing.html for the full list of required indexing behavior This function raises IndexError if the index ``key`` is invalid. It only raises ``IndexError`` on indices that are not already rejected by NumPy, as NumPy will already raise the appropriate error on such indices. ``shape`` may be None, in which case, only cases that are independent of the array shape are checked. The following cases are allowed by NumPy, but not specified by the array API specification: - Indices to not include an implicit ellipsis at the end. That is, every axis of an array must be explicitly indexed or an ellipsis included. This behaviour is sometimes referred to as flat indexing. - The start and stop of a slice may not be out of bounds. In particular, for a slice ``i:j:k`` on an axis of size ``n``, only the following are allowed: - ``i`` or ``j`` omitted (``None``). - ``-n <= i <= max(0, n - 1)``. - For ``k > 0`` or ``k`` omitted (``None``), ``-n <= j <= n``. - For ``k < 0``, ``-n - 1 <= j <= max(0, n - 1)``. - Boolean array indices are not allowed as part of a larger tuple index. - Integer array indices are not allowed (with the exception of 0-D arrays, which are treated the same as scalars). Additionally, it should be noted that indices that would return a scalar in NumPy will return a 0-D array. Array scalars are not allowed in the specification, only 0-D arrays. This is done in the ``Array._new`` constructor, not this function. """ _key = key if isinstance(key, tuple) else (key,) for i in _key: if isinstance(i, bool) or not ( isinstance(i, SupportsIndex) # i.e. ints or isinstance(i, slice) or i == Ellipsis or i is None or isinstance(i, Array) or isinstance(i, np.ndarray) ): raise IndexError( f"Single-axes index {i} has {type(i)=}, but only " "integers, slices (:), ellipsis (...), newaxis (None), " "zero-dimensional integer arrays and boolean arrays " "are specified in the Array API." ) nonexpanding_key = [] single_axes = [] n_ellipsis = 0 key_has_mask = False for i in _key: if i is not None: nonexpanding_key.append(i) if isinstance(i, Array) or isinstance(i, np.ndarray): if i.dtype in _boolean_dtypes: key_has_mask = True single_axes.append(i) else: # i must not be an array here, to avoid elementwise equals if i == Ellipsis: n_ellipsis += 1 else: single_axes.append(i) n_single_axes = len(single_axes) if n_ellipsis > 1: return # handled by ndarray elif n_ellipsis == 0: # Note boolean masks must be the sole index, which we check for # later on. if not key_has_mask and n_single_axes < self.ndim: raise IndexError( f"{self.ndim=}, but the multi-axes index only specifies " f"{n_single_axes} dimensions. If this was intentional, " "add a trailing ellipsis (...) which expands into as many " "slices (:) as necessary - this is what np.ndarray arrays " "implicitly do, but such flat indexing behaviour is not " "specified in the Array API." ) if n_ellipsis == 0: indexed_shape = self.shape else: ellipsis_start = None for pos, i in enumerate(nonexpanding_key): if not (isinstance(i, Array) or isinstance(i, np.ndarray)): if i == Ellipsis: ellipsis_start = pos break assert ellipsis_start is not None # sanity check ellipsis_end = self.ndim - (n_single_axes - ellipsis_start) indexed_shape = ( self.shape[:ellipsis_start] + self.shape[ellipsis_end:] ) for i, side in zip(single_axes, indexed_shape): if isinstance(i, slice): if side == 0: f_range = "0 (or None)" else: f_range = f"between -{side} and {side - 1} (or None)" if i.start is not None: try: start = operator.index(i.start) except TypeError: pass # handled by ndarray else: if not (-side <= start <= side): raise IndexError( f"Slice {i} contains {start=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds starts are not specified in " "the Array API)" ) if i.stop is not None: try: stop = operator.index(i.stop) except TypeError: pass # handled by ndarray else: if not (-side <= stop <= side): raise IndexError( f"Slice {i} contains {stop=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds stops are not specified in " "the Array API)" ) elif isinstance(i, Array): if i.dtype in _boolean_dtypes and len(_key) != 1: assert isinstance(key, tuple) # sanity check raise IndexError( f"Single-axes index {i} is a boolean array and " f"{len(key)=}, but masking is only specified in the " "Array API when the array is the sole index." ) elif i.dtype in _integer_dtypes and i.ndim != 0: raise IndexError( f"Single-axes index {i} is a non-zero-dimensional " "integer array, but advanced integer indexing is not " "specified in the Array API." ) elif isinstance(i, tuple): raise IndexError( f"Single-axes index {i} is a tuple, but nested tuple " "indices are not specified in the Array API." ) # Everything below this line is required by the spec. def __abs__(self: Array, /) -> Array: """ Performs the operation __abs__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __abs__") res = self._array.__abs__() return self.__class__._new(res) def __add__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __add__. """ other = self._check_allowed_dtypes(other, "numeric", "__add__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__add__(other._array) return self.__class__._new(res) def __and__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __and__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__and__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__and__(other._array) return self.__class__._new(res) def __array_namespace__( self: Array, /, *, api_version: Optional[str] = None ) -> types.ModuleType: if api_version is not None and not api_version.startswith("2021."): raise ValueError(f"Unrecognized array API version: {api_version!r}") return array_api def __bool__(self: Array, /) -> bool: """ Performs the operation __bool__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("bool is only allowed on arrays with 0 dimensions") if self.dtype not in _boolean_dtypes: raise ValueError("bool is only allowed on boolean arrays") res = self._array.__bool__() return res def __dlpack__(self: Array, /, *, stream: None = None) -> PyCapsule: """ Performs the operation __dlpack__. """ return self._array.__dlpack__(stream=stream) def __dlpack_device__(self: Array, /) -> Tuple[IntEnum, int]: """ Performs the operation __dlpack_device__. """ # Note: device support is required for this return self._array.__dlpack_device__() def __eq__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __eq__. """ # Even though "all" dtypes are allowed, we still require them to be # promotable with each other. other = self._check_allowed_dtypes(other, "all", "__eq__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__eq__(other._array) return self.__class__._new(res) def __float__(self: Array, /) -> float: """ Performs the operation __float__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("float is only allowed on arrays with 0 dimensions") if self.dtype not in _floating_dtypes: raise ValueError("float is only allowed on floating-point arrays") res = self._array.__float__() return res def __floordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __floordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__floordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__floordiv__(other._array) return self.__class__._new(res) def __ge__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ge__. """ other = self._check_allowed_dtypes(other, "numeric", "__ge__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ge__(other._array) return self.__class__._new(res) def __getitem__( self: Array, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], /, ) -> Array: """ Performs the operation __getitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array res = self._array.__getitem__(key) return self._new(res) def __gt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __gt__. """ other = self._check_allowed_dtypes(other, "numeric", "__gt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__gt__(other._array) return self.__class__._new(res) def __int__(self: Array, /) -> int: """ Performs the operation __int__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("int is only allowed on arrays with 0 dimensions") if self.dtype not in _integer_dtypes: raise ValueError("int is only allowed on integer arrays") res = self._array.__int__() return res def __index__(self: Array, /) -> int: """ Performs the operation __index__. """ res = self._array.__index__() return res def __invert__(self: Array, /) -> Array: """ Performs the operation __invert__. """ if self.dtype not in _integer_or_boolean_dtypes: raise TypeError("Only integer or boolean dtypes are allowed in __invert__") res = self._array.__invert__() return self.__class__._new(res) def __le__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __le__. """ other = self._check_allowed_dtypes(other, "numeric", "__le__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__le__(other._array) return self.__class__._new(res) def __lshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __lshift__. """ other = self._check_allowed_dtypes(other, "integer", "__lshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lshift__(other._array) return self.__class__._new(res) def __lt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __lt__. """ other = self._check_allowed_dtypes(other, "numeric", "__lt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lt__(other._array) return self.__class__._new(res) def __matmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __matmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__matmul__") if other is NotImplemented: return other res = self._array.__matmul__(other._array) return self.__class__._new(res) def __mod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mod__. """ other = self._check_allowed_dtypes(other, "numeric", "__mod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mod__(other._array) return self.__class__._new(res) def __mul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mul__. """ other = self._check_allowed_dtypes(other, "numeric", "__mul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mul__(other._array) return self.__class__._new(res) def __ne__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __ne__. """ other = self._check_allowed_dtypes(other, "all", "__ne__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ne__(other._array) return self.__class__._new(res) def __neg__(self: Array, /) -> Array: """ Performs the operation __neg__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __neg__") res = self._array.__neg__() return self.__class__._new(res) def __or__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __or__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__or__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__or__(other._array) return self.__class__._new(res) def __pos__(self: Array, /) -> Array: """ Performs the operation __pos__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __pos__") res = self._array.__pos__() return self.__class__._new(res) def __pow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __pow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__pow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow type promotion rules for 0-d # arrays, so we use pow() here instead. return pow(self, other) def __rshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rshift__(other._array) return self.__class__._new(res) def __setitem__( self, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], value: Union[int, float, bool, Array], /, ) -> None: """ Performs the operation __setitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array self._array.__setitem__(key, asarray(value)._array) def __sub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __sub__. """ other = self._check_allowed_dtypes(other, "numeric", "__sub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__sub__(other._array) return self.__class__._new(res) # PEP 484 requires int to be a subtype of float, but __truediv__ should # not accept int. def __truediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __truediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__truediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__truediv__(other._array) return self.__class__._new(res) def __xor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __xor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__xor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__xor__(other._array) return self.__class__._new(res) def __iadd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __iadd__. """ other = self._check_allowed_dtypes(other, "numeric", "__iadd__") if other is NotImplemented: return other self._array.__iadd__(other._array) return self def __radd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __radd__. """ other = self._check_allowed_dtypes(other, "numeric", "__radd__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__radd__(other._array) return self.__class__._new(res) def __iand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __iand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__iand__") if other is NotImplemented: return other self._array.__iand__(other._array) return self def __rand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rand__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rand__(other._array) return self.__class__._new(res) def __ifloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ifloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__ifloordiv__") if other is NotImplemented: return other self._array.__ifloordiv__(other._array) return self def __rfloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rfloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__rfloordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rfloordiv__(other._array) return self.__class__._new(res) def __ilshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __ilshift__. """ other = self._check_allowed_dtypes(other, "integer", "__ilshift__") if other is NotImplemented: return other self._array.__ilshift__(other._array) return self def __rlshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rlshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rlshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rlshift__(other._array) return self.__class__._new(res) def __imatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __imatmul__. """ # Note: NumPy does not implement __imatmul__. # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__imatmul__") if other is NotImplemented: return other # __imatmul__ can only be allowed when it would not change the shape # of self. other_shape = other.shape if self.shape == () or other_shape == (): raise ValueError("@= requires at least one dimension") if len(other_shape) == 1 or other_shape[-1] != other_shape[-2]: raise ValueError("@= cannot change the shape of the input array") self._array[:] = self._array.__matmul__(other._array) return self def __rmatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __rmatmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__rmatmul__") if other is NotImplemented: return other res = self._array.__rmatmul__(other._array) return self.__class__._new(res) def __imod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imod__. """ other = self._check_allowed_dtypes(other, "numeric", "__imod__") if other is NotImplemented: return other self._array.__imod__(other._array) return self def __rmod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmod__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmod__(other._array) return self.__class__._new(res) def __imul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imul__. """ other = self._check_allowed_dtypes(other, "numeric", "__imul__") if other is NotImplemented: return other self._array.__imul__(other._array) return self def __rmul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmul__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmul__(other._array) return self.__class__._new(res) def __ior__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ior__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ior__") if other is NotImplemented: return other self._array.__ior__(other._array) return self def __ror__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ror__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ror__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ror__(other._array) return self.__class__._new(res) def __ipow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ipow__. """ other = self._check_allowed_dtypes(other, "numeric", "__ipow__") if other is NotImplemented: return other self._array.__ipow__(other._array) return self def __rpow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rpow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__rpow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow the spec type promotion rules # for 0-d arrays, so we use pow() here instead. return pow(other, self) def __irshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __irshift__. """ other = self._check_allowed_dtypes(other, "integer", "__irshift__") if other is NotImplemented: return other self._array.__irshift__(other._array) return self def __rrshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rrshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rrshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rrshift__(other._array) return self.__class__._new(res) def __isub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __isub__. """ other = self._check_allowed_dtypes(other, "numeric", "__isub__") if other is NotImplemented: return other self._array.__isub__(other._array) return self def __rsub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rsub__. """ other = self._check_allowed_dtypes(other, "numeric", "__rsub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rsub__(other._array) return self.__class__._new(res) def __itruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __itruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__itruediv__") if other is NotImplemented: return other self._array.__itruediv__(other._array) return self def __rtruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __rtruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__rtruediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rtruediv__(other._array) return self.__class__._new(res) def __ixor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ixor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ixor__") if other is NotImplemented: return other self._array.__ixor__(other._array) return self def __rxor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rxor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rxor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rxor__(other._array) return self.__class__._new(res) def to_device(self: Array, device: Device, /, stream: None = None) -> Array: if stream is not None: raise ValueError("The stream argument to to_device() is not supported") if device == 'cpu': return self raise ValueError(f"Unsupported device {device!r}") def dtype(self) -> Dtype: """ Array API compatible wrapper for :py:meth:`np.ndarray.dtype <numpy.ndarray.dtype>`. See its docstring for more information. """ return self._array.dtype def device(self) -> Device: return "cpu" # Note: mT is new in array API spec (see matrix_transpose) def mT(self) -> Array: from .linalg import matrix_transpose return matrix_transpose(self) def ndim(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.ndim <numpy.ndarray.ndim>`. See its docstring for more information. """ return self._array.ndim def shape(self) -> Tuple[int, ...]: """ Array API compatible wrapper for :py:meth:`np.ndarray.shape <numpy.ndarray.shape>`. See its docstring for more information. """ return self._array.shape def size(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.size <numpy.ndarray.size>`. See its docstring for more information. """ return self._array.size def T(self) -> Array: """ Array API compatible wrapper for :py:meth:`np.ndarray.T <numpy.ndarray.T>`. See its docstring for more information. """ # Note: T only works on 2-dimensional arrays. See the corresponding # note in the specification: # https://data-apis.org/array-api/latest/API_specification/array_object.html#t if self.ndim != 2: raise ValueError("x.T requires x to have 2 dimensions. Use x.mT to transpose stacks of matrices and permute_dims() to permute dimensions.") return self.__class__._new(self._array.T) def result_type(*arrays_and_dtypes: Union[Array, Dtype]) -> Dtype: """ Array API compatible wrapper for :py:func:`np.result_type <numpy.result_type>`. See its docstring for more information. """ # Note: we use a custom implementation that gives only the type promotions # required by the spec rather than using np.result_type. NumPy implements # too many extra type promotions like int64 + uint64 -> float64, and does # value-based casting on scalar arrays. A = [] for a in arrays_and_dtypes: if isinstance(a, Array): a = a.dtype elif isinstance(a, np.ndarray) or a not in _all_dtypes: raise TypeError("result_type() inputs must be array_api arrays or dtypes") A.append(a) if len(A) == 0: raise ValueError("at least one array or dtype is required") elif len(A) == 1: return A[0] else: t = A[0] for t2 in A[1:]: t = _result_type(t, t2) return t Union: _SpecialForm = ... List = _Alias() class Tuple(BaseTypingInstance): def _is_homogenous(self): # To specify a variable-length tuple of homogeneous type, Tuple[T, ...] # is used. return self._generics_manager.is_homogenous_tuple() def py__simple_getitem__(self, index): if self._is_homogenous(): return self._generics_manager.get_index_and_execute(0) else: if isinstance(index, int): return self._generics_manager.get_index_and_execute(index) debug.dbg('The getitem type on Tuple was %s' % index) return NO_VALUES def py__iter__(self, contextualized_node=None): if self._is_homogenous(): yield LazyKnownValues(self._generics_manager.get_index_and_execute(0)) else: for v in self._generics_manager.to_tuple(): yield LazyKnownValues(v.execute_annotation()) def py__getitem__(self, index_value_set, contextualized_node): if self._is_homogenous(): return self._generics_manager.get_index_and_execute(0) return ValueSet.from_sets( self._generics_manager.to_tuple() ).execute_annotation() def _get_wrapped_value(self): tuple_, = self.inference_state.builtins_module \ .py__getattribute__('tuple').execute_annotation() return tuple_ def name(self): return self._wrapped_value.name def infer_type_vars(self, value_set): # Circular from jedi.inference.gradual.annotation import merge_pairwise_generics, merge_type_var_dicts value_set = value_set.filter( lambda x: x.py__name__().lower() == 'tuple', ) if self._is_homogenous(): # The parameter annotation is of the form `Tuple[T, ...]`, # so we treat the incoming tuple like a iterable sequence # rather than a positional container of elements. return self._class_value.get_generics()[0].infer_type_vars( value_set.merge_types_of_iterate(), ) else: # The parameter annotation has only explicit type parameters # (e.g: `Tuple[T]`, `Tuple[T, U]`, `Tuple[T, U, V]`, etc.) so we # treat the incoming values as needing to match the annotation # exactly, just as we would for non-tuple annotations. type_var_dict = {} for element in value_set: try: method = element.get_annotated_class_object except AttributeError: # This might still happen, because the tuple name matching # above is not 100% correct, so just catch the remaining # cases here. continue py_class = method() merge_type_var_dicts( type_var_dict, merge_pairwise_generics(self._class_value, py_class), ) return type_var_dict The provided code snippet includes necessary dependencies for implementing the `stack` function. Write a Python function `def stack(arrays: Union[Tuple[Array, ...], List[Array]], /, *, axis: int = 0) -> Array` to solve the following problem: Array API compatible wrapper for :py:func:`np.stack <numpy.stack>`. See its docstring for more information. Here is the function: def stack(arrays: Union[Tuple[Array, ...], List[Array]], /, *, axis: int = 0) -> Array: """ Array API compatible wrapper for :py:func:`np.stack <numpy.stack>`. See its docstring for more information. """ # Call result type here just to raise on disallowed type combinations result_type(*arrays) arrays = tuple(a._array for a in arrays) return Array._new(np.stack(arrays, axis=axis))
Array API compatible wrapper for :py:func:`np.stack <numpy.stack>`. See its docstring for more information.
170,086
import builtins import inspect import operator import warnings import textwrap import re from functools import reduce import numpy as np import numpy.core.umath as umath import numpy.core.numerictypes as ntypes from numpy.core import multiarray as mu from numpy import ndarray, amax, amin, iscomplexobj, bool_, _NoValue from numpy import array as narray from numpy.lib.function_base import angle from numpy.compat import ( getargspec, formatargspec, long, unicode, bytes ) from numpy import expand_dims from numpy.core.numeric import normalize_axis_tuple The provided code snippet includes necessary dependencies for implementing the `doc_note` function. Write a Python function `def doc_note(initialdoc, note)` to solve the following problem: Adds a Notes section to an existing docstring. Here is the function: def doc_note(initialdoc, note): """ Adds a Notes section to an existing docstring. """ if initialdoc is None: return if note is None: return initialdoc notesplit = re.split(r'\n\s*?Notes\n\s*?-----', inspect.cleandoc(initialdoc)) notedoc = "\n\nNotes\n-----\n%s\n" % inspect.cleandoc(note) return ''.join(notesplit[:1] + [notedoc] + notesplit[1:])
Adds a Notes section to an existing docstring.
170,087
import builtins import inspect import operator import warnings import textwrap import re from functools import reduce import numpy as np import numpy.core.umath as umath import numpy.core.numerictypes as ntypes from numpy.core import multiarray as mu from numpy import ndarray, amax, amin, iscomplexobj, bool_, _NoValue from numpy import array as narray from numpy.lib.function_base import angle from numpy.compat import ( getargspec, formatargspec, long, unicode, bytes ) from numpy import expand_dims from numpy.core.numeric import normalize_axis_tuple The provided code snippet includes necessary dependencies for implementing the `get_object_signature` function. Write a Python function `def get_object_signature(obj)` to solve the following problem: Get the signature from obj Here is the function: def get_object_signature(obj): """ Get the signature from obj """ try: sig = formatargspec(*getargspec(obj)) except TypeError: sig = '' return sig
Get the signature from obj
170,088
import builtins import inspect import operator import warnings import textwrap import re from functools import reduce import numpy as np import numpy.core.umath as umath import numpy.core.numerictypes as ntypes from numpy.core import multiarray as mu from numpy import ndarray, amax, amin, iscomplexobj, bool_, _NoValue from numpy import array as narray from numpy.lib.function_base import angle from numpy.compat import ( getargspec, formatargspec, long, unicode, bytes ) from numpy import expand_dims from numpy.core.numeric import normalize_axis_tuple max_filler = ntypes._minvals max_filler.update([(k, -np.inf) for k in float_types_list[:4]]) max_filler.update([(k, complex(-np.inf, -np.inf)) for k in float_types_list[-3:]]) def _extremum_fill_value(obj, extremum, extremum_name): def _scalar_fill_value(dtype): try: return extremum[dtype] except KeyError as e: raise TypeError( f"Unsuitable type {dtype} for calculating {extremum_name}." ) from None dtype = _get_dtype_of(obj) return _recursive_fill_value(dtype, _scalar_fill_value) The provided code snippet includes necessary dependencies for implementing the `maximum_fill_value` function. Write a Python function `def maximum_fill_value(obj)` to solve the following problem: Return the minimum value that can be represented by the dtype of an object. This function is useful for calculating a fill value suitable for taking the maximum of an array with a given dtype. Parameters ---------- obj : ndarray, dtype or scalar An object that can be queried for it's numeric type. Returns ------- val : scalar The minimum representable value. Raises ------ TypeError If `obj` isn't a suitable numeric type. See Also -------- minimum_fill_value : The inverse function. set_fill_value : Set the filling value of a masked array. MaskedArray.fill_value : Return current fill value. Examples -------- >>> import numpy.ma as ma >>> a = np.int8() >>> ma.maximum_fill_value(a) -128 >>> a = np.int32() >>> ma.maximum_fill_value(a) -2147483648 An array of numeric data can also be passed. >>> a = np.array([1, 2, 3], dtype=np.int8) >>> ma.maximum_fill_value(a) -128 >>> a = np.array([1, 2, 3], dtype=np.float32) >>> ma.maximum_fill_value(a) -inf Here is the function: def maximum_fill_value(obj): """ Return the minimum value that can be represented by the dtype of an object. This function is useful for calculating a fill value suitable for taking the maximum of an array with a given dtype. Parameters ---------- obj : ndarray, dtype or scalar An object that can be queried for it's numeric type. Returns ------- val : scalar The minimum representable value. Raises ------ TypeError If `obj` isn't a suitable numeric type. See Also -------- minimum_fill_value : The inverse function. set_fill_value : Set the filling value of a masked array. MaskedArray.fill_value : Return current fill value. Examples -------- >>> import numpy.ma as ma >>> a = np.int8() >>> ma.maximum_fill_value(a) -128 >>> a = np.int32() >>> ma.maximum_fill_value(a) -2147483648 An array of numeric data can also be passed. >>> a = np.array([1, 2, 3], dtype=np.int8) >>> ma.maximum_fill_value(a) -128 >>> a = np.array([1, 2, 3], dtype=np.float32) >>> ma.maximum_fill_value(a) -inf """ return _extremum_fill_value(obj, max_filler, "maximum")
Return the minimum value that can be represented by the dtype of an object. This function is useful for calculating a fill value suitable for taking the maximum of an array with a given dtype. Parameters ---------- obj : ndarray, dtype or scalar An object that can be queried for it's numeric type. Returns ------- val : scalar The minimum representable value. Raises ------ TypeError If `obj` isn't a suitable numeric type. See Also -------- minimum_fill_value : The inverse function. set_fill_value : Set the filling value of a masked array. MaskedArray.fill_value : Return current fill value. Examples -------- >>> import numpy.ma as ma >>> a = np.int8() >>> ma.maximum_fill_value(a) -128 >>> a = np.int32() >>> ma.maximum_fill_value(a) -2147483648 An array of numeric data can also be passed. >>> a = np.array([1, 2, 3], dtype=np.int8) >>> ma.maximum_fill_value(a) -128 >>> a = np.array([1, 2, 3], dtype=np.float32) >>> ma.maximum_fill_value(a) -inf
170,089
import builtins import inspect import operator import warnings import textwrap import re from functools import reduce import numpy as np import numpy.core.umath as umath import numpy.core.numerictypes as ntypes from numpy.core import multiarray as mu from numpy import ndarray, amax, amin, iscomplexobj, bool_, _NoValue from numpy import array as narray from numpy.lib.function_base import angle from numpy.compat import ( getargspec, formatargspec, long, unicode, bytes ) from numpy import expand_dims from numpy.core.numeric import normalize_axis_tuple def default_fill_value(obj): """ Return the default fill value for the argument object. The default filling value depends on the datatype of the input array or the type of the input scalar: ======== ======== datatype default ======== ======== bool True int 999999 float 1.e20 complex 1.e20+0j object '?' string 'N/A' ======== ======== For structured types, a structured scalar is returned, with each field the default fill value for its type. For subarray types, the fill value is an array of the same size containing the default scalar fill value. Parameters ---------- obj : ndarray, dtype or scalar The array data-type or scalar for which the default fill value is returned. Returns ------- fill_value : scalar The default fill value. Examples -------- >>> np.ma.default_fill_value(1) 999999 >>> np.ma.default_fill_value(np.array([1.1, 2., np.pi])) 1e+20 >>> np.ma.default_fill_value(np.dtype(complex)) (1e+20+0j) """ def _scalar_fill_value(dtype): if dtype.kind in 'Mm': return default_filler.get(dtype.str[1:], '?') else: return default_filler.get(dtype.kind, '?') dtype = _get_dtype_of(obj) return _recursive_fill_value(dtype, _scalar_fill_value) def _recursive_set_fill_value(fillvalue, dt): """ Create a fill value for a structured dtype. Parameters ---------- fillvalue : scalar or array_like Scalar or array representing the fill value. If it is of shorter length than the number of fields in dt, it will be resized. dt : dtype The structured dtype for which to create the fill value. Returns ------- val : tuple A tuple of values corresponding to the structured fill value. """ fillvalue = np.resize(fillvalue, len(dt.names)) output_value = [] for (fval, name) in zip(fillvalue, dt.names): cdtype = dt[name] if cdtype.subdtype: cdtype = cdtype.subdtype[0] if cdtype.names is not None: output_value.append(tuple(_recursive_set_fill_value(fval, cdtype))) else: output_value.append(np.array(fval, dtype=cdtype).item()) return tuple(output_value) def array(data, dtype=None, copy=False, order=None, mask=nomask, fill_value=None, keep_mask=True, hard_mask=False, shrink=True, subok=True, ndmin=0): """ Shortcut to MaskedArray. The options are in a different order for convenience and backwards compatibility. """ return MaskedArray(data, mask=mask, dtype=dtype, copy=copy, subok=subok, keep_mask=keep_mask, hard_mask=hard_mask, fill_value=fill_value, ndmin=ndmin, shrink=shrink, order=order) array.__doc__ = masked_array.__doc__ copy = _frommethod('copy') def asarray(a, dtype=None, order=None): """ Convert the input to a masked array of the given data-type. No copy is performed if the input is already an `ndarray`. If `a` is a subclass of `MaskedArray`, a base class `MaskedArray` is returned. Parameters ---------- a : array_like Input data, in any form that can be converted to a masked array. This includes lists, lists of tuples, tuples, tuples of tuples, tuples of lists, ndarrays and masked arrays. dtype : dtype, optional By default, the data-type is inferred from the input data. order : {'C', 'F'}, optional Whether to use row-major ('C') or column-major ('FORTRAN') memory representation. Default is 'C'. Returns ------- out : MaskedArray Masked array interpretation of `a`. See Also -------- asanyarray : Similar to `asarray`, but conserves subclasses. Examples -------- >>> x = np.arange(10.).reshape(2, 5) >>> x array([[0., 1., 2., 3., 4.], [5., 6., 7., 8., 9.]]) >>> np.ma.asarray(x) masked_array( data=[[0., 1., 2., 3., 4.], [5., 6., 7., 8., 9.]], mask=False, fill_value=1e+20) >>> type(np.ma.asarray(x)) <class 'numpy.ma.core.MaskedArray'> """ order = order or 'C' return masked_array(a, dtype=dtype, copy=False, keep_mask=True, subok=False, order=order) The provided code snippet includes necessary dependencies for implementing the `_check_fill_value` function. Write a Python function `def _check_fill_value(fill_value, ndtype)` to solve the following problem: Private function validating the given `fill_value` for the given dtype. If fill_value is None, it is set to the default corresponding to the dtype. If fill_value is not None, its value is forced to the given dtype. The result is always a 0d array. Here is the function: def _check_fill_value(fill_value, ndtype): """ Private function validating the given `fill_value` for the given dtype. If fill_value is None, it is set to the default corresponding to the dtype. If fill_value is not None, its value is forced to the given dtype. The result is always a 0d array. """ ndtype = np.dtype(ndtype) if fill_value is None: fill_value = default_fill_value(ndtype) elif ndtype.names is not None: if isinstance(fill_value, (ndarray, np.void)): try: fill_value = np.array(fill_value, copy=False, dtype=ndtype) except ValueError as e: err_msg = "Unable to transform %s to dtype %s" raise ValueError(err_msg % (fill_value, ndtype)) from e else: fill_value = np.asarray(fill_value, dtype=object) fill_value = np.array(_recursive_set_fill_value(fill_value, ndtype), dtype=ndtype) else: if isinstance(fill_value, str) and (ndtype.char not in 'OSVU'): # Note this check doesn't work if fill_value is not a scalar err_msg = "Cannot set fill value of string with array of dtype %s" raise TypeError(err_msg % ndtype) else: # In case we want to convert 1e20 to int. # Also in case of converting string arrays. try: fill_value = np.array(fill_value, copy=False, dtype=ndtype) except (OverflowError, ValueError) as e: # Raise TypeError instead of OverflowError or ValueError. # OverflowError is seldom used, and the real problem here is # that the passed fill_value is not compatible with the ndtype. err_msg = "Cannot convert fill_value %s to dtype %s" raise TypeError(err_msg % (fill_value, ndtype)) from e return np.array(fill_value)
Private function validating the given `fill_value` for the given dtype. If fill_value is None, it is set to the default corresponding to the dtype. If fill_value is not None, its value is forced to the given dtype. The result is always a 0d array.
170,090
import builtins import inspect import operator import warnings import textwrap import re from functools import reduce import numpy as np import numpy.core.umath as umath import numpy.core.numerictypes as ntypes from numpy.core import multiarray as mu from numpy import ndarray, amax, amin, iscomplexobj, bool_, _NoValue from numpy import array as narray from numpy.lib.function_base import angle from numpy.compat import ( getargspec, formatargspec, long, unicode, bytes ) from numpy import expand_dims from numpy.core.numeric import normalize_axis_tuple class MaskedArray(ndarray): """ An array class with possibly masked values. Masked values of True exclude the corresponding element from any computation. Construction:: x = MaskedArray(data, mask=nomask, dtype=None, copy=False, subok=True, ndmin=0, fill_value=None, keep_mask=True, hard_mask=None, shrink=True, order=None) Parameters ---------- data : array_like Input data. mask : sequence, optional Mask. Must be convertible to an array of booleans with the same shape as `data`. True indicates a masked (i.e. invalid) data. dtype : dtype, optional Data type of the output. If `dtype` is None, the type of the data argument (``data.dtype``) is used. If `dtype` is not None and different from ``data.dtype``, a copy is performed. copy : bool, optional Whether to copy the input data (True), or to use a reference instead. Default is False. subok : bool, optional Whether to return a subclass of `MaskedArray` if possible (True) or a plain `MaskedArray`. Default is True. ndmin : int, optional Minimum number of dimensions. Default is 0. fill_value : scalar, optional Value used to fill in the masked values when necessary. If None, a default based on the data-type is used. keep_mask : bool, optional Whether to combine `mask` with the mask of the input data, if any (True), or to use only `mask` for the output (False). Default is True. hard_mask : bool, optional Whether to use a hard mask or not. With a hard mask, masked values cannot be unmasked. Default is False. shrink : bool, optional Whether to force compression of an empty mask. Default is True. order : {'C', 'F', 'A'}, optional Specify the order of the array. If order is 'C', then the array will be in C-contiguous order (last-index varies the fastest). If order is 'F', then the returned array will be in Fortran-contiguous order (first-index varies the fastest). If order is 'A' (default), then the returned array may be in any order (either C-, Fortran-contiguous, or even discontiguous), unless a copy is required, in which case it will be C-contiguous. Examples -------- The ``mask`` can be initialized with an array of boolean values with the same shape as ``data``. >>> data = np.arange(6).reshape((2, 3)) >>> np.ma.MaskedArray(data, mask=[[False, True, False], ... [False, False, True]]) masked_array( data=[[0, --, 2], [3, 4, --]], mask=[[False, True, False], [False, False, True]], fill_value=999999) Alternatively, the ``mask`` can be initialized to homogeneous boolean array with the same shape as ``data`` by passing in a scalar boolean value: >>> np.ma.MaskedArray(data, mask=False) masked_array( data=[[0, 1, 2], [3, 4, 5]], mask=[[False, False, False], [False, False, False]], fill_value=999999) >>> np.ma.MaskedArray(data, mask=True) masked_array( data=[[--, --, --], [--, --, --]], mask=[[ True, True, True], [ True, True, True]], fill_value=999999, dtype=int64) .. note:: The recommended practice for initializing ``mask`` with a scalar boolean value is to use ``True``/``False`` rather than ``np.True_``/``np.False_``. The reason is :attr:`nomask` is represented internally as ``np.False_``. >>> np.False_ is np.ma.nomask True """ __array_priority__ = 15 _defaultmask = nomask _defaulthardmask = False _baseclass = ndarray # Maximum number of elements per axis used when printing an array. The # 1d case is handled separately because we need more values in this case. _print_width = 100 _print_width_1d = 1500 def __new__(cls, data=None, mask=nomask, dtype=None, copy=False, subok=True, ndmin=0, fill_value=None, keep_mask=True, hard_mask=None, shrink=True, order=None): """ Create a new masked array from scratch. Notes ----- A masked array can also be created by taking a .view(MaskedArray). """ # Process data. _data = np.array(data, dtype=dtype, copy=copy, order=order, subok=True, ndmin=ndmin) _baseclass = getattr(data, '_baseclass', type(_data)) # Check that we're not erasing the mask. if isinstance(data, MaskedArray) and (data.shape != _data.shape): copy = True # Here, we copy the _view_, so that we can attach new properties to it # we must never do .view(MaskedConstant), as that would create a new # instance of np.ma.masked, which make identity comparison fail if isinstance(data, cls) and subok and not isinstance(data, MaskedConstant): _data = ndarray.view(_data, type(data)) else: _data = ndarray.view(_data, cls) # Handle the case where data is not a subclass of ndarray, but # still has the _mask attribute like MaskedArrays if hasattr(data, '_mask') and not isinstance(data, ndarray): _data._mask = data._mask # FIXME: should we set `_data._sharedmask = True`? # Process mask. # Type of the mask mdtype = make_mask_descr(_data.dtype) if mask is nomask: # Case 1. : no mask in input. # Erase the current mask ? if not keep_mask: # With a reduced version if shrink: _data._mask = nomask # With full version else: _data._mask = np.zeros(_data.shape, dtype=mdtype) # Check whether we missed something elif isinstance(data, (tuple, list)): try: # If data is a sequence of masked array mask = np.array( [getmaskarray(np.asanyarray(m, dtype=_data.dtype)) for m in data], dtype=mdtype) except ValueError: # If data is nested mask = nomask # Force shrinking of the mask if needed (and possible) if (mdtype == MaskType) and mask.any(): _data._mask = mask _data._sharedmask = False else: _data._sharedmask = not copy if copy: _data._mask = _data._mask.copy() # Reset the shape of the original mask if getmask(data) is not nomask: data._mask.shape = data.shape else: # Case 2. : With a mask in input. # If mask is boolean, create an array of True or False if mask is True and mdtype == MaskType: mask = np.ones(_data.shape, dtype=mdtype) elif mask is False and mdtype == MaskType: mask = np.zeros(_data.shape, dtype=mdtype) else: # Read the mask with the current mdtype try: mask = np.array(mask, copy=copy, dtype=mdtype) # Or assume it's a sequence of bool/int except TypeError: mask = np.array([tuple([m] * len(mdtype)) for m in mask], dtype=mdtype) # Make sure the mask and the data have the same shape if mask.shape != _data.shape: (nd, nm) = (_data.size, mask.size) if nm == 1: mask = np.resize(mask, _data.shape) elif nm == nd: mask = np.reshape(mask, _data.shape) else: msg = "Mask and data not compatible: data size is %i, " + \ "mask size is %i." raise MaskError(msg % (nd, nm)) copy = True # Set the mask to the new value if _data._mask is nomask: _data._mask = mask _data._sharedmask = not copy else: if not keep_mask: _data._mask = mask _data._sharedmask = not copy else: if _data.dtype.names is not None: def _recursive_or(a, b): "do a|=b on each field of a, recursively" for name in a.dtype.names: (af, bf) = (a[name], b[name]) if af.dtype.names is not None: _recursive_or(af, bf) else: af |= bf _recursive_or(_data._mask, mask) else: _data._mask = np.logical_or(mask, _data._mask) _data._sharedmask = False # Update fill_value. if fill_value is None: fill_value = getattr(data, '_fill_value', None) # But don't run the check unless we have something to check. if fill_value is not None: _data._fill_value = _check_fill_value(fill_value, _data.dtype) # Process extra options .. if hard_mask is None: _data._hardmask = getattr(data, '_hardmask', False) else: _data._hardmask = hard_mask _data._baseclass = _baseclass return _data def _update_from(self, obj): """ Copies some attributes of obj to self. """ if isinstance(obj, ndarray): _baseclass = type(obj) else: _baseclass = ndarray # We need to copy the _basedict to avoid backward propagation _optinfo = {} _optinfo.update(getattr(obj, '_optinfo', {})) _optinfo.update(getattr(obj, '_basedict', {})) if not isinstance(obj, MaskedArray): _optinfo.update(getattr(obj, '__dict__', {})) _dict = dict(_fill_value=getattr(obj, '_fill_value', None), _hardmask=getattr(obj, '_hardmask', False), _sharedmask=getattr(obj, '_sharedmask', False), _isfield=getattr(obj, '_isfield', False), _baseclass=getattr(obj, '_baseclass', _baseclass), _optinfo=_optinfo, _basedict=_optinfo) self.__dict__.update(_dict) self.__dict__.update(_optinfo) return def __array_finalize__(self, obj): """ Finalizes the masked array. """ # Get main attributes. self._update_from(obj) # We have to decide how to initialize self.mask, based on # obj.mask. This is very difficult. There might be some # correspondence between the elements in the array we are being # created from (= obj) and us. Or there might not. This method can # be called in all kinds of places for all kinds of reasons -- could # be empty_like, could be slicing, could be a ufunc, could be a view. # The numpy subclassing interface simply doesn't give us any way # to know, which means that at best this method will be based on # guesswork and heuristics. To make things worse, there isn't even any # clear consensus about what the desired behavior is. For instance, # most users think that np.empty_like(marr) -- which goes via this # method -- should return a masked array with an empty mask (see # gh-3404 and linked discussions), but others disagree, and they have # existing code which depends on empty_like returning an array that # matches the input mask. # # Historically our algorithm was: if the template object mask had the # same *number of elements* as us, then we used *it's mask object # itself* as our mask, so that writes to us would also write to the # original array. This is horribly broken in multiple ways. # # Now what we do instead is, if the template object mask has the same # number of elements as us, and we do not have the same base pointer # as the template object (b/c views like arr[...] should keep the same # mask), then we make a copy of the template object mask and use # that. This is also horribly broken but somewhat less so. Maybe. if isinstance(obj, ndarray): # XX: This looks like a bug -- shouldn't it check self.dtype # instead? if obj.dtype.names is not None: _mask = getmaskarray(obj) else: _mask = getmask(obj) # If self and obj point to exactly the same data, then probably # self is a simple view of obj (e.g., self = obj[...]), so they # should share the same mask. (This isn't 100% reliable, e.g. self # could be the first row of obj, or have strange strides, but as a # heuristic it's not bad.) In all other cases, we make a copy of # the mask, so that future modifications to 'self' do not end up # side-effecting 'obj' as well. if (_mask is not nomask and obj.__array_interface__["data"][0] != self.__array_interface__["data"][0]): # We should make a copy. But we could get here via astype, # in which case the mask might need a new dtype as well # (e.g., changing to or from a structured dtype), and the # order could have changed. So, change the mask type if # needed and use astype instead of copy. if self.dtype == obj.dtype: _mask_dtype = _mask.dtype else: _mask_dtype = make_mask_descr(self.dtype) if self.flags.c_contiguous: order = "C" elif self.flags.f_contiguous: order = "F" else: order = "K" _mask = _mask.astype(_mask_dtype, order) else: # Take a view so shape changes, etc., do not propagate back. _mask = _mask.view() else: _mask = nomask self._mask = _mask # Finalize the mask if self._mask is not nomask: try: self._mask.shape = self.shape except ValueError: self._mask = nomask except (TypeError, AttributeError): # When _mask.shape is not writable (because it's a void) pass # Finalize the fill_value if self._fill_value is not None: self._fill_value = _check_fill_value(self._fill_value, self.dtype) elif self.dtype.names is not None: # Finalize the default fill_value for structured arrays self._fill_value = _check_fill_value(None, self.dtype) def __array_wrap__(self, obj, context=None): """ Special hook for ufuncs. Wraps the numpy array and sets the mask according to context. """ if obj is self: # for in-place operations result = obj else: result = obj.view(type(self)) result._update_from(self) if context is not None: result._mask = result._mask.copy() func, args, out_i = context # args sometimes contains outputs (gh-10459), which we don't want input_args = args[:func.nin] m = reduce(mask_or, [getmaskarray(arg) for arg in input_args]) # Get the domain mask domain = ufunc_domain.get(func, None) if domain is not None: # Take the domain, and make sure it's a ndarray with np.errstate(divide='ignore', invalid='ignore'): d = filled(domain(*input_args), True) if d.any(): # Fill the result where the domain is wrong try: # Binary domain: take the last value fill_value = ufunc_fills[func][-1] except TypeError: # Unary domain: just use this one fill_value = ufunc_fills[func] except KeyError: # Domain not recognized, use fill_value instead fill_value = self.fill_value np.copyto(result, fill_value, where=d) # Update the mask if m is nomask: m = d else: # Don't modify inplace, we risk back-propagation m = (m | d) # Make sure the mask has the proper size if result is not self and result.shape == () and m: return masked else: result._mask = m result._sharedmask = False return result def view(self, dtype=None, type=None, fill_value=None): """ Return a view of the MaskedArray data. Parameters ---------- dtype : data-type or ndarray sub-class, optional Data-type descriptor of the returned view, e.g., float32 or int16. The default, None, results in the view having the same data-type as `a`. As with ``ndarray.view``, dtype can also be specified as an ndarray sub-class, which then specifies the type of the returned object (this is equivalent to setting the ``type`` parameter). type : Python type, optional Type of the returned view, either ndarray or a subclass. The default None results in type preservation. fill_value : scalar, optional The value to use for invalid entries (None by default). If None, then this argument is inferred from the passed `dtype`, or in its absence the original array, as discussed in the notes below. See Also -------- numpy.ndarray.view : Equivalent method on ndarray object. Notes ----- ``a.view()`` is used two different ways: ``a.view(some_dtype)`` or ``a.view(dtype=some_dtype)`` constructs a view of the array's memory with a different data-type. This can cause a reinterpretation of the bytes of memory. ``a.view(ndarray_subclass)`` or ``a.view(type=ndarray_subclass)`` just returns an instance of `ndarray_subclass` that looks at the same array (same shape, dtype, etc.) This does not cause a reinterpretation of the memory. If `fill_value` is not specified, but `dtype` is specified (and is not an ndarray sub-class), the `fill_value` of the MaskedArray will be reset. If neither `fill_value` nor `dtype` are specified (or if `dtype` is an ndarray sub-class), then the fill value is preserved. Finally, if `fill_value` is specified, but `dtype` is not, the fill value is set to the specified value. For ``a.view(some_dtype)``, if ``some_dtype`` has a different number of bytes per entry than the previous dtype (for example, converting a regular array to a structured array), then the behavior of the view cannot be predicted just from the superficial appearance of ``a`` (shown by ``print(a)``). It also depends on exactly how ``a`` is stored in memory. Therefore if ``a`` is C-ordered versus fortran-ordered, versus defined as a slice or transpose, etc., the view may give different results. """ if dtype is None: if type is None: output = ndarray.view(self) else: output = ndarray.view(self, type) elif type is None: try: if issubclass(dtype, ndarray): output = ndarray.view(self, dtype) dtype = None else: output = ndarray.view(self, dtype) except TypeError: output = ndarray.view(self, dtype) else: output = ndarray.view(self, dtype, type) # also make the mask be a view (so attr changes to the view's # mask do no affect original object's mask) # (especially important to avoid affecting np.masked singleton) if getmask(output) is not nomask: output._mask = output._mask.view() # Make sure to reset the _fill_value if needed if getattr(output, '_fill_value', None) is not None: if fill_value is None: if dtype is None: pass # leave _fill_value as is else: output._fill_value = None else: output.fill_value = fill_value return output def __getitem__(self, indx): """ x.__getitem__(y) <==> x[y] Return the item described by i, as a masked array. """ # We could directly use ndarray.__getitem__ on self. # But then we would have to modify __array_finalize__ to prevent the # mask of being reshaped if it hasn't been set up properly yet # So it's easier to stick to the current version dout = self.data[indx] _mask = self._mask def _is_scalar(m): return not isinstance(m, np.ndarray) def _scalar_heuristic(arr, elem): """ Return whether `elem` is a scalar result of indexing `arr`, or None if undecidable without promoting nomask to a full mask """ # obviously a scalar if not isinstance(elem, np.ndarray): return True # object array scalar indexing can return anything elif arr.dtype.type is np.object_: if arr.dtype is not elem.dtype: # elem is an array, but dtypes do not match, so must be # an element return True # well-behaved subclass that only returns 0d arrays when # expected - this is not a scalar elif type(arr).__getitem__ == ndarray.__getitem__: return False return None if _mask is not nomask: # _mask cannot be a subclass, so it tells us whether we should # expect a scalar. It also cannot be of dtype object. mout = _mask[indx] scalar_expected = _is_scalar(mout) else: # attempt to apply the heuristic to avoid constructing a full mask mout = nomask scalar_expected = _scalar_heuristic(self.data, dout) if scalar_expected is None: # heuristics have failed # construct a full array, so we can be certain. This is costly. # we could also fall back on ndarray.__getitem__(self.data, indx) scalar_expected = _is_scalar(getmaskarray(self)[indx]) # Did we extract a single item? if scalar_expected: # A record if isinstance(dout, np.void): # We should always re-cast to mvoid, otherwise users can # change masks on rows that already have masked values, but not # on rows that have no masked values, which is inconsistent. return mvoid(dout, mask=mout, hardmask=self._hardmask) # special case introduced in gh-5962 elif (self.dtype.type is np.object_ and isinstance(dout, np.ndarray) and dout is not masked): # If masked, turn into a MaskedArray, with everything masked. if mout: return MaskedArray(dout, mask=True) else: return dout # Just a scalar else: if mout: return masked else: return dout else: # Force dout to MA dout = dout.view(type(self)) # Inherit attributes from self dout._update_from(self) # Check the fill_value if is_string_or_list_of_strings(indx): if self._fill_value is not None: dout._fill_value = self._fill_value[indx] # Something like gh-15895 has happened if this check fails. # _fill_value should always be an ndarray. if not isinstance(dout._fill_value, np.ndarray): raise RuntimeError('Internal NumPy error.') # If we're indexing a multidimensional field in a # structured array (such as dtype("(2,)i2,(2,)i1")), # dimensionality goes up (M[field].ndim == M.ndim + # M.dtype[field].ndim). That's fine for # M[field] but problematic for M[field].fill_value # which should have shape () to avoid breaking several # methods. There is no great way out, so set to # first element. See issue #6723. if dout._fill_value.ndim > 0: if not (dout._fill_value == dout._fill_value.flat[0]).all(): warnings.warn( "Upon accessing multidimensional field " f"{indx!s}, need to keep dimensionality " "of fill_value at 0. Discarding " "heterogeneous fill_value and setting " f"all to {dout._fill_value[0]!s}.", stacklevel=2) # Need to use `.flat[0:1].squeeze(...)` instead of just # `.flat[0]` to ensure the result is a 0d array and not # a scalar. dout._fill_value = dout._fill_value.flat[0:1].squeeze(axis=0) dout._isfield = True # Update the mask if needed if mout is not nomask: # set shape to match that of data; this is needed for matrices dout._mask = reshape(mout, dout.shape) dout._sharedmask = True # Note: Don't try to check for m.any(), that'll take too long return dout def __setitem__(self, indx, value): """ x.__setitem__(i, y) <==> x[i]=y Set item described by index. If value is masked, masks those locations. """ if self is masked: raise MaskError('Cannot alter the masked element.') _data = self._data _mask = self._mask if isinstance(indx, str): _data[indx] = value if _mask is nomask: self._mask = _mask = make_mask_none(self.shape, self.dtype) _mask[indx] = getmask(value) return _dtype = _data.dtype if value is masked: # The mask wasn't set: create a full version. if _mask is nomask: _mask = self._mask = make_mask_none(self.shape, _dtype) # Now, set the mask to its value. if _dtype.names is not None: _mask[indx] = tuple([True] * len(_dtype.names)) else: _mask[indx] = True return # Get the _data part of the new value dval = getattr(value, '_data', value) # Get the _mask part of the new value mval = getmask(value) if _dtype.names is not None and mval is nomask: mval = tuple([False] * len(_dtype.names)) if _mask is nomask: # Set the data, then the mask _data[indx] = dval if mval is not nomask: _mask = self._mask = make_mask_none(self.shape, _dtype) _mask[indx] = mval elif not self._hardmask: # Set the data, then the mask if (isinstance(indx, masked_array) and not isinstance(value, masked_array)): _data[indx.data] = dval else: _data[indx] = dval _mask[indx] = mval elif hasattr(indx, 'dtype') and (indx.dtype == MaskType): indx = indx * umath.logical_not(_mask) _data[indx] = dval else: if _dtype.names is not None: err_msg = "Flexible 'hard' masks are not yet supported." raise NotImplementedError(err_msg) mindx = mask_or(_mask[indx], mval, copy=True) dindx = self._data[indx] if dindx.size > 1: np.copyto(dindx, dval, where=~mindx) elif mindx is nomask: dindx = dval _data[indx] = dindx _mask[indx] = mindx return # Define so that we can overwrite the setter. def dtype(self): return super().dtype def dtype(self, dtype): super(MaskedArray, type(self)).dtype.__set__(self, dtype) if self._mask is not nomask: self._mask = self._mask.view(make_mask_descr(dtype), ndarray) # Try to reset the shape of the mask (if we don't have a void). # This raises a ValueError if the dtype change won't work. try: self._mask.shape = self.shape except (AttributeError, TypeError): pass def shape(self): return super().shape def shape(self, shape): super(MaskedArray, type(self)).shape.__set__(self, shape) # Cannot use self._mask, since it may not (yet) exist when a # masked matrix sets the shape. if getmask(self) is not nomask: self._mask.shape = self.shape def __setmask__(self, mask, copy=False): """ Set the mask. """ idtype = self.dtype current_mask = self._mask if mask is masked: mask = True if current_mask is nomask: # Make sure the mask is set # Just don't do anything if there's nothing to do. if mask is nomask: return current_mask = self._mask = make_mask_none(self.shape, idtype) if idtype.names is None: # No named fields. # Hardmask: don't unmask the data if self._hardmask: current_mask |= mask # Softmask: set everything to False # If it's obviously a compatible scalar, use a quick update # method. elif isinstance(mask, (int, float, np.bool_, np.number)): current_mask[...] = mask # Otherwise fall back to the slower, general purpose way. else: current_mask.flat = mask else: # Named fields w/ mdtype = current_mask.dtype mask = np.array(mask, copy=False) # Mask is a singleton if not mask.ndim: # It's a boolean : make a record if mask.dtype.kind == 'b': mask = np.array(tuple([mask.item()] * len(mdtype)), dtype=mdtype) # It's a record: make sure the dtype is correct else: mask = mask.astype(mdtype) # Mask is a sequence else: # Make sure the new mask is a ndarray with the proper dtype try: mask = np.array(mask, copy=copy, dtype=mdtype) # Or assume it's a sequence of bool/int except TypeError: mask = np.array([tuple([m] * len(mdtype)) for m in mask], dtype=mdtype) # Hardmask: don't unmask the data if self._hardmask: for n in idtype.names: current_mask[n] |= mask[n] # Softmask: set everything to False # If it's obviously a compatible scalar, use a quick update # method. elif isinstance(mask, (int, float, np.bool_, np.number)): current_mask[...] = mask # Otherwise fall back to the slower, general purpose way. else: current_mask.flat = mask # Reshape if needed if current_mask.shape: current_mask.shape = self.shape return _set_mask = __setmask__ def mask(self): """ Current mask. """ # We could try to force a reshape, but that wouldn't work in some # cases. # Return a view so that the dtype and shape cannot be changed in place # This still preserves nomask by identity return self._mask.view() def mask(self, value): self.__setmask__(value) def recordmask(self): """ Get or set the mask of the array if it has no named fields. For structured arrays, returns a ndarray of booleans where entries are ``True`` if **all** the fields are masked, ``False`` otherwise: >>> x = np.ma.array([(1, 1), (2, 2), (3, 3), (4, 4), (5, 5)], ... mask=[(0, 0), (1, 0), (1, 1), (0, 1), (0, 0)], ... dtype=[('a', int), ('b', int)]) >>> x.recordmask array([False, False, True, False, False]) """ _mask = self._mask.view(ndarray) if _mask.dtype.names is None: return _mask return np.all(flatten_structured_array(_mask), axis=-1) def recordmask(self, mask): raise NotImplementedError("Coming soon: setting the mask per records!") def harden_mask(self): """ Force the mask to hard, preventing unmasking by assignment. Whether the mask of a masked array is hard or soft is determined by its `~ma.MaskedArray.hardmask` property. `harden_mask` sets `~ma.MaskedArray.hardmask` to ``True`` (and returns the modified self). See Also -------- ma.MaskedArray.hardmask ma.MaskedArray.soften_mask """ self._hardmask = True return self def soften_mask(self): """ Force the mask to soft (default), allowing unmasking by assignment. Whether the mask of a masked array is hard or soft is determined by its `~ma.MaskedArray.hardmask` property. `soften_mask` sets `~ma.MaskedArray.hardmask` to ``False`` (and returns the modified self). See Also -------- ma.MaskedArray.hardmask ma.MaskedArray.harden_mask """ self._hardmask = False return self def hardmask(self): """ Specifies whether values can be unmasked through assignments. By default, assigning definite values to masked array entries will unmask them. When `hardmask` is ``True``, the mask will not change through assignments. See Also -------- ma.MaskedArray.harden_mask ma.MaskedArray.soften_mask Examples -------- >>> x = np.arange(10) >>> m = np.ma.masked_array(x, x>5) >>> assert not m.hardmask Since `m` has a soft mask, assigning an element value unmasks that element: >>> m[8] = 42 >>> m masked_array(data=[0, 1, 2, 3, 4, 5, --, --, 42, --], mask=[False, False, False, False, False, False, True, True, False, True], fill_value=999999) After hardening, the mask is not affected by assignments: >>> hardened = np.ma.harden_mask(m) >>> assert m.hardmask and hardened is m >>> m[:] = 23 >>> m masked_array(data=[23, 23, 23, 23, 23, 23, --, --, 23, --], mask=[False, False, False, False, False, False, True, True, False, True], fill_value=999999) """ return self._hardmask def unshare_mask(self): """ Copy the mask and set the `sharedmask` flag to ``False``. Whether the mask is shared between masked arrays can be seen from the `sharedmask` property. `unshare_mask` ensures the mask is not shared. A copy of the mask is only made if it was shared. See Also -------- sharedmask """ if self._sharedmask: self._mask = self._mask.copy() self._sharedmask = False return self def sharedmask(self): """ Share status of the mask (read-only). """ return self._sharedmask def shrink_mask(self): """ Reduce a mask to nomask when possible. Parameters ---------- None Returns ------- None Examples -------- >>> x = np.ma.array([[1,2 ], [3, 4]], mask=[0]*4) >>> x.mask array([[False, False], [False, False]]) >>> x.shrink_mask() masked_array( data=[[1, 2], [3, 4]], mask=False, fill_value=999999) >>> x.mask False """ self._mask = _shrink_mask(self._mask) return self def baseclass(self): """ Class of the underlying data (read-only). """ return self._baseclass def _get_data(self): """ Returns the underlying data, as a view of the masked array. If the underlying data is a subclass of :class:`numpy.ndarray`, it is returned as such. >>> x = np.ma.array(np.matrix([[1, 2], [3, 4]]), mask=[[0, 1], [1, 0]]) >>> x.data matrix([[1, 2], [3, 4]]) The type of the data can be accessed through the :attr:`baseclass` attribute. """ return ndarray.view(self, self._baseclass) _data = property(fget=_get_data) data = property(fget=_get_data) def flat(self): """ Return a flat iterator, or set a flattened version of self to value. """ return MaskedIterator(self) def flat(self, value): y = self.ravel() y[:] = value def fill_value(self): """ The filling value of the masked array is a scalar. When setting, None will set to a default based on the data type. Examples -------- >>> for dt in [np.int32, np.int64, np.float64, np.complex128]: ... np.ma.array([0, 1], dtype=dt).get_fill_value() ... 999999 999999 1e+20 (1e+20+0j) >>> x = np.ma.array([0, 1.], fill_value=-np.inf) >>> x.fill_value -inf >>> x.fill_value = np.pi >>> x.fill_value 3.1415926535897931 # may vary Reset to default: >>> x.fill_value = None >>> x.fill_value 1e+20 """ if self._fill_value is None: self._fill_value = _check_fill_value(None, self.dtype) # Temporary workaround to account for the fact that str and bytes # scalars cannot be indexed with (), whereas all other numpy # scalars can. See issues #7259 and #7267. # The if-block can be removed after #7267 has been fixed. if isinstance(self._fill_value, ndarray): return self._fill_value[()] return self._fill_value def fill_value(self, value=None): target = _check_fill_value(value, self.dtype) if not target.ndim == 0: # 2019-11-12, 1.18.0 warnings.warn( "Non-scalar arrays for the fill value are deprecated. Use " "arrays with scalar values instead. The filled function " "still supports any array as `fill_value`.", DeprecationWarning, stacklevel=2) _fill_value = self._fill_value if _fill_value is None: # Create the attribute if it was undefined self._fill_value = target else: # Don't overwrite the attribute, just fill it (for propagation) _fill_value[()] = target # kept for compatibility get_fill_value = fill_value.fget set_fill_value = fill_value.fset def filled(self, fill_value=None): """ Return a copy of self, with masked values filled with a given value. **However**, if there are no masked values to fill, self will be returned instead as an ndarray. Parameters ---------- fill_value : array_like, optional The value to use for invalid entries. Can be scalar or non-scalar. If non-scalar, the resulting ndarray must be broadcastable over input array. Default is None, in which case, the `fill_value` attribute of the array is used instead. Returns ------- filled_array : ndarray A copy of ``self`` with invalid entries replaced by *fill_value* (be it the function argument or the attribute of ``self``), or ``self`` itself as an ndarray if there are no invalid entries to be replaced. Notes ----- The result is **not** a MaskedArray! Examples -------- >>> x = np.ma.array([1,2,3,4,5], mask=[0,0,1,0,1], fill_value=-999) >>> x.filled() array([ 1, 2, -999, 4, -999]) >>> x.filled(fill_value=1000) array([ 1, 2, 1000, 4, 1000]) >>> type(x.filled()) <class 'numpy.ndarray'> Subclassing is preserved. This means that if, e.g., the data part of the masked array is a recarray, `filled` returns a recarray: >>> x = np.array([(-1, 2), (-3, 4)], dtype='i8,i8').view(np.recarray) >>> m = np.ma.array(x, mask=[(True, False), (False, True)]) >>> m.filled() rec.array([(999999, 2), ( -3, 999999)], dtype=[('f0', '<i8'), ('f1', '<i8')]) """ m = self._mask if m is nomask: return self._data if fill_value is None: fill_value = self.fill_value else: fill_value = _check_fill_value(fill_value, self.dtype) if self is masked_singleton: return np.asanyarray(fill_value) if m.dtype.names is not None: result = self._data.copy('K') _recursive_filled(result, self._mask, fill_value) elif not m.any(): return self._data else: result = self._data.copy('K') try: np.copyto(result, fill_value, where=m) except (TypeError, AttributeError): fill_value = narray(fill_value, dtype=object) d = result.astype(object) result = np.choose(m, (d, fill_value)) except IndexError: # ok, if scalar if self._data.shape: raise elif m: result = np.array(fill_value, dtype=self.dtype) else: result = self._data return result def compressed(self): """ Return all the non-masked data as a 1-D array. Returns ------- data : ndarray A new `ndarray` holding the non-masked data is returned. Notes ----- The result is **not** a MaskedArray! Examples -------- >>> x = np.ma.array(np.arange(5), mask=[0]*2 + [1]*3) >>> x.compressed() array([0, 1]) >>> type(x.compressed()) <class 'numpy.ndarray'> """ data = ndarray.ravel(self._data) if self._mask is not nomask: data = data.compress(np.logical_not(ndarray.ravel(self._mask))) return data def compress(self, condition, axis=None, out=None): """ Return `a` where condition is ``True``. If condition is a `~ma.MaskedArray`, missing values are considered as ``False``. Parameters ---------- condition : var Boolean 1-d array selecting which entries to return. If len(condition) is less than the size of a along the axis, then output is truncated to length of condition array. axis : {None, int}, optional Axis along which the operation must be performed. out : {None, ndarray}, optional Alternative output array in which to place the result. It must have the same shape as the expected output but the type will be cast if necessary. Returns ------- result : MaskedArray A :class:`~ma.MaskedArray` object. Notes ----- Please note the difference with :meth:`compressed` ! The output of :meth:`compress` has a mask, the output of :meth:`compressed` does not. Examples -------- >>> x = np.ma.array([[1,2,3],[4,5,6],[7,8,9]], mask=[0] + [1,0]*4) >>> x masked_array( data=[[1, --, 3], [--, 5, --], [7, --, 9]], mask=[[False, True, False], [ True, False, True], [False, True, False]], fill_value=999999) >>> x.compress([1, 0, 1]) masked_array(data=[1, 3], mask=[False, False], fill_value=999999) >>> x.compress([1, 0, 1], axis=1) masked_array( data=[[1, 3], [--, --], [7, 9]], mask=[[False, False], [ True, True], [False, False]], fill_value=999999) """ # Get the basic components (_data, _mask) = (self._data, self._mask) # Force the condition to a regular ndarray and forget the missing # values. condition = np.asarray(condition) _new = _data.compress(condition, axis=axis, out=out).view(type(self)) _new._update_from(self) if _mask is not nomask: _new._mask = _mask.compress(condition, axis=axis) return _new def _insert_masked_print(self): """ Replace masked values with masked_print_option, casting all innermost dtypes to object. """ if masked_print_option.enabled(): mask = self._mask if mask is nomask: res = self._data else: # convert to object array to make filled work data = self._data # For big arrays, to avoid a costly conversion to the # object dtype, extract the corners before the conversion. print_width = (self._print_width if self.ndim > 1 else self._print_width_1d) for axis in range(self.ndim): if data.shape[axis] > print_width: ind = print_width // 2 arr = np.split(data, (ind, -ind), axis=axis) data = np.concatenate((arr[0], arr[2]), axis=axis) arr = np.split(mask, (ind, -ind), axis=axis) mask = np.concatenate((arr[0], arr[2]), axis=axis) rdtype = _replace_dtype_fields(self.dtype, "O") res = data.astype(rdtype) _recursive_printoption(res, mask, masked_print_option) else: res = self.filled(self.fill_value) return res def __str__(self): return str(self._insert_masked_print()) def __repr__(self): """ Literal string representation. """ if self._baseclass is np.ndarray: name = 'array' else: name = self._baseclass.__name__ # 2016-11-19: Demoted to legacy format if np.core.arrayprint._get_legacy_print_mode() <= 113: is_long = self.ndim > 1 parameters = dict( name=name, nlen=" " * len(name), data=str(self), mask=str(self._mask), fill=str(self.fill_value), dtype=str(self.dtype) ) is_structured = bool(self.dtype.names) key = '{}_{}'.format( 'long' if is_long else 'short', 'flx' if is_structured else 'std' ) return _legacy_print_templates[key] % parameters prefix = f"masked_{name}(" dtype_needed = ( not np.core.arrayprint.dtype_is_implied(self.dtype) or np.all(self.mask) or self.size == 0 ) # determine which keyword args need to be shown keys = ['data', 'mask', 'fill_value'] if dtype_needed: keys.append('dtype') # array has only one row (non-column) is_one_row = builtins.all(dim == 1 for dim in self.shape[:-1]) # choose what to indent each keyword with min_indent = 2 if is_one_row: # first key on the same line as the type, remaining keys # aligned by equals indents = {} indents[keys[0]] = prefix for k in keys[1:]: n = builtins.max(min_indent, len(prefix + keys[0]) - len(k)) indents[k] = ' ' * n prefix = '' # absorbed into the first indent else: # each key on its own line, indented by two spaces indents = {k: ' ' * min_indent for k in keys} prefix = prefix + '\n' # first key on the next line # format the field values reprs = {} reprs['data'] = np.array2string( self._insert_masked_print(), separator=", ", prefix=indents['data'] + 'data=', suffix=',') reprs['mask'] = np.array2string( self._mask, separator=", ", prefix=indents['mask'] + 'mask=', suffix=',') reprs['fill_value'] = repr(self.fill_value) if dtype_needed: reprs['dtype'] = np.core.arrayprint.dtype_short_repr(self.dtype) # join keys with values and indentations result = ',\n'.join( '{}{}={}'.format(indents[k], k, reprs[k]) for k in keys ) return prefix + result + ')' def _delegate_binop(self, other): # This emulates the logic in # private/binop_override.h:forward_binop_should_defer if isinstance(other, type(self)): return False array_ufunc = getattr(other, "__array_ufunc__", False) if array_ufunc is False: other_priority = getattr(other, "__array_priority__", -1000000) return self.__array_priority__ < other_priority else: # If array_ufunc is not None, it will be called inside the ufunc; # None explicitly tells us to not call the ufunc, i.e., defer. return array_ufunc is None def _comparison(self, other, compare): """Compare self with other using operator.eq or operator.ne. When either of the elements is masked, the result is masked as well, but the underlying boolean data are still set, with self and other considered equal if both are masked, and unequal otherwise. For structured arrays, all fields are combined, with masked values ignored. The result is masked if all fields were masked, with self and other considered equal only if both were fully masked. """ omask = getmask(other) smask = self.mask mask = mask_or(smask, omask, copy=True) odata = getdata(other) if mask.dtype.names is not None: # only == and != are reasonably defined for structured dtypes, # so give up early for all other comparisons: if compare not in (operator.eq, operator.ne): return NotImplemented # For possibly masked structured arrays we need to be careful, # since the standard structured array comparison will use all # fields, masked or not. To avoid masked fields influencing the # outcome, we set all masked fields in self to other, so they'll # count as equal. To prepare, we ensure we have the right shape. broadcast_shape = np.broadcast(self, odata).shape sbroadcast = np.broadcast_to(self, broadcast_shape, subok=True) sbroadcast._mask = mask sdata = sbroadcast.filled(odata) # Now take care of the mask; the merged mask should have an item # masked if all fields were masked (in one and/or other). mask = (mask == np.ones((), mask.dtype)) else: # For regular arrays, just use the data as they come. sdata = self.data check = compare(sdata, odata) if isinstance(check, (np.bool_, bool)): return masked if mask else check if mask is not nomask and compare in (operator.eq, operator.ne): # Adjust elements that were masked, which should be treated # as equal if masked in both, unequal if masked in one. # Note that this works automatically for structured arrays too. # Ignore this for operations other than `==` and `!=` check = np.where(mask, compare(smask, omask), check) if mask.shape != check.shape: # Guarantee consistency of the shape, making a copy since the # the mask may need to get written to later. mask = np.broadcast_to(mask, check.shape).copy() check = check.view(type(self)) check._update_from(self) check._mask = mask # Cast fill value to bool_ if needed. If it cannot be cast, the # default boolean fill value is used. if check._fill_value is not None: try: fill = _check_fill_value(check._fill_value, np.bool_) except (TypeError, ValueError): fill = _check_fill_value(None, np.bool_) check._fill_value = fill return check def __eq__(self, other): """Check whether other equals self elementwise. When either of the elements is masked, the result is masked as well, but the underlying boolean data are still set, with self and other considered equal if both are masked, and unequal otherwise. For structured arrays, all fields are combined, with masked values ignored. The result is masked if all fields were masked, with self and other considered equal only if both were fully masked. """ return self._comparison(other, operator.eq) def __ne__(self, other): """Check whether other does not equal self elementwise. When either of the elements is masked, the result is masked as well, but the underlying boolean data are still set, with self and other considered equal if both are masked, and unequal otherwise. For structured arrays, all fields are combined, with masked values ignored. The result is masked if all fields were masked, with self and other considered equal only if both were fully masked. """ return self._comparison(other, operator.ne) # All other comparisons: def __le__(self, other): return self._comparison(other, operator.le) def __lt__(self, other): return self._comparison(other, operator.lt) def __ge__(self, other): return self._comparison(other, operator.ge) def __gt__(self, other): return self._comparison(other, operator.gt) def __add__(self, other): """ Add self to other, and return a new masked array. """ if self._delegate_binop(other): return NotImplemented return add(self, other) def __radd__(self, other): """ Add other to self, and return a new masked array. """ # In analogy with __rsub__ and __rdiv__, use original order: # we get here from `other + self`. return add(other, self) def __sub__(self, other): """ Subtract other from self, and return a new masked array. """ if self._delegate_binop(other): return NotImplemented return subtract(self, other) def __rsub__(self, other): """ Subtract self from other, and return a new masked array. """ return subtract(other, self) def __mul__(self, other): "Multiply self by other, and return a new masked array." if self._delegate_binop(other): return NotImplemented return multiply(self, other) def __rmul__(self, other): """ Multiply other by self, and return a new masked array. """ # In analogy with __rsub__ and __rdiv__, use original order: # we get here from `other * self`. return multiply(other, self) def __div__(self, other): """ Divide other into self, and return a new masked array. """ if self._delegate_binop(other): return NotImplemented return divide(self, other) def __truediv__(self, other): """ Divide other into self, and return a new masked array. """ if self._delegate_binop(other): return NotImplemented return true_divide(self, other) def __rtruediv__(self, other): """ Divide self into other, and return a new masked array. """ return true_divide(other, self) def __floordiv__(self, other): """ Divide other into self, and return a new masked array. """ if self._delegate_binop(other): return NotImplemented return floor_divide(self, other) def __rfloordiv__(self, other): """ Divide self into other, and return a new masked array. """ return floor_divide(other, self) def __pow__(self, other): """ Raise self to the power other, masking the potential NaNs/Infs """ if self._delegate_binop(other): return NotImplemented return power(self, other) def __rpow__(self, other): """ Raise other to the power self, masking the potential NaNs/Infs """ return power(other, self) def __iadd__(self, other): """ Add other to self in-place. """ m = getmask(other) if self._mask is nomask: if m is not nomask and m.any(): self._mask = make_mask_none(self.shape, self.dtype) self._mask += m else: if m is not nomask: self._mask += m other_data = getdata(other) other_data = np.where(self._mask, other_data.dtype.type(0), other_data) self._data.__iadd__(other_data) return self def __isub__(self, other): """ Subtract other from self in-place. """ m = getmask(other) if self._mask is nomask: if m is not nomask and m.any(): self._mask = make_mask_none(self.shape, self.dtype) self._mask += m elif m is not nomask: self._mask += m other_data = getdata(other) other_data = np.where(self._mask, other_data.dtype.type(0), other_data) self._data.__isub__(other_data) return self def __imul__(self, other): """ Multiply self by other in-place. """ m = getmask(other) if self._mask is nomask: if m is not nomask and m.any(): self._mask = make_mask_none(self.shape, self.dtype) self._mask += m elif m is not nomask: self._mask += m other_data = getdata(other) other_data = np.where(self._mask, other_data.dtype.type(1), other_data) self._data.__imul__(other_data) return self def __idiv__(self, other): """ Divide self by other in-place. """ other_data = getdata(other) dom_mask = _DomainSafeDivide().__call__(self._data, other_data) other_mask = getmask(other) new_mask = mask_or(other_mask, dom_mask) # The following 4 lines control the domain filling if dom_mask.any(): (_, fval) = ufunc_fills[np.divide] other_data = np.where( dom_mask, other_data.dtype.type(fval), other_data) self._mask |= new_mask other_data = np.where(self._mask, other_data.dtype.type(1), other_data) self._data.__idiv__(other_data) return self def __ifloordiv__(self, other): """ Floor divide self by other in-place. """ other_data = getdata(other) dom_mask = _DomainSafeDivide().__call__(self._data, other_data) other_mask = getmask(other) new_mask = mask_or(other_mask, dom_mask) # The following 3 lines control the domain filling if dom_mask.any(): (_, fval) = ufunc_fills[np.floor_divide] other_data = np.where( dom_mask, other_data.dtype.type(fval), other_data) self._mask |= new_mask other_data = np.where(self._mask, other_data.dtype.type(1), other_data) self._data.__ifloordiv__(other_data) return self def __itruediv__(self, other): """ True divide self by other in-place. """ other_data = getdata(other) dom_mask = _DomainSafeDivide().__call__(self._data, other_data) other_mask = getmask(other) new_mask = mask_or(other_mask, dom_mask) # The following 3 lines control the domain filling if dom_mask.any(): (_, fval) = ufunc_fills[np.true_divide] other_data = np.where( dom_mask, other_data.dtype.type(fval), other_data) self._mask |= new_mask other_data = np.where(self._mask, other_data.dtype.type(1), other_data) self._data.__itruediv__(other_data) return self def __ipow__(self, other): """ Raise self to the power other, in place. """ other_data = getdata(other) other_data = np.where(self._mask, other_data.dtype.type(1), other_data) other_mask = getmask(other) with np.errstate(divide='ignore', invalid='ignore'): self._data.__ipow__(other_data) invalid = np.logical_not(np.isfinite(self._data)) if invalid.any(): if self._mask is not nomask: self._mask |= invalid else: self._mask = invalid np.copyto(self._data, self.fill_value, where=invalid) new_mask = mask_or(other_mask, invalid) self._mask = mask_or(self._mask, new_mask) return self def __float__(self): """ Convert to float. """ if self.size > 1: raise TypeError("Only length-1 arrays can be converted " "to Python scalars") elif self._mask: warnings.warn("Warning: converting a masked element to nan.", stacklevel=2) return np.nan return float(self.item()) def __int__(self): """ Convert to int. """ if self.size > 1: raise TypeError("Only length-1 arrays can be converted " "to Python scalars") elif self._mask: raise MaskError('Cannot convert masked element to a Python int.') return int(self.item()) def imag(self): """ The imaginary part of the masked array. This property is a view on the imaginary part of this `MaskedArray`. See Also -------- real Examples -------- >>> x = np.ma.array([1+1.j, -2j, 3.45+1.6j], mask=[False, True, False]) >>> x.imag masked_array(data=[1.0, --, 1.6], mask=[False, True, False], fill_value=1e+20) """ result = self._data.imag.view(type(self)) result.__setmask__(self._mask) return result # kept for compatibility get_imag = imag.fget def real(self): """ The real part of the masked array. This property is a view on the real part of this `MaskedArray`. See Also -------- imag Examples -------- >>> x = np.ma.array([1+1.j, -2j, 3.45+1.6j], mask=[False, True, False]) >>> x.real masked_array(data=[1.0, --, 3.45], mask=[False, True, False], fill_value=1e+20) """ result = self._data.real.view(type(self)) result.__setmask__(self._mask) return result # kept for compatibility get_real = real.fget def count(self, axis=None, keepdims=np._NoValue): """ Count the non-masked elements of the array along the given axis. Parameters ---------- axis : None or int or tuple of ints, optional Axis or axes along which the count is performed. The default, None, performs the count over all the dimensions of the input array. `axis` may be negative, in which case it counts from the last to the first axis. .. versionadded:: 1.10.0 If this is a tuple of ints, the count is performed on multiple axes, instead of a single axis or all the axes as before. keepdims : bool, optional If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the array. Returns ------- result : ndarray or scalar An array with the same shape as the input array, with the specified axis removed. If the array is a 0-d array, or if `axis` is None, a scalar is returned. See Also -------- ma.count_masked : Count masked elements in array or along a given axis. Examples -------- >>> import numpy.ma as ma >>> a = ma.arange(6).reshape((2, 3)) >>> a[1, :] = ma.masked >>> a masked_array( data=[[0, 1, 2], [--, --, --]], mask=[[False, False, False], [ True, True, True]], fill_value=999999) >>> a.count() 3 When the `axis` keyword is specified an array of appropriate size is returned. >>> a.count(axis=0) array([1, 1, 1]) >>> a.count(axis=1) array([3, 0]) """ kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims} m = self._mask # special case for matrices (we assume no other subclasses modify # their dimensions) if isinstance(self.data, np.matrix): if m is nomask: m = np.zeros(self.shape, dtype=np.bool_) m = m.view(type(self.data)) if m is nomask: # compare to _count_reduce_items in _methods.py if self.shape == (): if axis not in (None, 0): raise np.AxisError(axis=axis, ndim=self.ndim) return 1 elif axis is None: if kwargs.get('keepdims', False): return np.array(self.size, dtype=np.intp, ndmin=self.ndim) return self.size axes = normalize_axis_tuple(axis, self.ndim) items = 1 for ax in axes: items *= self.shape[ax] if kwargs.get('keepdims', False): out_dims = list(self.shape) for a in axes: out_dims[a] = 1 else: out_dims = [d for n, d in enumerate(self.shape) if n not in axes] # make sure to return a 0-d array if axis is supplied return np.full(out_dims, items, dtype=np.intp) # take care of the masked singleton if self is masked: return 0 return (~m).sum(axis=axis, dtype=np.intp, **kwargs) def ravel(self, order='C'): """ Returns a 1D version of self, as a view. Parameters ---------- order : {'C', 'F', 'A', 'K'}, optional The elements of `a` are read using this index order. 'C' means to index the elements in C-like order, with the last axis index changing fastest, back to the first axis index changing slowest. 'F' means to index the elements in Fortran-like index order, with the first index changing fastest, and the last index changing slowest. Note that the 'C' and 'F' options take no account of the memory layout of the underlying array, and only refer to the order of axis indexing. 'A' means to read the elements in Fortran-like index order if `m` is Fortran *contiguous* in memory, C-like order otherwise. 'K' means to read the elements in the order they occur in memory, except for reversing the data when strides are negative. By default, 'C' index order is used. Returns ------- MaskedArray Output view is of shape ``(self.size,)`` (or ``(np.ma.product(self.shape),)``). Examples -------- >>> x = np.ma.array([[1,2,3],[4,5,6],[7,8,9]], mask=[0] + [1,0]*4) >>> x masked_array( data=[[1, --, 3], [--, 5, --], [7, --, 9]], mask=[[False, True, False], [ True, False, True], [False, True, False]], fill_value=999999) >>> x.ravel() masked_array(data=[1, --, 3, --, 5, --, 7, --, 9], mask=[False, True, False, True, False, True, False, True, False], fill_value=999999) """ r = ndarray.ravel(self._data, order=order).view(type(self)) r._update_from(self) if self._mask is not nomask: r._mask = ndarray.ravel(self._mask, order=order).reshape(r.shape) else: r._mask = nomask return r def reshape(self, *s, **kwargs): """ Give a new shape to the array without changing its data. Returns a masked array containing the same data, but with a new shape. The result is a view on the original array; if this is not possible, a ValueError is raised. Parameters ---------- shape : int or tuple of ints The new shape should be compatible with the original shape. If an integer is supplied, then the result will be a 1-D array of that length. order : {'C', 'F'}, optional Determines whether the array data should be viewed as in C (row-major) or FORTRAN (column-major) order. Returns ------- reshaped_array : array A new view on the array. See Also -------- reshape : Equivalent function in the masked array module. numpy.ndarray.reshape : Equivalent method on ndarray object. numpy.reshape : Equivalent function in the NumPy module. Notes ----- The reshaping operation cannot guarantee that a copy will not be made, to modify the shape in place, use ``a.shape = s`` Examples -------- >>> x = np.ma.array([[1,2],[3,4]], mask=[1,0,0,1]) >>> x masked_array( data=[[--, 2], [3, --]], mask=[[ True, False], [False, True]], fill_value=999999) >>> x = x.reshape((4,1)) >>> x masked_array( data=[[--], [2], [3], [--]], mask=[[ True], [False], [False], [ True]], fill_value=999999) """ kwargs.update(order=kwargs.get('order', 'C')) result = self._data.reshape(*s, **kwargs).view(type(self)) result._update_from(self) mask = self._mask if mask is not nomask: result._mask = mask.reshape(*s, **kwargs) return result def resize(self, newshape, refcheck=True, order=False): """ .. warning:: This method does nothing, except raise a ValueError exception. A masked array does not own its data and therefore cannot safely be resized in place. Use the `numpy.ma.resize` function instead. This method is difficult to implement safely and may be deprecated in future releases of NumPy. """ # Note : the 'order' keyword looks broken, let's just drop it errmsg = "A masked array does not own its data "\ "and therefore cannot be resized.\n" \ "Use the numpy.ma.resize function instead." raise ValueError(errmsg) def put(self, indices, values, mode='raise'): """ Set storage-indexed locations to corresponding values. Sets self._data.flat[n] = values[n] for each n in indices. If `values` is shorter than `indices` then it will repeat. If `values` has some masked values, the initial mask is updated in consequence, else the corresponding values are unmasked. Parameters ---------- indices : 1-D array_like Target indices, interpreted as integers. values : array_like Values to place in self._data copy at target indices. mode : {'raise', 'wrap', 'clip'}, optional Specifies how out-of-bounds indices will behave. 'raise' : raise an error. 'wrap' : wrap around. 'clip' : clip to the range. Notes ----- `values` can be a scalar or length 1 array. Examples -------- >>> x = np.ma.array([[1,2,3],[4,5,6],[7,8,9]], mask=[0] + [1,0]*4) >>> x masked_array( data=[[1, --, 3], [--, 5, --], [7, --, 9]], mask=[[False, True, False], [ True, False, True], [False, True, False]], fill_value=999999) >>> x.put([0,4,8],[10,20,30]) >>> x masked_array( data=[[10, --, 3], [--, 20, --], [7, --, 30]], mask=[[False, True, False], [ True, False, True], [False, True, False]], fill_value=999999) >>> x.put(4,999) >>> x masked_array( data=[[10, --, 3], [--, 999, --], [7, --, 30]], mask=[[False, True, False], [ True, False, True], [False, True, False]], fill_value=999999) """ # Hard mask: Get rid of the values/indices that fall on masked data if self._hardmask and self._mask is not nomask: mask = self._mask[indices] indices = narray(indices, copy=False) values = narray(values, copy=False, subok=True) values.resize(indices.shape) indices = indices[~mask] values = values[~mask] self._data.put(indices, values, mode=mode) # short circuit if neither self nor values are masked if self._mask is nomask and getmask(values) is nomask: return m = getmaskarray(self) if getmask(values) is nomask: m.put(indices, False, mode=mode) else: m.put(indices, values._mask, mode=mode) m = make_mask(m, copy=False, shrink=True) self._mask = m return def ids(self): """ Return the addresses of the data and mask areas. Parameters ---------- None Examples -------- >>> x = np.ma.array([1, 2, 3], mask=[0, 1, 1]) >>> x.ids() (166670640, 166659832) # may vary If the array has no mask, the address of `nomask` is returned. This address is typically not close to the data in memory: >>> x = np.ma.array([1, 2, 3]) >>> x.ids() (166691080, 3083169284) # may vary """ if self._mask is nomask: return (self.ctypes.data, id(nomask)) return (self.ctypes.data, self._mask.ctypes.data) def iscontiguous(self): """ Return a boolean indicating whether the data is contiguous. Parameters ---------- None Examples -------- >>> x = np.ma.array([1, 2, 3]) >>> x.iscontiguous() True `iscontiguous` returns one of the flags of the masked array: >>> x.flags C_CONTIGUOUS : True F_CONTIGUOUS : True OWNDATA : False WRITEABLE : True ALIGNED : True WRITEBACKIFCOPY : False """ return self.flags['CONTIGUOUS'] def all(self, axis=None, out=None, keepdims=np._NoValue): """ Returns True if all elements evaluate to True. The output array is masked where all the values along the given axis are masked: if the output would have been a scalar and that all the values are masked, then the output is `masked`. Refer to `numpy.all` for full documentation. See Also -------- numpy.ndarray.all : corresponding function for ndarrays numpy.all : equivalent function Examples -------- >>> np.ma.array([1,2,3]).all() True >>> a = np.ma.array([1,2,3], mask=True) >>> (a.all() is np.ma.masked) True """ kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims} mask = _check_mask_axis(self._mask, axis, **kwargs) if out is None: d = self.filled(True).all(axis=axis, **kwargs).view(type(self)) if d.ndim: d.__setmask__(mask) elif mask: return masked return d self.filled(True).all(axis=axis, out=out, **kwargs) if isinstance(out, MaskedArray): if out.ndim or mask: out.__setmask__(mask) return out def any(self, axis=None, out=None, keepdims=np._NoValue): """ Returns True if any of the elements of `a` evaluate to True. Masked values are considered as False during computation. Refer to `numpy.any` for full documentation. See Also -------- numpy.ndarray.any : corresponding function for ndarrays numpy.any : equivalent function """ kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims} mask = _check_mask_axis(self._mask, axis, **kwargs) if out is None: d = self.filled(False).any(axis=axis, **kwargs).view(type(self)) if d.ndim: d.__setmask__(mask) elif mask: d = masked return d self.filled(False).any(axis=axis, out=out, **kwargs) if isinstance(out, MaskedArray): if out.ndim or mask: out.__setmask__(mask) return out def nonzero(self): """ Return the indices of unmasked elements that are not zero. Returns a tuple of arrays, one for each dimension, containing the indices of the non-zero elements in that dimension. The corresponding non-zero values can be obtained with:: a[a.nonzero()] To group the indices by element, rather than dimension, use instead:: np.transpose(a.nonzero()) The result of this is always a 2d array, with a row for each non-zero element. Parameters ---------- None Returns ------- tuple_of_arrays : tuple Indices of elements that are non-zero. See Also -------- numpy.nonzero : Function operating on ndarrays. flatnonzero : Return indices that are non-zero in the flattened version of the input array. numpy.ndarray.nonzero : Equivalent ndarray method. count_nonzero : Counts the number of non-zero elements in the input array. Examples -------- >>> import numpy.ma as ma >>> x = ma.array(np.eye(3)) >>> x masked_array( data=[[1., 0., 0.], [0., 1., 0.], [0., 0., 1.]], mask=False, fill_value=1e+20) >>> x.nonzero() (array([0, 1, 2]), array([0, 1, 2])) Masked elements are ignored. >>> x[1, 1] = ma.masked >>> x masked_array( data=[[1.0, 0.0, 0.0], [0.0, --, 0.0], [0.0, 0.0, 1.0]], mask=[[False, False, False], [False, True, False], [False, False, False]], fill_value=1e+20) >>> x.nonzero() (array([0, 2]), array([0, 2])) Indices can also be grouped by element. >>> np.transpose(x.nonzero()) array([[0, 0], [2, 2]]) A common use for ``nonzero`` is to find the indices of an array, where a condition is True. Given an array `a`, the condition `a` > 3 is a boolean array and since False is interpreted as 0, ma.nonzero(a > 3) yields the indices of the `a` where the condition is true. >>> a = ma.array([[1,2,3],[4,5,6],[7,8,9]]) >>> a > 3 masked_array( data=[[False, False, False], [ True, True, True], [ True, True, True]], mask=False, fill_value=True) >>> ma.nonzero(a > 3) (array([1, 1, 1, 2, 2, 2]), array([0, 1, 2, 0, 1, 2])) The ``nonzero`` method of the condition array can also be called. >>> (a > 3).nonzero() (array([1, 1, 1, 2, 2, 2]), array([0, 1, 2, 0, 1, 2])) """ return narray(self.filled(0), copy=False).nonzero() def trace(self, offset=0, axis1=0, axis2=1, dtype=None, out=None): """ (this docstring should be overwritten) """ #!!!: implement out + test! m = self._mask if m is nomask: result = super().trace(offset=offset, axis1=axis1, axis2=axis2, out=out) return result.astype(dtype) else: D = self.diagonal(offset=offset, axis1=axis1, axis2=axis2) return D.astype(dtype).filled(0).sum(axis=-1, out=out) trace.__doc__ = ndarray.trace.__doc__ def dot(self, b, out=None, strict=False): """ a.dot(b, out=None) Masked dot product of two arrays. Note that `out` and `strict` are located in different positions than in `ma.dot`. In order to maintain compatibility with the functional version, it is recommended that the optional arguments be treated as keyword only. At some point that may be mandatory. .. versionadded:: 1.10.0 Parameters ---------- b : masked_array_like Inputs array. out : masked_array, optional Output argument. This must have the exact kind that would be returned if it was not used. In particular, it must have the right type, must be C-contiguous, and its dtype must be the dtype that would be returned for `ma.dot(a,b)`. This is a performance feature. Therefore, if these conditions are not met, an exception is raised, instead of attempting to be flexible. strict : bool, optional Whether masked data are propagated (True) or set to 0 (False) for the computation. Default is False. Propagating the mask means that if a masked value appears in a row or column, the whole row or column is considered masked. .. versionadded:: 1.10.2 See Also -------- numpy.ma.dot : equivalent function """ return dot(self, b, out=out, strict=strict) def sum(self, axis=None, dtype=None, out=None, keepdims=np._NoValue): """ Return the sum of the array elements over the given axis. Masked elements are set to 0 internally. Refer to `numpy.sum` for full documentation. See Also -------- numpy.ndarray.sum : corresponding function for ndarrays numpy.sum : equivalent function Examples -------- >>> x = np.ma.array([[1,2,3],[4,5,6],[7,8,9]], mask=[0] + [1,0]*4) >>> x masked_array( data=[[1, --, 3], [--, 5, --], [7, --, 9]], mask=[[False, True, False], [ True, False, True], [False, True, False]], fill_value=999999) >>> x.sum() 25 >>> x.sum(axis=1) masked_array(data=[4, 5, 16], mask=[False, False, False], fill_value=999999) >>> x.sum(axis=0) masked_array(data=[8, 5, 12], mask=[False, False, False], fill_value=999999) >>> print(type(x.sum(axis=0, dtype=np.int64)[0])) <class 'numpy.int64'> """ kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims} _mask = self._mask newmask = _check_mask_axis(_mask, axis, **kwargs) # No explicit output if out is None: result = self.filled(0).sum(axis, dtype=dtype, **kwargs) rndim = getattr(result, 'ndim', 0) if rndim: result = result.view(type(self)) result.__setmask__(newmask) elif newmask: result = masked return result # Explicit output result = self.filled(0).sum(axis, dtype=dtype, out=out, **kwargs) if isinstance(out, MaskedArray): outmask = getmask(out) if outmask is nomask: outmask = out._mask = make_mask_none(out.shape) outmask.flat = newmask return out def cumsum(self, axis=None, dtype=None, out=None): """ Return the cumulative sum of the array elements over the given axis. Masked values are set to 0 internally during the computation. However, their position is saved, and the result will be masked at the same locations. Refer to `numpy.cumsum` for full documentation. Notes ----- The mask is lost if `out` is not a valid :class:`ma.MaskedArray` ! Arithmetic is modular when using integer types, and no error is raised on overflow. See Also -------- numpy.ndarray.cumsum : corresponding function for ndarrays numpy.cumsum : equivalent function Examples -------- >>> marr = np.ma.array(np.arange(10), mask=[0,0,0,1,1,1,0,0,0,0]) >>> marr.cumsum() masked_array(data=[0, 1, 3, --, --, --, 9, 16, 24, 33], mask=[False, False, False, True, True, True, False, False, False, False], fill_value=999999) """ result = self.filled(0).cumsum(axis=axis, dtype=dtype, out=out) if out is not None: if isinstance(out, MaskedArray): out.__setmask__(self.mask) return out result = result.view(type(self)) result.__setmask__(self._mask) return result def prod(self, axis=None, dtype=None, out=None, keepdims=np._NoValue): """ Return the product of the array elements over the given axis. Masked elements are set to 1 internally for computation. Refer to `numpy.prod` for full documentation. Notes ----- Arithmetic is modular when using integer types, and no error is raised on overflow. See Also -------- numpy.ndarray.prod : corresponding function for ndarrays numpy.prod : equivalent function """ kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims} _mask = self._mask newmask = _check_mask_axis(_mask, axis, **kwargs) # No explicit output if out is None: result = self.filled(1).prod(axis, dtype=dtype, **kwargs) rndim = getattr(result, 'ndim', 0) if rndim: result = result.view(type(self)) result.__setmask__(newmask) elif newmask: result = masked return result # Explicit output result = self.filled(1).prod(axis, dtype=dtype, out=out, **kwargs) if isinstance(out, MaskedArray): outmask = getmask(out) if outmask is nomask: outmask = out._mask = make_mask_none(out.shape) outmask.flat = newmask return out product = prod def cumprod(self, axis=None, dtype=None, out=None): """ Return the cumulative product of the array elements over the given axis. Masked values are set to 1 internally during the computation. However, their position is saved, and the result will be masked at the same locations. Refer to `numpy.cumprod` for full documentation. Notes ----- The mask is lost if `out` is not a valid MaskedArray ! Arithmetic is modular when using integer types, and no error is raised on overflow. See Also -------- numpy.ndarray.cumprod : corresponding function for ndarrays numpy.cumprod : equivalent function """ result = self.filled(1).cumprod(axis=axis, dtype=dtype, out=out) if out is not None: if isinstance(out, MaskedArray): out.__setmask__(self._mask) return out result = result.view(type(self)) result.__setmask__(self._mask) return result def mean(self, axis=None, dtype=None, out=None, keepdims=np._NoValue): """ Returns the average of the array elements along given axis. Masked entries are ignored, and result elements which are not finite will be masked. Refer to `numpy.mean` for full documentation. See Also -------- numpy.ndarray.mean : corresponding function for ndarrays numpy.mean : Equivalent function numpy.ma.average : Weighted average. Examples -------- >>> a = np.ma.array([1,2,3], mask=[False, False, True]) >>> a masked_array(data=[1, 2, --], mask=[False, False, True], fill_value=999999) >>> a.mean() 1.5 """ kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims} if self._mask is nomask: result = super().mean(axis=axis, dtype=dtype, **kwargs)[()] else: is_float16_result = False if dtype is None: if issubclass(self.dtype.type, (ntypes.integer, ntypes.bool_)): dtype = mu.dtype('f8') elif issubclass(self.dtype.type, ntypes.float16): dtype = mu.dtype('f4') is_float16_result = True dsum = self.sum(axis=axis, dtype=dtype, **kwargs) cnt = self.count(axis=axis, **kwargs) if cnt.shape == () and (cnt == 0): result = masked elif is_float16_result: result = self.dtype.type(dsum * 1. / cnt) else: result = dsum * 1. / cnt if out is not None: out.flat = result if isinstance(out, MaskedArray): outmask = getmask(out) if outmask is nomask: outmask = out._mask = make_mask_none(out.shape) outmask.flat = getmask(result) return out return result def anom(self, axis=None, dtype=None): """ Compute the anomalies (deviations from the arithmetic mean) along the given axis. Returns an array of anomalies, with the same shape as the input and where the arithmetic mean is computed along the given axis. Parameters ---------- axis : int, optional Axis over which the anomalies are taken. The default is to use the mean of the flattened array as reference. dtype : dtype, optional Type to use in computing the variance. For arrays of integer type the default is float32; for arrays of float types it is the same as the array type. See Also -------- mean : Compute the mean of the array. Examples -------- >>> a = np.ma.array([1,2,3]) >>> a.anom() masked_array(data=[-1., 0., 1.], mask=False, fill_value=1e+20) """ m = self.mean(axis, dtype) if not axis: return self - m else: return self - expand_dims(m, axis) def var(self, axis=None, dtype=None, out=None, ddof=0, keepdims=np._NoValue): """ Returns the variance of the array elements along given axis. Masked entries are ignored, and result elements which are not finite will be masked. Refer to `numpy.var` for full documentation. See Also -------- numpy.ndarray.var : corresponding function for ndarrays numpy.var : Equivalent function """ kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims} # Easy case: nomask, business as usual if self._mask is nomask: ret = super().var(axis=axis, dtype=dtype, out=out, ddof=ddof, **kwargs)[()] if out is not None: if isinstance(out, MaskedArray): out.__setmask__(nomask) return out return ret # Some data are masked, yay! cnt = self.count(axis=axis, **kwargs) - ddof danom = self - self.mean(axis, dtype, keepdims=True) if iscomplexobj(self): danom = umath.absolute(danom) ** 2 else: danom *= danom dvar = divide(danom.sum(axis, **kwargs), cnt).view(type(self)) # Apply the mask if it's not a scalar if dvar.ndim: dvar._mask = mask_or(self._mask.all(axis, **kwargs), (cnt <= 0)) dvar._update_from(self) elif getmask(dvar): # Make sure that masked is returned when the scalar is masked. dvar = masked if out is not None: if isinstance(out, MaskedArray): out.flat = 0 out.__setmask__(True) elif out.dtype.kind in 'biu': errmsg = "Masked data information would be lost in one or "\ "more location." raise MaskError(errmsg) else: out.flat = np.nan return out # In case with have an explicit output if out is not None: # Set the data out.flat = dvar # Set the mask if needed if isinstance(out, MaskedArray): out.__setmask__(dvar.mask) return out return dvar var.__doc__ = np.var.__doc__ def std(self, axis=None, dtype=None, out=None, ddof=0, keepdims=np._NoValue): """ Returns the standard deviation of the array elements along given axis. Masked entries are ignored. Refer to `numpy.std` for full documentation. See Also -------- numpy.ndarray.std : corresponding function for ndarrays numpy.std : Equivalent function """ kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims} dvar = self.var(axis, dtype, out, ddof, **kwargs) if dvar is not masked: if out is not None: np.power(out, 0.5, out=out, casting='unsafe') return out dvar = sqrt(dvar) return dvar def round(self, decimals=0, out=None): """ Return each element rounded to the given number of decimals. Refer to `numpy.around` for full documentation. See Also -------- numpy.ndarray.round : corresponding function for ndarrays numpy.around : equivalent function """ result = self._data.round(decimals=decimals, out=out).view(type(self)) if result.ndim > 0: result._mask = self._mask result._update_from(self) elif self._mask: # Return masked when the scalar is masked result = masked # No explicit output: we're done if out is None: return result if isinstance(out, MaskedArray): out.__setmask__(self._mask) return out def argsort(self, axis=np._NoValue, kind=None, order=None, endwith=True, fill_value=None): """ Return an ndarray of indices that sort the array along the specified axis. Masked values are filled beforehand to `fill_value`. Parameters ---------- axis : int, optional Axis along which to sort. If None, the default, the flattened array is used. .. versionchanged:: 1.13.0 Previously, the default was documented to be -1, but that was in error. At some future date, the default will change to -1, as originally intended. Until then, the axis should be given explicitly when ``arr.ndim > 1``, to avoid a FutureWarning. kind : {'quicksort', 'mergesort', 'heapsort', 'stable'}, optional The sorting algorithm used. order : list, optional When `a` is an array with fields defined, this argument specifies which fields to compare first, second, etc. Not all fields need be specified. endwith : {True, False}, optional Whether missing values (if any) should be treated as the largest values (True) or the smallest values (False) When the array contains unmasked values at the same extremes of the datatype, the ordering of these values and the masked values is undefined. fill_value : scalar or None, optional Value used internally for the masked values. If ``fill_value`` is not None, it supersedes ``endwith``. Returns ------- index_array : ndarray, int Array of indices that sort `a` along the specified axis. In other words, ``a[index_array]`` yields a sorted `a`. See Also -------- ma.MaskedArray.sort : Describes sorting algorithms used. lexsort : Indirect stable sort with multiple keys. numpy.ndarray.sort : Inplace sort. Notes ----- See `sort` for notes on the different sorting algorithms. Examples -------- >>> a = np.ma.array([3,2,1], mask=[False, False, True]) >>> a masked_array(data=[3, 2, --], mask=[False, False, True], fill_value=999999) >>> a.argsort() array([1, 0, 2]) """ # 2017-04-11, Numpy 1.13.0, gh-8701: warn on axis default if axis is np._NoValue: axis = _deprecate_argsort_axis(self) if fill_value is None: if endwith: # nan > inf if np.issubdtype(self.dtype, np.floating): fill_value = np.nan else: fill_value = minimum_fill_value(self) else: fill_value = maximum_fill_value(self) filled = self.filled(fill_value) return filled.argsort(axis=axis, kind=kind, order=order) def argmin(self, axis=None, fill_value=None, out=None, *, keepdims=np._NoValue): """ Return array of indices to the minimum values along the given axis. Parameters ---------- axis : {None, integer} If None, the index is into the flattened array, otherwise along the specified axis fill_value : scalar or None, optional Value used to fill in the masked values. If None, the output of minimum_fill_value(self._data) is used instead. out : {None, array}, optional Array into which the result can be placed. Its type is preserved and it must be of the right shape to hold the output. Returns ------- ndarray or scalar If multi-dimension input, returns a new ndarray of indices to the minimum values along the given axis. Otherwise, returns a scalar of index to the minimum values along the given axis. Examples -------- >>> x = np.ma.array(np.arange(4), mask=[1,1,0,0]) >>> x.shape = (2,2) >>> x masked_array( data=[[--, --], [2, 3]], mask=[[ True, True], [False, False]], fill_value=999999) >>> x.argmin(axis=0, fill_value=-1) array([0, 0]) >>> x.argmin(axis=0, fill_value=9) array([1, 1]) """ if fill_value is None: fill_value = minimum_fill_value(self) d = self.filled(fill_value).view(ndarray) keepdims = False if keepdims is np._NoValue else bool(keepdims) return d.argmin(axis, out=out, keepdims=keepdims) def argmax(self, axis=None, fill_value=None, out=None, *, keepdims=np._NoValue): """ Returns array of indices of the maximum values along the given axis. Masked values are treated as if they had the value fill_value. Parameters ---------- axis : {None, integer} If None, the index is into the flattened array, otherwise along the specified axis fill_value : scalar or None, optional Value used to fill in the masked values. If None, the output of maximum_fill_value(self._data) is used instead. out : {None, array}, optional Array into which the result can be placed. Its type is preserved and it must be of the right shape to hold the output. Returns ------- index_array : {integer_array} Examples -------- >>> a = np.arange(6).reshape(2,3) >>> a.argmax() 5 >>> a.argmax(0) array([1, 1, 1]) >>> a.argmax(1) array([2, 2]) """ if fill_value is None: fill_value = maximum_fill_value(self._data) d = self.filled(fill_value).view(ndarray) keepdims = False if keepdims is np._NoValue else bool(keepdims) return d.argmax(axis, out=out, keepdims=keepdims) def sort(self, axis=-1, kind=None, order=None, endwith=True, fill_value=None): """ Sort the array, in-place Parameters ---------- a : array_like Array to be sorted. axis : int, optional Axis along which to sort. If None, the array is flattened before sorting. The default is -1, which sorts along the last axis. kind : {'quicksort', 'mergesort', 'heapsort', 'stable'}, optional The sorting algorithm used. order : list, optional When `a` is a structured array, this argument specifies which fields to compare first, second, and so on. This list does not need to include all of the fields. endwith : {True, False}, optional Whether missing values (if any) should be treated as the largest values (True) or the smallest values (False) When the array contains unmasked values sorting at the same extremes of the datatype, the ordering of these values and the masked values is undefined. fill_value : scalar or None, optional Value used internally for the masked values. If ``fill_value`` is not None, it supersedes ``endwith``. Returns ------- sorted_array : ndarray Array of the same type and shape as `a`. See Also -------- numpy.ndarray.sort : Method to sort an array in-place. argsort : Indirect sort. lexsort : Indirect stable sort on multiple keys. searchsorted : Find elements in a sorted array. Notes ----- See ``sort`` for notes on the different sorting algorithms. Examples -------- >>> a = np.ma.array([1, 2, 5, 4, 3],mask=[0, 1, 0, 1, 0]) >>> # Default >>> a.sort() >>> a masked_array(data=[1, 3, 5, --, --], mask=[False, False, False, True, True], fill_value=999999) >>> a = np.ma.array([1, 2, 5, 4, 3],mask=[0, 1, 0, 1, 0]) >>> # Put missing values in the front >>> a.sort(endwith=False) >>> a masked_array(data=[--, --, 1, 3, 5], mask=[ True, True, False, False, False], fill_value=999999) >>> a = np.ma.array([1, 2, 5, 4, 3],mask=[0, 1, 0, 1, 0]) >>> # fill_value takes over endwith >>> a.sort(endwith=False, fill_value=3) >>> a masked_array(data=[1, --, --, 3, 5], mask=[False, True, True, False, False], fill_value=999999) """ if self._mask is nomask: ndarray.sort(self, axis=axis, kind=kind, order=order) return if self is masked: return sidx = self.argsort(axis=axis, kind=kind, order=order, fill_value=fill_value, endwith=endwith) self[...] = np.take_along_axis(self, sidx, axis=axis) def min(self, axis=None, out=None, fill_value=None, keepdims=np._NoValue): """ Return the minimum along a given axis. Parameters ---------- axis : None or int or tuple of ints, optional Axis along which to operate. By default, ``axis`` is None and the flattened input is used. .. versionadded:: 1.7.0 If this is a tuple of ints, the minimum is selected over multiple axes, instead of a single axis or all the axes as before. out : array_like, optional Alternative output array in which to place the result. Must be of the same shape and buffer length as the expected output. fill_value : scalar or None, optional Value used to fill in the masked values. If None, use the output of `minimum_fill_value`. keepdims : bool, optional If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the array. Returns ------- amin : array_like New array holding the result. If ``out`` was specified, ``out`` is returned. See Also -------- ma.minimum_fill_value Returns the minimum filling value for a given datatype. Examples -------- >>> import numpy.ma as ma >>> x = [[1., -2., 3.], [0.2, -0.7, 0.1]] >>> mask = [[1, 1, 0], [0, 0, 1]] >>> masked_x = ma.masked_array(x, mask) >>> masked_x masked_array( data=[[--, --, 3.0], [0.2, -0.7, --]], mask=[[ True, True, False], [False, False, True]], fill_value=1e+20) >>> ma.min(masked_x) -0.7 >>> ma.min(masked_x, axis=-1) masked_array(data=[3.0, -0.7], mask=[False, False], fill_value=1e+20) >>> ma.min(masked_x, axis=0, keepdims=True) masked_array(data=[[0.2, -0.7, 3.0]], mask=[[False, False, False]], fill_value=1e+20) >>> mask = [[1, 1, 1,], [1, 1, 1]] >>> masked_x = ma.masked_array(x, mask) >>> ma.min(masked_x, axis=0) masked_array(data=[--, --, --], mask=[ True, True, True], fill_value=1e+20, dtype=float64) """ kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims} _mask = self._mask newmask = _check_mask_axis(_mask, axis, **kwargs) if fill_value is None: fill_value = minimum_fill_value(self) # No explicit output if out is None: result = self.filled(fill_value).min( axis=axis, out=out, **kwargs).view(type(self)) if result.ndim: # Set the mask result.__setmask__(newmask) # Get rid of Infs if newmask.ndim: np.copyto(result, result.fill_value, where=newmask) elif newmask: result = masked return result # Explicit output result = self.filled(fill_value).min(axis=axis, out=out, **kwargs) if isinstance(out, MaskedArray): outmask = getmask(out) if outmask is nomask: outmask = out._mask = make_mask_none(out.shape) outmask.flat = newmask else: if out.dtype.kind in 'biu': errmsg = "Masked data information would be lost in one or more"\ " location." raise MaskError(errmsg) np.copyto(out, np.nan, where=newmask) return out def max(self, axis=None, out=None, fill_value=None, keepdims=np._NoValue): """ Return the maximum along a given axis. Parameters ---------- axis : None or int or tuple of ints, optional Axis along which to operate. By default, ``axis`` is None and the flattened input is used. .. versionadded:: 1.7.0 If this is a tuple of ints, the maximum is selected over multiple axes, instead of a single axis or all the axes as before. out : array_like, optional Alternative output array in which to place the result. Must be of the same shape and buffer length as the expected output. fill_value : scalar or None, optional Value used to fill in the masked values. If None, use the output of maximum_fill_value(). keepdims : bool, optional If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the array. Returns ------- amax : array_like New array holding the result. If ``out`` was specified, ``out`` is returned. See Also -------- ma.maximum_fill_value Returns the maximum filling value for a given datatype. Examples -------- >>> import numpy.ma as ma >>> x = [[-1., 2.5], [4., -2.], [3., 0.]] >>> mask = [[0, 0], [1, 0], [1, 0]] >>> masked_x = ma.masked_array(x, mask) >>> masked_x masked_array( data=[[-1.0, 2.5], [--, -2.0], [--, 0.0]], mask=[[False, False], [ True, False], [ True, False]], fill_value=1e+20) >>> ma.max(masked_x) 2.5 >>> ma.max(masked_x, axis=0) masked_array(data=[-1.0, 2.5], mask=[False, False], fill_value=1e+20) >>> ma.max(masked_x, axis=1, keepdims=True) masked_array( data=[[2.5], [-2.0], [0.0]], mask=[[False], [False], [False]], fill_value=1e+20) >>> mask = [[1, 1], [1, 1], [1, 1]] >>> masked_x = ma.masked_array(x, mask) >>> ma.max(masked_x, axis=1) masked_array(data=[--, --, --], mask=[ True, True, True], fill_value=1e+20, dtype=float64) """ kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims} _mask = self._mask newmask = _check_mask_axis(_mask, axis, **kwargs) if fill_value is None: fill_value = maximum_fill_value(self) # No explicit output if out is None: result = self.filled(fill_value).max( axis=axis, out=out, **kwargs).view(type(self)) if result.ndim: # Set the mask result.__setmask__(newmask) # Get rid of Infs if newmask.ndim: np.copyto(result, result.fill_value, where=newmask) elif newmask: result = masked return result # Explicit output result = self.filled(fill_value).max(axis=axis, out=out, **kwargs) if isinstance(out, MaskedArray): outmask = getmask(out) if outmask is nomask: outmask = out._mask = make_mask_none(out.shape) outmask.flat = newmask else: if out.dtype.kind in 'biu': errmsg = "Masked data information would be lost in one or more"\ " location." raise MaskError(errmsg) np.copyto(out, np.nan, where=newmask) return out def ptp(self, axis=None, out=None, fill_value=None, keepdims=False): """ Return (maximum - minimum) along the given dimension (i.e. peak-to-peak value). .. warning:: `ptp` preserves the data type of the array. This means the return value for an input of signed integers with n bits (e.g. `np.int8`, `np.int16`, etc) is also a signed integer with n bits. In that case, peak-to-peak values greater than ``2**(n-1)-1`` will be returned as negative values. An example with a work-around is shown below. Parameters ---------- axis : {None, int}, optional Axis along which to find the peaks. If None (default) the flattened array is used. out : {None, array_like}, optional Alternative output array in which to place the result. It must have the same shape and buffer length as the expected output but the type will be cast if necessary. fill_value : scalar or None, optional Value used to fill in the masked values. keepdims : bool, optional If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the array. Returns ------- ptp : ndarray. A new array holding the result, unless ``out`` was specified, in which case a reference to ``out`` is returned. Examples -------- >>> x = np.ma.MaskedArray([[4, 9, 2, 10], ... [6, 9, 7, 12]]) >>> x.ptp(axis=1) masked_array(data=[8, 6], mask=False, fill_value=999999) >>> x.ptp(axis=0) masked_array(data=[2, 0, 5, 2], mask=False, fill_value=999999) >>> x.ptp() 10 This example shows that a negative value can be returned when the input is an array of signed integers. >>> y = np.ma.MaskedArray([[1, 127], ... [0, 127], ... [-1, 127], ... [-2, 127]], dtype=np.int8) >>> y.ptp(axis=1) masked_array(data=[ 126, 127, -128, -127], mask=False, fill_value=999999, dtype=int8) A work-around is to use the `view()` method to view the result as unsigned integers with the same bit width: >>> y.ptp(axis=1).view(np.uint8) masked_array(data=[126, 127, 128, 129], mask=False, fill_value=999999, dtype=uint8) """ if out is None: result = self.max(axis=axis, fill_value=fill_value, keepdims=keepdims) result -= self.min(axis=axis, fill_value=fill_value, keepdims=keepdims) return result out.flat = self.max(axis=axis, out=out, fill_value=fill_value, keepdims=keepdims) min_value = self.min(axis=axis, fill_value=fill_value, keepdims=keepdims) np.subtract(out, min_value, out=out, casting='unsafe') return out def partition(self, *args, **kwargs): warnings.warn("Warning: 'partition' will ignore the 'mask' " f"of the {self.__class__.__name__}.", stacklevel=2) return super().partition(*args, **kwargs) def argpartition(self, *args, **kwargs): warnings.warn("Warning: 'argpartition' will ignore the 'mask' " f"of the {self.__class__.__name__}.", stacklevel=2) return super().argpartition(*args, **kwargs) def take(self, indices, axis=None, out=None, mode='raise'): """ """ (_data, _mask) = (self._data, self._mask) cls = type(self) # Make sure the indices are not masked maskindices = getmask(indices) if maskindices is not nomask: indices = indices.filled(0) # Get the data, promoting scalars to 0d arrays with [...] so that # .view works correctly if out is None: out = _data.take(indices, axis=axis, mode=mode)[...].view(cls) else: np.take(_data, indices, axis=axis, mode=mode, out=out) # Get the mask if isinstance(out, MaskedArray): if _mask is nomask: outmask = maskindices else: outmask = _mask.take(indices, axis=axis, mode=mode) outmask |= maskindices out.__setmask__(outmask) # demote 0d arrays back to scalars, for consistency with ndarray.take return out[()] # Array methods copy = _arraymethod('copy') diagonal = _arraymethod('diagonal') flatten = _arraymethod('flatten') repeat = _arraymethod('repeat') squeeze = _arraymethod('squeeze') swapaxes = _arraymethod('swapaxes') T = property(fget=lambda self: self.transpose()) transpose = _arraymethod('transpose') def tolist(self, fill_value=None): """ Return the data portion of the masked array as a hierarchical Python list. Data items are converted to the nearest compatible Python type. Masked values are converted to `fill_value`. If `fill_value` is None, the corresponding entries in the output list will be ``None``. Parameters ---------- fill_value : scalar, optional The value to use for invalid entries. Default is None. Returns ------- result : list The Python list representation of the masked array. Examples -------- >>> x = np.ma.array([[1,2,3], [4,5,6], [7,8,9]], mask=[0] + [1,0]*4) >>> x.tolist() [[1, None, 3], [None, 5, None], [7, None, 9]] >>> x.tolist(-999) [[1, -999, 3], [-999, 5, -999], [7, -999, 9]] """ _mask = self._mask # No mask ? Just return .data.tolist ? if _mask is nomask: return self._data.tolist() # Explicit fill_value: fill the array and get the list if fill_value is not None: return self.filled(fill_value).tolist() # Structured array. names = self.dtype.names if names: result = self._data.astype([(_, object) for _ in names]) for n in names: result[n][_mask[n]] = None return result.tolist() # Standard arrays. if _mask is nomask: return [None] # Set temps to save time when dealing w/ marrays. inishape = self.shape result = np.array(self._data.ravel(), dtype=object) result[_mask.ravel()] = None result.shape = inishape return result.tolist() def tostring(self, fill_value=None, order='C'): r""" A compatibility alias for `tobytes`, with exactly the same behavior. Despite its name, it returns `bytes` not `str`\ s. .. deprecated:: 1.19.0 """ # 2020-03-30, Numpy 1.19.0 warnings.warn( "tostring() is deprecated. Use tobytes() instead.", DeprecationWarning, stacklevel=2) return self.tobytes(fill_value, order=order) def tobytes(self, fill_value=None, order='C'): """ Return the array data as a string containing the raw bytes in the array. The array is filled with a fill value before the string conversion. .. versionadded:: 1.9.0 Parameters ---------- fill_value : scalar, optional Value used to fill in the masked values. Default is None, in which case `MaskedArray.fill_value` is used. order : {'C','F','A'}, optional Order of the data item in the copy. Default is 'C'. - 'C' -- C order (row major). - 'F' -- Fortran order (column major). - 'A' -- Any, current order of array. - None -- Same as 'A'. See Also -------- numpy.ndarray.tobytes tolist, tofile Notes ----- As for `ndarray.tobytes`, information about the shape, dtype, etc., but also about `fill_value`, will be lost. Examples -------- >>> x = np.ma.array(np.array([[1, 2], [3, 4]]), mask=[[0, 1], [1, 0]]) >>> x.tobytes() b'\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00?B\\x0f\\x00\\x00\\x00\\x00\\x00?B\\x0f\\x00\\x00\\x00\\x00\\x00\\x04\\x00\\x00\\x00\\x00\\x00\\x00\\x00' """ return self.filled(fill_value).tobytes(order=order) def tofile(self, fid, sep="", format="%s"): """ Save a masked array to a file in binary format. .. warning:: This function is not implemented yet. Raises ------ NotImplementedError When `tofile` is called. """ raise NotImplementedError("MaskedArray.tofile() not implemented yet.") def toflex(self): """ Transforms a masked array into a flexible-type array. The flexible type array that is returned will have two fields: * the ``_data`` field stores the ``_data`` part of the array. * the ``_mask`` field stores the ``_mask`` part of the array. Parameters ---------- None Returns ------- record : ndarray A new flexible-type `ndarray` with two fields: the first element containing a value, the second element containing the corresponding mask boolean. The returned record shape matches self.shape. Notes ----- A side-effect of transforming a masked array into a flexible `ndarray` is that meta information (``fill_value``, ...) will be lost. Examples -------- >>> x = np.ma.array([[1,2,3],[4,5,6],[7,8,9]], mask=[0] + [1,0]*4) >>> x masked_array( data=[[1, --, 3], [--, 5, --], [7, --, 9]], mask=[[False, True, False], [ True, False, True], [False, True, False]], fill_value=999999) >>> x.toflex() array([[(1, False), (2, True), (3, False)], [(4, True), (5, False), (6, True)], [(7, False), (8, True), (9, False)]], dtype=[('_data', '<i8'), ('_mask', '?')]) """ # Get the basic dtype. ddtype = self.dtype # Make sure we have a mask _mask = self._mask if _mask is None: _mask = make_mask_none(self.shape, ddtype) # And get its dtype mdtype = self._mask.dtype record = np.ndarray(shape=self.shape, dtype=[('_data', ddtype), ('_mask', mdtype)]) record['_data'] = self._data record['_mask'] = self._mask return record torecords = toflex # Pickling def __getstate__(self): """Return the internal state of the masked array, for pickling purposes. """ cf = 'CF'[self.flags.fnc] data_state = super().__reduce__()[2] return data_state + (getmaskarray(self).tobytes(cf), self._fill_value) def __setstate__(self, state): """Restore the internal state of the masked array, for pickling purposes. ``state`` is typically the output of the ``__getstate__`` output, and is a 5-tuple: - class name - a tuple giving the shape of the data - a typecode for the data - a binary string for the data - a binary string for the mask. """ (_, shp, typ, isf, raw, msk, flv) = state super().__setstate__((shp, typ, isf, raw)) self._mask.__setstate__((shp, make_mask_descr(typ), isf, msk)) self.fill_value = flv def __reduce__(self): """Return a 3-tuple for pickling a MaskedArray. """ return (_mareconstruct, (self.__class__, self._baseclass, (0,), 'b',), self.__getstate__()) def __deepcopy__(self, memo=None): from copy import deepcopy copied = MaskedArray.__new__(type(self), self, copy=True) if memo is None: memo = {} memo[id(self)] = copied for (k, v) in self.__dict__.items(): copied.__dict__[k] = deepcopy(v, memo) return copied The provided code snippet includes necessary dependencies for implementing the `set_fill_value` function. Write a Python function `def set_fill_value(a, fill_value)` to solve the following problem: Set the filling value of a, if a is a masked array. This function changes the fill value of the masked array `a` in place. If `a` is not a masked array, the function returns silently, without doing anything. Parameters ---------- a : array_like Input array. fill_value : dtype Filling value. A consistency test is performed to make sure the value is compatible with the dtype of `a`. Returns ------- None Nothing returned by this function. See Also -------- maximum_fill_value : Return the default fill value for a dtype. MaskedArray.fill_value : Return current fill value. MaskedArray.set_fill_value : Equivalent method. Examples -------- >>> import numpy.ma as ma >>> a = np.arange(5) >>> a array([0, 1, 2, 3, 4]) >>> a = ma.masked_where(a < 3, a) >>> a masked_array(data=[--, --, --, 3, 4], mask=[ True, True, True, False, False], fill_value=999999) >>> ma.set_fill_value(a, -999) >>> a masked_array(data=[--, --, --, 3, 4], mask=[ True, True, True, False, False], fill_value=-999) Nothing happens if `a` is not a masked array. >>> a = list(range(5)) >>> a [0, 1, 2, 3, 4] >>> ma.set_fill_value(a, 100) >>> a [0, 1, 2, 3, 4] >>> a = np.arange(5) >>> a array([0, 1, 2, 3, 4]) >>> ma.set_fill_value(a, 100) >>> a array([0, 1, 2, 3, 4]) Here is the function: def set_fill_value(a, fill_value): """ Set the filling value of a, if a is a masked array. This function changes the fill value of the masked array `a` in place. If `a` is not a masked array, the function returns silently, without doing anything. Parameters ---------- a : array_like Input array. fill_value : dtype Filling value. A consistency test is performed to make sure the value is compatible with the dtype of `a`. Returns ------- None Nothing returned by this function. See Also -------- maximum_fill_value : Return the default fill value for a dtype. MaskedArray.fill_value : Return current fill value. MaskedArray.set_fill_value : Equivalent method. Examples -------- >>> import numpy.ma as ma >>> a = np.arange(5) >>> a array([0, 1, 2, 3, 4]) >>> a = ma.masked_where(a < 3, a) >>> a masked_array(data=[--, --, --, 3, 4], mask=[ True, True, True, False, False], fill_value=999999) >>> ma.set_fill_value(a, -999) >>> a masked_array(data=[--, --, --, 3, 4], mask=[ True, True, True, False, False], fill_value=-999) Nothing happens if `a` is not a masked array. >>> a = list(range(5)) >>> a [0, 1, 2, 3, 4] >>> ma.set_fill_value(a, 100) >>> a [0, 1, 2, 3, 4] >>> a = np.arange(5) >>> a array([0, 1, 2, 3, 4]) >>> ma.set_fill_value(a, 100) >>> a array([0, 1, 2, 3, 4]) """ if isinstance(a, MaskedArray): a.set_fill_value(fill_value) return
Set the filling value of a, if a is a masked array. This function changes the fill value of the masked array `a` in place. If `a` is not a masked array, the function returns silently, without doing anything. Parameters ---------- a : array_like Input array. fill_value : dtype Filling value. A consistency test is performed to make sure the value is compatible with the dtype of `a`. Returns ------- None Nothing returned by this function. See Also -------- maximum_fill_value : Return the default fill value for a dtype. MaskedArray.fill_value : Return current fill value. MaskedArray.set_fill_value : Equivalent method. Examples -------- >>> import numpy.ma as ma >>> a = np.arange(5) >>> a array([0, 1, 2, 3, 4]) >>> a = ma.masked_where(a < 3, a) >>> a masked_array(data=[--, --, --, 3, 4], mask=[ True, True, True, False, False], fill_value=999999) >>> ma.set_fill_value(a, -999) >>> a masked_array(data=[--, --, --, 3, 4], mask=[ True, True, True, False, False], fill_value=-999) Nothing happens if `a` is not a masked array. >>> a = list(range(5)) >>> a [0, 1, 2, 3, 4] >>> ma.set_fill_value(a, 100) >>> a [0, 1, 2, 3, 4] >>> a = np.arange(5) >>> a array([0, 1, 2, 3, 4]) >>> ma.set_fill_value(a, 100) >>> a array([0, 1, 2, 3, 4])
170,091
import builtins import inspect import operator import warnings import textwrap import re from functools import reduce import numpy as np import numpy.core.umath as umath import numpy.core.numerictypes as ntypes from numpy.core import multiarray as mu from numpy import ndarray, amax, amin, iscomplexobj, bool_, _NoValue from numpy import array as narray from numpy.lib.function_base import angle from numpy.compat import ( getargspec, formatargspec, long, unicode, bytes ) from numpy import expand_dims from numpy.core.numeric import normalize_axis_tuple def get_fill_value(a): """ Return the filling value of a, if any. Otherwise, returns the default filling value for that type. """ if isinstance(a, MaskedArray): result = a.fill_value else: result = default_fill_value(a) return result The provided code snippet includes necessary dependencies for implementing the `common_fill_value` function. Write a Python function `def common_fill_value(a, b)` to solve the following problem: Return the common filling value of two masked arrays, if any. If ``a.fill_value == b.fill_value``, return the fill value, otherwise return None. Parameters ---------- a, b : MaskedArray The masked arrays for which to compare fill values. Returns ------- fill_value : scalar or None The common fill value, or None. Examples -------- >>> x = np.ma.array([0, 1.], fill_value=3) >>> y = np.ma.array([0, 1.], fill_value=3) >>> np.ma.common_fill_value(x, y) 3.0 Here is the function: def common_fill_value(a, b): """ Return the common filling value of two masked arrays, if any. If ``a.fill_value == b.fill_value``, return the fill value, otherwise return None. Parameters ---------- a, b : MaskedArray The masked arrays for which to compare fill values. Returns ------- fill_value : scalar or None The common fill value, or None. Examples -------- >>> x = np.ma.array([0, 1.], fill_value=3) >>> y = np.ma.array([0, 1.], fill_value=3) >>> np.ma.common_fill_value(x, y) 3.0 """ t1 = get_fill_value(a) t2 = get_fill_value(b) if t1 == t2: return t1 return None
Return the common filling value of two masked arrays, if any. If ``a.fill_value == b.fill_value``, return the fill value, otherwise return None. Parameters ---------- a, b : MaskedArray The masked arrays for which to compare fill values. Returns ------- fill_value : scalar or None The common fill value, or None. Examples -------- >>> x = np.ma.array([0, 1.], fill_value=3) >>> y = np.ma.array([0, 1.], fill_value=3) >>> np.ma.common_fill_value(x, y) 3.0
170,092
import builtins import inspect import operator import warnings import textwrap import re from functools import reduce import numpy as np import numpy.core.umath as umath import numpy.core.numerictypes as ntypes from numpy.core import multiarray as mu from numpy import ndarray, amax, amin, iscomplexobj, bool_, _NoValue from numpy import array as narray from numpy.lib.function_base import angle from numpy.compat import ( getargspec, formatargspec, long, unicode, bytes ) from numpy import expand_dims from numpy.core.numeric import normalize_axis_tuple nomask = MaskType(0) logical_not = _MaskedUnaryOperation(umath.logical_not) masked_array = MaskedArray any = _frommethod('any') The provided code snippet includes necessary dependencies for implementing the `fix_invalid` function. Write a Python function `def fix_invalid(a, mask=nomask, copy=True, fill_value=None)` to solve the following problem: Return input with invalid data masked and replaced by a fill value. Invalid data means values of `nan`, `inf`, etc. Parameters ---------- a : array_like Input array, a (subclass of) ndarray. mask : sequence, optional Mask. Must be convertible to an array of booleans with the same shape as `data`. True indicates a masked (i.e. invalid) data. copy : bool, optional Whether to use a copy of `a` (True) or to fix `a` in place (False). Default is True. fill_value : scalar, optional Value used for fixing invalid data. Default is None, in which case the ``a.fill_value`` is used. Returns ------- b : MaskedArray The input array with invalid entries fixed. Notes ----- A copy is performed by default. Examples -------- >>> x = np.ma.array([1., -1, np.nan, np.inf], mask=[1] + [0]*3) >>> x masked_array(data=[--, -1.0, nan, inf], mask=[ True, False, False, False], fill_value=1e+20) >>> np.ma.fix_invalid(x) masked_array(data=[--, -1.0, --, --], mask=[ True, False, True, True], fill_value=1e+20) >>> fixed = np.ma.fix_invalid(x) >>> fixed.data array([ 1.e+00, -1.e+00, 1.e+20, 1.e+20]) >>> x.data array([ 1., -1., nan, inf]) Here is the function: def fix_invalid(a, mask=nomask, copy=True, fill_value=None): """ Return input with invalid data masked and replaced by a fill value. Invalid data means values of `nan`, `inf`, etc. Parameters ---------- a : array_like Input array, a (subclass of) ndarray. mask : sequence, optional Mask. Must be convertible to an array of booleans with the same shape as `data`. True indicates a masked (i.e. invalid) data. copy : bool, optional Whether to use a copy of `a` (True) or to fix `a` in place (False). Default is True. fill_value : scalar, optional Value used for fixing invalid data. Default is None, in which case the ``a.fill_value`` is used. Returns ------- b : MaskedArray The input array with invalid entries fixed. Notes ----- A copy is performed by default. Examples -------- >>> x = np.ma.array([1., -1, np.nan, np.inf], mask=[1] + [0]*3) >>> x masked_array(data=[--, -1.0, nan, inf], mask=[ True, False, False, False], fill_value=1e+20) >>> np.ma.fix_invalid(x) masked_array(data=[--, -1.0, --, --], mask=[ True, False, True, True], fill_value=1e+20) >>> fixed = np.ma.fix_invalid(x) >>> fixed.data array([ 1.e+00, -1.e+00, 1.e+20, 1.e+20]) >>> x.data array([ 1., -1., nan, inf]) """ a = masked_array(a, copy=copy, mask=mask, subok=True) invalid = np.logical_not(np.isfinite(a._data)) if not invalid.any(): return a a._mask |= invalid if fill_value is None: fill_value = a.fill_value a._data[invalid] = fill_value return a
Return input with invalid data masked and replaced by a fill value. Invalid data means values of `nan`, `inf`, etc. Parameters ---------- a : array_like Input array, a (subclass of) ndarray. mask : sequence, optional Mask. Must be convertible to an array of booleans with the same shape as `data`. True indicates a masked (i.e. invalid) data. copy : bool, optional Whether to use a copy of `a` (True) or to fix `a` in place (False). Default is True. fill_value : scalar, optional Value used for fixing invalid data. Default is None, in which case the ``a.fill_value`` is used. Returns ------- b : MaskedArray The input array with invalid entries fixed. Notes ----- A copy is performed by default. Examples -------- >>> x = np.ma.array([1., -1, np.nan, np.inf], mask=[1] + [0]*3) >>> x masked_array(data=[--, -1.0, nan, inf], mask=[ True, False, False, False], fill_value=1e+20) >>> np.ma.fix_invalid(x) masked_array(data=[--, -1.0, --, --], mask=[ True, False, True, True], fill_value=1e+20) >>> fixed = np.ma.fix_invalid(x) >>> fixed.data array([ 1.e+00, -1.e+00, 1.e+20, 1.e+20]) >>> x.data array([ 1., -1., nan, inf])
170,093
import builtins import inspect import operator import warnings import textwrap import re from functools import reduce import numpy as np import numpy.core.umath as umath import numpy.core.numerictypes as ntypes from numpy.core import multiarray as mu from numpy import ndarray, amax, amin, iscomplexobj, bool_, _NoValue from numpy import array as narray from numpy.lib.function_base import angle from numpy.compat import ( getargspec, formatargspec, long, unicode, bytes ) from numpy import expand_dims from numpy.core.numeric import normalize_axis_tuple all = _frommethod('all') def is_string_or_list_of_strings(val): return (isinstance(val, str) or (isinstance(val, list) and val and builtins.all(isinstance(s, str) for s in val)))
null
170,094
import builtins import inspect import operator import warnings import textwrap import re from functools import reduce import numpy as np import numpy.core.umath as umath import numpy.core.numerictypes as ntypes from numpy.core import multiarray as mu from numpy import ndarray, amax, amin, iscomplexobj, bool_, _NoValue from numpy import array as narray from numpy.lib.function_base import angle from numpy.compat import ( getargspec, formatargspec, long, unicode, bytes ) from numpy import expand_dims from numpy.core.numeric import normalize_axis_tuple def array(data, dtype=None, copy=False, order=None, mask=nomask, fill_value=None, keep_mask=True, hard_mask=False, shrink=True, subok=True, ndmin=0): """ Shortcut to MaskedArray. The options are in a different order for convenience and backwards compatibility. """ return MaskedArray(data, mask=mask, dtype=dtype, copy=copy, subok=subok, keep_mask=keep_mask, hard_mask=hard_mask, fill_value=fill_value, ndmin=ndmin, shrink=shrink, order=order) array.__doc__ = masked_array.__doc__ def asarray(a, dtype=None, order=None): """ Convert the input to a masked array of the given data-type. No copy is performed if the input is already an `ndarray`. If `a` is a subclass of `MaskedArray`, a base class `MaskedArray` is returned. Parameters ---------- a : array_like Input data, in any form that can be converted to a masked array. This includes lists, lists of tuples, tuples, tuples of tuples, tuples of lists, ndarrays and masked arrays. dtype : dtype, optional By default, the data-type is inferred from the input data. order : {'C', 'F'}, optional Whether to use row-major ('C') or column-major ('FORTRAN') memory representation. Default is 'C'. Returns ------- out : MaskedArray Masked array interpretation of `a`. See Also -------- asanyarray : Similar to `asarray`, but conserves subclasses. Examples -------- >>> x = np.arange(10.).reshape(2, 5) >>> x array([[0., 1., 2., 3., 4.], [5., 6., 7., 8., 9.]]) >>> np.ma.asarray(x) masked_array( data=[[0., 1., 2., 3., 4.], [5., 6., 7., 8., 9.]], mask=False, fill_value=1e+20) >>> type(np.ma.asarray(x)) <class 'numpy.ma.core.MaskedArray'> """ order = order or 'C' return masked_array(a, dtype=dtype, copy=False, keep_mask=True, subok=False, order=order) The provided code snippet includes necessary dependencies for implementing the `flatten_mask` function. Write a Python function `def flatten_mask(mask)` to solve the following problem: Returns a completely flattened version of the mask, where nested fields are collapsed. Parameters ---------- mask : array_like Input array, which will be interpreted as booleans. Returns ------- flattened_mask : ndarray of bools The flattened input. Examples -------- >>> mask = np.array([0, 0, 1]) >>> np.ma.flatten_mask(mask) array([False, False, True]) >>> mask = np.array([(0, 0), (0, 1)], dtype=[('a', bool), ('b', bool)]) >>> np.ma.flatten_mask(mask) array([False, False, False, True]) >>> mdtype = [('a', bool), ('b', [('ba', bool), ('bb', bool)])] >>> mask = np.array([(0, (0, 0)), (0, (0, 1))], dtype=mdtype) >>> np.ma.flatten_mask(mask) array([False, False, False, False, False, True]) Here is the function: def flatten_mask(mask): """ Returns a completely flattened version of the mask, where nested fields are collapsed. Parameters ---------- mask : array_like Input array, which will be interpreted as booleans. Returns ------- flattened_mask : ndarray of bools The flattened input. Examples -------- >>> mask = np.array([0, 0, 1]) >>> np.ma.flatten_mask(mask) array([False, False, True]) >>> mask = np.array([(0, 0), (0, 1)], dtype=[('a', bool), ('b', bool)]) >>> np.ma.flatten_mask(mask) array([False, False, False, True]) >>> mdtype = [('a', bool), ('b', [('ba', bool), ('bb', bool)])] >>> mask = np.array([(0, (0, 0)), (0, (0, 1))], dtype=mdtype) >>> np.ma.flatten_mask(mask) array([False, False, False, False, False, True]) """ def _flatmask(mask): "Flatten the mask and returns a (maybe nested) sequence of booleans." mnames = mask.dtype.names if mnames is not None: return [flatten_mask(mask[name]) for name in mnames] else: return mask def _flatsequence(sequence): "Generates a flattened version of the sequence." try: for element in sequence: if hasattr(element, '__iter__'): yield from _flatsequence(element) else: yield element except TypeError: yield sequence mask = np.asarray(mask) flattened = _flatsequence(_flatmask(mask)) return np.array([_ for _ in flattened], dtype=bool)
Returns a completely flattened version of the mask, where nested fields are collapsed. Parameters ---------- mask : array_like Input array, which will be interpreted as booleans. Returns ------- flattened_mask : ndarray of bools The flattened input. Examples -------- >>> mask = np.array([0, 0, 1]) >>> np.ma.flatten_mask(mask) array([False, False, True]) >>> mask = np.array([(0, 0), (0, 1)], dtype=[('a', bool), ('b', bool)]) >>> np.ma.flatten_mask(mask) array([False, False, False, True]) >>> mdtype = [('a', bool), ('b', [('ba', bool), ('bb', bool)])] >>> mask = np.array([(0, (0, 0)), (0, (0, 1))], dtype=mdtype) >>> np.ma.flatten_mask(mask) array([False, False, False, False, False, True])
170,095
import builtins import inspect import operator import warnings import textwrap import re from functools import reduce import numpy as np import numpy.core.umath as umath import numpy.core.numerictypes as ntypes from numpy.core import multiarray as mu from numpy import ndarray, amax, amin, iscomplexobj, bool_, _NoValue from numpy import array as narray from numpy.lib.function_base import angle from numpy.compat import ( getargspec, formatargspec, long, unicode, bytes ) from numpy import expand_dims from numpy.core.numeric import normalize_axis_tuple nomask = MaskType(0) all = _frommethod('all') The provided code snippet includes necessary dependencies for implementing the `_check_mask_axis` function. Write a Python function `def _check_mask_axis(mask, axis, keepdims=np._NoValue)` to solve the following problem: Check whether there are masked values along the given axis Here is the function: def _check_mask_axis(mask, axis, keepdims=np._NoValue): "Check whether there are masked values along the given axis" kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims} if mask is not nomask: return mask.all(axis=axis, **kwargs) return nomask
Check whether there are masked values along the given axis
170,096
import builtins import inspect import operator import warnings import textwrap import re from functools import reduce import numpy as np import numpy.core.umath as umath import numpy.core.numerictypes as ntypes from numpy.core import multiarray as mu from numpy import ndarray, amax, amin, iscomplexobj, bool_, _NoValue from numpy import array as narray from numpy.lib.function_base import angle from numpy.compat import ( getargspec, formatargspec, long, unicode, bytes ) from numpy import expand_dims from numpy.core.numeric import normalize_axis_tuple greater = _MaskedBinaryOperation(umath.greater) greater.reduce = None def masked_where(condition, a, copy=True): """ Mask an array where a condition is met. Return `a` as an array masked where `condition` is True. Any masked values of `a` or `condition` are also masked in the output. Parameters ---------- condition : array_like Masking condition. When `condition` tests floating point values for equality, consider using ``masked_values`` instead. a : array_like Array to mask. copy : bool If True (default) make a copy of `a` in the result. If False modify `a` in place and return a view. Returns ------- result : MaskedArray The result of masking `a` where `condition` is True. See Also -------- masked_values : Mask using floating point equality. masked_equal : Mask where equal to a given value. masked_not_equal : Mask where `not` equal to a given value. masked_less_equal : Mask where less than or equal to a given value. masked_greater_equal : Mask where greater than or equal to a given value. masked_less : Mask where less than a given value. masked_greater : Mask where greater than a given value. masked_inside : Mask inside a given interval. masked_outside : Mask outside a given interval. masked_invalid : Mask invalid values (NaNs or infs). Examples -------- >>> import numpy.ma as ma >>> a = np.arange(4) >>> a array([0, 1, 2, 3]) >>> ma.masked_where(a <= 2, a) masked_array(data=[--, --, --, 3], mask=[ True, True, True, False], fill_value=999999) Mask array `b` conditional on `a`. >>> b = ['a', 'b', 'c', 'd'] >>> ma.masked_where(a == 2, b) masked_array(data=['a', 'b', --, 'd'], mask=[False, False, True, False], fill_value='N/A', dtype='<U1') Effect of the `copy` argument. >>> c = ma.masked_where(a <= 2, a) >>> c masked_array(data=[--, --, --, 3], mask=[ True, True, True, False], fill_value=999999) >>> c[0] = 99 >>> c masked_array(data=[99, --, --, 3], mask=[False, True, True, False], fill_value=999999) >>> a array([0, 1, 2, 3]) >>> c = ma.masked_where(a <= 2, a, copy=False) >>> c[0] = 99 >>> c masked_array(data=[99, --, --, 3], mask=[False, True, True, False], fill_value=999999) >>> a array([99, 1, 2, 3]) When `condition` or `a` contain masked values. >>> a = np.arange(4) >>> a = ma.masked_where(a == 2, a) >>> a masked_array(data=[0, 1, --, 3], mask=[False, False, True, False], fill_value=999999) >>> b = np.arange(4) >>> b = ma.masked_where(b == 0, b) >>> b masked_array(data=[--, 1, 2, 3], mask=[ True, False, False, False], fill_value=999999) >>> ma.masked_where(a == 3, b) masked_array(data=[--, 1, --, --], mask=[ True, False, True, True], fill_value=999999) """ # Make sure that condition is a valid standard-type mask. cond = make_mask(condition, shrink=False) a = np.array(a, copy=copy, subok=True) (cshape, ashape) = (cond.shape, a.shape) if cshape and cshape != ashape: raise IndexError("Inconsistent shape between the condition and the input" " (got %s and %s)" % (cshape, ashape)) if hasattr(a, '_mask'): cond = mask_or(cond, a._mask) cls = type(a) else: cls = MaskedArray result = a.view(cls) # Assign to *.mask so that structured masks are handled correctly. result.mask = _shrink_mask(cond) # There is no view of a boolean so when 'a' is a MaskedArray with nomask # the update to the result's mask has no effect. if not copy and hasattr(a, '_mask') and getmask(a) is nomask: a._mask = result._mask.view() return result The provided code snippet includes necessary dependencies for implementing the `masked_greater` function. Write a Python function `def masked_greater(x, value, copy=True)` to solve the following problem: Mask an array where greater than a given value. This function is a shortcut to ``masked_where``, with `condition` = (x > value). See Also -------- masked_where : Mask where a condition is met. Examples -------- >>> import numpy.ma as ma >>> a = np.arange(4) >>> a array([0, 1, 2, 3]) >>> ma.masked_greater(a, 2) masked_array(data=[0, 1, 2, --], mask=[False, False, False, True], fill_value=999999) Here is the function: def masked_greater(x, value, copy=True): """ Mask an array where greater than a given value. This function is a shortcut to ``masked_where``, with `condition` = (x > value). See Also -------- masked_where : Mask where a condition is met. Examples -------- >>> import numpy.ma as ma >>> a = np.arange(4) >>> a array([0, 1, 2, 3]) >>> ma.masked_greater(a, 2) masked_array(data=[0, 1, 2, --], mask=[False, False, False, True], fill_value=999999) """ return masked_where(greater(x, value), x, copy=copy)
Mask an array where greater than a given value. This function is a shortcut to ``masked_where``, with `condition` = (x > value). See Also -------- masked_where : Mask where a condition is met. Examples -------- >>> import numpy.ma as ma >>> a = np.arange(4) >>> a array([0, 1, 2, 3]) >>> ma.masked_greater(a, 2) masked_array(data=[0, 1, 2, --], mask=[False, False, False, True], fill_value=999999)
170,097
import builtins import inspect import operator import warnings import textwrap import re from functools import reduce import numpy as np import numpy.core.umath as umath import numpy.core.numerictypes as ntypes from numpy.core import multiarray as mu from numpy import ndarray, amax, amin, iscomplexobj, bool_, _NoValue from numpy import array as narray from numpy.lib.function_base import angle from numpy.compat import ( getargspec, formatargspec, long, unicode, bytes ) from numpy import expand_dims from numpy.core.numeric import normalize_axis_tuple greater_equal = _MaskedBinaryOperation(umath.greater_equal) greater_equal.reduce = None def masked_where(condition, a, copy=True): """ Mask an array where a condition is met. Return `a` as an array masked where `condition` is True. Any masked values of `a` or `condition` are also masked in the output. Parameters ---------- condition : array_like Masking condition. When `condition` tests floating point values for equality, consider using ``masked_values`` instead. a : array_like Array to mask. copy : bool If True (default) make a copy of `a` in the result. If False modify `a` in place and return a view. Returns ------- result : MaskedArray The result of masking `a` where `condition` is True. See Also -------- masked_values : Mask using floating point equality. masked_equal : Mask where equal to a given value. masked_not_equal : Mask where `not` equal to a given value. masked_less_equal : Mask where less than or equal to a given value. masked_greater_equal : Mask where greater than or equal to a given value. masked_less : Mask where less than a given value. masked_greater : Mask where greater than a given value. masked_inside : Mask inside a given interval. masked_outside : Mask outside a given interval. masked_invalid : Mask invalid values (NaNs or infs). Examples -------- >>> import numpy.ma as ma >>> a = np.arange(4) >>> a array([0, 1, 2, 3]) >>> ma.masked_where(a <= 2, a) masked_array(data=[--, --, --, 3], mask=[ True, True, True, False], fill_value=999999) Mask array `b` conditional on `a`. >>> b = ['a', 'b', 'c', 'd'] >>> ma.masked_where(a == 2, b) masked_array(data=['a', 'b', --, 'd'], mask=[False, False, True, False], fill_value='N/A', dtype='<U1') Effect of the `copy` argument. >>> c = ma.masked_where(a <= 2, a) >>> c masked_array(data=[--, --, --, 3], mask=[ True, True, True, False], fill_value=999999) >>> c[0] = 99 >>> c masked_array(data=[99, --, --, 3], mask=[False, True, True, False], fill_value=999999) >>> a array([0, 1, 2, 3]) >>> c = ma.masked_where(a <= 2, a, copy=False) >>> c[0] = 99 >>> c masked_array(data=[99, --, --, 3], mask=[False, True, True, False], fill_value=999999) >>> a array([99, 1, 2, 3]) When `condition` or `a` contain masked values. >>> a = np.arange(4) >>> a = ma.masked_where(a == 2, a) >>> a masked_array(data=[0, 1, --, 3], mask=[False, False, True, False], fill_value=999999) >>> b = np.arange(4) >>> b = ma.masked_where(b == 0, b) >>> b masked_array(data=[--, 1, 2, 3], mask=[ True, False, False, False], fill_value=999999) >>> ma.masked_where(a == 3, b) masked_array(data=[--, 1, --, --], mask=[ True, False, True, True], fill_value=999999) """ # Make sure that condition is a valid standard-type mask. cond = make_mask(condition, shrink=False) a = np.array(a, copy=copy, subok=True) (cshape, ashape) = (cond.shape, a.shape) if cshape and cshape != ashape: raise IndexError("Inconsistent shape between the condition and the input" " (got %s and %s)" % (cshape, ashape)) if hasattr(a, '_mask'): cond = mask_or(cond, a._mask) cls = type(a) else: cls = MaskedArray result = a.view(cls) # Assign to *.mask so that structured masks are handled correctly. result.mask = _shrink_mask(cond) # There is no view of a boolean so when 'a' is a MaskedArray with nomask # the update to the result's mask has no effect. if not copy and hasattr(a, '_mask') and getmask(a) is nomask: a._mask = result._mask.view() return result The provided code snippet includes necessary dependencies for implementing the `masked_greater_equal` function. Write a Python function `def masked_greater_equal(x, value, copy=True)` to solve the following problem: Mask an array where greater than or equal to a given value. This function is a shortcut to ``masked_where``, with `condition` = (x >= value). See Also -------- masked_where : Mask where a condition is met. Examples -------- >>> import numpy.ma as ma >>> a = np.arange(4) >>> a array([0, 1, 2, 3]) >>> ma.masked_greater_equal(a, 2) masked_array(data=[0, 1, --, --], mask=[False, False, True, True], fill_value=999999) Here is the function: def masked_greater_equal(x, value, copy=True): """ Mask an array where greater than or equal to a given value. This function is a shortcut to ``masked_where``, with `condition` = (x >= value). See Also -------- masked_where : Mask where a condition is met. Examples -------- >>> import numpy.ma as ma >>> a = np.arange(4) >>> a array([0, 1, 2, 3]) >>> ma.masked_greater_equal(a, 2) masked_array(data=[0, 1, --, --], mask=[False, False, True, True], fill_value=999999) """ return masked_where(greater_equal(x, value), x, copy=copy)
Mask an array where greater than or equal to a given value. This function is a shortcut to ``masked_where``, with `condition` = (x >= value). See Also -------- masked_where : Mask where a condition is met. Examples -------- >>> import numpy.ma as ma >>> a = np.arange(4) >>> a array([0, 1, 2, 3]) >>> ma.masked_greater_equal(a, 2) masked_array(data=[0, 1, --, --], mask=[False, False, True, True], fill_value=999999)
170,098
import builtins import inspect import operator import warnings import textwrap import re from functools import reduce import numpy as np import numpy.core.umath as umath import numpy.core.numerictypes as ntypes from numpy.core import multiarray as mu from numpy import ndarray, amax, amin, iscomplexobj, bool_, _NoValue from numpy import array as narray from numpy.lib.function_base import angle from numpy.compat import ( getargspec, formatargspec, long, unicode, bytes ) from numpy import expand_dims from numpy.core.numeric import normalize_axis_tuple less = _MaskedBinaryOperation(umath.less) less.reduce = None def masked_where(condition, a, copy=True): """ Mask an array where a condition is met. Return `a` as an array masked where `condition` is True. Any masked values of `a` or `condition` are also masked in the output. Parameters ---------- condition : array_like Masking condition. When `condition` tests floating point values for equality, consider using ``masked_values`` instead. a : array_like Array to mask. copy : bool If True (default) make a copy of `a` in the result. If False modify `a` in place and return a view. Returns ------- result : MaskedArray The result of masking `a` where `condition` is True. See Also -------- masked_values : Mask using floating point equality. masked_equal : Mask where equal to a given value. masked_not_equal : Mask where `not` equal to a given value. masked_less_equal : Mask where less than or equal to a given value. masked_greater_equal : Mask where greater than or equal to a given value. masked_less : Mask where less than a given value. masked_greater : Mask where greater than a given value. masked_inside : Mask inside a given interval. masked_outside : Mask outside a given interval. masked_invalid : Mask invalid values (NaNs or infs). Examples -------- >>> import numpy.ma as ma >>> a = np.arange(4) >>> a array([0, 1, 2, 3]) >>> ma.masked_where(a <= 2, a) masked_array(data=[--, --, --, 3], mask=[ True, True, True, False], fill_value=999999) Mask array `b` conditional on `a`. >>> b = ['a', 'b', 'c', 'd'] >>> ma.masked_where(a == 2, b) masked_array(data=['a', 'b', --, 'd'], mask=[False, False, True, False], fill_value='N/A', dtype='<U1') Effect of the `copy` argument. >>> c = ma.masked_where(a <= 2, a) >>> c masked_array(data=[--, --, --, 3], mask=[ True, True, True, False], fill_value=999999) >>> c[0] = 99 >>> c masked_array(data=[99, --, --, 3], mask=[False, True, True, False], fill_value=999999) >>> a array([0, 1, 2, 3]) >>> c = ma.masked_where(a <= 2, a, copy=False) >>> c[0] = 99 >>> c masked_array(data=[99, --, --, 3], mask=[False, True, True, False], fill_value=999999) >>> a array([99, 1, 2, 3]) When `condition` or `a` contain masked values. >>> a = np.arange(4) >>> a = ma.masked_where(a == 2, a) >>> a masked_array(data=[0, 1, --, 3], mask=[False, False, True, False], fill_value=999999) >>> b = np.arange(4) >>> b = ma.masked_where(b == 0, b) >>> b masked_array(data=[--, 1, 2, 3], mask=[ True, False, False, False], fill_value=999999) >>> ma.masked_where(a == 3, b) masked_array(data=[--, 1, --, --], mask=[ True, False, True, True], fill_value=999999) """ # Make sure that condition is a valid standard-type mask. cond = make_mask(condition, shrink=False) a = np.array(a, copy=copy, subok=True) (cshape, ashape) = (cond.shape, a.shape) if cshape and cshape != ashape: raise IndexError("Inconsistent shape between the condition and the input" " (got %s and %s)" % (cshape, ashape)) if hasattr(a, '_mask'): cond = mask_or(cond, a._mask) cls = type(a) else: cls = MaskedArray result = a.view(cls) # Assign to *.mask so that structured masks are handled correctly. result.mask = _shrink_mask(cond) # There is no view of a boolean so when 'a' is a MaskedArray with nomask # the update to the result's mask has no effect. if not copy and hasattr(a, '_mask') and getmask(a) is nomask: a._mask = result._mask.view() return result The provided code snippet includes necessary dependencies for implementing the `masked_less` function. Write a Python function `def masked_less(x, value, copy=True)` to solve the following problem: Mask an array where less than a given value. This function is a shortcut to ``masked_where``, with `condition` = (x < value). See Also -------- masked_where : Mask where a condition is met. Examples -------- >>> import numpy.ma as ma >>> a = np.arange(4) >>> a array([0, 1, 2, 3]) >>> ma.masked_less(a, 2) masked_array(data=[--, --, 2, 3], mask=[ True, True, False, False], fill_value=999999) Here is the function: def masked_less(x, value, copy=True): """ Mask an array where less than a given value. This function is a shortcut to ``masked_where``, with `condition` = (x < value). See Also -------- masked_where : Mask where a condition is met. Examples -------- >>> import numpy.ma as ma >>> a = np.arange(4) >>> a array([0, 1, 2, 3]) >>> ma.masked_less(a, 2) masked_array(data=[--, --, 2, 3], mask=[ True, True, False, False], fill_value=999999) """ return masked_where(less(x, value), x, copy=copy)
Mask an array where less than a given value. This function is a shortcut to ``masked_where``, with `condition` = (x < value). See Also -------- masked_where : Mask where a condition is met. Examples -------- >>> import numpy.ma as ma >>> a = np.arange(4) >>> a array([0, 1, 2, 3]) >>> ma.masked_less(a, 2) masked_array(data=[--, --, 2, 3], mask=[ True, True, False, False], fill_value=999999)
170,099
import builtins import inspect import operator import warnings import textwrap import re from functools import reduce import numpy as np import numpy.core.umath as umath import numpy.core.numerictypes as ntypes from numpy.core import multiarray as mu from numpy import ndarray, amax, amin, iscomplexobj, bool_, _NoValue from numpy import array as narray from numpy.lib.function_base import angle from numpy.compat import ( getargspec, formatargspec, long, unicode, bytes ) from numpy import expand_dims from numpy.core.numeric import normalize_axis_tuple less_equal = _MaskedBinaryOperation(umath.less_equal) less_equal.reduce = None def masked_where(condition, a, copy=True): """ Mask an array where a condition is met. Return `a` as an array masked where `condition` is True. Any masked values of `a` or `condition` are also masked in the output. Parameters ---------- condition : array_like Masking condition. When `condition` tests floating point values for equality, consider using ``masked_values`` instead. a : array_like Array to mask. copy : bool If True (default) make a copy of `a` in the result. If False modify `a` in place and return a view. Returns ------- result : MaskedArray The result of masking `a` where `condition` is True. See Also -------- masked_values : Mask using floating point equality. masked_equal : Mask where equal to a given value. masked_not_equal : Mask where `not` equal to a given value. masked_less_equal : Mask where less than or equal to a given value. masked_greater_equal : Mask where greater than or equal to a given value. masked_less : Mask where less than a given value. masked_greater : Mask where greater than a given value. masked_inside : Mask inside a given interval. masked_outside : Mask outside a given interval. masked_invalid : Mask invalid values (NaNs or infs). Examples -------- >>> import numpy.ma as ma >>> a = np.arange(4) >>> a array([0, 1, 2, 3]) >>> ma.masked_where(a <= 2, a) masked_array(data=[--, --, --, 3], mask=[ True, True, True, False], fill_value=999999) Mask array `b` conditional on `a`. >>> b = ['a', 'b', 'c', 'd'] >>> ma.masked_where(a == 2, b) masked_array(data=['a', 'b', --, 'd'], mask=[False, False, True, False], fill_value='N/A', dtype='<U1') Effect of the `copy` argument. >>> c = ma.masked_where(a <= 2, a) >>> c masked_array(data=[--, --, --, 3], mask=[ True, True, True, False], fill_value=999999) >>> c[0] = 99 >>> c masked_array(data=[99, --, --, 3], mask=[False, True, True, False], fill_value=999999) >>> a array([0, 1, 2, 3]) >>> c = ma.masked_where(a <= 2, a, copy=False) >>> c[0] = 99 >>> c masked_array(data=[99, --, --, 3], mask=[False, True, True, False], fill_value=999999) >>> a array([99, 1, 2, 3]) When `condition` or `a` contain masked values. >>> a = np.arange(4) >>> a = ma.masked_where(a == 2, a) >>> a masked_array(data=[0, 1, --, 3], mask=[False, False, True, False], fill_value=999999) >>> b = np.arange(4) >>> b = ma.masked_where(b == 0, b) >>> b masked_array(data=[--, 1, 2, 3], mask=[ True, False, False, False], fill_value=999999) >>> ma.masked_where(a == 3, b) masked_array(data=[--, 1, --, --], mask=[ True, False, True, True], fill_value=999999) """ # Make sure that condition is a valid standard-type mask. cond = make_mask(condition, shrink=False) a = np.array(a, copy=copy, subok=True) (cshape, ashape) = (cond.shape, a.shape) if cshape and cshape != ashape: raise IndexError("Inconsistent shape between the condition and the input" " (got %s and %s)" % (cshape, ashape)) if hasattr(a, '_mask'): cond = mask_or(cond, a._mask) cls = type(a) else: cls = MaskedArray result = a.view(cls) # Assign to *.mask so that structured masks are handled correctly. result.mask = _shrink_mask(cond) # There is no view of a boolean so when 'a' is a MaskedArray with nomask # the update to the result's mask has no effect. if not copy and hasattr(a, '_mask') and getmask(a) is nomask: a._mask = result._mask.view() return result The provided code snippet includes necessary dependencies for implementing the `masked_less_equal` function. Write a Python function `def masked_less_equal(x, value, copy=True)` to solve the following problem: Mask an array where less than or equal to a given value. This function is a shortcut to ``masked_where``, with `condition` = (x <= value). See Also -------- masked_where : Mask where a condition is met. Examples -------- >>> import numpy.ma as ma >>> a = np.arange(4) >>> a array([0, 1, 2, 3]) >>> ma.masked_less_equal(a, 2) masked_array(data=[--, --, --, 3], mask=[ True, True, True, False], fill_value=999999) Here is the function: def masked_less_equal(x, value, copy=True): """ Mask an array where less than or equal to a given value. This function is a shortcut to ``masked_where``, with `condition` = (x <= value). See Also -------- masked_where : Mask where a condition is met. Examples -------- >>> import numpy.ma as ma >>> a = np.arange(4) >>> a array([0, 1, 2, 3]) >>> ma.masked_less_equal(a, 2) masked_array(data=[--, --, --, 3], mask=[ True, True, True, False], fill_value=999999) """ return masked_where(less_equal(x, value), x, copy=copy)
Mask an array where less than or equal to a given value. This function is a shortcut to ``masked_where``, with `condition` = (x <= value). See Also -------- masked_where : Mask where a condition is met. Examples -------- >>> import numpy.ma as ma >>> a = np.arange(4) >>> a array([0, 1, 2, 3]) >>> ma.masked_less_equal(a, 2) masked_array(data=[--, --, --, 3], mask=[ True, True, True, False], fill_value=999999)
170,100
import builtins import inspect import operator import warnings import textwrap import re from functools import reduce import numpy as np import numpy.core.umath as umath import numpy.core.numerictypes as ntypes from numpy.core import multiarray as mu from numpy import ndarray, amax, amin, iscomplexobj, bool_, _NoValue from numpy import array as narray from numpy.lib.function_base import angle from numpy.compat import ( getargspec, formatargspec, long, unicode, bytes ) from numpy import expand_dims from numpy.core.numeric import normalize_axis_tuple not_equal = _MaskedBinaryOperation(umath.not_equal) not_equal.reduce = None def masked_where(condition, a, copy=True): """ Mask an array where a condition is met. Return `a` as an array masked where `condition` is True. Any masked values of `a` or `condition` are also masked in the output. Parameters ---------- condition : array_like Masking condition. When `condition` tests floating point values for equality, consider using ``masked_values`` instead. a : array_like Array to mask. copy : bool If True (default) make a copy of `a` in the result. If False modify `a` in place and return a view. Returns ------- result : MaskedArray The result of masking `a` where `condition` is True. See Also -------- masked_values : Mask using floating point equality. masked_equal : Mask where equal to a given value. masked_not_equal : Mask where `not` equal to a given value. masked_less_equal : Mask where less than or equal to a given value. masked_greater_equal : Mask where greater than or equal to a given value. masked_less : Mask where less than a given value. masked_greater : Mask where greater than a given value. masked_inside : Mask inside a given interval. masked_outside : Mask outside a given interval. masked_invalid : Mask invalid values (NaNs or infs). Examples -------- >>> import numpy.ma as ma >>> a = np.arange(4) >>> a array([0, 1, 2, 3]) >>> ma.masked_where(a <= 2, a) masked_array(data=[--, --, --, 3], mask=[ True, True, True, False], fill_value=999999) Mask array `b` conditional on `a`. >>> b = ['a', 'b', 'c', 'd'] >>> ma.masked_where(a == 2, b) masked_array(data=['a', 'b', --, 'd'], mask=[False, False, True, False], fill_value='N/A', dtype='<U1') Effect of the `copy` argument. >>> c = ma.masked_where(a <= 2, a) >>> c masked_array(data=[--, --, --, 3], mask=[ True, True, True, False], fill_value=999999) >>> c[0] = 99 >>> c masked_array(data=[99, --, --, 3], mask=[False, True, True, False], fill_value=999999) >>> a array([0, 1, 2, 3]) >>> c = ma.masked_where(a <= 2, a, copy=False) >>> c[0] = 99 >>> c masked_array(data=[99, --, --, 3], mask=[False, True, True, False], fill_value=999999) >>> a array([99, 1, 2, 3]) When `condition` or `a` contain masked values. >>> a = np.arange(4) >>> a = ma.masked_where(a == 2, a) >>> a masked_array(data=[0, 1, --, 3], mask=[False, False, True, False], fill_value=999999) >>> b = np.arange(4) >>> b = ma.masked_where(b == 0, b) >>> b masked_array(data=[--, 1, 2, 3], mask=[ True, False, False, False], fill_value=999999) >>> ma.masked_where(a == 3, b) masked_array(data=[--, 1, --, --], mask=[ True, False, True, True], fill_value=999999) """ # Make sure that condition is a valid standard-type mask. cond = make_mask(condition, shrink=False) a = np.array(a, copy=copy, subok=True) (cshape, ashape) = (cond.shape, a.shape) if cshape and cshape != ashape: raise IndexError("Inconsistent shape between the condition and the input" " (got %s and %s)" % (cshape, ashape)) if hasattr(a, '_mask'): cond = mask_or(cond, a._mask) cls = type(a) else: cls = MaskedArray result = a.view(cls) # Assign to *.mask so that structured masks are handled correctly. result.mask = _shrink_mask(cond) # There is no view of a boolean so when 'a' is a MaskedArray with nomask # the update to the result's mask has no effect. if not copy and hasattr(a, '_mask') and getmask(a) is nomask: a._mask = result._mask.view() return result The provided code snippet includes necessary dependencies for implementing the `masked_not_equal` function. Write a Python function `def masked_not_equal(x, value, copy=True)` to solve the following problem: Mask an array where `not` equal to a given value. This function is a shortcut to ``masked_where``, with `condition` = (x != value). See Also -------- masked_where : Mask where a condition is met. Examples -------- >>> import numpy.ma as ma >>> a = np.arange(4) >>> a array([0, 1, 2, 3]) >>> ma.masked_not_equal(a, 2) masked_array(data=[--, --, 2, --], mask=[ True, True, False, True], fill_value=999999) Here is the function: def masked_not_equal(x, value, copy=True): """ Mask an array where `not` equal to a given value. This function is a shortcut to ``masked_where``, with `condition` = (x != value). See Also -------- masked_where : Mask where a condition is met. Examples -------- >>> import numpy.ma as ma >>> a = np.arange(4) >>> a array([0, 1, 2, 3]) >>> ma.masked_not_equal(a, 2) masked_array(data=[--, --, 2, --], mask=[ True, True, False, True], fill_value=999999) """ return masked_where(not_equal(x, value), x, copy=copy)
Mask an array where `not` equal to a given value. This function is a shortcut to ``masked_where``, with `condition` = (x != value). See Also -------- masked_where : Mask where a condition is met. Examples -------- >>> import numpy.ma as ma >>> a = np.arange(4) >>> a array([0, 1, 2, 3]) >>> ma.masked_not_equal(a, 2) masked_array(data=[--, --, 2, --], mask=[ True, True, False, True], fill_value=999999)
170,101
import builtins import inspect import operator import warnings import textwrap import re from functools import reduce import numpy as np import numpy.core.umath as umath import numpy.core.numerictypes as ntypes from numpy.core import multiarray as mu from numpy import ndarray, amax, amin, iscomplexobj, bool_, _NoValue from numpy import array as narray from numpy.lib.function_base import angle from numpy.compat import ( getargspec, formatargspec, long, unicode, bytes ) from numpy import expand_dims from numpy.core.numeric import normalize_axis_tuple equal = _MaskedBinaryOperation(umath.equal) equal.reduce = None def masked_where(condition, a, copy=True): """ Mask an array where a condition is met. Return `a` as an array masked where `condition` is True. Any masked values of `a` or `condition` are also masked in the output. Parameters ---------- condition : array_like Masking condition. When `condition` tests floating point values for equality, consider using ``masked_values`` instead. a : array_like Array to mask. copy : bool If True (default) make a copy of `a` in the result. If False modify `a` in place and return a view. Returns ------- result : MaskedArray The result of masking `a` where `condition` is True. See Also -------- masked_values : Mask using floating point equality. masked_equal : Mask where equal to a given value. masked_not_equal : Mask where `not` equal to a given value. masked_less_equal : Mask where less than or equal to a given value. masked_greater_equal : Mask where greater than or equal to a given value. masked_less : Mask where less than a given value. masked_greater : Mask where greater than a given value. masked_inside : Mask inside a given interval. masked_outside : Mask outside a given interval. masked_invalid : Mask invalid values (NaNs or infs). Examples -------- >>> import numpy.ma as ma >>> a = np.arange(4) >>> a array([0, 1, 2, 3]) >>> ma.masked_where(a <= 2, a) masked_array(data=[--, --, --, 3], mask=[ True, True, True, False], fill_value=999999) Mask array `b` conditional on `a`. >>> b = ['a', 'b', 'c', 'd'] >>> ma.masked_where(a == 2, b) masked_array(data=['a', 'b', --, 'd'], mask=[False, False, True, False], fill_value='N/A', dtype='<U1') Effect of the `copy` argument. >>> c = ma.masked_where(a <= 2, a) >>> c masked_array(data=[--, --, --, 3], mask=[ True, True, True, False], fill_value=999999) >>> c[0] = 99 >>> c masked_array(data=[99, --, --, 3], mask=[False, True, True, False], fill_value=999999) >>> a array([0, 1, 2, 3]) >>> c = ma.masked_where(a <= 2, a, copy=False) >>> c[0] = 99 >>> c masked_array(data=[99, --, --, 3], mask=[False, True, True, False], fill_value=999999) >>> a array([99, 1, 2, 3]) When `condition` or `a` contain masked values. >>> a = np.arange(4) >>> a = ma.masked_where(a == 2, a) >>> a masked_array(data=[0, 1, --, 3], mask=[False, False, True, False], fill_value=999999) >>> b = np.arange(4) >>> b = ma.masked_where(b == 0, b) >>> b masked_array(data=[--, 1, 2, 3], mask=[ True, False, False, False], fill_value=999999) >>> ma.masked_where(a == 3, b) masked_array(data=[--, 1, --, --], mask=[ True, False, True, True], fill_value=999999) """ # Make sure that condition is a valid standard-type mask. cond = make_mask(condition, shrink=False) a = np.array(a, copy=copy, subok=True) (cshape, ashape) = (cond.shape, a.shape) if cshape and cshape != ashape: raise IndexError("Inconsistent shape between the condition and the input" " (got %s and %s)" % (cshape, ashape)) if hasattr(a, '_mask'): cond = mask_or(cond, a._mask) cls = type(a) else: cls = MaskedArray result = a.view(cls) # Assign to *.mask so that structured masks are handled correctly. result.mask = _shrink_mask(cond) # There is no view of a boolean so when 'a' is a MaskedArray with nomask # the update to the result's mask has no effect. if not copy and hasattr(a, '_mask') and getmask(a) is nomask: a._mask = result._mask.view() return result The provided code snippet includes necessary dependencies for implementing the `masked_equal` function. Write a Python function `def masked_equal(x, value, copy=True)` to solve the following problem: Mask an array where equal to a given value. Return a MaskedArray, masked where the data in array `x` are equal to `value`. The fill_value of the returned MaskedArray is set to `value`. For floating point arrays, consider using ``masked_values(x, value)``. See Also -------- masked_where : Mask where a condition is met. masked_values : Mask using floating point equality. Examples -------- >>> import numpy.ma as ma >>> a = np.arange(4) >>> a array([0, 1, 2, 3]) >>> ma.masked_equal(a, 2) masked_array(data=[0, 1, --, 3], mask=[False, False, True, False], fill_value=2) Here is the function: def masked_equal(x, value, copy=True): """ Mask an array where equal to a given value. Return a MaskedArray, masked where the data in array `x` are equal to `value`. The fill_value of the returned MaskedArray is set to `value`. For floating point arrays, consider using ``masked_values(x, value)``. See Also -------- masked_where : Mask where a condition is met. masked_values : Mask using floating point equality. Examples -------- >>> import numpy.ma as ma >>> a = np.arange(4) >>> a array([0, 1, 2, 3]) >>> ma.masked_equal(a, 2) masked_array(data=[0, 1, --, 3], mask=[False, False, True, False], fill_value=2) """ output = masked_where(equal(x, value), x, copy=copy) output.fill_value = value return output
Mask an array where equal to a given value. Return a MaskedArray, masked where the data in array `x` are equal to `value`. The fill_value of the returned MaskedArray is set to `value`. For floating point arrays, consider using ``masked_values(x, value)``. See Also -------- masked_where : Mask where a condition is met. masked_values : Mask using floating point equality. Examples -------- >>> import numpy.ma as ma >>> a = np.arange(4) >>> a array([0, 1, 2, 3]) >>> ma.masked_equal(a, 2) masked_array(data=[0, 1, --, 3], mask=[False, False, True, False], fill_value=2)
170,102
import builtins import inspect import operator import warnings import textwrap import re from functools import reduce import numpy as np import numpy.core.umath as umath import numpy.core.numerictypes as ntypes from numpy.core import multiarray as mu from numpy import ndarray, amax, amin, iscomplexobj, bool_, _NoValue from numpy import array as narray from numpy.lib.function_base import angle from numpy.compat import ( getargspec, formatargspec, long, unicode, bytes ) from numpy import expand_dims from numpy.core.numeric import normalize_axis_tuple def filled(a, fill_value=None): """ Return input as an array with masked data replaced by a fill value. If `a` is not a `MaskedArray`, `a` itself is returned. If `a` is a `MaskedArray` and `fill_value` is None, `fill_value` is set to ``a.fill_value``. Parameters ---------- a : MaskedArray or array_like An input object. fill_value : array_like, optional. Can be scalar or non-scalar. If non-scalar, the resulting filled array should be broadcastable over input array. Default is None. Returns ------- a : ndarray The filled array. See Also -------- compressed Examples -------- >>> x = np.ma.array(np.arange(9).reshape(3, 3), mask=[[1, 0, 0], ... [1, 0, 0], ... [0, 0, 0]]) >>> x.filled() array([[999999, 1, 2], [999999, 4, 5], [ 6, 7, 8]]) >>> x.filled(fill_value=333) array([[333, 1, 2], [333, 4, 5], [ 6, 7, 8]]) >>> x.filled(fill_value=np.arange(3)) array([[0, 1, 2], [0, 4, 5], [6, 7, 8]]) """ if hasattr(a, 'filled'): return a.filled(fill_value) elif isinstance(a, ndarray): # Should we check for contiguity ? and a.flags['CONTIGUOUS']: return a elif isinstance(a, dict): return np.array(a, 'O') else: return np.array(a) def masked_where(condition, a, copy=True): """ Mask an array where a condition is met. Return `a` as an array masked where `condition` is True. Any masked values of `a` or `condition` are also masked in the output. Parameters ---------- condition : array_like Masking condition. When `condition` tests floating point values for equality, consider using ``masked_values`` instead. a : array_like Array to mask. copy : bool If True (default) make a copy of `a` in the result. If False modify `a` in place and return a view. Returns ------- result : MaskedArray The result of masking `a` where `condition` is True. See Also -------- masked_values : Mask using floating point equality. masked_equal : Mask where equal to a given value. masked_not_equal : Mask where `not` equal to a given value. masked_less_equal : Mask where less than or equal to a given value. masked_greater_equal : Mask where greater than or equal to a given value. masked_less : Mask where less than a given value. masked_greater : Mask where greater than a given value. masked_inside : Mask inside a given interval. masked_outside : Mask outside a given interval. masked_invalid : Mask invalid values (NaNs or infs). Examples -------- >>> import numpy.ma as ma >>> a = np.arange(4) >>> a array([0, 1, 2, 3]) >>> ma.masked_where(a <= 2, a) masked_array(data=[--, --, --, 3], mask=[ True, True, True, False], fill_value=999999) Mask array `b` conditional on `a`. >>> b = ['a', 'b', 'c', 'd'] >>> ma.masked_where(a == 2, b) masked_array(data=['a', 'b', --, 'd'], mask=[False, False, True, False], fill_value='N/A', dtype='<U1') Effect of the `copy` argument. >>> c = ma.masked_where(a <= 2, a) >>> c masked_array(data=[--, --, --, 3], mask=[ True, True, True, False], fill_value=999999) >>> c[0] = 99 >>> c masked_array(data=[99, --, --, 3], mask=[False, True, True, False], fill_value=999999) >>> a array([0, 1, 2, 3]) >>> c = ma.masked_where(a <= 2, a, copy=False) >>> c[0] = 99 >>> c masked_array(data=[99, --, --, 3], mask=[False, True, True, False], fill_value=999999) >>> a array([99, 1, 2, 3]) When `condition` or `a` contain masked values. >>> a = np.arange(4) >>> a = ma.masked_where(a == 2, a) >>> a masked_array(data=[0, 1, --, 3], mask=[False, False, True, False], fill_value=999999) >>> b = np.arange(4) >>> b = ma.masked_where(b == 0, b) >>> b masked_array(data=[--, 1, 2, 3], mask=[ True, False, False, False], fill_value=999999) >>> ma.masked_where(a == 3, b) masked_array(data=[--, 1, --, --], mask=[ True, False, True, True], fill_value=999999) """ # Make sure that condition is a valid standard-type mask. cond = make_mask(condition, shrink=False) a = np.array(a, copy=copy, subok=True) (cshape, ashape) = (cond.shape, a.shape) if cshape and cshape != ashape: raise IndexError("Inconsistent shape between the condition and the input" " (got %s and %s)" % (cshape, ashape)) if hasattr(a, '_mask'): cond = mask_or(cond, a._mask) cls = type(a) else: cls = MaskedArray result = a.view(cls) # Assign to *.mask so that structured masks are handled correctly. result.mask = _shrink_mask(cond) # There is no view of a boolean so when 'a' is a MaskedArray with nomask # the update to the result's mask has no effect. if not copy and hasattr(a, '_mask') and getmask(a) is nomask: a._mask = result._mask.view() return result The provided code snippet includes necessary dependencies for implementing the `masked_inside` function. Write a Python function `def masked_inside(x, v1, v2, copy=True)` to solve the following problem: Mask an array inside a given interval. Shortcut to ``masked_where``, where `condition` is True for `x` inside the interval [v1,v2] (v1 <= x <= v2). The boundaries `v1` and `v2` can be given in either order. See Also -------- masked_where : Mask where a condition is met. Notes ----- The array `x` is prefilled with its filling value. Examples -------- >>> import numpy.ma as ma >>> x = [0.31, 1.2, 0.01, 0.2, -0.4, -1.1] >>> ma.masked_inside(x, -0.3, 0.3) masked_array(data=[0.31, 1.2, --, --, -0.4, -1.1], mask=[False, False, True, True, False, False], fill_value=1e+20) The order of `v1` and `v2` doesn't matter. >>> ma.masked_inside(x, 0.3, -0.3) masked_array(data=[0.31, 1.2, --, --, -0.4, -1.1], mask=[False, False, True, True, False, False], fill_value=1e+20) Here is the function: def masked_inside(x, v1, v2, copy=True): """ Mask an array inside a given interval. Shortcut to ``masked_where``, where `condition` is True for `x` inside the interval [v1,v2] (v1 <= x <= v2). The boundaries `v1` and `v2` can be given in either order. See Also -------- masked_where : Mask where a condition is met. Notes ----- The array `x` is prefilled with its filling value. Examples -------- >>> import numpy.ma as ma >>> x = [0.31, 1.2, 0.01, 0.2, -0.4, -1.1] >>> ma.masked_inside(x, -0.3, 0.3) masked_array(data=[0.31, 1.2, --, --, -0.4, -1.1], mask=[False, False, True, True, False, False], fill_value=1e+20) The order of `v1` and `v2` doesn't matter. >>> ma.masked_inside(x, 0.3, -0.3) masked_array(data=[0.31, 1.2, --, --, -0.4, -1.1], mask=[False, False, True, True, False, False], fill_value=1e+20) """ if v2 < v1: (v1, v2) = (v2, v1) xf = filled(x) condition = (xf >= v1) & (xf <= v2) return masked_where(condition, x, copy=copy)
Mask an array inside a given interval. Shortcut to ``masked_where``, where `condition` is True for `x` inside the interval [v1,v2] (v1 <= x <= v2). The boundaries `v1` and `v2` can be given in either order. See Also -------- masked_where : Mask where a condition is met. Notes ----- The array `x` is prefilled with its filling value. Examples -------- >>> import numpy.ma as ma >>> x = [0.31, 1.2, 0.01, 0.2, -0.4, -1.1] >>> ma.masked_inside(x, -0.3, 0.3) masked_array(data=[0.31, 1.2, --, --, -0.4, -1.1], mask=[False, False, True, True, False, False], fill_value=1e+20) The order of `v1` and `v2` doesn't matter. >>> ma.masked_inside(x, 0.3, -0.3) masked_array(data=[0.31, 1.2, --, --, -0.4, -1.1], mask=[False, False, True, True, False, False], fill_value=1e+20)
170,103
import builtins import inspect import operator import warnings import textwrap import re from functools import reduce import numpy as np import numpy.core.umath as umath import numpy.core.numerictypes as ntypes from numpy.core import multiarray as mu from numpy import ndarray, amax, amin, iscomplexobj, bool_, _NoValue from numpy import array as narray from numpy.lib.function_base import angle from numpy.compat import ( getargspec, formatargspec, long, unicode, bytes ) from numpy import expand_dims from numpy.core.numeric import normalize_axis_tuple def filled(a, fill_value=None): """ Return input as an array with masked data replaced by a fill value. If `a` is not a `MaskedArray`, `a` itself is returned. If `a` is a `MaskedArray` and `fill_value` is None, `fill_value` is set to ``a.fill_value``. Parameters ---------- a : MaskedArray or array_like An input object. fill_value : array_like, optional. Can be scalar or non-scalar. If non-scalar, the resulting filled array should be broadcastable over input array. Default is None. Returns ------- a : ndarray The filled array. See Also -------- compressed Examples -------- >>> x = np.ma.array(np.arange(9).reshape(3, 3), mask=[[1, 0, 0], ... [1, 0, 0], ... [0, 0, 0]]) >>> x.filled() array([[999999, 1, 2], [999999, 4, 5], [ 6, 7, 8]]) >>> x.filled(fill_value=333) array([[333, 1, 2], [333, 4, 5], [ 6, 7, 8]]) >>> x.filled(fill_value=np.arange(3)) array([[0, 1, 2], [0, 4, 5], [6, 7, 8]]) """ if hasattr(a, 'filled'): return a.filled(fill_value) elif isinstance(a, ndarray): # Should we check for contiguity ? and a.flags['CONTIGUOUS']: return a elif isinstance(a, dict): return np.array(a, 'O') else: return np.array(a) def masked_where(condition, a, copy=True): """ Mask an array where a condition is met. Return `a` as an array masked where `condition` is True. Any masked values of `a` or `condition` are also masked in the output. Parameters ---------- condition : array_like Masking condition. When `condition` tests floating point values for equality, consider using ``masked_values`` instead. a : array_like Array to mask. copy : bool If True (default) make a copy of `a` in the result. If False modify `a` in place and return a view. Returns ------- result : MaskedArray The result of masking `a` where `condition` is True. See Also -------- masked_values : Mask using floating point equality. masked_equal : Mask where equal to a given value. masked_not_equal : Mask where `not` equal to a given value. masked_less_equal : Mask where less than or equal to a given value. masked_greater_equal : Mask where greater than or equal to a given value. masked_less : Mask where less than a given value. masked_greater : Mask where greater than a given value. masked_inside : Mask inside a given interval. masked_outside : Mask outside a given interval. masked_invalid : Mask invalid values (NaNs or infs). Examples -------- >>> import numpy.ma as ma >>> a = np.arange(4) >>> a array([0, 1, 2, 3]) >>> ma.masked_where(a <= 2, a) masked_array(data=[--, --, --, 3], mask=[ True, True, True, False], fill_value=999999) Mask array `b` conditional on `a`. >>> b = ['a', 'b', 'c', 'd'] >>> ma.masked_where(a == 2, b) masked_array(data=['a', 'b', --, 'd'], mask=[False, False, True, False], fill_value='N/A', dtype='<U1') Effect of the `copy` argument. >>> c = ma.masked_where(a <= 2, a) >>> c masked_array(data=[--, --, --, 3], mask=[ True, True, True, False], fill_value=999999) >>> c[0] = 99 >>> c masked_array(data=[99, --, --, 3], mask=[False, True, True, False], fill_value=999999) >>> a array([0, 1, 2, 3]) >>> c = ma.masked_where(a <= 2, a, copy=False) >>> c[0] = 99 >>> c masked_array(data=[99, --, --, 3], mask=[False, True, True, False], fill_value=999999) >>> a array([99, 1, 2, 3]) When `condition` or `a` contain masked values. >>> a = np.arange(4) >>> a = ma.masked_where(a == 2, a) >>> a masked_array(data=[0, 1, --, 3], mask=[False, False, True, False], fill_value=999999) >>> b = np.arange(4) >>> b = ma.masked_where(b == 0, b) >>> b masked_array(data=[--, 1, 2, 3], mask=[ True, False, False, False], fill_value=999999) >>> ma.masked_where(a == 3, b) masked_array(data=[--, 1, --, --], mask=[ True, False, True, True], fill_value=999999) """ # Make sure that condition is a valid standard-type mask. cond = make_mask(condition, shrink=False) a = np.array(a, copy=copy, subok=True) (cshape, ashape) = (cond.shape, a.shape) if cshape and cshape != ashape: raise IndexError("Inconsistent shape between the condition and the input" " (got %s and %s)" % (cshape, ashape)) if hasattr(a, '_mask'): cond = mask_or(cond, a._mask) cls = type(a) else: cls = MaskedArray result = a.view(cls) # Assign to *.mask so that structured masks are handled correctly. result.mask = _shrink_mask(cond) # There is no view of a boolean so when 'a' is a MaskedArray with nomask # the update to the result's mask has no effect. if not copy and hasattr(a, '_mask') and getmask(a) is nomask: a._mask = result._mask.view() return result The provided code snippet includes necessary dependencies for implementing the `masked_outside` function. Write a Python function `def masked_outside(x, v1, v2, copy=True)` to solve the following problem: Mask an array outside a given interval. Shortcut to ``masked_where``, where `condition` is True for `x` outside the interval [v1,v2] (x < v1)|(x > v2). The boundaries `v1` and `v2` can be given in either order. See Also -------- masked_where : Mask where a condition is met. Notes ----- The array `x` is prefilled with its filling value. Examples -------- >>> import numpy.ma as ma >>> x = [0.31, 1.2, 0.01, 0.2, -0.4, -1.1] >>> ma.masked_outside(x, -0.3, 0.3) masked_array(data=[--, --, 0.01, 0.2, --, --], mask=[ True, True, False, False, True, True], fill_value=1e+20) The order of `v1` and `v2` doesn't matter. >>> ma.masked_outside(x, 0.3, -0.3) masked_array(data=[--, --, 0.01, 0.2, --, --], mask=[ True, True, False, False, True, True], fill_value=1e+20) Here is the function: def masked_outside(x, v1, v2, copy=True): """ Mask an array outside a given interval. Shortcut to ``masked_where``, where `condition` is True for `x` outside the interval [v1,v2] (x < v1)|(x > v2). The boundaries `v1` and `v2` can be given in either order. See Also -------- masked_where : Mask where a condition is met. Notes ----- The array `x` is prefilled with its filling value. Examples -------- >>> import numpy.ma as ma >>> x = [0.31, 1.2, 0.01, 0.2, -0.4, -1.1] >>> ma.masked_outside(x, -0.3, 0.3) masked_array(data=[--, --, 0.01, 0.2, --, --], mask=[ True, True, False, False, True, True], fill_value=1e+20) The order of `v1` and `v2` doesn't matter. >>> ma.masked_outside(x, 0.3, -0.3) masked_array(data=[--, --, 0.01, 0.2, --, --], mask=[ True, True, False, False, True, True], fill_value=1e+20) """ if v2 < v1: (v1, v2) = (v2, v1) xf = filled(x) condition = (xf < v1) | (xf > v2) return masked_where(condition, x, copy=copy)
Mask an array outside a given interval. Shortcut to ``masked_where``, where `condition` is True for `x` outside the interval [v1,v2] (x < v1)|(x > v2). The boundaries `v1` and `v2` can be given in either order. See Also -------- masked_where : Mask where a condition is met. Notes ----- The array `x` is prefilled with its filling value. Examples -------- >>> import numpy.ma as ma >>> x = [0.31, 1.2, 0.01, 0.2, -0.4, -1.1] >>> ma.masked_outside(x, -0.3, 0.3) masked_array(data=[--, --, 0.01, 0.2, --, --], mask=[ True, True, False, False, True, True], fill_value=1e+20) The order of `v1` and `v2` doesn't matter. >>> ma.masked_outside(x, 0.3, -0.3) masked_array(data=[--, --, 0.01, 0.2, --, --], mask=[ True, True, False, False, True, True], fill_value=1e+20)
170,104
import builtins import inspect import operator import warnings import textwrap import re from functools import reduce import numpy as np import numpy.core.umath as umath import numpy.core.numerictypes as ntypes from numpy.core import multiarray as mu from numpy import ndarray, amax, amin, iscomplexobj, bool_, _NoValue from numpy import array as narray from numpy.lib.function_base import angle from numpy.compat import ( getargspec, formatargspec, long, unicode, bytes ) from numpy import expand_dims from numpy.core.numeric import normalize_axis_tuple nomask = MaskType(0) equal = _MaskedBinaryOperation(umath.equal) equal.reduce = None def make_mask(m, copy=False, shrink=True, dtype=MaskType): """ Create a boolean mask from an array. Return `m` as a boolean mask, creating a copy if necessary or requested. The function can accept any sequence that is convertible to integers, or ``nomask``. Does not require that contents must be 0s and 1s, values of 0 are interpreted as False, everything else as True. Parameters ---------- m : array_like Potential mask. copy : bool, optional Whether to return a copy of `m` (True) or `m` itself (False). shrink : bool, optional Whether to shrink `m` to ``nomask`` if all its values are False. dtype : dtype, optional Data-type of the output mask. By default, the output mask has a dtype of MaskType (bool). If the dtype is flexible, each field has a boolean dtype. This is ignored when `m` is ``nomask``, in which case ``nomask`` is always returned. Returns ------- result : ndarray A boolean mask derived from `m`. Examples -------- >>> import numpy.ma as ma >>> m = [True, False, True, True] >>> ma.make_mask(m) array([ True, False, True, True]) >>> m = [1, 0, 1, 1] >>> ma.make_mask(m) array([ True, False, True, True]) >>> m = [1, 0, 2, -3] >>> ma.make_mask(m) array([ True, False, True, True]) Effect of the `shrink` parameter. >>> m = np.zeros(4) >>> m array([0., 0., 0., 0.]) >>> ma.make_mask(m) False >>> ma.make_mask(m, shrink=False) array([False, False, False, False]) Using a flexible `dtype`. >>> m = [1, 0, 1, 1] >>> n = [0, 1, 0, 0] >>> arr = [] >>> for man, mouse in zip(m, n): ... arr.append((man, mouse)) >>> arr [(1, 0), (0, 1), (1, 0), (1, 0)] >>> dtype = np.dtype({'names':['man', 'mouse'], ... 'formats':[np.int64, np.int64]}) >>> arr = np.array(arr, dtype=dtype) >>> arr array([(1, 0), (0, 1), (1, 0), (1, 0)], dtype=[('man', '<i8'), ('mouse', '<i8')]) >>> ma.make_mask(arr, dtype=dtype) array([(True, False), (False, True), (True, False), (True, False)], dtype=[('man', '|b1'), ('mouse', '|b1')]) """ if m is nomask: return nomask # Make sure the input dtype is valid. dtype = make_mask_descr(dtype) # legacy boolean special case: "existence of fields implies true" if isinstance(m, ndarray) and m.dtype.fields and dtype == np.bool_: return np.ones(m.shape, dtype=dtype) # Fill the mask in case there are missing data; turn it into an ndarray. result = np.array(filled(m, True), copy=copy, dtype=dtype, subok=True) # Bas les masques ! if shrink: result = _shrink_mask(result) return result def mask_or(m1, m2, copy=False, shrink=True): """ Combine two masks with the ``logical_or`` operator. The result may be a view on `m1` or `m2` if the other is `nomask` (i.e. False). Parameters ---------- m1, m2 : array_like Input masks. copy : bool, optional If copy is False and one of the inputs is `nomask`, return a view of the other input mask. Defaults to False. shrink : bool, optional Whether to shrink the output to `nomask` if all its values are False. Defaults to True. Returns ------- mask : output mask The result masks values that are masked in either `m1` or `m2`. Raises ------ ValueError If `m1` and `m2` have different flexible dtypes. Examples -------- >>> m1 = np.ma.make_mask([0, 1, 1, 0]) >>> m2 = np.ma.make_mask([1, 0, 0, 0]) >>> np.ma.mask_or(m1, m2) array([ True, True, True, False]) """ if (m1 is nomask) or (m1 is False): dtype = getattr(m2, 'dtype', MaskType) return make_mask(m2, copy=copy, shrink=shrink, dtype=dtype) if (m2 is nomask) or (m2 is False): dtype = getattr(m1, 'dtype', MaskType) return make_mask(m1, copy=copy, shrink=shrink, dtype=dtype) if m1 is m2 and is_mask(m1): return m1 (dtype1, dtype2) = (getattr(m1, 'dtype', None), getattr(m2, 'dtype', None)) if dtype1 != dtype2: raise ValueError("Incompatible dtypes '%s'<>'%s'" % (dtype1, dtype2)) if dtype1.names is not None: # Allocate an output mask array with the properly broadcast shape. newmask = np.empty(np.broadcast(m1, m2).shape, dtype1) _recursive_mask_or(m1, m2, newmask) return newmask return make_mask(umath.logical_or(m1, m2), copy=copy, shrink=shrink) def isMaskedArray(x): """ Test whether input is an instance of MaskedArray. This function returns True if `x` is an instance of MaskedArray and returns False otherwise. Any object is accepted as input. Parameters ---------- x : object Object to test. Returns ------- result : bool True if `x` is a MaskedArray. See Also -------- isMA : Alias to isMaskedArray. isarray : Alias to isMaskedArray. Examples -------- >>> import numpy.ma as ma >>> a = np.eye(3, 3) >>> a array([[ 1., 0., 0.], [ 0., 1., 0.], [ 0., 0., 1.]]) >>> m = ma.masked_values(a, 0) >>> m masked_array( data=[[1.0, --, --], [--, 1.0, --], [--, --, 1.0]], mask=[[False, True, True], [ True, False, True], [ True, True, False]], fill_value=0.0) >>> ma.isMaskedArray(a) False >>> ma.isMaskedArray(m) True >>> ma.isMaskedArray([0, 1, 2]) False """ return isinstance(x, MaskedArray) masked_array = MaskedArray def asarray(a, dtype=None, order=None): """ Convert the input to a masked array of the given data-type. No copy is performed if the input is already an `ndarray`. If `a` is a subclass of `MaskedArray`, a base class `MaskedArray` is returned. Parameters ---------- a : array_like Input data, in any form that can be converted to a masked array. This includes lists, lists of tuples, tuples, tuples of tuples, tuples of lists, ndarrays and masked arrays. dtype : dtype, optional By default, the data-type is inferred from the input data. order : {'C', 'F'}, optional Whether to use row-major ('C') or column-major ('FORTRAN') memory representation. Default is 'C'. Returns ------- out : MaskedArray Masked array interpretation of `a`. See Also -------- asanyarray : Similar to `asarray`, but conserves subclasses. Examples -------- >>> x = np.arange(10.).reshape(2, 5) >>> x array([[0., 1., 2., 3., 4.], [5., 6., 7., 8., 9.]]) >>> np.ma.asarray(x) masked_array( data=[[0., 1., 2., 3., 4.], [5., 6., 7., 8., 9.]], mask=False, fill_value=1e+20) >>> type(np.ma.asarray(x)) <class 'numpy.ma.core.MaskedArray'> """ order = order or 'C' return masked_array(a, dtype=dtype, copy=False, keep_mask=True, subok=False, order=order) The provided code snippet includes necessary dependencies for implementing the `masked_object` function. Write a Python function `def masked_object(x, value, copy=True, shrink=True)` to solve the following problem: Mask the array `x` where the data are exactly equal to value. This function is similar to `masked_values`, but only suitable for object arrays: for floating point, use `masked_values` instead. Parameters ---------- x : array_like Array to mask value : object Comparison value copy : {True, False}, optional Whether to return a copy of `x`. shrink : {True, False}, optional Whether to collapse a mask full of False to nomask Returns ------- result : MaskedArray The result of masking `x` where equal to `value`. See Also -------- masked_where : Mask where a condition is met. masked_equal : Mask where equal to a given value (integers). masked_values : Mask using floating point equality. Examples -------- >>> import numpy.ma as ma >>> food = np.array(['green_eggs', 'ham'], dtype=object) >>> # don't eat spoiled food >>> eat = ma.masked_object(food, 'green_eggs') >>> eat masked_array(data=[--, 'ham'], mask=[ True, False], fill_value='green_eggs', dtype=object) >>> # plain ol` ham is boring >>> fresh_food = np.array(['cheese', 'ham', 'pineapple'], dtype=object) >>> eat = ma.masked_object(fresh_food, 'green_eggs') >>> eat masked_array(data=['cheese', 'ham', 'pineapple'], mask=False, fill_value='green_eggs', dtype=object) Note that `mask` is set to ``nomask`` if possible. >>> eat masked_array(data=['cheese', 'ham', 'pineapple'], mask=False, fill_value='green_eggs', dtype=object) Here is the function: def masked_object(x, value, copy=True, shrink=True): """ Mask the array `x` where the data are exactly equal to value. This function is similar to `masked_values`, but only suitable for object arrays: for floating point, use `masked_values` instead. Parameters ---------- x : array_like Array to mask value : object Comparison value copy : {True, False}, optional Whether to return a copy of `x`. shrink : {True, False}, optional Whether to collapse a mask full of False to nomask Returns ------- result : MaskedArray The result of masking `x` where equal to `value`. See Also -------- masked_where : Mask where a condition is met. masked_equal : Mask where equal to a given value (integers). masked_values : Mask using floating point equality. Examples -------- >>> import numpy.ma as ma >>> food = np.array(['green_eggs', 'ham'], dtype=object) >>> # don't eat spoiled food >>> eat = ma.masked_object(food, 'green_eggs') >>> eat masked_array(data=[--, 'ham'], mask=[ True, False], fill_value='green_eggs', dtype=object) >>> # plain ol` ham is boring >>> fresh_food = np.array(['cheese', 'ham', 'pineapple'], dtype=object) >>> eat = ma.masked_object(fresh_food, 'green_eggs') >>> eat masked_array(data=['cheese', 'ham', 'pineapple'], mask=False, fill_value='green_eggs', dtype=object) Note that `mask` is set to ``nomask`` if possible. >>> eat masked_array(data=['cheese', 'ham', 'pineapple'], mask=False, fill_value='green_eggs', dtype=object) """ if isMaskedArray(x): condition = umath.equal(x._data, value) mask = x._mask else: condition = umath.equal(np.asarray(x), value) mask = nomask mask = mask_or(mask, make_mask(condition, shrink=shrink)) return masked_array(x, mask=mask, copy=copy, fill_value=value)
Mask the array `x` where the data are exactly equal to value. This function is similar to `masked_values`, but only suitable for object arrays: for floating point, use `masked_values` instead. Parameters ---------- x : array_like Array to mask value : object Comparison value copy : {True, False}, optional Whether to return a copy of `x`. shrink : {True, False}, optional Whether to collapse a mask full of False to nomask Returns ------- result : MaskedArray The result of masking `x` where equal to `value`. See Also -------- masked_where : Mask where a condition is met. masked_equal : Mask where equal to a given value (integers). masked_values : Mask using floating point equality. Examples -------- >>> import numpy.ma as ma >>> food = np.array(['green_eggs', 'ham'], dtype=object) >>> # don't eat spoiled food >>> eat = ma.masked_object(food, 'green_eggs') >>> eat masked_array(data=[--, 'ham'], mask=[ True, False], fill_value='green_eggs', dtype=object) >>> # plain ol` ham is boring >>> fresh_food = np.array(['cheese', 'ham', 'pineapple'], dtype=object) >>> eat = ma.masked_object(fresh_food, 'green_eggs') >>> eat masked_array(data=['cheese', 'ham', 'pineapple'], mask=False, fill_value='green_eggs', dtype=object) Note that `mask` is set to ``nomask`` if possible. >>> eat masked_array(data=['cheese', 'ham', 'pineapple'], mask=False, fill_value='green_eggs', dtype=object)
170,105
import builtins import inspect import operator import warnings import textwrap import re from functools import reduce import numpy as np import numpy.core.umath as umath import numpy.core.numerictypes as ntypes from numpy.core import multiarray as mu from numpy import ndarray, amax, amin, iscomplexobj, bool_, _NoValue from numpy import array as narray from numpy.lib.function_base import angle from numpy.compat import ( getargspec, formatargspec, long, unicode, bytes ) from numpy import expand_dims from numpy.core.numeric import normalize_axis_tuple def filled(a, fill_value=None): """ Return input as an array with masked data replaced by a fill value. If `a` is not a `MaskedArray`, `a` itself is returned. If `a` is a `MaskedArray` and `fill_value` is None, `fill_value` is set to ``a.fill_value``. Parameters ---------- a : MaskedArray or array_like An input object. fill_value : array_like, optional. Can be scalar or non-scalar. If non-scalar, the resulting filled array should be broadcastable over input array. Default is None. Returns ------- a : ndarray The filled array. See Also -------- compressed Examples -------- >>> x = np.ma.array(np.arange(9).reshape(3, 3), mask=[[1, 0, 0], ... [1, 0, 0], ... [0, 0, 0]]) >>> x.filled() array([[999999, 1, 2], [999999, 4, 5], [ 6, 7, 8]]) >>> x.filled(fill_value=333) array([[333, 1, 2], [333, 4, 5], [ 6, 7, 8]]) >>> x.filled(fill_value=np.arange(3)) array([[0, 1, 2], [0, 4, 5], [6, 7, 8]]) """ if hasattr(a, 'filled'): return a.filled(fill_value) elif isinstance(a, ndarray): # Should we check for contiguity ? and a.flags['CONTIGUOUS']: return a elif isinstance(a, dict): return np.array(a, 'O') else: return np.array(a) equal = _MaskedBinaryOperation(umath.equal) equal.reduce = None masked_array = MaskedArray shrink_mask = _frommethod('shrink_mask') The provided code snippet includes necessary dependencies for implementing the `masked_values` function. Write a Python function `def masked_values(x, value, rtol=1e-5, atol=1e-8, copy=True, shrink=True)` to solve the following problem: Mask using floating point equality. Return a MaskedArray, masked where the data in array `x` are approximately equal to `value`, determined using `isclose`. The default tolerances for `masked_values` are the same as those for `isclose`. For integer types, exact equality is used, in the same way as `masked_equal`. The fill_value is set to `value` and the mask is set to ``nomask`` if possible. Parameters ---------- x : array_like Array to mask. value : float Masking value. rtol, atol : float, optional Tolerance parameters passed on to `isclose` copy : bool, optional Whether to return a copy of `x`. shrink : bool, optional Whether to collapse a mask full of False to ``nomask``. Returns ------- result : MaskedArray The result of masking `x` where approximately equal to `value`. See Also -------- masked_where : Mask where a condition is met. masked_equal : Mask where equal to a given value (integers). Examples -------- >>> import numpy.ma as ma >>> x = np.array([1, 1.1, 2, 1.1, 3]) >>> ma.masked_values(x, 1.1) masked_array(data=[1.0, --, 2.0, --, 3.0], mask=[False, True, False, True, False], fill_value=1.1) Note that `mask` is set to ``nomask`` if possible. >>> ma.masked_values(x, 2.1) masked_array(data=[1. , 1.1, 2. , 1.1, 3. ], mask=False, fill_value=2.1) Unlike `masked_equal`, `masked_values` can perform approximate equalities. >>> ma.masked_values(x, 2.1, atol=1e-1) masked_array(data=[1.0, 1.1, --, 1.1, 3.0], mask=[False, False, True, False, False], fill_value=2.1) Here is the function: def masked_values(x, value, rtol=1e-5, atol=1e-8, copy=True, shrink=True): """ Mask using floating point equality. Return a MaskedArray, masked where the data in array `x` are approximately equal to `value`, determined using `isclose`. The default tolerances for `masked_values` are the same as those for `isclose`. For integer types, exact equality is used, in the same way as `masked_equal`. The fill_value is set to `value` and the mask is set to ``nomask`` if possible. Parameters ---------- x : array_like Array to mask. value : float Masking value. rtol, atol : float, optional Tolerance parameters passed on to `isclose` copy : bool, optional Whether to return a copy of `x`. shrink : bool, optional Whether to collapse a mask full of False to ``nomask``. Returns ------- result : MaskedArray The result of masking `x` where approximately equal to `value`. See Also -------- masked_where : Mask where a condition is met. masked_equal : Mask where equal to a given value (integers). Examples -------- >>> import numpy.ma as ma >>> x = np.array([1, 1.1, 2, 1.1, 3]) >>> ma.masked_values(x, 1.1) masked_array(data=[1.0, --, 2.0, --, 3.0], mask=[False, True, False, True, False], fill_value=1.1) Note that `mask` is set to ``nomask`` if possible. >>> ma.masked_values(x, 2.1) masked_array(data=[1. , 1.1, 2. , 1.1, 3. ], mask=False, fill_value=2.1) Unlike `masked_equal`, `masked_values` can perform approximate equalities. >>> ma.masked_values(x, 2.1, atol=1e-1) masked_array(data=[1.0, 1.1, --, 1.1, 3.0], mask=[False, False, True, False, False], fill_value=2.1) """ xnew = filled(x, value) if np.issubdtype(xnew.dtype, np.floating): mask = np.isclose(xnew, value, atol=atol, rtol=rtol) else: mask = umath.equal(xnew, value) ret = masked_array(xnew, mask=mask, copy=copy, fill_value=value) if shrink: ret.shrink_mask() return ret
Mask using floating point equality. Return a MaskedArray, masked where the data in array `x` are approximately equal to `value`, determined using `isclose`. The default tolerances for `masked_values` are the same as those for `isclose`. For integer types, exact equality is used, in the same way as `masked_equal`. The fill_value is set to `value` and the mask is set to ``nomask`` if possible. Parameters ---------- x : array_like Array to mask. value : float Masking value. rtol, atol : float, optional Tolerance parameters passed on to `isclose` copy : bool, optional Whether to return a copy of `x`. shrink : bool, optional Whether to collapse a mask full of False to ``nomask``. Returns ------- result : MaskedArray The result of masking `x` where approximately equal to `value`. See Also -------- masked_where : Mask where a condition is met. masked_equal : Mask where equal to a given value (integers). Examples -------- >>> import numpy.ma as ma >>> x = np.array([1, 1.1, 2, 1.1, 3]) >>> ma.masked_values(x, 1.1) masked_array(data=[1.0, --, 2.0, --, 3.0], mask=[False, True, False, True, False], fill_value=1.1) Note that `mask` is set to ``nomask`` if possible. >>> ma.masked_values(x, 2.1) masked_array(data=[1. , 1.1, 2. , 1.1, 3. ], mask=False, fill_value=2.1) Unlike `masked_equal`, `masked_values` can perform approximate equalities. >>> ma.masked_values(x, 2.1, atol=1e-1) masked_array(data=[1.0, 1.1, --, 1.1, 3.0], mask=[False, False, True, False, False], fill_value=2.1)
170,106
import builtins import inspect import operator import warnings import textwrap import re from functools import reduce import numpy as np import numpy.core.umath as umath import numpy.core.numerictypes as ntypes from numpy.core import multiarray as mu from numpy import ndarray, amax, amin, iscomplexobj, bool_, _NoValue from numpy import array as narray from numpy.lib.function_base import angle from numpy.compat import ( getargspec, formatargspec, long, unicode, bytes ) from numpy import expand_dims from numpy.core.numeric import normalize_axis_tuple nomask = MaskType(0) def make_mask_none(newshape, dtype=None): """ Return a boolean mask of the given shape, filled with False. This function returns a boolean ndarray with all entries False, that can be used in common mask manipulations. If a complex dtype is specified, the type of each field is converted to a boolean type. Parameters ---------- newshape : tuple A tuple indicating the shape of the mask. dtype : {None, dtype}, optional If None, use a MaskType instance. Otherwise, use a new datatype with the same fields as `dtype`, converted to boolean types. Returns ------- result : ndarray An ndarray of appropriate shape and dtype, filled with False. See Also -------- make_mask : Create a boolean mask from an array. make_mask_descr : Construct a dtype description list from a given dtype. Examples -------- >>> import numpy.ma as ma >>> ma.make_mask_none((3,)) array([False, False, False]) Defining a more complex dtype. >>> dtype = np.dtype({'names':['foo', 'bar'], ... 'formats':[np.float32, np.int64]}) >>> dtype dtype([('foo', '<f4'), ('bar', '<i8')]) >>> ma.make_mask_none((3,), dtype=dtype) array([(False, False), (False, False), (False, False)], dtype=[('foo', '|b1'), ('bar', '|b1')]) """ if dtype is None: result = np.zeros(newshape, dtype=MaskType) else: result = np.zeros(newshape, dtype=make_mask_descr(dtype)) return result def masked_where(condition, a, copy=True): """ Mask an array where a condition is met. Return `a` as an array masked where `condition` is True. Any masked values of `a` or `condition` are also masked in the output. Parameters ---------- condition : array_like Masking condition. When `condition` tests floating point values for equality, consider using ``masked_values`` instead. a : array_like Array to mask. copy : bool If True (default) make a copy of `a` in the result. If False modify `a` in place and return a view. Returns ------- result : MaskedArray The result of masking `a` where `condition` is True. See Also -------- masked_values : Mask using floating point equality. masked_equal : Mask where equal to a given value. masked_not_equal : Mask where `not` equal to a given value. masked_less_equal : Mask where less than or equal to a given value. masked_greater_equal : Mask where greater than or equal to a given value. masked_less : Mask where less than a given value. masked_greater : Mask where greater than a given value. masked_inside : Mask inside a given interval. masked_outside : Mask outside a given interval. masked_invalid : Mask invalid values (NaNs or infs). Examples -------- >>> import numpy.ma as ma >>> a = np.arange(4) >>> a array([0, 1, 2, 3]) >>> ma.masked_where(a <= 2, a) masked_array(data=[--, --, --, 3], mask=[ True, True, True, False], fill_value=999999) Mask array `b` conditional on `a`. >>> b = ['a', 'b', 'c', 'd'] >>> ma.masked_where(a == 2, b) masked_array(data=['a', 'b', --, 'd'], mask=[False, False, True, False], fill_value='N/A', dtype='<U1') Effect of the `copy` argument. >>> c = ma.masked_where(a <= 2, a) >>> c masked_array(data=[--, --, --, 3], mask=[ True, True, True, False], fill_value=999999) >>> c[0] = 99 >>> c masked_array(data=[99, --, --, 3], mask=[False, True, True, False], fill_value=999999) >>> a array([0, 1, 2, 3]) >>> c = ma.masked_where(a <= 2, a, copy=False) >>> c[0] = 99 >>> c masked_array(data=[99, --, --, 3], mask=[False, True, True, False], fill_value=999999) >>> a array([99, 1, 2, 3]) When `condition` or `a` contain masked values. >>> a = np.arange(4) >>> a = ma.masked_where(a == 2, a) >>> a masked_array(data=[0, 1, --, 3], mask=[False, False, True, False], fill_value=999999) >>> b = np.arange(4) >>> b = ma.masked_where(b == 0, b) >>> b masked_array(data=[--, 1, 2, 3], mask=[ True, False, False, False], fill_value=999999) >>> ma.masked_where(a == 3, b) masked_array(data=[--, 1, --, --], mask=[ True, False, True, True], fill_value=999999) """ # Make sure that condition is a valid standard-type mask. cond = make_mask(condition, shrink=False) a = np.array(a, copy=copy, subok=True) (cshape, ashape) = (cond.shape, a.shape) if cshape and cshape != ashape: raise IndexError("Inconsistent shape between the condition and the input" " (got %s and %s)" % (cshape, ashape)) if hasattr(a, '_mask'): cond = mask_or(cond, a._mask) cls = type(a) else: cls = MaskedArray result = a.view(cls) # Assign to *.mask so that structured masks are handled correctly. result.mask = _shrink_mask(cond) # There is no view of a boolean so when 'a' is a MaskedArray with nomask # the update to the result's mask has no effect. if not copy and hasattr(a, '_mask') and getmask(a) is nomask: a._mask = result._mask.view() return result def array(data, dtype=None, copy=False, order=None, mask=nomask, fill_value=None, keep_mask=True, hard_mask=False, shrink=True, subok=True, ndmin=0): """ Shortcut to MaskedArray. The options are in a different order for convenience and backwards compatibility. """ return MaskedArray(data, mask=mask, dtype=dtype, copy=copy, subok=subok, keep_mask=keep_mask, hard_mask=hard_mask, fill_value=fill_value, ndmin=ndmin, shrink=shrink, order=order) array.__doc__ = masked_array.__doc__ def shape(obj): "maskedarray version of the numpy function." return np.shape(getdata(obj)) shape.__doc__ = np.shape.__doc__ The provided code snippet includes necessary dependencies for implementing the `masked_invalid` function. Write a Python function `def masked_invalid(a, copy=True)` to solve the following problem: Mask an array where invalid values occur (NaNs or infs). This function is a shortcut to ``masked_where``, with `condition` = ~(np.isfinite(a)). Any pre-existing mask is conserved. Only applies to arrays with a dtype where NaNs or infs make sense (i.e. floating point types), but accepts any array_like object. See Also -------- masked_where : Mask where a condition is met. Examples -------- >>> import numpy.ma as ma >>> a = np.arange(5, dtype=float) >>> a[2] = np.NaN >>> a[3] = np.PINF >>> a array([ 0., 1., nan, inf, 4.]) >>> ma.masked_invalid(a) masked_array(data=[0.0, 1.0, --, --, 4.0], mask=[False, False, True, True, False], fill_value=1e+20) Here is the function: def masked_invalid(a, copy=True): """ Mask an array where invalid values occur (NaNs or infs). This function is a shortcut to ``masked_where``, with `condition` = ~(np.isfinite(a)). Any pre-existing mask is conserved. Only applies to arrays with a dtype where NaNs or infs make sense (i.e. floating point types), but accepts any array_like object. See Also -------- masked_where : Mask where a condition is met. Examples -------- >>> import numpy.ma as ma >>> a = np.arange(5, dtype=float) >>> a[2] = np.NaN >>> a[3] = np.PINF >>> a array([ 0., 1., nan, inf, 4.]) >>> ma.masked_invalid(a) masked_array(data=[0.0, 1.0, --, --, 4.0], mask=[False, False, True, True, False], fill_value=1e+20) """ a = np.array(a, copy=False, subok=True) res = masked_where(~(np.isfinite(a)), a, copy=copy) # masked_invalid previously never returned nomask as a mask and doing so # threw off matplotlib (gh-22842). So use shrink=False: if res._mask is nomask: res._mask = make_mask_none(res.shape, res.dtype) return res
Mask an array where invalid values occur (NaNs or infs). This function is a shortcut to ``masked_where``, with `condition` = ~(np.isfinite(a)). Any pre-existing mask is conserved. Only applies to arrays with a dtype where NaNs or infs make sense (i.e. floating point types), but accepts any array_like object. See Also -------- masked_where : Mask where a condition is met. Examples -------- >>> import numpy.ma as ma >>> a = np.arange(5, dtype=float) >>> a[2] = np.NaN >>> a[3] = np.PINF >>> a array([ 0., 1., nan, inf, 4.]) >>> ma.masked_invalid(a) masked_array(data=[0.0, 1.0, --, --, 4.0], mask=[False, False, True, True, False], fill_value=1e+20)
170,107
import builtins import inspect import operator import warnings import textwrap import re from functools import reduce import numpy as np import numpy.core.umath as umath import numpy.core.numerictypes as ntypes from numpy.core import multiarray as mu from numpy import ndarray, amax, amin, iscomplexobj, bool_, _NoValue from numpy import array as narray from numpy.lib.function_base import angle from numpy.compat import ( getargspec, formatargspec, long, unicode, bytes ) from numpy import expand_dims from numpy.core.numeric import normalize_axis_tuple def where(condition, x=_NoValue, y=_NoValue): """ Return a masked array with elements from `x` or `y`, depending on condition. .. note:: When only `condition` is provided, this function is identical to `nonzero`. The rest of this documentation covers only the case where all three arguments are provided. Parameters ---------- condition : array_like, bool Where True, yield `x`, otherwise yield `y`. x, y : array_like, optional Values from which to choose. `x`, `y` and `condition` need to be broadcastable to some shape. Returns ------- out : MaskedArray An masked array with `masked` elements where the condition is masked, elements from `x` where `condition` is True, and elements from `y` elsewhere. See Also -------- numpy.where : Equivalent function in the top-level NumPy module. nonzero : The function that is called when x and y are omitted Examples -------- >>> x = np.ma.array(np.arange(9.).reshape(3, 3), mask=[[0, 1, 0], ... [1, 0, 1], ... [0, 1, 0]]) >>> x masked_array( data=[[0.0, --, 2.0], [--, 4.0, --], [6.0, --, 8.0]], mask=[[False, True, False], [ True, False, True], [False, True, False]], fill_value=1e+20) >>> np.ma.where(x > 5, x, -3.1416) masked_array( data=[[-3.1416, --, -3.1416], [--, -3.1416, --], [6.0, --, 8.0]], mask=[[False, True, False], [ True, False, True], [False, True, False]], fill_value=1e+20) """ # handle the single-argument case missing = (x is _NoValue, y is _NoValue).count(True) if missing == 1: raise ValueError("Must provide both 'x' and 'y' or neither.") if missing == 2: return nonzero(condition) # we only care if the condition is true - false or masked pick y cf = filled(condition, False) xd = getdata(x) yd = getdata(y) # we need the full arrays here for correct final dimensions cm = getmaskarray(condition) xm = getmaskarray(x) ym = getmaskarray(y) # deal with the fact that masked.dtype == float64, but we don't actually # want to treat it as that. if x is masked and y is not masked: xd = np.zeros((), dtype=yd.dtype) xm = np.ones((), dtype=ym.dtype) elif y is masked and x is not masked: yd = np.zeros((), dtype=xd.dtype) ym = np.ones((), dtype=xm.dtype) data = np.where(cf, xd, yd) mask = np.where(cf, xm, ym) mask = np.where(cm, np.ones((), dtype=mask.dtype), mask) # collapse the mask, for backwards compatibility mask = _shrink_mask(mask) return masked_array(data, mask=mask) The provided code snippet includes necessary dependencies for implementing the `_recursive_printoption` function. Write a Python function `def _recursive_printoption(result, mask, printopt)` to solve the following problem: Puts printoptions in result where mask is True. Private function allowing for recursion Here is the function: def _recursive_printoption(result, mask, printopt): """ Puts printoptions in result where mask is True. Private function allowing for recursion """ names = result.dtype.names if names is not None: for name in names: curdata = result[name] curmask = mask[name] _recursive_printoption(curdata, curmask, printopt) else: np.copyto(result, printopt, where=mask) return
Puts printoptions in result where mask is True. Private function allowing for recursion
170,108
import builtins import inspect import operator import warnings import textwrap import re from functools import reduce import numpy as np import numpy.core.umath as umath import numpy.core.numerictypes as ntypes from numpy.core import multiarray as mu from numpy import ndarray, amax, amin, iscomplexobj, bool_, _NoValue from numpy import array as narray from numpy.lib.function_base import angle from numpy.compat import ( getargspec, formatargspec, long, unicode, bytes ) from numpy import expand_dims from numpy.core.numeric import normalize_axis_tuple def where(condition, x=_NoValue, y=_NoValue): """ Return a masked array with elements from `x` or `y`, depending on condition. .. note:: When only `condition` is provided, this function is identical to `nonzero`. The rest of this documentation covers only the case where all three arguments are provided. Parameters ---------- condition : array_like, bool Where True, yield `x`, otherwise yield `y`. x, y : array_like, optional Values from which to choose. `x`, `y` and `condition` need to be broadcastable to some shape. Returns ------- out : MaskedArray An masked array with `masked` elements where the condition is masked, elements from `x` where `condition` is True, and elements from `y` elsewhere. See Also -------- numpy.where : Equivalent function in the top-level NumPy module. nonzero : The function that is called when x and y are omitted Examples -------- >>> x = np.ma.array(np.arange(9.).reshape(3, 3), mask=[[0, 1, 0], ... [1, 0, 1], ... [0, 1, 0]]) >>> x masked_array( data=[[0.0, --, 2.0], [--, 4.0, --], [6.0, --, 8.0]], mask=[[False, True, False], [ True, False, True], [False, True, False]], fill_value=1e+20) >>> np.ma.where(x > 5, x, -3.1416) masked_array( data=[[-3.1416, --, -3.1416], [--, -3.1416, --], [6.0, --, 8.0]], mask=[[False, True, False], [ True, False, True], [False, True, False]], fill_value=1e+20) """ # handle the single-argument case missing = (x is _NoValue, y is _NoValue).count(True) if missing == 1: raise ValueError("Must provide both 'x' and 'y' or neither.") if missing == 2: return nonzero(condition) # we only care if the condition is true - false or masked pick y cf = filled(condition, False) xd = getdata(x) yd = getdata(y) # we need the full arrays here for correct final dimensions cm = getmaskarray(condition) xm = getmaskarray(x) ym = getmaskarray(y) # deal with the fact that masked.dtype == float64, but we don't actually # want to treat it as that. if x is masked and y is not masked: xd = np.zeros((), dtype=yd.dtype) xm = np.ones((), dtype=ym.dtype) elif y is masked and x is not masked: yd = np.zeros((), dtype=xd.dtype) ym = np.ones((), dtype=xm.dtype) data = np.where(cf, xd, yd) mask = np.where(cf, xm, ym) mask = np.where(cm, np.ones((), dtype=mask.dtype), mask) # collapse the mask, for backwards compatibility mask = _shrink_mask(mask) return masked_array(data, mask=mask) The provided code snippet includes necessary dependencies for implementing the `_recursive_filled` function. Write a Python function `def _recursive_filled(a, mask, fill_value)` to solve the following problem: Recursively fill `a` with `fill_value`. Here is the function: def _recursive_filled(a, mask, fill_value): """ Recursively fill `a` with `fill_value`. """ names = a.dtype.names for name in names: current = a[name] if current.dtype.names is not None: _recursive_filled(current, mask[name], fill_value[name]) else: np.copyto(current, fill_value[name], where=mask[name])
Recursively fill `a` with `fill_value`.
170,109
import builtins import inspect import operator import warnings import textwrap import re from functools import reduce import numpy as np import numpy.core.umath as umath import numpy.core.numerictypes as ntypes from numpy.core import multiarray as mu from numpy import ndarray, amax, amin, iscomplexobj, bool_, _NoValue from numpy import array as narray from numpy.lib.function_base import angle from numpy.compat import ( getargspec, formatargspec, long, unicode, bytes ) from numpy import expand_dims from numpy.core.numeric import normalize_axis_tuple def getmaskarray(arr): """ Return the mask of a masked array, or full boolean array of False. Return the mask of `arr` as an ndarray if `arr` is a `MaskedArray` and the mask is not `nomask`, else return a full boolean array of False of the same shape as `arr`. Parameters ---------- arr : array_like Input `MaskedArray` for which the mask is required. See Also -------- getmask : Return the mask of a masked array, or nomask. getdata : Return the data of a masked array as an ndarray. Examples -------- >>> import numpy.ma as ma >>> a = ma.masked_equal([[1,2],[3,4]], 2) >>> a masked_array( data=[[1, --], [3, 4]], mask=[[False, True], [False, False]], fill_value=2) >>> ma.getmaskarray(a) array([[False, True], [False, False]]) Result when mask == ``nomask`` >>> b = ma.masked_array([[1,2],[3,4]]) >>> b masked_array( data=[[1, 2], [3, 4]], mask=False, fill_value=999999) >>> ma.getmaskarray(b) array([[False, False], [False, False]]) """ mask = getmask(arr) if mask is nomask: mask = make_mask_none(np.shape(arr), getattr(arr, 'dtype', None)) return mask class MaskedArray(ndarray): """ An array class with possibly masked values. Masked values of True exclude the corresponding element from any computation. Construction:: x = MaskedArray(data, mask=nomask, dtype=None, copy=False, subok=True, ndmin=0, fill_value=None, keep_mask=True, hard_mask=None, shrink=True, order=None) Parameters ---------- data : array_like Input data. mask : sequence, optional Mask. Must be convertible to an array of booleans with the same shape as `data`. True indicates a masked (i.e. invalid) data. dtype : dtype, optional Data type of the output. If `dtype` is None, the type of the data argument (``data.dtype``) is used. If `dtype` is not None and different from ``data.dtype``, a copy is performed. copy : bool, optional Whether to copy the input data (True), or to use a reference instead. Default is False. subok : bool, optional Whether to return a subclass of `MaskedArray` if possible (True) or a plain `MaskedArray`. Default is True. ndmin : int, optional Minimum number of dimensions. Default is 0. fill_value : scalar, optional Value used to fill in the masked values when necessary. If None, a default based on the data-type is used. keep_mask : bool, optional Whether to combine `mask` with the mask of the input data, if any (True), or to use only `mask` for the output (False). Default is True. hard_mask : bool, optional Whether to use a hard mask or not. With a hard mask, masked values cannot be unmasked. Default is False. shrink : bool, optional Whether to force compression of an empty mask. Default is True. order : {'C', 'F', 'A'}, optional Specify the order of the array. If order is 'C', then the array will be in C-contiguous order (last-index varies the fastest). If order is 'F', then the returned array will be in Fortran-contiguous order (first-index varies the fastest). If order is 'A' (default), then the returned array may be in any order (either C-, Fortran-contiguous, or even discontiguous), unless a copy is required, in which case it will be C-contiguous. Examples -------- The ``mask`` can be initialized with an array of boolean values with the same shape as ``data``. >>> data = np.arange(6).reshape((2, 3)) >>> np.ma.MaskedArray(data, mask=[[False, True, False], ... [False, False, True]]) masked_array( data=[[0, --, 2], [3, 4, --]], mask=[[False, True, False], [False, False, True]], fill_value=999999) Alternatively, the ``mask`` can be initialized to homogeneous boolean array with the same shape as ``data`` by passing in a scalar boolean value: >>> np.ma.MaskedArray(data, mask=False) masked_array( data=[[0, 1, 2], [3, 4, 5]], mask=[[False, False, False], [False, False, False]], fill_value=999999) >>> np.ma.MaskedArray(data, mask=True) masked_array( data=[[--, --, --], [--, --, --]], mask=[[ True, True, True], [ True, True, True]], fill_value=999999, dtype=int64) .. note:: The recommended practice for initializing ``mask`` with a scalar boolean value is to use ``True``/``False`` rather than ``np.True_``/``np.False_``. The reason is :attr:`nomask` is represented internally as ``np.False_``. >>> np.False_ is np.ma.nomask True """ __array_priority__ = 15 _defaultmask = nomask _defaulthardmask = False _baseclass = ndarray # Maximum number of elements per axis used when printing an array. The # 1d case is handled separately because we need more values in this case. _print_width = 100 _print_width_1d = 1500 def __new__(cls, data=None, mask=nomask, dtype=None, copy=False, subok=True, ndmin=0, fill_value=None, keep_mask=True, hard_mask=None, shrink=True, order=None): """ Create a new masked array from scratch. Notes ----- A masked array can also be created by taking a .view(MaskedArray). """ # Process data. _data = np.array(data, dtype=dtype, copy=copy, order=order, subok=True, ndmin=ndmin) _baseclass = getattr(data, '_baseclass', type(_data)) # Check that we're not erasing the mask. if isinstance(data, MaskedArray) and (data.shape != _data.shape): copy = True # Here, we copy the _view_, so that we can attach new properties to it # we must never do .view(MaskedConstant), as that would create a new # instance of np.ma.masked, which make identity comparison fail if isinstance(data, cls) and subok and not isinstance(data, MaskedConstant): _data = ndarray.view(_data, type(data)) else: _data = ndarray.view(_data, cls) # Handle the case where data is not a subclass of ndarray, but # still has the _mask attribute like MaskedArrays if hasattr(data, '_mask') and not isinstance(data, ndarray): _data._mask = data._mask # FIXME: should we set `_data._sharedmask = True`? # Process mask. # Type of the mask mdtype = make_mask_descr(_data.dtype) if mask is nomask: # Case 1. : no mask in input. # Erase the current mask ? if not keep_mask: # With a reduced version if shrink: _data._mask = nomask # With full version else: _data._mask = np.zeros(_data.shape, dtype=mdtype) # Check whether we missed something elif isinstance(data, (tuple, list)): try: # If data is a sequence of masked array mask = np.array( [getmaskarray(np.asanyarray(m, dtype=_data.dtype)) for m in data], dtype=mdtype) except ValueError: # If data is nested mask = nomask # Force shrinking of the mask if needed (and possible) if (mdtype == MaskType) and mask.any(): _data._mask = mask _data._sharedmask = False else: _data._sharedmask = not copy if copy: _data._mask = _data._mask.copy() # Reset the shape of the original mask if getmask(data) is not nomask: data._mask.shape = data.shape else: # Case 2. : With a mask in input. # If mask is boolean, create an array of True or False if mask is True and mdtype == MaskType: mask = np.ones(_data.shape, dtype=mdtype) elif mask is False and mdtype == MaskType: mask = np.zeros(_data.shape, dtype=mdtype) else: # Read the mask with the current mdtype try: mask = np.array(mask, copy=copy, dtype=mdtype) # Or assume it's a sequence of bool/int except TypeError: mask = np.array([tuple([m] * len(mdtype)) for m in mask], dtype=mdtype) # Make sure the mask and the data have the same shape if mask.shape != _data.shape: (nd, nm) = (_data.size, mask.size) if nm == 1: mask = np.resize(mask, _data.shape) elif nm == nd: mask = np.reshape(mask, _data.shape) else: msg = "Mask and data not compatible: data size is %i, " + \ "mask size is %i." raise MaskError(msg % (nd, nm)) copy = True # Set the mask to the new value if _data._mask is nomask: _data._mask = mask _data._sharedmask = not copy else: if not keep_mask: _data._mask = mask _data._sharedmask = not copy else: if _data.dtype.names is not None: def _recursive_or(a, b): "do a|=b on each field of a, recursively" for name in a.dtype.names: (af, bf) = (a[name], b[name]) if af.dtype.names is not None: _recursive_or(af, bf) else: af |= bf _recursive_or(_data._mask, mask) else: _data._mask = np.logical_or(mask, _data._mask) _data._sharedmask = False # Update fill_value. if fill_value is None: fill_value = getattr(data, '_fill_value', None) # But don't run the check unless we have something to check. if fill_value is not None: _data._fill_value = _check_fill_value(fill_value, _data.dtype) # Process extra options .. if hard_mask is None: _data._hardmask = getattr(data, '_hardmask', False) else: _data._hardmask = hard_mask _data._baseclass = _baseclass return _data def _update_from(self, obj): """ Copies some attributes of obj to self. """ if isinstance(obj, ndarray): _baseclass = type(obj) else: _baseclass = ndarray # We need to copy the _basedict to avoid backward propagation _optinfo = {} _optinfo.update(getattr(obj, '_optinfo', {})) _optinfo.update(getattr(obj, '_basedict', {})) if not isinstance(obj, MaskedArray): _optinfo.update(getattr(obj, '__dict__', {})) _dict = dict(_fill_value=getattr(obj, '_fill_value', None), _hardmask=getattr(obj, '_hardmask', False), _sharedmask=getattr(obj, '_sharedmask', False), _isfield=getattr(obj, '_isfield', False), _baseclass=getattr(obj, '_baseclass', _baseclass), _optinfo=_optinfo, _basedict=_optinfo) self.__dict__.update(_dict) self.__dict__.update(_optinfo) return def __array_finalize__(self, obj): """ Finalizes the masked array. """ # Get main attributes. self._update_from(obj) # We have to decide how to initialize self.mask, based on # obj.mask. This is very difficult. There might be some # correspondence between the elements in the array we are being # created from (= obj) and us. Or there might not. This method can # be called in all kinds of places for all kinds of reasons -- could # be empty_like, could be slicing, could be a ufunc, could be a view. # The numpy subclassing interface simply doesn't give us any way # to know, which means that at best this method will be based on # guesswork and heuristics. To make things worse, there isn't even any # clear consensus about what the desired behavior is. For instance, # most users think that np.empty_like(marr) -- which goes via this # method -- should return a masked array with an empty mask (see # gh-3404 and linked discussions), but others disagree, and they have # existing code which depends on empty_like returning an array that # matches the input mask. # # Historically our algorithm was: if the template object mask had the # same *number of elements* as us, then we used *it's mask object # itself* as our mask, so that writes to us would also write to the # original array. This is horribly broken in multiple ways. # # Now what we do instead is, if the template object mask has the same # number of elements as us, and we do not have the same base pointer # as the template object (b/c views like arr[...] should keep the same # mask), then we make a copy of the template object mask and use # that. This is also horribly broken but somewhat less so. Maybe. if isinstance(obj, ndarray): # XX: This looks like a bug -- shouldn't it check self.dtype # instead? if obj.dtype.names is not None: _mask = getmaskarray(obj) else: _mask = getmask(obj) # If self and obj point to exactly the same data, then probably # self is a simple view of obj (e.g., self = obj[...]), so they # should share the same mask. (This isn't 100% reliable, e.g. self # could be the first row of obj, or have strange strides, but as a # heuristic it's not bad.) In all other cases, we make a copy of # the mask, so that future modifications to 'self' do not end up # side-effecting 'obj' as well. if (_mask is not nomask and obj.__array_interface__["data"][0] != self.__array_interface__["data"][0]): # We should make a copy. But we could get here via astype, # in which case the mask might need a new dtype as well # (e.g., changing to or from a structured dtype), and the # order could have changed. So, change the mask type if # needed and use astype instead of copy. if self.dtype == obj.dtype: _mask_dtype = _mask.dtype else: _mask_dtype = make_mask_descr(self.dtype) if self.flags.c_contiguous: order = "C" elif self.flags.f_contiguous: order = "F" else: order = "K" _mask = _mask.astype(_mask_dtype, order) else: # Take a view so shape changes, etc., do not propagate back. _mask = _mask.view() else: _mask = nomask self._mask = _mask # Finalize the mask if self._mask is not nomask: try: self._mask.shape = self.shape except ValueError: self._mask = nomask except (TypeError, AttributeError): # When _mask.shape is not writable (because it's a void) pass # Finalize the fill_value if self._fill_value is not None: self._fill_value = _check_fill_value(self._fill_value, self.dtype) elif self.dtype.names is not None: # Finalize the default fill_value for structured arrays self._fill_value = _check_fill_value(None, self.dtype) def __array_wrap__(self, obj, context=None): """ Special hook for ufuncs. Wraps the numpy array and sets the mask according to context. """ if obj is self: # for in-place operations result = obj else: result = obj.view(type(self)) result._update_from(self) if context is not None: result._mask = result._mask.copy() func, args, out_i = context # args sometimes contains outputs (gh-10459), which we don't want input_args = args[:func.nin] m = reduce(mask_or, [getmaskarray(arg) for arg in input_args]) # Get the domain mask domain = ufunc_domain.get(func, None) if domain is not None: # Take the domain, and make sure it's a ndarray with np.errstate(divide='ignore', invalid='ignore'): d = filled(domain(*input_args), True) if d.any(): # Fill the result where the domain is wrong try: # Binary domain: take the last value fill_value = ufunc_fills[func][-1] except TypeError: # Unary domain: just use this one fill_value = ufunc_fills[func] except KeyError: # Domain not recognized, use fill_value instead fill_value = self.fill_value np.copyto(result, fill_value, where=d) # Update the mask if m is nomask: m = d else: # Don't modify inplace, we risk back-propagation m = (m | d) # Make sure the mask has the proper size if result is not self and result.shape == () and m: return masked else: result._mask = m result._sharedmask = False return result def view(self, dtype=None, type=None, fill_value=None): """ Return a view of the MaskedArray data. Parameters ---------- dtype : data-type or ndarray sub-class, optional Data-type descriptor of the returned view, e.g., float32 or int16. The default, None, results in the view having the same data-type as `a`. As with ``ndarray.view``, dtype can also be specified as an ndarray sub-class, which then specifies the type of the returned object (this is equivalent to setting the ``type`` parameter). type : Python type, optional Type of the returned view, either ndarray or a subclass. The default None results in type preservation. fill_value : scalar, optional The value to use for invalid entries (None by default). If None, then this argument is inferred from the passed `dtype`, or in its absence the original array, as discussed in the notes below. See Also -------- numpy.ndarray.view : Equivalent method on ndarray object. Notes ----- ``a.view()`` is used two different ways: ``a.view(some_dtype)`` or ``a.view(dtype=some_dtype)`` constructs a view of the array's memory with a different data-type. This can cause a reinterpretation of the bytes of memory. ``a.view(ndarray_subclass)`` or ``a.view(type=ndarray_subclass)`` just returns an instance of `ndarray_subclass` that looks at the same array (same shape, dtype, etc.) This does not cause a reinterpretation of the memory. If `fill_value` is not specified, but `dtype` is specified (and is not an ndarray sub-class), the `fill_value` of the MaskedArray will be reset. If neither `fill_value` nor `dtype` are specified (or if `dtype` is an ndarray sub-class), then the fill value is preserved. Finally, if `fill_value` is specified, but `dtype` is not, the fill value is set to the specified value. For ``a.view(some_dtype)``, if ``some_dtype`` has a different number of bytes per entry than the previous dtype (for example, converting a regular array to a structured array), then the behavior of the view cannot be predicted just from the superficial appearance of ``a`` (shown by ``print(a)``). It also depends on exactly how ``a`` is stored in memory. Therefore if ``a`` is C-ordered versus fortran-ordered, versus defined as a slice or transpose, etc., the view may give different results. """ if dtype is None: if type is None: output = ndarray.view(self) else: output = ndarray.view(self, type) elif type is None: try: if issubclass(dtype, ndarray): output = ndarray.view(self, dtype) dtype = None else: output = ndarray.view(self, dtype) except TypeError: output = ndarray.view(self, dtype) else: output = ndarray.view(self, dtype, type) # also make the mask be a view (so attr changes to the view's # mask do no affect original object's mask) # (especially important to avoid affecting np.masked singleton) if getmask(output) is not nomask: output._mask = output._mask.view() # Make sure to reset the _fill_value if needed if getattr(output, '_fill_value', None) is not None: if fill_value is None: if dtype is None: pass # leave _fill_value as is else: output._fill_value = None else: output.fill_value = fill_value return output def __getitem__(self, indx): """ x.__getitem__(y) <==> x[y] Return the item described by i, as a masked array. """ # We could directly use ndarray.__getitem__ on self. # But then we would have to modify __array_finalize__ to prevent the # mask of being reshaped if it hasn't been set up properly yet # So it's easier to stick to the current version dout = self.data[indx] _mask = self._mask def _is_scalar(m): return not isinstance(m, np.ndarray) def _scalar_heuristic(arr, elem): """ Return whether `elem` is a scalar result of indexing `arr`, or None if undecidable without promoting nomask to a full mask """ # obviously a scalar if not isinstance(elem, np.ndarray): return True # object array scalar indexing can return anything elif arr.dtype.type is np.object_: if arr.dtype is not elem.dtype: # elem is an array, but dtypes do not match, so must be # an element return True # well-behaved subclass that only returns 0d arrays when # expected - this is not a scalar elif type(arr).__getitem__ == ndarray.__getitem__: return False return None if _mask is not nomask: # _mask cannot be a subclass, so it tells us whether we should # expect a scalar. It also cannot be of dtype object. mout = _mask[indx] scalar_expected = _is_scalar(mout) else: # attempt to apply the heuristic to avoid constructing a full mask mout = nomask scalar_expected = _scalar_heuristic(self.data, dout) if scalar_expected is None: # heuristics have failed # construct a full array, so we can be certain. This is costly. # we could also fall back on ndarray.__getitem__(self.data, indx) scalar_expected = _is_scalar(getmaskarray(self)[indx]) # Did we extract a single item? if scalar_expected: # A record if isinstance(dout, np.void): # We should always re-cast to mvoid, otherwise users can # change masks on rows that already have masked values, but not # on rows that have no masked values, which is inconsistent. return mvoid(dout, mask=mout, hardmask=self._hardmask) # special case introduced in gh-5962 elif (self.dtype.type is np.object_ and isinstance(dout, np.ndarray) and dout is not masked): # If masked, turn into a MaskedArray, with everything masked. if mout: return MaskedArray(dout, mask=True) else: return dout # Just a scalar else: if mout: return masked else: return dout else: # Force dout to MA dout = dout.view(type(self)) # Inherit attributes from self dout._update_from(self) # Check the fill_value if is_string_or_list_of_strings(indx): if self._fill_value is not None: dout._fill_value = self._fill_value[indx] # Something like gh-15895 has happened if this check fails. # _fill_value should always be an ndarray. if not isinstance(dout._fill_value, np.ndarray): raise RuntimeError('Internal NumPy error.') # If we're indexing a multidimensional field in a # structured array (such as dtype("(2,)i2,(2,)i1")), # dimensionality goes up (M[field].ndim == M.ndim + # M.dtype[field].ndim). That's fine for # M[field] but problematic for M[field].fill_value # which should have shape () to avoid breaking several # methods. There is no great way out, so set to # first element. See issue #6723. if dout._fill_value.ndim > 0: if not (dout._fill_value == dout._fill_value.flat[0]).all(): warnings.warn( "Upon accessing multidimensional field " f"{indx!s}, need to keep dimensionality " "of fill_value at 0. Discarding " "heterogeneous fill_value and setting " f"all to {dout._fill_value[0]!s}.", stacklevel=2) # Need to use `.flat[0:1].squeeze(...)` instead of just # `.flat[0]` to ensure the result is a 0d array and not # a scalar. dout._fill_value = dout._fill_value.flat[0:1].squeeze(axis=0) dout._isfield = True # Update the mask if needed if mout is not nomask: # set shape to match that of data; this is needed for matrices dout._mask = reshape(mout, dout.shape) dout._sharedmask = True # Note: Don't try to check for m.any(), that'll take too long return dout def __setitem__(self, indx, value): """ x.__setitem__(i, y) <==> x[i]=y Set item described by index. If value is masked, masks those locations. """ if self is masked: raise MaskError('Cannot alter the masked element.') _data = self._data _mask = self._mask if isinstance(indx, str): _data[indx] = value if _mask is nomask: self._mask = _mask = make_mask_none(self.shape, self.dtype) _mask[indx] = getmask(value) return _dtype = _data.dtype if value is masked: # The mask wasn't set: create a full version. if _mask is nomask: _mask = self._mask = make_mask_none(self.shape, _dtype) # Now, set the mask to its value. if _dtype.names is not None: _mask[indx] = tuple([True] * len(_dtype.names)) else: _mask[indx] = True return # Get the _data part of the new value dval = getattr(value, '_data', value) # Get the _mask part of the new value mval = getmask(value) if _dtype.names is not None and mval is nomask: mval = tuple([False] * len(_dtype.names)) if _mask is nomask: # Set the data, then the mask _data[indx] = dval if mval is not nomask: _mask = self._mask = make_mask_none(self.shape, _dtype) _mask[indx] = mval elif not self._hardmask: # Set the data, then the mask if (isinstance(indx, masked_array) and not isinstance(value, masked_array)): _data[indx.data] = dval else: _data[indx] = dval _mask[indx] = mval elif hasattr(indx, 'dtype') and (indx.dtype == MaskType): indx = indx * umath.logical_not(_mask) _data[indx] = dval else: if _dtype.names is not None: err_msg = "Flexible 'hard' masks are not yet supported." raise NotImplementedError(err_msg) mindx = mask_or(_mask[indx], mval, copy=True) dindx = self._data[indx] if dindx.size > 1: np.copyto(dindx, dval, where=~mindx) elif mindx is nomask: dindx = dval _data[indx] = dindx _mask[indx] = mindx return # Define so that we can overwrite the setter. def dtype(self): return super().dtype def dtype(self, dtype): super(MaskedArray, type(self)).dtype.__set__(self, dtype) if self._mask is not nomask: self._mask = self._mask.view(make_mask_descr(dtype), ndarray) # Try to reset the shape of the mask (if we don't have a void). # This raises a ValueError if the dtype change won't work. try: self._mask.shape = self.shape except (AttributeError, TypeError): pass def shape(self): return super().shape def shape(self, shape): super(MaskedArray, type(self)).shape.__set__(self, shape) # Cannot use self._mask, since it may not (yet) exist when a # masked matrix sets the shape. if getmask(self) is not nomask: self._mask.shape = self.shape def __setmask__(self, mask, copy=False): """ Set the mask. """ idtype = self.dtype current_mask = self._mask if mask is masked: mask = True if current_mask is nomask: # Make sure the mask is set # Just don't do anything if there's nothing to do. if mask is nomask: return current_mask = self._mask = make_mask_none(self.shape, idtype) if idtype.names is None: # No named fields. # Hardmask: don't unmask the data if self._hardmask: current_mask |= mask # Softmask: set everything to False # If it's obviously a compatible scalar, use a quick update # method. elif isinstance(mask, (int, float, np.bool_, np.number)): current_mask[...] = mask # Otherwise fall back to the slower, general purpose way. else: current_mask.flat = mask else: # Named fields w/ mdtype = current_mask.dtype mask = np.array(mask, copy=False) # Mask is a singleton if not mask.ndim: # It's a boolean : make a record if mask.dtype.kind == 'b': mask = np.array(tuple([mask.item()] * len(mdtype)), dtype=mdtype) # It's a record: make sure the dtype is correct else: mask = mask.astype(mdtype) # Mask is a sequence else: # Make sure the new mask is a ndarray with the proper dtype try: mask = np.array(mask, copy=copy, dtype=mdtype) # Or assume it's a sequence of bool/int except TypeError: mask = np.array([tuple([m] * len(mdtype)) for m in mask], dtype=mdtype) # Hardmask: don't unmask the data if self._hardmask: for n in idtype.names: current_mask[n] |= mask[n] # Softmask: set everything to False # If it's obviously a compatible scalar, use a quick update # method. elif isinstance(mask, (int, float, np.bool_, np.number)): current_mask[...] = mask # Otherwise fall back to the slower, general purpose way. else: current_mask.flat = mask # Reshape if needed if current_mask.shape: current_mask.shape = self.shape return _set_mask = __setmask__ def mask(self): """ Current mask. """ # We could try to force a reshape, but that wouldn't work in some # cases. # Return a view so that the dtype and shape cannot be changed in place # This still preserves nomask by identity return self._mask.view() def mask(self, value): self.__setmask__(value) def recordmask(self): """ Get or set the mask of the array if it has no named fields. For structured arrays, returns a ndarray of booleans where entries are ``True`` if **all** the fields are masked, ``False`` otherwise: >>> x = np.ma.array([(1, 1), (2, 2), (3, 3), (4, 4), (5, 5)], ... mask=[(0, 0), (1, 0), (1, 1), (0, 1), (0, 0)], ... dtype=[('a', int), ('b', int)]) >>> x.recordmask array([False, False, True, False, False]) """ _mask = self._mask.view(ndarray) if _mask.dtype.names is None: return _mask return np.all(flatten_structured_array(_mask), axis=-1) def recordmask(self, mask): raise NotImplementedError("Coming soon: setting the mask per records!") def harden_mask(self): """ Force the mask to hard, preventing unmasking by assignment. Whether the mask of a masked array is hard or soft is determined by its `~ma.MaskedArray.hardmask` property. `harden_mask` sets `~ma.MaskedArray.hardmask` to ``True`` (and returns the modified self). See Also -------- ma.MaskedArray.hardmask ma.MaskedArray.soften_mask """ self._hardmask = True return self def soften_mask(self): """ Force the mask to soft (default), allowing unmasking by assignment. Whether the mask of a masked array is hard or soft is determined by its `~ma.MaskedArray.hardmask` property. `soften_mask` sets `~ma.MaskedArray.hardmask` to ``False`` (and returns the modified self). See Also -------- ma.MaskedArray.hardmask ma.MaskedArray.harden_mask """ self._hardmask = False return self def hardmask(self): """ Specifies whether values can be unmasked through assignments. By default, assigning definite values to masked array entries will unmask them. When `hardmask` is ``True``, the mask will not change through assignments. See Also -------- ma.MaskedArray.harden_mask ma.MaskedArray.soften_mask Examples -------- >>> x = np.arange(10) >>> m = np.ma.masked_array(x, x>5) >>> assert not m.hardmask Since `m` has a soft mask, assigning an element value unmasks that element: >>> m[8] = 42 >>> m masked_array(data=[0, 1, 2, 3, 4, 5, --, --, 42, --], mask=[False, False, False, False, False, False, True, True, False, True], fill_value=999999) After hardening, the mask is not affected by assignments: >>> hardened = np.ma.harden_mask(m) >>> assert m.hardmask and hardened is m >>> m[:] = 23 >>> m masked_array(data=[23, 23, 23, 23, 23, 23, --, --, 23, --], mask=[False, False, False, False, False, False, True, True, False, True], fill_value=999999) """ return self._hardmask def unshare_mask(self): """ Copy the mask and set the `sharedmask` flag to ``False``. Whether the mask is shared between masked arrays can be seen from the `sharedmask` property. `unshare_mask` ensures the mask is not shared. A copy of the mask is only made if it was shared. See Also -------- sharedmask """ if self._sharedmask: self._mask = self._mask.copy() self._sharedmask = False return self def sharedmask(self): """ Share status of the mask (read-only). """ return self._sharedmask def shrink_mask(self): """ Reduce a mask to nomask when possible. Parameters ---------- None Returns ------- None Examples -------- >>> x = np.ma.array([[1,2 ], [3, 4]], mask=[0]*4) >>> x.mask array([[False, False], [False, False]]) >>> x.shrink_mask() masked_array( data=[[1, 2], [3, 4]], mask=False, fill_value=999999) >>> x.mask False """ self._mask = _shrink_mask(self._mask) return self def baseclass(self): """ Class of the underlying data (read-only). """ return self._baseclass def _get_data(self): """ Returns the underlying data, as a view of the masked array. If the underlying data is a subclass of :class:`numpy.ndarray`, it is returned as such. >>> x = np.ma.array(np.matrix([[1, 2], [3, 4]]), mask=[[0, 1], [1, 0]]) >>> x.data matrix([[1, 2], [3, 4]]) The type of the data can be accessed through the :attr:`baseclass` attribute. """ return ndarray.view(self, self._baseclass) _data = property(fget=_get_data) data = property(fget=_get_data) def flat(self): """ Return a flat iterator, or set a flattened version of self to value. """ return MaskedIterator(self) def flat(self, value): y = self.ravel() y[:] = value def fill_value(self): """ The filling value of the masked array is a scalar. When setting, None will set to a default based on the data type. Examples -------- >>> for dt in [np.int32, np.int64, np.float64, np.complex128]: ... np.ma.array([0, 1], dtype=dt).get_fill_value() ... 999999 999999 1e+20 (1e+20+0j) >>> x = np.ma.array([0, 1.], fill_value=-np.inf) >>> x.fill_value -inf >>> x.fill_value = np.pi >>> x.fill_value 3.1415926535897931 # may vary Reset to default: >>> x.fill_value = None >>> x.fill_value 1e+20 """ if self._fill_value is None: self._fill_value = _check_fill_value(None, self.dtype) # Temporary workaround to account for the fact that str and bytes # scalars cannot be indexed with (), whereas all other numpy # scalars can. See issues #7259 and #7267. # The if-block can be removed after #7267 has been fixed. if isinstance(self._fill_value, ndarray): return self._fill_value[()] return self._fill_value def fill_value(self, value=None): target = _check_fill_value(value, self.dtype) if not target.ndim == 0: # 2019-11-12, 1.18.0 warnings.warn( "Non-scalar arrays for the fill value are deprecated. Use " "arrays with scalar values instead. The filled function " "still supports any array as `fill_value`.", DeprecationWarning, stacklevel=2) _fill_value = self._fill_value if _fill_value is None: # Create the attribute if it was undefined self._fill_value = target else: # Don't overwrite the attribute, just fill it (for propagation) _fill_value[()] = target # kept for compatibility get_fill_value = fill_value.fget set_fill_value = fill_value.fset def filled(self, fill_value=None): """ Return a copy of self, with masked values filled with a given value. **However**, if there are no masked values to fill, self will be returned instead as an ndarray. Parameters ---------- fill_value : array_like, optional The value to use for invalid entries. Can be scalar or non-scalar. If non-scalar, the resulting ndarray must be broadcastable over input array. Default is None, in which case, the `fill_value` attribute of the array is used instead. Returns ------- filled_array : ndarray A copy of ``self`` with invalid entries replaced by *fill_value* (be it the function argument or the attribute of ``self``), or ``self`` itself as an ndarray if there are no invalid entries to be replaced. Notes ----- The result is **not** a MaskedArray! Examples -------- >>> x = np.ma.array([1,2,3,4,5], mask=[0,0,1,0,1], fill_value=-999) >>> x.filled() array([ 1, 2, -999, 4, -999]) >>> x.filled(fill_value=1000) array([ 1, 2, 1000, 4, 1000]) >>> type(x.filled()) <class 'numpy.ndarray'> Subclassing is preserved. This means that if, e.g., the data part of the masked array is a recarray, `filled` returns a recarray: >>> x = np.array([(-1, 2), (-3, 4)], dtype='i8,i8').view(np.recarray) >>> m = np.ma.array(x, mask=[(True, False), (False, True)]) >>> m.filled() rec.array([(999999, 2), ( -3, 999999)], dtype=[('f0', '<i8'), ('f1', '<i8')]) """ m = self._mask if m is nomask: return self._data if fill_value is None: fill_value = self.fill_value else: fill_value = _check_fill_value(fill_value, self.dtype) if self is masked_singleton: return np.asanyarray(fill_value) if m.dtype.names is not None: result = self._data.copy('K') _recursive_filled(result, self._mask, fill_value) elif not m.any(): return self._data else: result = self._data.copy('K') try: np.copyto(result, fill_value, where=m) except (TypeError, AttributeError): fill_value = narray(fill_value, dtype=object) d = result.astype(object) result = np.choose(m, (d, fill_value)) except IndexError: # ok, if scalar if self._data.shape: raise elif m: result = np.array(fill_value, dtype=self.dtype) else: result = self._data return result def compressed(self): """ Return all the non-masked data as a 1-D array. Returns ------- data : ndarray A new `ndarray` holding the non-masked data is returned. Notes ----- The result is **not** a MaskedArray! Examples -------- >>> x = np.ma.array(np.arange(5), mask=[0]*2 + [1]*3) >>> x.compressed() array([0, 1]) >>> type(x.compressed()) <class 'numpy.ndarray'> """ data = ndarray.ravel(self._data) if self._mask is not nomask: data = data.compress(np.logical_not(ndarray.ravel(self._mask))) return data def compress(self, condition, axis=None, out=None): """ Return `a` where condition is ``True``. If condition is a `~ma.MaskedArray`, missing values are considered as ``False``. Parameters ---------- condition : var Boolean 1-d array selecting which entries to return. If len(condition) is less than the size of a along the axis, then output is truncated to length of condition array. axis : {None, int}, optional Axis along which the operation must be performed. out : {None, ndarray}, optional Alternative output array in which to place the result. It must have the same shape as the expected output but the type will be cast if necessary. Returns ------- result : MaskedArray A :class:`~ma.MaskedArray` object. Notes ----- Please note the difference with :meth:`compressed` ! The output of :meth:`compress` has a mask, the output of :meth:`compressed` does not. Examples -------- >>> x = np.ma.array([[1,2,3],[4,5,6],[7,8,9]], mask=[0] + [1,0]*4) >>> x masked_array( data=[[1, --, 3], [--, 5, --], [7, --, 9]], mask=[[False, True, False], [ True, False, True], [False, True, False]], fill_value=999999) >>> x.compress([1, 0, 1]) masked_array(data=[1, 3], mask=[False, False], fill_value=999999) >>> x.compress([1, 0, 1], axis=1) masked_array( data=[[1, 3], [--, --], [7, 9]], mask=[[False, False], [ True, True], [False, False]], fill_value=999999) """ # Get the basic components (_data, _mask) = (self._data, self._mask) # Force the condition to a regular ndarray and forget the missing # values. condition = np.asarray(condition) _new = _data.compress(condition, axis=axis, out=out).view(type(self)) _new._update_from(self) if _mask is not nomask: _new._mask = _mask.compress(condition, axis=axis) return _new def _insert_masked_print(self): """ Replace masked values with masked_print_option, casting all innermost dtypes to object. """ if masked_print_option.enabled(): mask = self._mask if mask is nomask: res = self._data else: # convert to object array to make filled work data = self._data # For big arrays, to avoid a costly conversion to the # object dtype, extract the corners before the conversion. print_width = (self._print_width if self.ndim > 1 else self._print_width_1d) for axis in range(self.ndim): if data.shape[axis] > print_width: ind = print_width // 2 arr = np.split(data, (ind, -ind), axis=axis) data = np.concatenate((arr[0], arr[2]), axis=axis) arr = np.split(mask, (ind, -ind), axis=axis) mask = np.concatenate((arr[0], arr[2]), axis=axis) rdtype = _replace_dtype_fields(self.dtype, "O") res = data.astype(rdtype) _recursive_printoption(res, mask, masked_print_option) else: res = self.filled(self.fill_value) return res def __str__(self): return str(self._insert_masked_print()) def __repr__(self): """ Literal string representation. """ if self._baseclass is np.ndarray: name = 'array' else: name = self._baseclass.__name__ # 2016-11-19: Demoted to legacy format if np.core.arrayprint._get_legacy_print_mode() <= 113: is_long = self.ndim > 1 parameters = dict( name=name, nlen=" " * len(name), data=str(self), mask=str(self._mask), fill=str(self.fill_value), dtype=str(self.dtype) ) is_structured = bool(self.dtype.names) key = '{}_{}'.format( 'long' if is_long else 'short', 'flx' if is_structured else 'std' ) return _legacy_print_templates[key] % parameters prefix = f"masked_{name}(" dtype_needed = ( not np.core.arrayprint.dtype_is_implied(self.dtype) or np.all(self.mask) or self.size == 0 ) # determine which keyword args need to be shown keys = ['data', 'mask', 'fill_value'] if dtype_needed: keys.append('dtype') # array has only one row (non-column) is_one_row = builtins.all(dim == 1 for dim in self.shape[:-1]) # choose what to indent each keyword with min_indent = 2 if is_one_row: # first key on the same line as the type, remaining keys # aligned by equals indents = {} indents[keys[0]] = prefix for k in keys[1:]: n = builtins.max(min_indent, len(prefix + keys[0]) - len(k)) indents[k] = ' ' * n prefix = '' # absorbed into the first indent else: # each key on its own line, indented by two spaces indents = {k: ' ' * min_indent for k in keys} prefix = prefix + '\n' # first key on the next line # format the field values reprs = {} reprs['data'] = np.array2string( self._insert_masked_print(), separator=", ", prefix=indents['data'] + 'data=', suffix=',') reprs['mask'] = np.array2string( self._mask, separator=", ", prefix=indents['mask'] + 'mask=', suffix=',') reprs['fill_value'] = repr(self.fill_value) if dtype_needed: reprs['dtype'] = np.core.arrayprint.dtype_short_repr(self.dtype) # join keys with values and indentations result = ',\n'.join( '{}{}={}'.format(indents[k], k, reprs[k]) for k in keys ) return prefix + result + ')' def _delegate_binop(self, other): # This emulates the logic in # private/binop_override.h:forward_binop_should_defer if isinstance(other, type(self)): return False array_ufunc = getattr(other, "__array_ufunc__", False) if array_ufunc is False: other_priority = getattr(other, "__array_priority__", -1000000) return self.__array_priority__ < other_priority else: # If array_ufunc is not None, it will be called inside the ufunc; # None explicitly tells us to not call the ufunc, i.e., defer. return array_ufunc is None def _comparison(self, other, compare): """Compare self with other using operator.eq or operator.ne. When either of the elements is masked, the result is masked as well, but the underlying boolean data are still set, with self and other considered equal if both are masked, and unequal otherwise. For structured arrays, all fields are combined, with masked values ignored. The result is masked if all fields were masked, with self and other considered equal only if both were fully masked. """ omask = getmask(other) smask = self.mask mask = mask_or(smask, omask, copy=True) odata = getdata(other) if mask.dtype.names is not None: # only == and != are reasonably defined for structured dtypes, # so give up early for all other comparisons: if compare not in (operator.eq, operator.ne): return NotImplemented # For possibly masked structured arrays we need to be careful, # since the standard structured array comparison will use all # fields, masked or not. To avoid masked fields influencing the # outcome, we set all masked fields in self to other, so they'll # count as equal. To prepare, we ensure we have the right shape. broadcast_shape = np.broadcast(self, odata).shape sbroadcast = np.broadcast_to(self, broadcast_shape, subok=True) sbroadcast._mask = mask sdata = sbroadcast.filled(odata) # Now take care of the mask; the merged mask should have an item # masked if all fields were masked (in one and/or other). mask = (mask == np.ones((), mask.dtype)) else: # For regular arrays, just use the data as they come. sdata = self.data check = compare(sdata, odata) if isinstance(check, (np.bool_, bool)): return masked if mask else check if mask is not nomask and compare in (operator.eq, operator.ne): # Adjust elements that were masked, which should be treated # as equal if masked in both, unequal if masked in one. # Note that this works automatically for structured arrays too. # Ignore this for operations other than `==` and `!=` check = np.where(mask, compare(smask, omask), check) if mask.shape != check.shape: # Guarantee consistency of the shape, making a copy since the # the mask may need to get written to later. mask = np.broadcast_to(mask, check.shape).copy() check = check.view(type(self)) check._update_from(self) check._mask = mask # Cast fill value to bool_ if needed. If it cannot be cast, the # default boolean fill value is used. if check._fill_value is not None: try: fill = _check_fill_value(check._fill_value, np.bool_) except (TypeError, ValueError): fill = _check_fill_value(None, np.bool_) check._fill_value = fill return check def __eq__(self, other): """Check whether other equals self elementwise. When either of the elements is masked, the result is masked as well, but the underlying boolean data are still set, with self and other considered equal if both are masked, and unequal otherwise. For structured arrays, all fields are combined, with masked values ignored. The result is masked if all fields were masked, with self and other considered equal only if both were fully masked. """ return self._comparison(other, operator.eq) def __ne__(self, other): """Check whether other does not equal self elementwise. When either of the elements is masked, the result is masked as well, but the underlying boolean data are still set, with self and other considered equal if both are masked, and unequal otherwise. For structured arrays, all fields are combined, with masked values ignored. The result is masked if all fields were masked, with self and other considered equal only if both were fully masked. """ return self._comparison(other, operator.ne) # All other comparisons: def __le__(self, other): return self._comparison(other, operator.le) def __lt__(self, other): return self._comparison(other, operator.lt) def __ge__(self, other): return self._comparison(other, operator.ge) def __gt__(self, other): return self._comparison(other, operator.gt) def __add__(self, other): """ Add self to other, and return a new masked array. """ if self._delegate_binop(other): return NotImplemented return add(self, other) def __radd__(self, other): """ Add other to self, and return a new masked array. """ # In analogy with __rsub__ and __rdiv__, use original order: # we get here from `other + self`. return add(other, self) def __sub__(self, other): """ Subtract other from self, and return a new masked array. """ if self._delegate_binop(other): return NotImplemented return subtract(self, other) def __rsub__(self, other): """ Subtract self from other, and return a new masked array. """ return subtract(other, self) def __mul__(self, other): "Multiply self by other, and return a new masked array." if self._delegate_binop(other): return NotImplemented return multiply(self, other) def __rmul__(self, other): """ Multiply other by self, and return a new masked array. """ # In analogy with __rsub__ and __rdiv__, use original order: # we get here from `other * self`. return multiply(other, self) def __div__(self, other): """ Divide other into self, and return a new masked array. """ if self._delegate_binop(other): return NotImplemented return divide(self, other) def __truediv__(self, other): """ Divide other into self, and return a new masked array. """ if self._delegate_binop(other): return NotImplemented return true_divide(self, other) def __rtruediv__(self, other): """ Divide self into other, and return a new masked array. """ return true_divide(other, self) def __floordiv__(self, other): """ Divide other into self, and return a new masked array. """ if self._delegate_binop(other): return NotImplemented return floor_divide(self, other) def __rfloordiv__(self, other): """ Divide self into other, and return a new masked array. """ return floor_divide(other, self) def __pow__(self, other): """ Raise self to the power other, masking the potential NaNs/Infs """ if self._delegate_binop(other): return NotImplemented return power(self, other) def __rpow__(self, other): """ Raise other to the power self, masking the potential NaNs/Infs """ return power(other, self) def __iadd__(self, other): """ Add other to self in-place. """ m = getmask(other) if self._mask is nomask: if m is not nomask and m.any(): self._mask = make_mask_none(self.shape, self.dtype) self._mask += m else: if m is not nomask: self._mask += m other_data = getdata(other) other_data = np.where(self._mask, other_data.dtype.type(0), other_data) self._data.__iadd__(other_data) return self def __isub__(self, other): """ Subtract other from self in-place. """ m = getmask(other) if self._mask is nomask: if m is not nomask and m.any(): self._mask = make_mask_none(self.shape, self.dtype) self._mask += m elif m is not nomask: self._mask += m other_data = getdata(other) other_data = np.where(self._mask, other_data.dtype.type(0), other_data) self._data.__isub__(other_data) return self def __imul__(self, other): """ Multiply self by other in-place. """ m = getmask(other) if self._mask is nomask: if m is not nomask and m.any(): self._mask = make_mask_none(self.shape, self.dtype) self._mask += m elif m is not nomask: self._mask += m other_data = getdata(other) other_data = np.where(self._mask, other_data.dtype.type(1), other_data) self._data.__imul__(other_data) return self def __idiv__(self, other): """ Divide self by other in-place. """ other_data = getdata(other) dom_mask = _DomainSafeDivide().__call__(self._data, other_data) other_mask = getmask(other) new_mask = mask_or(other_mask, dom_mask) # The following 4 lines control the domain filling if dom_mask.any(): (_, fval) = ufunc_fills[np.divide] other_data = np.where( dom_mask, other_data.dtype.type(fval), other_data) self._mask |= new_mask other_data = np.where(self._mask, other_data.dtype.type(1), other_data) self._data.__idiv__(other_data) return self def __ifloordiv__(self, other): """ Floor divide self by other in-place. """ other_data = getdata(other) dom_mask = _DomainSafeDivide().__call__(self._data, other_data) other_mask = getmask(other) new_mask = mask_or(other_mask, dom_mask) # The following 3 lines control the domain filling if dom_mask.any(): (_, fval) = ufunc_fills[np.floor_divide] other_data = np.where( dom_mask, other_data.dtype.type(fval), other_data) self._mask |= new_mask other_data = np.where(self._mask, other_data.dtype.type(1), other_data) self._data.__ifloordiv__(other_data) return self def __itruediv__(self, other): """ True divide self by other in-place. """ other_data = getdata(other) dom_mask = _DomainSafeDivide().__call__(self._data, other_data) other_mask = getmask(other) new_mask = mask_or(other_mask, dom_mask) # The following 3 lines control the domain filling if dom_mask.any(): (_, fval) = ufunc_fills[np.true_divide] other_data = np.where( dom_mask, other_data.dtype.type(fval), other_data) self._mask |= new_mask other_data = np.where(self._mask, other_data.dtype.type(1), other_data) self._data.__itruediv__(other_data) return self def __ipow__(self, other): """ Raise self to the power other, in place. """ other_data = getdata(other) other_data = np.where(self._mask, other_data.dtype.type(1), other_data) other_mask = getmask(other) with np.errstate(divide='ignore', invalid='ignore'): self._data.__ipow__(other_data) invalid = np.logical_not(np.isfinite(self._data)) if invalid.any(): if self._mask is not nomask: self._mask |= invalid else: self._mask = invalid np.copyto(self._data, self.fill_value, where=invalid) new_mask = mask_or(other_mask, invalid) self._mask = mask_or(self._mask, new_mask) return self def __float__(self): """ Convert to float. """ if self.size > 1: raise TypeError("Only length-1 arrays can be converted " "to Python scalars") elif self._mask: warnings.warn("Warning: converting a masked element to nan.", stacklevel=2) return np.nan return float(self.item()) def __int__(self): """ Convert to int. """ if self.size > 1: raise TypeError("Only length-1 arrays can be converted " "to Python scalars") elif self._mask: raise MaskError('Cannot convert masked element to a Python int.') return int(self.item()) def imag(self): """ The imaginary part of the masked array. This property is a view on the imaginary part of this `MaskedArray`. See Also -------- real Examples -------- >>> x = np.ma.array([1+1.j, -2j, 3.45+1.6j], mask=[False, True, False]) >>> x.imag masked_array(data=[1.0, --, 1.6], mask=[False, True, False], fill_value=1e+20) """ result = self._data.imag.view(type(self)) result.__setmask__(self._mask) return result # kept for compatibility get_imag = imag.fget def real(self): """ The real part of the masked array. This property is a view on the real part of this `MaskedArray`. See Also -------- imag Examples -------- >>> x = np.ma.array([1+1.j, -2j, 3.45+1.6j], mask=[False, True, False]) >>> x.real masked_array(data=[1.0, --, 3.45], mask=[False, True, False], fill_value=1e+20) """ result = self._data.real.view(type(self)) result.__setmask__(self._mask) return result # kept for compatibility get_real = real.fget def count(self, axis=None, keepdims=np._NoValue): """ Count the non-masked elements of the array along the given axis. Parameters ---------- axis : None or int or tuple of ints, optional Axis or axes along which the count is performed. The default, None, performs the count over all the dimensions of the input array. `axis` may be negative, in which case it counts from the last to the first axis. .. versionadded:: 1.10.0 If this is a tuple of ints, the count is performed on multiple axes, instead of a single axis or all the axes as before. keepdims : bool, optional If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the array. Returns ------- result : ndarray or scalar An array with the same shape as the input array, with the specified axis removed. If the array is a 0-d array, or if `axis` is None, a scalar is returned. See Also -------- ma.count_masked : Count masked elements in array or along a given axis. Examples -------- >>> import numpy.ma as ma >>> a = ma.arange(6).reshape((2, 3)) >>> a[1, :] = ma.masked >>> a masked_array( data=[[0, 1, 2], [--, --, --]], mask=[[False, False, False], [ True, True, True]], fill_value=999999) >>> a.count() 3 When the `axis` keyword is specified an array of appropriate size is returned. >>> a.count(axis=0) array([1, 1, 1]) >>> a.count(axis=1) array([3, 0]) """ kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims} m = self._mask # special case for matrices (we assume no other subclasses modify # their dimensions) if isinstance(self.data, np.matrix): if m is nomask: m = np.zeros(self.shape, dtype=np.bool_) m = m.view(type(self.data)) if m is nomask: # compare to _count_reduce_items in _methods.py if self.shape == (): if axis not in (None, 0): raise np.AxisError(axis=axis, ndim=self.ndim) return 1 elif axis is None: if kwargs.get('keepdims', False): return np.array(self.size, dtype=np.intp, ndmin=self.ndim) return self.size axes = normalize_axis_tuple(axis, self.ndim) items = 1 for ax in axes: items *= self.shape[ax] if kwargs.get('keepdims', False): out_dims = list(self.shape) for a in axes: out_dims[a] = 1 else: out_dims = [d for n, d in enumerate(self.shape) if n not in axes] # make sure to return a 0-d array if axis is supplied return np.full(out_dims, items, dtype=np.intp) # take care of the masked singleton if self is masked: return 0 return (~m).sum(axis=axis, dtype=np.intp, **kwargs) def ravel(self, order='C'): """ Returns a 1D version of self, as a view. Parameters ---------- order : {'C', 'F', 'A', 'K'}, optional The elements of `a` are read using this index order. 'C' means to index the elements in C-like order, with the last axis index changing fastest, back to the first axis index changing slowest. 'F' means to index the elements in Fortran-like index order, with the first index changing fastest, and the last index changing slowest. Note that the 'C' and 'F' options take no account of the memory layout of the underlying array, and only refer to the order of axis indexing. 'A' means to read the elements in Fortran-like index order if `m` is Fortran *contiguous* in memory, C-like order otherwise. 'K' means to read the elements in the order they occur in memory, except for reversing the data when strides are negative. By default, 'C' index order is used. Returns ------- MaskedArray Output view is of shape ``(self.size,)`` (or ``(np.ma.product(self.shape),)``). Examples -------- >>> x = np.ma.array([[1,2,3],[4,5,6],[7,8,9]], mask=[0] + [1,0]*4) >>> x masked_array( data=[[1, --, 3], [--, 5, --], [7, --, 9]], mask=[[False, True, False], [ True, False, True], [False, True, False]], fill_value=999999) >>> x.ravel() masked_array(data=[1, --, 3, --, 5, --, 7, --, 9], mask=[False, True, False, True, False, True, False, True, False], fill_value=999999) """ r = ndarray.ravel(self._data, order=order).view(type(self)) r._update_from(self) if self._mask is not nomask: r._mask = ndarray.ravel(self._mask, order=order).reshape(r.shape) else: r._mask = nomask return r def reshape(self, *s, **kwargs): """ Give a new shape to the array without changing its data. Returns a masked array containing the same data, but with a new shape. The result is a view on the original array; if this is not possible, a ValueError is raised. Parameters ---------- shape : int or tuple of ints The new shape should be compatible with the original shape. If an integer is supplied, then the result will be a 1-D array of that length. order : {'C', 'F'}, optional Determines whether the array data should be viewed as in C (row-major) or FORTRAN (column-major) order. Returns ------- reshaped_array : array A new view on the array. See Also -------- reshape : Equivalent function in the masked array module. numpy.ndarray.reshape : Equivalent method on ndarray object. numpy.reshape : Equivalent function in the NumPy module. Notes ----- The reshaping operation cannot guarantee that a copy will not be made, to modify the shape in place, use ``a.shape = s`` Examples -------- >>> x = np.ma.array([[1,2],[3,4]], mask=[1,0,0,1]) >>> x masked_array( data=[[--, 2], [3, --]], mask=[[ True, False], [False, True]], fill_value=999999) >>> x = x.reshape((4,1)) >>> x masked_array( data=[[--], [2], [3], [--]], mask=[[ True], [False], [False], [ True]], fill_value=999999) """ kwargs.update(order=kwargs.get('order', 'C')) result = self._data.reshape(*s, **kwargs).view(type(self)) result._update_from(self) mask = self._mask if mask is not nomask: result._mask = mask.reshape(*s, **kwargs) return result def resize(self, newshape, refcheck=True, order=False): """ .. warning:: This method does nothing, except raise a ValueError exception. A masked array does not own its data and therefore cannot safely be resized in place. Use the `numpy.ma.resize` function instead. This method is difficult to implement safely and may be deprecated in future releases of NumPy. """ # Note : the 'order' keyword looks broken, let's just drop it errmsg = "A masked array does not own its data "\ "and therefore cannot be resized.\n" \ "Use the numpy.ma.resize function instead." raise ValueError(errmsg) def put(self, indices, values, mode='raise'): """ Set storage-indexed locations to corresponding values. Sets self._data.flat[n] = values[n] for each n in indices. If `values` is shorter than `indices` then it will repeat. If `values` has some masked values, the initial mask is updated in consequence, else the corresponding values are unmasked. Parameters ---------- indices : 1-D array_like Target indices, interpreted as integers. values : array_like Values to place in self._data copy at target indices. mode : {'raise', 'wrap', 'clip'}, optional Specifies how out-of-bounds indices will behave. 'raise' : raise an error. 'wrap' : wrap around. 'clip' : clip to the range. Notes ----- `values` can be a scalar or length 1 array. Examples -------- >>> x = np.ma.array([[1,2,3],[4,5,6],[7,8,9]], mask=[0] + [1,0]*4) >>> x masked_array( data=[[1, --, 3], [--, 5, --], [7, --, 9]], mask=[[False, True, False], [ True, False, True], [False, True, False]], fill_value=999999) >>> x.put([0,4,8],[10,20,30]) >>> x masked_array( data=[[10, --, 3], [--, 20, --], [7, --, 30]], mask=[[False, True, False], [ True, False, True], [False, True, False]], fill_value=999999) >>> x.put(4,999) >>> x masked_array( data=[[10, --, 3], [--, 999, --], [7, --, 30]], mask=[[False, True, False], [ True, False, True], [False, True, False]], fill_value=999999) """ # Hard mask: Get rid of the values/indices that fall on masked data if self._hardmask and self._mask is not nomask: mask = self._mask[indices] indices = narray(indices, copy=False) values = narray(values, copy=False, subok=True) values.resize(indices.shape) indices = indices[~mask] values = values[~mask] self._data.put(indices, values, mode=mode) # short circuit if neither self nor values are masked if self._mask is nomask and getmask(values) is nomask: return m = getmaskarray(self) if getmask(values) is nomask: m.put(indices, False, mode=mode) else: m.put(indices, values._mask, mode=mode) m = make_mask(m, copy=False, shrink=True) self._mask = m return def ids(self): """ Return the addresses of the data and mask areas. Parameters ---------- None Examples -------- >>> x = np.ma.array([1, 2, 3], mask=[0, 1, 1]) >>> x.ids() (166670640, 166659832) # may vary If the array has no mask, the address of `nomask` is returned. This address is typically not close to the data in memory: >>> x = np.ma.array([1, 2, 3]) >>> x.ids() (166691080, 3083169284) # may vary """ if self._mask is nomask: return (self.ctypes.data, id(nomask)) return (self.ctypes.data, self._mask.ctypes.data) def iscontiguous(self): """ Return a boolean indicating whether the data is contiguous. Parameters ---------- None Examples -------- >>> x = np.ma.array([1, 2, 3]) >>> x.iscontiguous() True `iscontiguous` returns one of the flags of the masked array: >>> x.flags C_CONTIGUOUS : True F_CONTIGUOUS : True OWNDATA : False WRITEABLE : True ALIGNED : True WRITEBACKIFCOPY : False """ return self.flags['CONTIGUOUS'] def all(self, axis=None, out=None, keepdims=np._NoValue): """ Returns True if all elements evaluate to True. The output array is masked where all the values along the given axis are masked: if the output would have been a scalar and that all the values are masked, then the output is `masked`. Refer to `numpy.all` for full documentation. See Also -------- numpy.ndarray.all : corresponding function for ndarrays numpy.all : equivalent function Examples -------- >>> np.ma.array([1,2,3]).all() True >>> a = np.ma.array([1,2,3], mask=True) >>> (a.all() is np.ma.masked) True """ kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims} mask = _check_mask_axis(self._mask, axis, **kwargs) if out is None: d = self.filled(True).all(axis=axis, **kwargs).view(type(self)) if d.ndim: d.__setmask__(mask) elif mask: return masked return d self.filled(True).all(axis=axis, out=out, **kwargs) if isinstance(out, MaskedArray): if out.ndim or mask: out.__setmask__(mask) return out def any(self, axis=None, out=None, keepdims=np._NoValue): """ Returns True if any of the elements of `a` evaluate to True. Masked values are considered as False during computation. Refer to `numpy.any` for full documentation. See Also -------- numpy.ndarray.any : corresponding function for ndarrays numpy.any : equivalent function """ kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims} mask = _check_mask_axis(self._mask, axis, **kwargs) if out is None: d = self.filled(False).any(axis=axis, **kwargs).view(type(self)) if d.ndim: d.__setmask__(mask) elif mask: d = masked return d self.filled(False).any(axis=axis, out=out, **kwargs) if isinstance(out, MaskedArray): if out.ndim or mask: out.__setmask__(mask) return out def nonzero(self): """ Return the indices of unmasked elements that are not zero. Returns a tuple of arrays, one for each dimension, containing the indices of the non-zero elements in that dimension. The corresponding non-zero values can be obtained with:: a[a.nonzero()] To group the indices by element, rather than dimension, use instead:: np.transpose(a.nonzero()) The result of this is always a 2d array, with a row for each non-zero element. Parameters ---------- None Returns ------- tuple_of_arrays : tuple Indices of elements that are non-zero. See Also -------- numpy.nonzero : Function operating on ndarrays. flatnonzero : Return indices that are non-zero in the flattened version of the input array. numpy.ndarray.nonzero : Equivalent ndarray method. count_nonzero : Counts the number of non-zero elements in the input array. Examples -------- >>> import numpy.ma as ma >>> x = ma.array(np.eye(3)) >>> x masked_array( data=[[1., 0., 0.], [0., 1., 0.], [0., 0., 1.]], mask=False, fill_value=1e+20) >>> x.nonzero() (array([0, 1, 2]), array([0, 1, 2])) Masked elements are ignored. >>> x[1, 1] = ma.masked >>> x masked_array( data=[[1.0, 0.0, 0.0], [0.0, --, 0.0], [0.0, 0.0, 1.0]], mask=[[False, False, False], [False, True, False], [False, False, False]], fill_value=1e+20) >>> x.nonzero() (array([0, 2]), array([0, 2])) Indices can also be grouped by element. >>> np.transpose(x.nonzero()) array([[0, 0], [2, 2]]) A common use for ``nonzero`` is to find the indices of an array, where a condition is True. Given an array `a`, the condition `a` > 3 is a boolean array and since False is interpreted as 0, ma.nonzero(a > 3) yields the indices of the `a` where the condition is true. >>> a = ma.array([[1,2,3],[4,5,6],[7,8,9]]) >>> a > 3 masked_array( data=[[False, False, False], [ True, True, True], [ True, True, True]], mask=False, fill_value=True) >>> ma.nonzero(a > 3) (array([1, 1, 1, 2, 2, 2]), array([0, 1, 2, 0, 1, 2])) The ``nonzero`` method of the condition array can also be called. >>> (a > 3).nonzero() (array([1, 1, 1, 2, 2, 2]), array([0, 1, 2, 0, 1, 2])) """ return narray(self.filled(0), copy=False).nonzero() def trace(self, offset=0, axis1=0, axis2=1, dtype=None, out=None): """ (this docstring should be overwritten) """ #!!!: implement out + test! m = self._mask if m is nomask: result = super().trace(offset=offset, axis1=axis1, axis2=axis2, out=out) return result.astype(dtype) else: D = self.diagonal(offset=offset, axis1=axis1, axis2=axis2) return D.astype(dtype).filled(0).sum(axis=-1, out=out) trace.__doc__ = ndarray.trace.__doc__ def dot(self, b, out=None, strict=False): """ a.dot(b, out=None) Masked dot product of two arrays. Note that `out` and `strict` are located in different positions than in `ma.dot`. In order to maintain compatibility with the functional version, it is recommended that the optional arguments be treated as keyword only. At some point that may be mandatory. .. versionadded:: 1.10.0 Parameters ---------- b : masked_array_like Inputs array. out : masked_array, optional Output argument. This must have the exact kind that would be returned if it was not used. In particular, it must have the right type, must be C-contiguous, and its dtype must be the dtype that would be returned for `ma.dot(a,b)`. This is a performance feature. Therefore, if these conditions are not met, an exception is raised, instead of attempting to be flexible. strict : bool, optional Whether masked data are propagated (True) or set to 0 (False) for the computation. Default is False. Propagating the mask means that if a masked value appears in a row or column, the whole row or column is considered masked. .. versionadded:: 1.10.2 See Also -------- numpy.ma.dot : equivalent function """ return dot(self, b, out=out, strict=strict) def sum(self, axis=None, dtype=None, out=None, keepdims=np._NoValue): """ Return the sum of the array elements over the given axis. Masked elements are set to 0 internally. Refer to `numpy.sum` for full documentation. See Also -------- numpy.ndarray.sum : corresponding function for ndarrays numpy.sum : equivalent function Examples -------- >>> x = np.ma.array([[1,2,3],[4,5,6],[7,8,9]], mask=[0] + [1,0]*4) >>> x masked_array( data=[[1, --, 3], [--, 5, --], [7, --, 9]], mask=[[False, True, False], [ True, False, True], [False, True, False]], fill_value=999999) >>> x.sum() 25 >>> x.sum(axis=1) masked_array(data=[4, 5, 16], mask=[False, False, False], fill_value=999999) >>> x.sum(axis=0) masked_array(data=[8, 5, 12], mask=[False, False, False], fill_value=999999) >>> print(type(x.sum(axis=0, dtype=np.int64)[0])) <class 'numpy.int64'> """ kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims} _mask = self._mask newmask = _check_mask_axis(_mask, axis, **kwargs) # No explicit output if out is None: result = self.filled(0).sum(axis, dtype=dtype, **kwargs) rndim = getattr(result, 'ndim', 0) if rndim: result = result.view(type(self)) result.__setmask__(newmask) elif newmask: result = masked return result # Explicit output result = self.filled(0).sum(axis, dtype=dtype, out=out, **kwargs) if isinstance(out, MaskedArray): outmask = getmask(out) if outmask is nomask: outmask = out._mask = make_mask_none(out.shape) outmask.flat = newmask return out def cumsum(self, axis=None, dtype=None, out=None): """ Return the cumulative sum of the array elements over the given axis. Masked values are set to 0 internally during the computation. However, their position is saved, and the result will be masked at the same locations. Refer to `numpy.cumsum` for full documentation. Notes ----- The mask is lost if `out` is not a valid :class:`ma.MaskedArray` ! Arithmetic is modular when using integer types, and no error is raised on overflow. See Also -------- numpy.ndarray.cumsum : corresponding function for ndarrays numpy.cumsum : equivalent function Examples -------- >>> marr = np.ma.array(np.arange(10), mask=[0,0,0,1,1,1,0,0,0,0]) >>> marr.cumsum() masked_array(data=[0, 1, 3, --, --, --, 9, 16, 24, 33], mask=[False, False, False, True, True, True, False, False, False, False], fill_value=999999) """ result = self.filled(0).cumsum(axis=axis, dtype=dtype, out=out) if out is not None: if isinstance(out, MaskedArray): out.__setmask__(self.mask) return out result = result.view(type(self)) result.__setmask__(self._mask) return result def prod(self, axis=None, dtype=None, out=None, keepdims=np._NoValue): """ Return the product of the array elements over the given axis. Masked elements are set to 1 internally for computation. Refer to `numpy.prod` for full documentation. Notes ----- Arithmetic is modular when using integer types, and no error is raised on overflow. See Also -------- numpy.ndarray.prod : corresponding function for ndarrays numpy.prod : equivalent function """ kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims} _mask = self._mask newmask = _check_mask_axis(_mask, axis, **kwargs) # No explicit output if out is None: result = self.filled(1).prod(axis, dtype=dtype, **kwargs) rndim = getattr(result, 'ndim', 0) if rndim: result = result.view(type(self)) result.__setmask__(newmask) elif newmask: result = masked return result # Explicit output result = self.filled(1).prod(axis, dtype=dtype, out=out, **kwargs) if isinstance(out, MaskedArray): outmask = getmask(out) if outmask is nomask: outmask = out._mask = make_mask_none(out.shape) outmask.flat = newmask return out product = prod def cumprod(self, axis=None, dtype=None, out=None): """ Return the cumulative product of the array elements over the given axis. Masked values are set to 1 internally during the computation. However, their position is saved, and the result will be masked at the same locations. Refer to `numpy.cumprod` for full documentation. Notes ----- The mask is lost if `out` is not a valid MaskedArray ! Arithmetic is modular when using integer types, and no error is raised on overflow. See Also -------- numpy.ndarray.cumprod : corresponding function for ndarrays numpy.cumprod : equivalent function """ result = self.filled(1).cumprod(axis=axis, dtype=dtype, out=out) if out is not None: if isinstance(out, MaskedArray): out.__setmask__(self._mask) return out result = result.view(type(self)) result.__setmask__(self._mask) return result def mean(self, axis=None, dtype=None, out=None, keepdims=np._NoValue): """ Returns the average of the array elements along given axis. Masked entries are ignored, and result elements which are not finite will be masked. Refer to `numpy.mean` for full documentation. See Also -------- numpy.ndarray.mean : corresponding function for ndarrays numpy.mean : Equivalent function numpy.ma.average : Weighted average. Examples -------- >>> a = np.ma.array([1,2,3], mask=[False, False, True]) >>> a masked_array(data=[1, 2, --], mask=[False, False, True], fill_value=999999) >>> a.mean() 1.5 """ kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims} if self._mask is nomask: result = super().mean(axis=axis, dtype=dtype, **kwargs)[()] else: is_float16_result = False if dtype is None: if issubclass(self.dtype.type, (ntypes.integer, ntypes.bool_)): dtype = mu.dtype('f8') elif issubclass(self.dtype.type, ntypes.float16): dtype = mu.dtype('f4') is_float16_result = True dsum = self.sum(axis=axis, dtype=dtype, **kwargs) cnt = self.count(axis=axis, **kwargs) if cnt.shape == () and (cnt == 0): result = masked elif is_float16_result: result = self.dtype.type(dsum * 1. / cnt) else: result = dsum * 1. / cnt if out is not None: out.flat = result if isinstance(out, MaskedArray): outmask = getmask(out) if outmask is nomask: outmask = out._mask = make_mask_none(out.shape) outmask.flat = getmask(result) return out return result def anom(self, axis=None, dtype=None): """ Compute the anomalies (deviations from the arithmetic mean) along the given axis. Returns an array of anomalies, with the same shape as the input and where the arithmetic mean is computed along the given axis. Parameters ---------- axis : int, optional Axis over which the anomalies are taken. The default is to use the mean of the flattened array as reference. dtype : dtype, optional Type to use in computing the variance. For arrays of integer type the default is float32; for arrays of float types it is the same as the array type. See Also -------- mean : Compute the mean of the array. Examples -------- >>> a = np.ma.array([1,2,3]) >>> a.anom() masked_array(data=[-1., 0., 1.], mask=False, fill_value=1e+20) """ m = self.mean(axis, dtype) if not axis: return self - m else: return self - expand_dims(m, axis) def var(self, axis=None, dtype=None, out=None, ddof=0, keepdims=np._NoValue): """ Returns the variance of the array elements along given axis. Masked entries are ignored, and result elements which are not finite will be masked. Refer to `numpy.var` for full documentation. See Also -------- numpy.ndarray.var : corresponding function for ndarrays numpy.var : Equivalent function """ kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims} # Easy case: nomask, business as usual if self._mask is nomask: ret = super().var(axis=axis, dtype=dtype, out=out, ddof=ddof, **kwargs)[()] if out is not None: if isinstance(out, MaskedArray): out.__setmask__(nomask) return out return ret # Some data are masked, yay! cnt = self.count(axis=axis, **kwargs) - ddof danom = self - self.mean(axis, dtype, keepdims=True) if iscomplexobj(self): danom = umath.absolute(danom) ** 2 else: danom *= danom dvar = divide(danom.sum(axis, **kwargs), cnt).view(type(self)) # Apply the mask if it's not a scalar if dvar.ndim: dvar._mask = mask_or(self._mask.all(axis, **kwargs), (cnt <= 0)) dvar._update_from(self) elif getmask(dvar): # Make sure that masked is returned when the scalar is masked. dvar = masked if out is not None: if isinstance(out, MaskedArray): out.flat = 0 out.__setmask__(True) elif out.dtype.kind in 'biu': errmsg = "Masked data information would be lost in one or "\ "more location." raise MaskError(errmsg) else: out.flat = np.nan return out # In case with have an explicit output if out is not None: # Set the data out.flat = dvar # Set the mask if needed if isinstance(out, MaskedArray): out.__setmask__(dvar.mask) return out return dvar var.__doc__ = np.var.__doc__ def std(self, axis=None, dtype=None, out=None, ddof=0, keepdims=np._NoValue): """ Returns the standard deviation of the array elements along given axis. Masked entries are ignored. Refer to `numpy.std` for full documentation. See Also -------- numpy.ndarray.std : corresponding function for ndarrays numpy.std : Equivalent function """ kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims} dvar = self.var(axis, dtype, out, ddof, **kwargs) if dvar is not masked: if out is not None: np.power(out, 0.5, out=out, casting='unsafe') return out dvar = sqrt(dvar) return dvar def round(self, decimals=0, out=None): """ Return each element rounded to the given number of decimals. Refer to `numpy.around` for full documentation. See Also -------- numpy.ndarray.round : corresponding function for ndarrays numpy.around : equivalent function """ result = self._data.round(decimals=decimals, out=out).view(type(self)) if result.ndim > 0: result._mask = self._mask result._update_from(self) elif self._mask: # Return masked when the scalar is masked result = masked # No explicit output: we're done if out is None: return result if isinstance(out, MaskedArray): out.__setmask__(self._mask) return out def argsort(self, axis=np._NoValue, kind=None, order=None, endwith=True, fill_value=None): """ Return an ndarray of indices that sort the array along the specified axis. Masked values are filled beforehand to `fill_value`. Parameters ---------- axis : int, optional Axis along which to sort. If None, the default, the flattened array is used. .. versionchanged:: 1.13.0 Previously, the default was documented to be -1, but that was in error. At some future date, the default will change to -1, as originally intended. Until then, the axis should be given explicitly when ``arr.ndim > 1``, to avoid a FutureWarning. kind : {'quicksort', 'mergesort', 'heapsort', 'stable'}, optional The sorting algorithm used. order : list, optional When `a` is an array with fields defined, this argument specifies which fields to compare first, second, etc. Not all fields need be specified. endwith : {True, False}, optional Whether missing values (if any) should be treated as the largest values (True) or the smallest values (False) When the array contains unmasked values at the same extremes of the datatype, the ordering of these values and the masked values is undefined. fill_value : scalar or None, optional Value used internally for the masked values. If ``fill_value`` is not None, it supersedes ``endwith``. Returns ------- index_array : ndarray, int Array of indices that sort `a` along the specified axis. In other words, ``a[index_array]`` yields a sorted `a`. See Also -------- ma.MaskedArray.sort : Describes sorting algorithms used. lexsort : Indirect stable sort with multiple keys. numpy.ndarray.sort : Inplace sort. Notes ----- See `sort` for notes on the different sorting algorithms. Examples -------- >>> a = np.ma.array([3,2,1], mask=[False, False, True]) >>> a masked_array(data=[3, 2, --], mask=[False, False, True], fill_value=999999) >>> a.argsort() array([1, 0, 2]) """ # 2017-04-11, Numpy 1.13.0, gh-8701: warn on axis default if axis is np._NoValue: axis = _deprecate_argsort_axis(self) if fill_value is None: if endwith: # nan > inf if np.issubdtype(self.dtype, np.floating): fill_value = np.nan else: fill_value = minimum_fill_value(self) else: fill_value = maximum_fill_value(self) filled = self.filled(fill_value) return filled.argsort(axis=axis, kind=kind, order=order) def argmin(self, axis=None, fill_value=None, out=None, *, keepdims=np._NoValue): """ Return array of indices to the minimum values along the given axis. Parameters ---------- axis : {None, integer} If None, the index is into the flattened array, otherwise along the specified axis fill_value : scalar or None, optional Value used to fill in the masked values. If None, the output of minimum_fill_value(self._data) is used instead. out : {None, array}, optional Array into which the result can be placed. Its type is preserved and it must be of the right shape to hold the output. Returns ------- ndarray or scalar If multi-dimension input, returns a new ndarray of indices to the minimum values along the given axis. Otherwise, returns a scalar of index to the minimum values along the given axis. Examples -------- >>> x = np.ma.array(np.arange(4), mask=[1,1,0,0]) >>> x.shape = (2,2) >>> x masked_array( data=[[--, --], [2, 3]], mask=[[ True, True], [False, False]], fill_value=999999) >>> x.argmin(axis=0, fill_value=-1) array([0, 0]) >>> x.argmin(axis=0, fill_value=9) array([1, 1]) """ if fill_value is None: fill_value = minimum_fill_value(self) d = self.filled(fill_value).view(ndarray) keepdims = False if keepdims is np._NoValue else bool(keepdims) return d.argmin(axis, out=out, keepdims=keepdims) def argmax(self, axis=None, fill_value=None, out=None, *, keepdims=np._NoValue): """ Returns array of indices of the maximum values along the given axis. Masked values are treated as if they had the value fill_value. Parameters ---------- axis : {None, integer} If None, the index is into the flattened array, otherwise along the specified axis fill_value : scalar or None, optional Value used to fill in the masked values. If None, the output of maximum_fill_value(self._data) is used instead. out : {None, array}, optional Array into which the result can be placed. Its type is preserved and it must be of the right shape to hold the output. Returns ------- index_array : {integer_array} Examples -------- >>> a = np.arange(6).reshape(2,3) >>> a.argmax() 5 >>> a.argmax(0) array([1, 1, 1]) >>> a.argmax(1) array([2, 2]) """ if fill_value is None: fill_value = maximum_fill_value(self._data) d = self.filled(fill_value).view(ndarray) keepdims = False if keepdims is np._NoValue else bool(keepdims) return d.argmax(axis, out=out, keepdims=keepdims) def sort(self, axis=-1, kind=None, order=None, endwith=True, fill_value=None): """ Sort the array, in-place Parameters ---------- a : array_like Array to be sorted. axis : int, optional Axis along which to sort. If None, the array is flattened before sorting. The default is -1, which sorts along the last axis. kind : {'quicksort', 'mergesort', 'heapsort', 'stable'}, optional The sorting algorithm used. order : list, optional When `a` is a structured array, this argument specifies which fields to compare first, second, and so on. This list does not need to include all of the fields. endwith : {True, False}, optional Whether missing values (if any) should be treated as the largest values (True) or the smallest values (False) When the array contains unmasked values sorting at the same extremes of the datatype, the ordering of these values and the masked values is undefined. fill_value : scalar or None, optional Value used internally for the masked values. If ``fill_value`` is not None, it supersedes ``endwith``. Returns ------- sorted_array : ndarray Array of the same type and shape as `a`. See Also -------- numpy.ndarray.sort : Method to sort an array in-place. argsort : Indirect sort. lexsort : Indirect stable sort on multiple keys. searchsorted : Find elements in a sorted array. Notes ----- See ``sort`` for notes on the different sorting algorithms. Examples -------- >>> a = np.ma.array([1, 2, 5, 4, 3],mask=[0, 1, 0, 1, 0]) >>> # Default >>> a.sort() >>> a masked_array(data=[1, 3, 5, --, --], mask=[False, False, False, True, True], fill_value=999999) >>> a = np.ma.array([1, 2, 5, 4, 3],mask=[0, 1, 0, 1, 0]) >>> # Put missing values in the front >>> a.sort(endwith=False) >>> a masked_array(data=[--, --, 1, 3, 5], mask=[ True, True, False, False, False], fill_value=999999) >>> a = np.ma.array([1, 2, 5, 4, 3],mask=[0, 1, 0, 1, 0]) >>> # fill_value takes over endwith >>> a.sort(endwith=False, fill_value=3) >>> a masked_array(data=[1, --, --, 3, 5], mask=[False, True, True, False, False], fill_value=999999) """ if self._mask is nomask: ndarray.sort(self, axis=axis, kind=kind, order=order) return if self is masked: return sidx = self.argsort(axis=axis, kind=kind, order=order, fill_value=fill_value, endwith=endwith) self[...] = np.take_along_axis(self, sidx, axis=axis) def min(self, axis=None, out=None, fill_value=None, keepdims=np._NoValue): """ Return the minimum along a given axis. Parameters ---------- axis : None or int or tuple of ints, optional Axis along which to operate. By default, ``axis`` is None and the flattened input is used. .. versionadded:: 1.7.0 If this is a tuple of ints, the minimum is selected over multiple axes, instead of a single axis or all the axes as before. out : array_like, optional Alternative output array in which to place the result. Must be of the same shape and buffer length as the expected output. fill_value : scalar or None, optional Value used to fill in the masked values. If None, use the output of `minimum_fill_value`. keepdims : bool, optional If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the array. Returns ------- amin : array_like New array holding the result. If ``out`` was specified, ``out`` is returned. See Also -------- ma.minimum_fill_value Returns the minimum filling value for a given datatype. Examples -------- >>> import numpy.ma as ma >>> x = [[1., -2., 3.], [0.2, -0.7, 0.1]] >>> mask = [[1, 1, 0], [0, 0, 1]] >>> masked_x = ma.masked_array(x, mask) >>> masked_x masked_array( data=[[--, --, 3.0], [0.2, -0.7, --]], mask=[[ True, True, False], [False, False, True]], fill_value=1e+20) >>> ma.min(masked_x) -0.7 >>> ma.min(masked_x, axis=-1) masked_array(data=[3.0, -0.7], mask=[False, False], fill_value=1e+20) >>> ma.min(masked_x, axis=0, keepdims=True) masked_array(data=[[0.2, -0.7, 3.0]], mask=[[False, False, False]], fill_value=1e+20) >>> mask = [[1, 1, 1,], [1, 1, 1]] >>> masked_x = ma.masked_array(x, mask) >>> ma.min(masked_x, axis=0) masked_array(data=[--, --, --], mask=[ True, True, True], fill_value=1e+20, dtype=float64) """ kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims} _mask = self._mask newmask = _check_mask_axis(_mask, axis, **kwargs) if fill_value is None: fill_value = minimum_fill_value(self) # No explicit output if out is None: result = self.filled(fill_value).min( axis=axis, out=out, **kwargs).view(type(self)) if result.ndim: # Set the mask result.__setmask__(newmask) # Get rid of Infs if newmask.ndim: np.copyto(result, result.fill_value, where=newmask) elif newmask: result = masked return result # Explicit output result = self.filled(fill_value).min(axis=axis, out=out, **kwargs) if isinstance(out, MaskedArray): outmask = getmask(out) if outmask is nomask: outmask = out._mask = make_mask_none(out.shape) outmask.flat = newmask else: if out.dtype.kind in 'biu': errmsg = "Masked data information would be lost in one or more"\ " location." raise MaskError(errmsg) np.copyto(out, np.nan, where=newmask) return out def max(self, axis=None, out=None, fill_value=None, keepdims=np._NoValue): """ Return the maximum along a given axis. Parameters ---------- axis : None or int or tuple of ints, optional Axis along which to operate. By default, ``axis`` is None and the flattened input is used. .. versionadded:: 1.7.0 If this is a tuple of ints, the maximum is selected over multiple axes, instead of a single axis or all the axes as before. out : array_like, optional Alternative output array in which to place the result. Must be of the same shape and buffer length as the expected output. fill_value : scalar or None, optional Value used to fill in the masked values. If None, use the output of maximum_fill_value(). keepdims : bool, optional If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the array. Returns ------- amax : array_like New array holding the result. If ``out`` was specified, ``out`` is returned. See Also -------- ma.maximum_fill_value Returns the maximum filling value for a given datatype. Examples -------- >>> import numpy.ma as ma >>> x = [[-1., 2.5], [4., -2.], [3., 0.]] >>> mask = [[0, 0], [1, 0], [1, 0]] >>> masked_x = ma.masked_array(x, mask) >>> masked_x masked_array( data=[[-1.0, 2.5], [--, -2.0], [--, 0.0]], mask=[[False, False], [ True, False], [ True, False]], fill_value=1e+20) >>> ma.max(masked_x) 2.5 >>> ma.max(masked_x, axis=0) masked_array(data=[-1.0, 2.5], mask=[False, False], fill_value=1e+20) >>> ma.max(masked_x, axis=1, keepdims=True) masked_array( data=[[2.5], [-2.0], [0.0]], mask=[[False], [False], [False]], fill_value=1e+20) >>> mask = [[1, 1], [1, 1], [1, 1]] >>> masked_x = ma.masked_array(x, mask) >>> ma.max(masked_x, axis=1) masked_array(data=[--, --, --], mask=[ True, True, True], fill_value=1e+20, dtype=float64) """ kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims} _mask = self._mask newmask = _check_mask_axis(_mask, axis, **kwargs) if fill_value is None: fill_value = maximum_fill_value(self) # No explicit output if out is None: result = self.filled(fill_value).max( axis=axis, out=out, **kwargs).view(type(self)) if result.ndim: # Set the mask result.__setmask__(newmask) # Get rid of Infs if newmask.ndim: np.copyto(result, result.fill_value, where=newmask) elif newmask: result = masked return result # Explicit output result = self.filled(fill_value).max(axis=axis, out=out, **kwargs) if isinstance(out, MaskedArray): outmask = getmask(out) if outmask is nomask: outmask = out._mask = make_mask_none(out.shape) outmask.flat = newmask else: if out.dtype.kind in 'biu': errmsg = "Masked data information would be lost in one or more"\ " location." raise MaskError(errmsg) np.copyto(out, np.nan, where=newmask) return out def ptp(self, axis=None, out=None, fill_value=None, keepdims=False): """ Return (maximum - minimum) along the given dimension (i.e. peak-to-peak value). .. warning:: `ptp` preserves the data type of the array. This means the return value for an input of signed integers with n bits (e.g. `np.int8`, `np.int16`, etc) is also a signed integer with n bits. In that case, peak-to-peak values greater than ``2**(n-1)-1`` will be returned as negative values. An example with a work-around is shown below. Parameters ---------- axis : {None, int}, optional Axis along which to find the peaks. If None (default) the flattened array is used. out : {None, array_like}, optional Alternative output array in which to place the result. It must have the same shape and buffer length as the expected output but the type will be cast if necessary. fill_value : scalar or None, optional Value used to fill in the masked values. keepdims : bool, optional If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the array. Returns ------- ptp : ndarray. A new array holding the result, unless ``out`` was specified, in which case a reference to ``out`` is returned. Examples -------- >>> x = np.ma.MaskedArray([[4, 9, 2, 10], ... [6, 9, 7, 12]]) >>> x.ptp(axis=1) masked_array(data=[8, 6], mask=False, fill_value=999999) >>> x.ptp(axis=0) masked_array(data=[2, 0, 5, 2], mask=False, fill_value=999999) >>> x.ptp() 10 This example shows that a negative value can be returned when the input is an array of signed integers. >>> y = np.ma.MaskedArray([[1, 127], ... [0, 127], ... [-1, 127], ... [-2, 127]], dtype=np.int8) >>> y.ptp(axis=1) masked_array(data=[ 126, 127, -128, -127], mask=False, fill_value=999999, dtype=int8) A work-around is to use the `view()` method to view the result as unsigned integers with the same bit width: >>> y.ptp(axis=1).view(np.uint8) masked_array(data=[126, 127, 128, 129], mask=False, fill_value=999999, dtype=uint8) """ if out is None: result = self.max(axis=axis, fill_value=fill_value, keepdims=keepdims) result -= self.min(axis=axis, fill_value=fill_value, keepdims=keepdims) return result out.flat = self.max(axis=axis, out=out, fill_value=fill_value, keepdims=keepdims) min_value = self.min(axis=axis, fill_value=fill_value, keepdims=keepdims) np.subtract(out, min_value, out=out, casting='unsafe') return out def partition(self, *args, **kwargs): warnings.warn("Warning: 'partition' will ignore the 'mask' " f"of the {self.__class__.__name__}.", stacklevel=2) return super().partition(*args, **kwargs) def argpartition(self, *args, **kwargs): warnings.warn("Warning: 'argpartition' will ignore the 'mask' " f"of the {self.__class__.__name__}.", stacklevel=2) return super().argpartition(*args, **kwargs) def take(self, indices, axis=None, out=None, mode='raise'): """ """ (_data, _mask) = (self._data, self._mask) cls = type(self) # Make sure the indices are not masked maskindices = getmask(indices) if maskindices is not nomask: indices = indices.filled(0) # Get the data, promoting scalars to 0d arrays with [...] so that # .view works correctly if out is None: out = _data.take(indices, axis=axis, mode=mode)[...].view(cls) else: np.take(_data, indices, axis=axis, mode=mode, out=out) # Get the mask if isinstance(out, MaskedArray): if _mask is nomask: outmask = maskindices else: outmask = _mask.take(indices, axis=axis, mode=mode) outmask |= maskindices out.__setmask__(outmask) # demote 0d arrays back to scalars, for consistency with ndarray.take return out[()] # Array methods copy = _arraymethod('copy') diagonal = _arraymethod('diagonal') flatten = _arraymethod('flatten') repeat = _arraymethod('repeat') squeeze = _arraymethod('squeeze') swapaxes = _arraymethod('swapaxes') T = property(fget=lambda self: self.transpose()) transpose = _arraymethod('transpose') def tolist(self, fill_value=None): """ Return the data portion of the masked array as a hierarchical Python list. Data items are converted to the nearest compatible Python type. Masked values are converted to `fill_value`. If `fill_value` is None, the corresponding entries in the output list will be ``None``. Parameters ---------- fill_value : scalar, optional The value to use for invalid entries. Default is None. Returns ------- result : list The Python list representation of the masked array. Examples -------- >>> x = np.ma.array([[1,2,3], [4,5,6], [7,8,9]], mask=[0] + [1,0]*4) >>> x.tolist() [[1, None, 3], [None, 5, None], [7, None, 9]] >>> x.tolist(-999) [[1, -999, 3], [-999, 5, -999], [7, -999, 9]] """ _mask = self._mask # No mask ? Just return .data.tolist ? if _mask is nomask: return self._data.tolist() # Explicit fill_value: fill the array and get the list if fill_value is not None: return self.filled(fill_value).tolist() # Structured array. names = self.dtype.names if names: result = self._data.astype([(_, object) for _ in names]) for n in names: result[n][_mask[n]] = None return result.tolist() # Standard arrays. if _mask is nomask: return [None] # Set temps to save time when dealing w/ marrays. inishape = self.shape result = np.array(self._data.ravel(), dtype=object) result[_mask.ravel()] = None result.shape = inishape return result.tolist() def tostring(self, fill_value=None, order='C'): r""" A compatibility alias for `tobytes`, with exactly the same behavior. Despite its name, it returns `bytes` not `str`\ s. .. deprecated:: 1.19.0 """ # 2020-03-30, Numpy 1.19.0 warnings.warn( "tostring() is deprecated. Use tobytes() instead.", DeprecationWarning, stacklevel=2) return self.tobytes(fill_value, order=order) def tobytes(self, fill_value=None, order='C'): """ Return the array data as a string containing the raw bytes in the array. The array is filled with a fill value before the string conversion. .. versionadded:: 1.9.0 Parameters ---------- fill_value : scalar, optional Value used to fill in the masked values. Default is None, in which case `MaskedArray.fill_value` is used. order : {'C','F','A'}, optional Order of the data item in the copy. Default is 'C'. - 'C' -- C order (row major). - 'F' -- Fortran order (column major). - 'A' -- Any, current order of array. - None -- Same as 'A'. See Also -------- numpy.ndarray.tobytes tolist, tofile Notes ----- As for `ndarray.tobytes`, information about the shape, dtype, etc., but also about `fill_value`, will be lost. Examples -------- >>> x = np.ma.array(np.array([[1, 2], [3, 4]]), mask=[[0, 1], [1, 0]]) >>> x.tobytes() b'\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00?B\\x0f\\x00\\x00\\x00\\x00\\x00?B\\x0f\\x00\\x00\\x00\\x00\\x00\\x04\\x00\\x00\\x00\\x00\\x00\\x00\\x00' """ return self.filled(fill_value).tobytes(order=order) def tofile(self, fid, sep="", format="%s"): """ Save a masked array to a file in binary format. .. warning:: This function is not implemented yet. Raises ------ NotImplementedError When `tofile` is called. """ raise NotImplementedError("MaskedArray.tofile() not implemented yet.") def toflex(self): """ Transforms a masked array into a flexible-type array. The flexible type array that is returned will have two fields: * the ``_data`` field stores the ``_data`` part of the array. * the ``_mask`` field stores the ``_mask`` part of the array. Parameters ---------- None Returns ------- record : ndarray A new flexible-type `ndarray` with two fields: the first element containing a value, the second element containing the corresponding mask boolean. The returned record shape matches self.shape. Notes ----- A side-effect of transforming a masked array into a flexible `ndarray` is that meta information (``fill_value``, ...) will be lost. Examples -------- >>> x = np.ma.array([[1,2,3],[4,5,6],[7,8,9]], mask=[0] + [1,0]*4) >>> x masked_array( data=[[1, --, 3], [--, 5, --], [7, --, 9]], mask=[[False, True, False], [ True, False, True], [False, True, False]], fill_value=999999) >>> x.toflex() array([[(1, False), (2, True), (3, False)], [(4, True), (5, False), (6, True)], [(7, False), (8, True), (9, False)]], dtype=[('_data', '<i8'), ('_mask', '?')]) """ # Get the basic dtype. ddtype = self.dtype # Make sure we have a mask _mask = self._mask if _mask is None: _mask = make_mask_none(self.shape, ddtype) # And get its dtype mdtype = self._mask.dtype record = np.ndarray(shape=self.shape, dtype=[('_data', ddtype), ('_mask', mdtype)]) record['_data'] = self._data record['_mask'] = self._mask return record torecords = toflex # Pickling def __getstate__(self): """Return the internal state of the masked array, for pickling purposes. """ cf = 'CF'[self.flags.fnc] data_state = super().__reduce__()[2] return data_state + (getmaskarray(self).tobytes(cf), self._fill_value) def __setstate__(self, state): """Restore the internal state of the masked array, for pickling purposes. ``state`` is typically the output of the ``__getstate__`` output, and is a 5-tuple: - class name - a tuple giving the shape of the data - a typecode for the data - a binary string for the data - a binary string for the mask. """ (_, shp, typ, isf, raw, msk, flv) = state super().__setstate__((shp, typ, isf, raw)) self._mask.__setstate__((shp, make_mask_descr(typ), isf, msk)) self.fill_value = flv def __reduce__(self): """Return a 3-tuple for pickling a MaskedArray. """ return (_mareconstruct, (self.__class__, self._baseclass, (0,), 'b',), self.__getstate__()) def __deepcopy__(self, memo=None): from copy import deepcopy copied = MaskedArray.__new__(type(self), self, copy=True) if memo is None: memo = {} memo[id(self)] = copied for (k, v) in self.__dict__.items(): copied.__dict__[k] = deepcopy(v, memo) return copied def array(data, dtype=None, copy=False, order=None, mask=nomask, fill_value=None, keep_mask=True, hard_mask=False, shrink=True, subok=True, ndmin=0): """ Shortcut to MaskedArray. The options are in a different order for convenience and backwards compatibility. """ return MaskedArray(data, mask=mask, dtype=dtype, copy=copy, subok=subok, keep_mask=keep_mask, hard_mask=hard_mask, fill_value=fill_value, ndmin=ndmin, shrink=shrink, order=order) array.__doc__ = masked_array.__doc__ ravel = _frommethod('ravel') def shape(obj): "maskedarray version of the numpy function." return np.shape(getdata(obj)) shape.__doc__ = np.shape.__doc__ def asanyarray(a, dtype=None): """ Convert the input to a masked array, conserving subclasses. If `a` is a subclass of `MaskedArray`, its class is conserved. No copy is performed if the input is already an `ndarray`. Parameters ---------- a : array_like Input data, in any form that can be converted to an array. dtype : dtype, optional By default, the data-type is inferred from the input data. order : {'C', 'F'}, optional Whether to use row-major ('C') or column-major ('FORTRAN') memory representation. Default is 'C'. Returns ------- out : MaskedArray MaskedArray interpretation of `a`. See Also -------- asarray : Similar to `asanyarray`, but does not conserve subclass. Examples -------- >>> x = np.arange(10.).reshape(2, 5) >>> x array([[0., 1., 2., 3., 4.], [5., 6., 7., 8., 9.]]) >>> np.ma.asanyarray(x) masked_array( data=[[0., 1., 2., 3., 4.], [5., 6., 7., 8., 9.]], mask=False, fill_value=1e+20) >>> type(np.ma.asanyarray(x)) <class 'numpy.ma.core.MaskedArray'> """ # workaround for #8666, to preserve identity. Ideally the bottom line # would handle this for us. if isinstance(a, MaskedArray) and (dtype is None or dtype == a.dtype): return a return masked_array(a, dtype=dtype, copy=False, keep_mask=True, subok=True) The provided code snippet includes necessary dependencies for implementing the `flatten_structured_array` function. Write a Python function `def flatten_structured_array(a)` to solve the following problem: Flatten a structured array. The data type of the output is chosen such that it can represent all of the (nested) fields. Parameters ---------- a : structured array Returns ------- output : masked array or ndarray A flattened masked array if the input is a masked array, otherwise a standard ndarray. Examples -------- >>> ndtype = [('a', int), ('b', float)] >>> a = np.array([(1, 1), (2, 2)], dtype=ndtype) >>> np.ma.flatten_structured_array(a) array([[1., 1.], [2., 2.]]) Here is the function: def flatten_structured_array(a): """ Flatten a structured array. The data type of the output is chosen such that it can represent all of the (nested) fields. Parameters ---------- a : structured array Returns ------- output : masked array or ndarray A flattened masked array if the input is a masked array, otherwise a standard ndarray. Examples -------- >>> ndtype = [('a', int), ('b', float)] >>> a = np.array([(1, 1), (2, 2)], dtype=ndtype) >>> np.ma.flatten_structured_array(a) array([[1., 1.], [2., 2.]]) """ def flatten_sequence(iterable): """ Flattens a compound of nested iterables. """ for elm in iter(iterable): if hasattr(elm, '__iter__'): yield from flatten_sequence(elm) else: yield elm a = np.asanyarray(a) inishape = a.shape a = a.ravel() if isinstance(a, MaskedArray): out = np.array([tuple(flatten_sequence(d.item())) for d in a._data]) out = out.view(MaskedArray) out._mask = np.array([tuple(flatten_sequence(d.item())) for d in getmaskarray(a)]) else: out = np.array([tuple(flatten_sequence(d.item())) for d in a]) if len(inishape) > 1: newshape = list(out.shape) newshape[0] = inishape out.shape = tuple(flatten_sequence(newshape)) return out
Flatten a structured array. The data type of the output is chosen such that it can represent all of the (nested) fields. Parameters ---------- a : structured array Returns ------- output : masked array or ndarray A flattened masked array if the input is a masked array, otherwise a standard ndarray. Examples -------- >>> ndtype = [('a', int), ('b', float)] >>> a = np.array([(1, 1), (2, 2)], dtype=ndtype) >>> np.ma.flatten_structured_array(a) array([[1., 1.], [2., 2.]])
170,110
import builtins import inspect import operator import warnings import textwrap import re from functools import reduce import numpy as np import numpy.core.umath as umath import numpy.core.numerictypes as ntypes from numpy.core import multiarray as mu from numpy import ndarray, amax, amin, iscomplexobj, bool_, _NoValue from numpy import array as narray from numpy.lib.function_base import angle from numpy.compat import ( getargspec, formatargspec, long, unicode, bytes ) from numpy import expand_dims from numpy.core.numeric import normalize_axis_tuple nomask = MaskType(0) The provided code snippet includes necessary dependencies for implementing the `_arraymethod` function. Write a Python function `def _arraymethod(funcname, onmask=True)` to solve the following problem: Return a class method wrapper around a basic array method. Creates a class method which returns a masked array, where the new ``_data`` array is the output of the corresponding basic method called on the original ``_data``. If `onmask` is True, the new mask is the output of the method called on the initial mask. Otherwise, the new mask is just a reference to the initial mask. Parameters ---------- funcname : str Name of the function to apply on data. onmask : bool Whether the mask must be processed also (True) or left alone (False). Default is True. Make available as `_onmask` attribute. Returns ------- method : instancemethod Class method wrapper of the specified basic array method. Here is the function: def _arraymethod(funcname, onmask=True): """ Return a class method wrapper around a basic array method. Creates a class method which returns a masked array, where the new ``_data`` array is the output of the corresponding basic method called on the original ``_data``. If `onmask` is True, the new mask is the output of the method called on the initial mask. Otherwise, the new mask is just a reference to the initial mask. Parameters ---------- funcname : str Name of the function to apply on data. onmask : bool Whether the mask must be processed also (True) or left alone (False). Default is True. Make available as `_onmask` attribute. Returns ------- method : instancemethod Class method wrapper of the specified basic array method. """ def wrapped_method(self, *args, **params): result = getattr(self._data, funcname)(*args, **params) result = result.view(type(self)) result._update_from(self) mask = self._mask if not onmask: result.__setmask__(mask) elif mask is not nomask: # __setmask__ makes a copy, which we don't want result._mask = getattr(mask, funcname)(*args, **params) return result methdoc = getattr(ndarray, funcname, None) or getattr(np, funcname, None) if methdoc is not None: wrapped_method.__doc__ = methdoc.__doc__ wrapped_method.__name__ = funcname return wrapped_method
Return a class method wrapper around a basic array method. Creates a class method which returns a masked array, where the new ``_data`` array is the output of the corresponding basic method called on the original ``_data``. If `onmask` is True, the new mask is the output of the method called on the initial mask. Otherwise, the new mask is just a reference to the initial mask. Parameters ---------- funcname : str Name of the function to apply on data. onmask : bool Whether the mask must be processed also (True) or left alone (False). Default is True. Make available as `_onmask` attribute. Returns ------- method : instancemethod Class method wrapper of the specified basic array method.
170,111
import builtins import inspect import operator import warnings import textwrap import re from functools import reduce import numpy as np import numpy.core.umath as umath import numpy.core.numerictypes as ntypes from numpy.core import multiarray as mu from numpy import ndarray, amax, amin, iscomplexobj, bool_, _NoValue from numpy import array as narray from numpy.lib.function_base import angle from numpy.compat import ( getargspec, formatargspec, long, unicode, bytes ) from numpy import expand_dims from numpy.core.numeric import normalize_axis_tuple def make_mask_descr(ndtype): """ Construct a dtype description list from a given dtype. Returns a new dtype object, with the type of all fields in `ndtype` to a boolean type. Field names are not altered. Parameters ---------- ndtype : dtype The dtype to convert. Returns ------- result : dtype A dtype that looks like `ndtype`, the type of all fields is boolean. Examples -------- >>> import numpy.ma as ma >>> dtype = np.dtype({'names':['foo', 'bar'], ... 'formats':[np.float32, np.int64]}) >>> dtype dtype([('foo', '<f4'), ('bar', '<i8')]) >>> ma.make_mask_descr(dtype) dtype([('foo', '|b1'), ('bar', '|b1')]) >>> ma.make_mask_descr(np.float32) dtype('bool') """ return _replace_dtype_fields(ndtype, MaskType) The provided code snippet includes necessary dependencies for implementing the `_mareconstruct` function. Write a Python function `def _mareconstruct(subtype, baseclass, baseshape, basetype,)` to solve the following problem: Internal function that builds a new MaskedArray from the information stored in a pickle. Here is the function: def _mareconstruct(subtype, baseclass, baseshape, basetype,): """Internal function that builds a new MaskedArray from the information stored in a pickle. """ _data = ndarray.__new__(baseclass, baseshape, basetype) _mask = ndarray.__new__(ndarray, baseshape, make_mask_descr(basetype)) return subtype.__new__(subtype, _data, mask=_mask, dtype=basetype,)
Internal function that builds a new MaskedArray from the information stored in a pickle.
170,112
import builtins import inspect import operator import warnings import textwrap import re from functools import reduce import numpy as np import numpy.core.umath as umath import numpy.core.numerictypes as ntypes from numpy.core import multiarray as mu from numpy import ndarray, amax, amin, iscomplexobj, bool_, _NoValue from numpy import array as narray from numpy.lib.function_base import angle from numpy.compat import ( getargspec, formatargspec, long, unicode, bytes ) from numpy import expand_dims from numpy.core.numeric import normalize_axis_tuple def asanyarray(a, dtype=None): """ Convert the input to a masked array, conserving subclasses. If `a` is a subclass of `MaskedArray`, its class is conserved. No copy is performed if the input is already an `ndarray`. Parameters ---------- a : array_like Input data, in any form that can be converted to an array. dtype : dtype, optional By default, the data-type is inferred from the input data. order : {'C', 'F'}, optional Whether to use row-major ('C') or column-major ('FORTRAN') memory representation. Default is 'C'. Returns ------- out : MaskedArray MaskedArray interpretation of `a`. See Also -------- asarray : Similar to `asanyarray`, but does not conserve subclass. Examples -------- >>> x = np.arange(10.).reshape(2, 5) >>> x array([[0., 1., 2., 3., 4.], [5., 6., 7., 8., 9.]]) >>> np.ma.asanyarray(x) masked_array( data=[[0., 1., 2., 3., 4.], [5., 6., 7., 8., 9.]], mask=False, fill_value=1e+20) >>> type(np.ma.asanyarray(x)) <class 'numpy.ma.core.MaskedArray'> """ # workaround for #8666, to preserve identity. Ideally the bottom line # would handle this for us. if isinstance(a, MaskedArray) and (dtype is None or dtype == a.dtype): return a return masked_array(a, dtype=dtype, copy=False, keep_mask=True, subok=True) def ptp(obj, axis=None, out=None, fill_value=None, keepdims=np._NoValue): kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims} try: return obj.ptp(axis, out=out, fill_value=fill_value, **kwargs) except (AttributeError, TypeError): # If obj doesn't have a ptp method or if the method doesn't accept # a fill_value argument return asanyarray(obj).ptp(axis=axis, fill_value=fill_value, out=out, **kwargs)
null
170,113
import builtins import inspect import operator import warnings import textwrap import re from functools import reduce import numpy as np import numpy.core.umath as umath import numpy.core.numerictypes as ntypes from numpy.core import multiarray as mu from numpy import ndarray, amax, amin, iscomplexobj, bool_, _NoValue from numpy import array as narray from numpy.lib.function_base import angle from numpy.compat import ( getargspec, formatargspec, long, unicode, bytes ) from numpy import expand_dims from numpy.core.numeric import normalize_axis_tuple nomask = MaskType(0) class MaskError(MAError): """ Class for mask related errors. """ pass def getdata(a, subok=True): """ Return the data of a masked array as an ndarray. Return the data of `a` (if any) as an ndarray if `a` is a ``MaskedArray``, else return `a` as a ndarray or subclass (depending on `subok`) if not. Parameters ---------- a : array_like Input ``MaskedArray``, alternatively a ndarray or a subclass thereof. subok : bool Whether to force the output to be a `pure` ndarray (False) or to return a subclass of ndarray if appropriate (True, default). See Also -------- getmask : Return the mask of a masked array, or nomask. getmaskarray : Return the mask of a masked array, or full array of False. Examples -------- >>> import numpy.ma as ma >>> a = ma.masked_equal([[1,2],[3,4]], 2) >>> a masked_array( data=[[1, --], [3, 4]], mask=[[False, True], [False, False]], fill_value=2) >>> ma.getdata(a) array([[1, 2], [3, 4]]) Equivalently use the ``MaskedArray`` `data` attribute. >>> a.data array([[1, 2], [3, 4]]) """ try: data = a._data except AttributeError: data = np.array(a, copy=False, subok=subok) if not subok: return data.view(ndarray) return data logical_not = _MaskedUnaryOperation(umath.logical_not) logical_or = _MaskedBinaryOperation(umath.logical_or) divide = _DomainedBinaryOperation(umath.divide, _DomainSafeDivide(), 0, 1) def getmask(a): """ Return the mask of a masked array, or nomask. Return the mask of `a` as an ndarray if `a` is a `MaskedArray` and the mask is not `nomask`, else return `nomask`. To guarantee a full array of booleans of the same shape as a, use `getmaskarray`. Parameters ---------- a : array_like Input `MaskedArray` for which the mask is required. See Also -------- getdata : Return the data of a masked array as an ndarray. getmaskarray : Return the mask of a masked array, or full array of False. Examples -------- >>> import numpy.ma as ma >>> a = ma.masked_equal([[1,2],[3,4]], 2) >>> a masked_array( data=[[1, --], [3, 4]], mask=[[False, True], [False, False]], fill_value=2) >>> ma.getmask(a) array([[False, True], [False, False]]) Equivalently use the `MaskedArray` `mask` attribute. >>> a.mask array([[False, True], [False, False]]) Result when mask == `nomask` >>> b = ma.masked_array([[1,2],[3,4]]) >>> b masked_array( data=[[1, 2], [3, 4]], mask=False, fill_value=999999) >>> ma.nomask False >>> ma.getmask(b) == ma.nomask True >>> b.mask == ma.nomask True """ return getattr(a, '_mask', nomask) def mask_or(m1, m2, copy=False, shrink=True): """ Combine two masks with the ``logical_or`` operator. The result may be a view on `m1` or `m2` if the other is `nomask` (i.e. False). Parameters ---------- m1, m2 : array_like Input masks. copy : bool, optional If copy is False and one of the inputs is `nomask`, return a view of the other input mask. Defaults to False. shrink : bool, optional Whether to shrink the output to `nomask` if all its values are False. Defaults to True. Returns ------- mask : output mask The result masks values that are masked in either `m1` or `m2`. Raises ------ ValueError If `m1` and `m2` have different flexible dtypes. Examples -------- >>> m1 = np.ma.make_mask([0, 1, 1, 0]) >>> m2 = np.ma.make_mask([1, 0, 0, 0]) >>> np.ma.mask_or(m1, m2) array([ True, True, True, False]) """ if (m1 is nomask) or (m1 is False): dtype = getattr(m2, 'dtype', MaskType) return make_mask(m2, copy=copy, shrink=shrink, dtype=dtype) if (m2 is nomask) or (m2 is False): dtype = getattr(m1, 'dtype', MaskType) return make_mask(m1, copy=copy, shrink=shrink, dtype=dtype) if m1 is m2 and is_mask(m1): return m1 (dtype1, dtype2) = (getattr(m1, 'dtype', None), getattr(m2, 'dtype', None)) if dtype1 != dtype2: raise ValueError("Incompatible dtypes '%s'<>'%s'" % (dtype1, dtype2)) if dtype1.names is not None: # Allocate an output mask array with the properly broadcast shape. newmask = np.empty(np.broadcast(m1, m2).shape, dtype1) _recursive_mask_or(m1, m2, newmask) return newmask return make_mask(umath.logical_or(m1, m2), copy=copy, shrink=shrink) class MaskedArray(ndarray): """ An array class with possibly masked values. Masked values of True exclude the corresponding element from any computation. Construction:: x = MaskedArray(data, mask=nomask, dtype=None, copy=False, subok=True, ndmin=0, fill_value=None, keep_mask=True, hard_mask=None, shrink=True, order=None) Parameters ---------- data : array_like Input data. mask : sequence, optional Mask. Must be convertible to an array of booleans with the same shape as `data`. True indicates a masked (i.e. invalid) data. dtype : dtype, optional Data type of the output. If `dtype` is None, the type of the data argument (``data.dtype``) is used. If `dtype` is not None and different from ``data.dtype``, a copy is performed. copy : bool, optional Whether to copy the input data (True), or to use a reference instead. Default is False. subok : bool, optional Whether to return a subclass of `MaskedArray` if possible (True) or a plain `MaskedArray`. Default is True. ndmin : int, optional Minimum number of dimensions. Default is 0. fill_value : scalar, optional Value used to fill in the masked values when necessary. If None, a default based on the data-type is used. keep_mask : bool, optional Whether to combine `mask` with the mask of the input data, if any (True), or to use only `mask` for the output (False). Default is True. hard_mask : bool, optional Whether to use a hard mask or not. With a hard mask, masked values cannot be unmasked. Default is False. shrink : bool, optional Whether to force compression of an empty mask. Default is True. order : {'C', 'F', 'A'}, optional Specify the order of the array. If order is 'C', then the array will be in C-contiguous order (last-index varies the fastest). If order is 'F', then the returned array will be in Fortran-contiguous order (first-index varies the fastest). If order is 'A' (default), then the returned array may be in any order (either C-, Fortran-contiguous, or even discontiguous), unless a copy is required, in which case it will be C-contiguous. Examples -------- The ``mask`` can be initialized with an array of boolean values with the same shape as ``data``. >>> data = np.arange(6).reshape((2, 3)) >>> np.ma.MaskedArray(data, mask=[[False, True, False], ... [False, False, True]]) masked_array( data=[[0, --, 2], [3, 4, --]], mask=[[False, True, False], [False, False, True]], fill_value=999999) Alternatively, the ``mask`` can be initialized to homogeneous boolean array with the same shape as ``data`` by passing in a scalar boolean value: >>> np.ma.MaskedArray(data, mask=False) masked_array( data=[[0, 1, 2], [3, 4, 5]], mask=[[False, False, False], [False, False, False]], fill_value=999999) >>> np.ma.MaskedArray(data, mask=True) masked_array( data=[[--, --, --], [--, --, --]], mask=[[ True, True, True], [ True, True, True]], fill_value=999999, dtype=int64) .. note:: The recommended practice for initializing ``mask`` with a scalar boolean value is to use ``True``/``False`` rather than ``np.True_``/``np.False_``. The reason is :attr:`nomask` is represented internally as ``np.False_``. >>> np.False_ is np.ma.nomask True """ __array_priority__ = 15 _defaultmask = nomask _defaulthardmask = False _baseclass = ndarray # Maximum number of elements per axis used when printing an array. The # 1d case is handled separately because we need more values in this case. _print_width = 100 _print_width_1d = 1500 def __new__(cls, data=None, mask=nomask, dtype=None, copy=False, subok=True, ndmin=0, fill_value=None, keep_mask=True, hard_mask=None, shrink=True, order=None): """ Create a new masked array from scratch. Notes ----- A masked array can also be created by taking a .view(MaskedArray). """ # Process data. _data = np.array(data, dtype=dtype, copy=copy, order=order, subok=True, ndmin=ndmin) _baseclass = getattr(data, '_baseclass', type(_data)) # Check that we're not erasing the mask. if isinstance(data, MaskedArray) and (data.shape != _data.shape): copy = True # Here, we copy the _view_, so that we can attach new properties to it # we must never do .view(MaskedConstant), as that would create a new # instance of np.ma.masked, which make identity comparison fail if isinstance(data, cls) and subok and not isinstance(data, MaskedConstant): _data = ndarray.view(_data, type(data)) else: _data = ndarray.view(_data, cls) # Handle the case where data is not a subclass of ndarray, but # still has the _mask attribute like MaskedArrays if hasattr(data, '_mask') and not isinstance(data, ndarray): _data._mask = data._mask # FIXME: should we set `_data._sharedmask = True`? # Process mask. # Type of the mask mdtype = make_mask_descr(_data.dtype) if mask is nomask: # Case 1. : no mask in input. # Erase the current mask ? if not keep_mask: # With a reduced version if shrink: _data._mask = nomask # With full version else: _data._mask = np.zeros(_data.shape, dtype=mdtype) # Check whether we missed something elif isinstance(data, (tuple, list)): try: # If data is a sequence of masked array mask = np.array( [getmaskarray(np.asanyarray(m, dtype=_data.dtype)) for m in data], dtype=mdtype) except ValueError: # If data is nested mask = nomask # Force shrinking of the mask if needed (and possible) if (mdtype == MaskType) and mask.any(): _data._mask = mask _data._sharedmask = False else: _data._sharedmask = not copy if copy: _data._mask = _data._mask.copy() # Reset the shape of the original mask if getmask(data) is not nomask: data._mask.shape = data.shape else: # Case 2. : With a mask in input. # If mask is boolean, create an array of True or False if mask is True and mdtype == MaskType: mask = np.ones(_data.shape, dtype=mdtype) elif mask is False and mdtype == MaskType: mask = np.zeros(_data.shape, dtype=mdtype) else: # Read the mask with the current mdtype try: mask = np.array(mask, copy=copy, dtype=mdtype) # Or assume it's a sequence of bool/int except TypeError: mask = np.array([tuple([m] * len(mdtype)) for m in mask], dtype=mdtype) # Make sure the mask and the data have the same shape if mask.shape != _data.shape: (nd, nm) = (_data.size, mask.size) if nm == 1: mask = np.resize(mask, _data.shape) elif nm == nd: mask = np.reshape(mask, _data.shape) else: msg = "Mask and data not compatible: data size is %i, " + \ "mask size is %i." raise MaskError(msg % (nd, nm)) copy = True # Set the mask to the new value if _data._mask is nomask: _data._mask = mask _data._sharedmask = not copy else: if not keep_mask: _data._mask = mask _data._sharedmask = not copy else: if _data.dtype.names is not None: def _recursive_or(a, b): "do a|=b on each field of a, recursively" for name in a.dtype.names: (af, bf) = (a[name], b[name]) if af.dtype.names is not None: _recursive_or(af, bf) else: af |= bf _recursive_or(_data._mask, mask) else: _data._mask = np.logical_or(mask, _data._mask) _data._sharedmask = False # Update fill_value. if fill_value is None: fill_value = getattr(data, '_fill_value', None) # But don't run the check unless we have something to check. if fill_value is not None: _data._fill_value = _check_fill_value(fill_value, _data.dtype) # Process extra options .. if hard_mask is None: _data._hardmask = getattr(data, '_hardmask', False) else: _data._hardmask = hard_mask _data._baseclass = _baseclass return _data def _update_from(self, obj): """ Copies some attributes of obj to self. """ if isinstance(obj, ndarray): _baseclass = type(obj) else: _baseclass = ndarray # We need to copy the _basedict to avoid backward propagation _optinfo = {} _optinfo.update(getattr(obj, '_optinfo', {})) _optinfo.update(getattr(obj, '_basedict', {})) if not isinstance(obj, MaskedArray): _optinfo.update(getattr(obj, '__dict__', {})) _dict = dict(_fill_value=getattr(obj, '_fill_value', None), _hardmask=getattr(obj, '_hardmask', False), _sharedmask=getattr(obj, '_sharedmask', False), _isfield=getattr(obj, '_isfield', False), _baseclass=getattr(obj, '_baseclass', _baseclass), _optinfo=_optinfo, _basedict=_optinfo) self.__dict__.update(_dict) self.__dict__.update(_optinfo) return def __array_finalize__(self, obj): """ Finalizes the masked array. """ # Get main attributes. self._update_from(obj) # We have to decide how to initialize self.mask, based on # obj.mask. This is very difficult. There might be some # correspondence between the elements in the array we are being # created from (= obj) and us. Or there might not. This method can # be called in all kinds of places for all kinds of reasons -- could # be empty_like, could be slicing, could be a ufunc, could be a view. # The numpy subclassing interface simply doesn't give us any way # to know, which means that at best this method will be based on # guesswork and heuristics. To make things worse, there isn't even any # clear consensus about what the desired behavior is. For instance, # most users think that np.empty_like(marr) -- which goes via this # method -- should return a masked array with an empty mask (see # gh-3404 and linked discussions), but others disagree, and they have # existing code which depends on empty_like returning an array that # matches the input mask. # # Historically our algorithm was: if the template object mask had the # same *number of elements* as us, then we used *it's mask object # itself* as our mask, so that writes to us would also write to the # original array. This is horribly broken in multiple ways. # # Now what we do instead is, if the template object mask has the same # number of elements as us, and we do not have the same base pointer # as the template object (b/c views like arr[...] should keep the same # mask), then we make a copy of the template object mask and use # that. This is also horribly broken but somewhat less so. Maybe. if isinstance(obj, ndarray): # XX: This looks like a bug -- shouldn't it check self.dtype # instead? if obj.dtype.names is not None: _mask = getmaskarray(obj) else: _mask = getmask(obj) # If self and obj point to exactly the same data, then probably # self is a simple view of obj (e.g., self = obj[...]), so they # should share the same mask. (This isn't 100% reliable, e.g. self # could be the first row of obj, or have strange strides, but as a # heuristic it's not bad.) In all other cases, we make a copy of # the mask, so that future modifications to 'self' do not end up # side-effecting 'obj' as well. if (_mask is not nomask and obj.__array_interface__["data"][0] != self.__array_interface__["data"][0]): # We should make a copy. But we could get here via astype, # in which case the mask might need a new dtype as well # (e.g., changing to or from a structured dtype), and the # order could have changed. So, change the mask type if # needed and use astype instead of copy. if self.dtype == obj.dtype: _mask_dtype = _mask.dtype else: _mask_dtype = make_mask_descr(self.dtype) if self.flags.c_contiguous: order = "C" elif self.flags.f_contiguous: order = "F" else: order = "K" _mask = _mask.astype(_mask_dtype, order) else: # Take a view so shape changes, etc., do not propagate back. _mask = _mask.view() else: _mask = nomask self._mask = _mask # Finalize the mask if self._mask is not nomask: try: self._mask.shape = self.shape except ValueError: self._mask = nomask except (TypeError, AttributeError): # When _mask.shape is not writable (because it's a void) pass # Finalize the fill_value if self._fill_value is not None: self._fill_value = _check_fill_value(self._fill_value, self.dtype) elif self.dtype.names is not None: # Finalize the default fill_value for structured arrays self._fill_value = _check_fill_value(None, self.dtype) def __array_wrap__(self, obj, context=None): """ Special hook for ufuncs. Wraps the numpy array and sets the mask according to context. """ if obj is self: # for in-place operations result = obj else: result = obj.view(type(self)) result._update_from(self) if context is not None: result._mask = result._mask.copy() func, args, out_i = context # args sometimes contains outputs (gh-10459), which we don't want input_args = args[:func.nin] m = reduce(mask_or, [getmaskarray(arg) for arg in input_args]) # Get the domain mask domain = ufunc_domain.get(func, None) if domain is not None: # Take the domain, and make sure it's a ndarray with np.errstate(divide='ignore', invalid='ignore'): d = filled(domain(*input_args), True) if d.any(): # Fill the result where the domain is wrong try: # Binary domain: take the last value fill_value = ufunc_fills[func][-1] except TypeError: # Unary domain: just use this one fill_value = ufunc_fills[func] except KeyError: # Domain not recognized, use fill_value instead fill_value = self.fill_value np.copyto(result, fill_value, where=d) # Update the mask if m is nomask: m = d else: # Don't modify inplace, we risk back-propagation m = (m | d) # Make sure the mask has the proper size if result is not self and result.shape == () and m: return masked else: result._mask = m result._sharedmask = False return result def view(self, dtype=None, type=None, fill_value=None): """ Return a view of the MaskedArray data. Parameters ---------- dtype : data-type or ndarray sub-class, optional Data-type descriptor of the returned view, e.g., float32 or int16. The default, None, results in the view having the same data-type as `a`. As with ``ndarray.view``, dtype can also be specified as an ndarray sub-class, which then specifies the type of the returned object (this is equivalent to setting the ``type`` parameter). type : Python type, optional Type of the returned view, either ndarray or a subclass. The default None results in type preservation. fill_value : scalar, optional The value to use for invalid entries (None by default). If None, then this argument is inferred from the passed `dtype`, or in its absence the original array, as discussed in the notes below. See Also -------- numpy.ndarray.view : Equivalent method on ndarray object. Notes ----- ``a.view()`` is used two different ways: ``a.view(some_dtype)`` or ``a.view(dtype=some_dtype)`` constructs a view of the array's memory with a different data-type. This can cause a reinterpretation of the bytes of memory. ``a.view(ndarray_subclass)`` or ``a.view(type=ndarray_subclass)`` just returns an instance of `ndarray_subclass` that looks at the same array (same shape, dtype, etc.) This does not cause a reinterpretation of the memory. If `fill_value` is not specified, but `dtype` is specified (and is not an ndarray sub-class), the `fill_value` of the MaskedArray will be reset. If neither `fill_value` nor `dtype` are specified (or if `dtype` is an ndarray sub-class), then the fill value is preserved. Finally, if `fill_value` is specified, but `dtype` is not, the fill value is set to the specified value. For ``a.view(some_dtype)``, if ``some_dtype`` has a different number of bytes per entry than the previous dtype (for example, converting a regular array to a structured array), then the behavior of the view cannot be predicted just from the superficial appearance of ``a`` (shown by ``print(a)``). It also depends on exactly how ``a`` is stored in memory. Therefore if ``a`` is C-ordered versus fortran-ordered, versus defined as a slice or transpose, etc., the view may give different results. """ if dtype is None: if type is None: output = ndarray.view(self) else: output = ndarray.view(self, type) elif type is None: try: if issubclass(dtype, ndarray): output = ndarray.view(self, dtype) dtype = None else: output = ndarray.view(self, dtype) except TypeError: output = ndarray.view(self, dtype) else: output = ndarray.view(self, dtype, type) # also make the mask be a view (so attr changes to the view's # mask do no affect original object's mask) # (especially important to avoid affecting np.masked singleton) if getmask(output) is not nomask: output._mask = output._mask.view() # Make sure to reset the _fill_value if needed if getattr(output, '_fill_value', None) is not None: if fill_value is None: if dtype is None: pass # leave _fill_value as is else: output._fill_value = None else: output.fill_value = fill_value return output def __getitem__(self, indx): """ x.__getitem__(y) <==> x[y] Return the item described by i, as a masked array. """ # We could directly use ndarray.__getitem__ on self. # But then we would have to modify __array_finalize__ to prevent the # mask of being reshaped if it hasn't been set up properly yet # So it's easier to stick to the current version dout = self.data[indx] _mask = self._mask def _is_scalar(m): return not isinstance(m, np.ndarray) def _scalar_heuristic(arr, elem): """ Return whether `elem` is a scalar result of indexing `arr`, or None if undecidable without promoting nomask to a full mask """ # obviously a scalar if not isinstance(elem, np.ndarray): return True # object array scalar indexing can return anything elif arr.dtype.type is np.object_: if arr.dtype is not elem.dtype: # elem is an array, but dtypes do not match, so must be # an element return True # well-behaved subclass that only returns 0d arrays when # expected - this is not a scalar elif type(arr).__getitem__ == ndarray.__getitem__: return False return None if _mask is not nomask: # _mask cannot be a subclass, so it tells us whether we should # expect a scalar. It also cannot be of dtype object. mout = _mask[indx] scalar_expected = _is_scalar(mout) else: # attempt to apply the heuristic to avoid constructing a full mask mout = nomask scalar_expected = _scalar_heuristic(self.data, dout) if scalar_expected is None: # heuristics have failed # construct a full array, so we can be certain. This is costly. # we could also fall back on ndarray.__getitem__(self.data, indx) scalar_expected = _is_scalar(getmaskarray(self)[indx]) # Did we extract a single item? if scalar_expected: # A record if isinstance(dout, np.void): # We should always re-cast to mvoid, otherwise users can # change masks on rows that already have masked values, but not # on rows that have no masked values, which is inconsistent. return mvoid(dout, mask=mout, hardmask=self._hardmask) # special case introduced in gh-5962 elif (self.dtype.type is np.object_ and isinstance(dout, np.ndarray) and dout is not masked): # If masked, turn into a MaskedArray, with everything masked. if mout: return MaskedArray(dout, mask=True) else: return dout # Just a scalar else: if mout: return masked else: return dout else: # Force dout to MA dout = dout.view(type(self)) # Inherit attributes from self dout._update_from(self) # Check the fill_value if is_string_or_list_of_strings(indx): if self._fill_value is not None: dout._fill_value = self._fill_value[indx] # Something like gh-15895 has happened if this check fails. # _fill_value should always be an ndarray. if not isinstance(dout._fill_value, np.ndarray): raise RuntimeError('Internal NumPy error.') # If we're indexing a multidimensional field in a # structured array (such as dtype("(2,)i2,(2,)i1")), # dimensionality goes up (M[field].ndim == M.ndim + # M.dtype[field].ndim). That's fine for # M[field] but problematic for M[field].fill_value # which should have shape () to avoid breaking several # methods. There is no great way out, so set to # first element. See issue #6723. if dout._fill_value.ndim > 0: if not (dout._fill_value == dout._fill_value.flat[0]).all(): warnings.warn( "Upon accessing multidimensional field " f"{indx!s}, need to keep dimensionality " "of fill_value at 0. Discarding " "heterogeneous fill_value and setting " f"all to {dout._fill_value[0]!s}.", stacklevel=2) # Need to use `.flat[0:1].squeeze(...)` instead of just # `.flat[0]` to ensure the result is a 0d array and not # a scalar. dout._fill_value = dout._fill_value.flat[0:1].squeeze(axis=0) dout._isfield = True # Update the mask if needed if mout is not nomask: # set shape to match that of data; this is needed for matrices dout._mask = reshape(mout, dout.shape) dout._sharedmask = True # Note: Don't try to check for m.any(), that'll take too long return dout def __setitem__(self, indx, value): """ x.__setitem__(i, y) <==> x[i]=y Set item described by index. If value is masked, masks those locations. """ if self is masked: raise MaskError('Cannot alter the masked element.') _data = self._data _mask = self._mask if isinstance(indx, str): _data[indx] = value if _mask is nomask: self._mask = _mask = make_mask_none(self.shape, self.dtype) _mask[indx] = getmask(value) return _dtype = _data.dtype if value is masked: # The mask wasn't set: create a full version. if _mask is nomask: _mask = self._mask = make_mask_none(self.shape, _dtype) # Now, set the mask to its value. if _dtype.names is not None: _mask[indx] = tuple([True] * len(_dtype.names)) else: _mask[indx] = True return # Get the _data part of the new value dval = getattr(value, '_data', value) # Get the _mask part of the new value mval = getmask(value) if _dtype.names is not None and mval is nomask: mval = tuple([False] * len(_dtype.names)) if _mask is nomask: # Set the data, then the mask _data[indx] = dval if mval is not nomask: _mask = self._mask = make_mask_none(self.shape, _dtype) _mask[indx] = mval elif not self._hardmask: # Set the data, then the mask if (isinstance(indx, masked_array) and not isinstance(value, masked_array)): _data[indx.data] = dval else: _data[indx] = dval _mask[indx] = mval elif hasattr(indx, 'dtype') and (indx.dtype == MaskType): indx = indx * umath.logical_not(_mask) _data[indx] = dval else: if _dtype.names is not None: err_msg = "Flexible 'hard' masks are not yet supported." raise NotImplementedError(err_msg) mindx = mask_or(_mask[indx], mval, copy=True) dindx = self._data[indx] if dindx.size > 1: np.copyto(dindx, dval, where=~mindx) elif mindx is nomask: dindx = dval _data[indx] = dindx _mask[indx] = mindx return # Define so that we can overwrite the setter. def dtype(self): return super().dtype def dtype(self, dtype): super(MaskedArray, type(self)).dtype.__set__(self, dtype) if self._mask is not nomask: self._mask = self._mask.view(make_mask_descr(dtype), ndarray) # Try to reset the shape of the mask (if we don't have a void). # This raises a ValueError if the dtype change won't work. try: self._mask.shape = self.shape except (AttributeError, TypeError): pass def shape(self): return super().shape def shape(self, shape): super(MaskedArray, type(self)).shape.__set__(self, shape) # Cannot use self._mask, since it may not (yet) exist when a # masked matrix sets the shape. if getmask(self) is not nomask: self._mask.shape = self.shape def __setmask__(self, mask, copy=False): """ Set the mask. """ idtype = self.dtype current_mask = self._mask if mask is masked: mask = True if current_mask is nomask: # Make sure the mask is set # Just don't do anything if there's nothing to do. if mask is nomask: return current_mask = self._mask = make_mask_none(self.shape, idtype) if idtype.names is None: # No named fields. # Hardmask: don't unmask the data if self._hardmask: current_mask |= mask # Softmask: set everything to False # If it's obviously a compatible scalar, use a quick update # method. elif isinstance(mask, (int, float, np.bool_, np.number)): current_mask[...] = mask # Otherwise fall back to the slower, general purpose way. else: current_mask.flat = mask else: # Named fields w/ mdtype = current_mask.dtype mask = np.array(mask, copy=False) # Mask is a singleton if not mask.ndim: # It's a boolean : make a record if mask.dtype.kind == 'b': mask = np.array(tuple([mask.item()] * len(mdtype)), dtype=mdtype) # It's a record: make sure the dtype is correct else: mask = mask.astype(mdtype) # Mask is a sequence else: # Make sure the new mask is a ndarray with the proper dtype try: mask = np.array(mask, copy=copy, dtype=mdtype) # Or assume it's a sequence of bool/int except TypeError: mask = np.array([tuple([m] * len(mdtype)) for m in mask], dtype=mdtype) # Hardmask: don't unmask the data if self._hardmask: for n in idtype.names: current_mask[n] |= mask[n] # Softmask: set everything to False # If it's obviously a compatible scalar, use a quick update # method. elif isinstance(mask, (int, float, np.bool_, np.number)): current_mask[...] = mask # Otherwise fall back to the slower, general purpose way. else: current_mask.flat = mask # Reshape if needed if current_mask.shape: current_mask.shape = self.shape return _set_mask = __setmask__ def mask(self): """ Current mask. """ # We could try to force a reshape, but that wouldn't work in some # cases. # Return a view so that the dtype and shape cannot be changed in place # This still preserves nomask by identity return self._mask.view() def mask(self, value): self.__setmask__(value) def recordmask(self): """ Get or set the mask of the array if it has no named fields. For structured arrays, returns a ndarray of booleans where entries are ``True`` if **all** the fields are masked, ``False`` otherwise: >>> x = np.ma.array([(1, 1), (2, 2), (3, 3), (4, 4), (5, 5)], ... mask=[(0, 0), (1, 0), (1, 1), (0, 1), (0, 0)], ... dtype=[('a', int), ('b', int)]) >>> x.recordmask array([False, False, True, False, False]) """ _mask = self._mask.view(ndarray) if _mask.dtype.names is None: return _mask return np.all(flatten_structured_array(_mask), axis=-1) def recordmask(self, mask): raise NotImplementedError("Coming soon: setting the mask per records!") def harden_mask(self): """ Force the mask to hard, preventing unmasking by assignment. Whether the mask of a masked array is hard or soft is determined by its `~ma.MaskedArray.hardmask` property. `harden_mask` sets `~ma.MaskedArray.hardmask` to ``True`` (and returns the modified self). See Also -------- ma.MaskedArray.hardmask ma.MaskedArray.soften_mask """ self._hardmask = True return self def soften_mask(self): """ Force the mask to soft (default), allowing unmasking by assignment. Whether the mask of a masked array is hard or soft is determined by its `~ma.MaskedArray.hardmask` property. `soften_mask` sets `~ma.MaskedArray.hardmask` to ``False`` (and returns the modified self). See Also -------- ma.MaskedArray.hardmask ma.MaskedArray.harden_mask """ self._hardmask = False return self def hardmask(self): """ Specifies whether values can be unmasked through assignments. By default, assigning definite values to masked array entries will unmask them. When `hardmask` is ``True``, the mask will not change through assignments. See Also -------- ma.MaskedArray.harden_mask ma.MaskedArray.soften_mask Examples -------- >>> x = np.arange(10) >>> m = np.ma.masked_array(x, x>5) >>> assert not m.hardmask Since `m` has a soft mask, assigning an element value unmasks that element: >>> m[8] = 42 >>> m masked_array(data=[0, 1, 2, 3, 4, 5, --, --, 42, --], mask=[False, False, False, False, False, False, True, True, False, True], fill_value=999999) After hardening, the mask is not affected by assignments: >>> hardened = np.ma.harden_mask(m) >>> assert m.hardmask and hardened is m >>> m[:] = 23 >>> m masked_array(data=[23, 23, 23, 23, 23, 23, --, --, 23, --], mask=[False, False, False, False, False, False, True, True, False, True], fill_value=999999) """ return self._hardmask def unshare_mask(self): """ Copy the mask and set the `sharedmask` flag to ``False``. Whether the mask is shared between masked arrays can be seen from the `sharedmask` property. `unshare_mask` ensures the mask is not shared. A copy of the mask is only made if it was shared. See Also -------- sharedmask """ if self._sharedmask: self._mask = self._mask.copy() self._sharedmask = False return self def sharedmask(self): """ Share status of the mask (read-only). """ return self._sharedmask def shrink_mask(self): """ Reduce a mask to nomask when possible. Parameters ---------- None Returns ------- None Examples -------- >>> x = np.ma.array([[1,2 ], [3, 4]], mask=[0]*4) >>> x.mask array([[False, False], [False, False]]) >>> x.shrink_mask() masked_array( data=[[1, 2], [3, 4]], mask=False, fill_value=999999) >>> x.mask False """ self._mask = _shrink_mask(self._mask) return self def baseclass(self): """ Class of the underlying data (read-only). """ return self._baseclass def _get_data(self): """ Returns the underlying data, as a view of the masked array. If the underlying data is a subclass of :class:`numpy.ndarray`, it is returned as such. >>> x = np.ma.array(np.matrix([[1, 2], [3, 4]]), mask=[[0, 1], [1, 0]]) >>> x.data matrix([[1, 2], [3, 4]]) The type of the data can be accessed through the :attr:`baseclass` attribute. """ return ndarray.view(self, self._baseclass) _data = property(fget=_get_data) data = property(fget=_get_data) def flat(self): """ Return a flat iterator, or set a flattened version of self to value. """ return MaskedIterator(self) def flat(self, value): y = self.ravel() y[:] = value def fill_value(self): """ The filling value of the masked array is a scalar. When setting, None will set to a default based on the data type. Examples -------- >>> for dt in [np.int32, np.int64, np.float64, np.complex128]: ... np.ma.array([0, 1], dtype=dt).get_fill_value() ... 999999 999999 1e+20 (1e+20+0j) >>> x = np.ma.array([0, 1.], fill_value=-np.inf) >>> x.fill_value -inf >>> x.fill_value = np.pi >>> x.fill_value 3.1415926535897931 # may vary Reset to default: >>> x.fill_value = None >>> x.fill_value 1e+20 """ if self._fill_value is None: self._fill_value = _check_fill_value(None, self.dtype) # Temporary workaround to account for the fact that str and bytes # scalars cannot be indexed with (), whereas all other numpy # scalars can. See issues #7259 and #7267. # The if-block can be removed after #7267 has been fixed. if isinstance(self._fill_value, ndarray): return self._fill_value[()] return self._fill_value def fill_value(self, value=None): target = _check_fill_value(value, self.dtype) if not target.ndim == 0: # 2019-11-12, 1.18.0 warnings.warn( "Non-scalar arrays for the fill value are deprecated. Use " "arrays with scalar values instead. The filled function " "still supports any array as `fill_value`.", DeprecationWarning, stacklevel=2) _fill_value = self._fill_value if _fill_value is None: # Create the attribute if it was undefined self._fill_value = target else: # Don't overwrite the attribute, just fill it (for propagation) _fill_value[()] = target # kept for compatibility get_fill_value = fill_value.fget set_fill_value = fill_value.fset def filled(self, fill_value=None): """ Return a copy of self, with masked values filled with a given value. **However**, if there are no masked values to fill, self will be returned instead as an ndarray. Parameters ---------- fill_value : array_like, optional The value to use for invalid entries. Can be scalar or non-scalar. If non-scalar, the resulting ndarray must be broadcastable over input array. Default is None, in which case, the `fill_value` attribute of the array is used instead. Returns ------- filled_array : ndarray A copy of ``self`` with invalid entries replaced by *fill_value* (be it the function argument or the attribute of ``self``), or ``self`` itself as an ndarray if there are no invalid entries to be replaced. Notes ----- The result is **not** a MaskedArray! Examples -------- >>> x = np.ma.array([1,2,3,4,5], mask=[0,0,1,0,1], fill_value=-999) >>> x.filled() array([ 1, 2, -999, 4, -999]) >>> x.filled(fill_value=1000) array([ 1, 2, 1000, 4, 1000]) >>> type(x.filled()) <class 'numpy.ndarray'> Subclassing is preserved. This means that if, e.g., the data part of the masked array is a recarray, `filled` returns a recarray: >>> x = np.array([(-1, 2), (-3, 4)], dtype='i8,i8').view(np.recarray) >>> m = np.ma.array(x, mask=[(True, False), (False, True)]) >>> m.filled() rec.array([(999999, 2), ( -3, 999999)], dtype=[('f0', '<i8'), ('f1', '<i8')]) """ m = self._mask if m is nomask: return self._data if fill_value is None: fill_value = self.fill_value else: fill_value = _check_fill_value(fill_value, self.dtype) if self is masked_singleton: return np.asanyarray(fill_value) if m.dtype.names is not None: result = self._data.copy('K') _recursive_filled(result, self._mask, fill_value) elif not m.any(): return self._data else: result = self._data.copy('K') try: np.copyto(result, fill_value, where=m) except (TypeError, AttributeError): fill_value = narray(fill_value, dtype=object) d = result.astype(object) result = np.choose(m, (d, fill_value)) except IndexError: # ok, if scalar if self._data.shape: raise elif m: result = np.array(fill_value, dtype=self.dtype) else: result = self._data return result def compressed(self): """ Return all the non-masked data as a 1-D array. Returns ------- data : ndarray A new `ndarray` holding the non-masked data is returned. Notes ----- The result is **not** a MaskedArray! Examples -------- >>> x = np.ma.array(np.arange(5), mask=[0]*2 + [1]*3) >>> x.compressed() array([0, 1]) >>> type(x.compressed()) <class 'numpy.ndarray'> """ data = ndarray.ravel(self._data) if self._mask is not nomask: data = data.compress(np.logical_not(ndarray.ravel(self._mask))) return data def compress(self, condition, axis=None, out=None): """ Return `a` where condition is ``True``. If condition is a `~ma.MaskedArray`, missing values are considered as ``False``. Parameters ---------- condition : var Boolean 1-d array selecting which entries to return. If len(condition) is less than the size of a along the axis, then output is truncated to length of condition array. axis : {None, int}, optional Axis along which the operation must be performed. out : {None, ndarray}, optional Alternative output array in which to place the result. It must have the same shape as the expected output but the type will be cast if necessary. Returns ------- result : MaskedArray A :class:`~ma.MaskedArray` object. Notes ----- Please note the difference with :meth:`compressed` ! The output of :meth:`compress` has a mask, the output of :meth:`compressed` does not. Examples -------- >>> x = np.ma.array([[1,2,3],[4,5,6],[7,8,9]], mask=[0] + [1,0]*4) >>> x masked_array( data=[[1, --, 3], [--, 5, --], [7, --, 9]], mask=[[False, True, False], [ True, False, True], [False, True, False]], fill_value=999999) >>> x.compress([1, 0, 1]) masked_array(data=[1, 3], mask=[False, False], fill_value=999999) >>> x.compress([1, 0, 1], axis=1) masked_array( data=[[1, 3], [--, --], [7, 9]], mask=[[False, False], [ True, True], [False, False]], fill_value=999999) """ # Get the basic components (_data, _mask) = (self._data, self._mask) # Force the condition to a regular ndarray and forget the missing # values. condition = np.asarray(condition) _new = _data.compress(condition, axis=axis, out=out).view(type(self)) _new._update_from(self) if _mask is not nomask: _new._mask = _mask.compress(condition, axis=axis) return _new def _insert_masked_print(self): """ Replace masked values with masked_print_option, casting all innermost dtypes to object. """ if masked_print_option.enabled(): mask = self._mask if mask is nomask: res = self._data else: # convert to object array to make filled work data = self._data # For big arrays, to avoid a costly conversion to the # object dtype, extract the corners before the conversion. print_width = (self._print_width if self.ndim > 1 else self._print_width_1d) for axis in range(self.ndim): if data.shape[axis] > print_width: ind = print_width // 2 arr = np.split(data, (ind, -ind), axis=axis) data = np.concatenate((arr[0], arr[2]), axis=axis) arr = np.split(mask, (ind, -ind), axis=axis) mask = np.concatenate((arr[0], arr[2]), axis=axis) rdtype = _replace_dtype_fields(self.dtype, "O") res = data.astype(rdtype) _recursive_printoption(res, mask, masked_print_option) else: res = self.filled(self.fill_value) return res def __str__(self): return str(self._insert_masked_print()) def __repr__(self): """ Literal string representation. """ if self._baseclass is np.ndarray: name = 'array' else: name = self._baseclass.__name__ # 2016-11-19: Demoted to legacy format if np.core.arrayprint._get_legacy_print_mode() <= 113: is_long = self.ndim > 1 parameters = dict( name=name, nlen=" " * len(name), data=str(self), mask=str(self._mask), fill=str(self.fill_value), dtype=str(self.dtype) ) is_structured = bool(self.dtype.names) key = '{}_{}'.format( 'long' if is_long else 'short', 'flx' if is_structured else 'std' ) return _legacy_print_templates[key] % parameters prefix = f"masked_{name}(" dtype_needed = ( not np.core.arrayprint.dtype_is_implied(self.dtype) or np.all(self.mask) or self.size == 0 ) # determine which keyword args need to be shown keys = ['data', 'mask', 'fill_value'] if dtype_needed: keys.append('dtype') # array has only one row (non-column) is_one_row = builtins.all(dim == 1 for dim in self.shape[:-1]) # choose what to indent each keyword with min_indent = 2 if is_one_row: # first key on the same line as the type, remaining keys # aligned by equals indents = {} indents[keys[0]] = prefix for k in keys[1:]: n = builtins.max(min_indent, len(prefix + keys[0]) - len(k)) indents[k] = ' ' * n prefix = '' # absorbed into the first indent else: # each key on its own line, indented by two spaces indents = {k: ' ' * min_indent for k in keys} prefix = prefix + '\n' # first key on the next line # format the field values reprs = {} reprs['data'] = np.array2string( self._insert_masked_print(), separator=", ", prefix=indents['data'] + 'data=', suffix=',') reprs['mask'] = np.array2string( self._mask, separator=", ", prefix=indents['mask'] + 'mask=', suffix=',') reprs['fill_value'] = repr(self.fill_value) if dtype_needed: reprs['dtype'] = np.core.arrayprint.dtype_short_repr(self.dtype) # join keys with values and indentations result = ',\n'.join( '{}{}={}'.format(indents[k], k, reprs[k]) for k in keys ) return prefix + result + ')' def _delegate_binop(self, other): # This emulates the logic in # private/binop_override.h:forward_binop_should_defer if isinstance(other, type(self)): return False array_ufunc = getattr(other, "__array_ufunc__", False) if array_ufunc is False: other_priority = getattr(other, "__array_priority__", -1000000) return self.__array_priority__ < other_priority else: # If array_ufunc is not None, it will be called inside the ufunc; # None explicitly tells us to not call the ufunc, i.e., defer. return array_ufunc is None def _comparison(self, other, compare): """Compare self with other using operator.eq or operator.ne. When either of the elements is masked, the result is masked as well, but the underlying boolean data are still set, with self and other considered equal if both are masked, and unequal otherwise. For structured arrays, all fields are combined, with masked values ignored. The result is masked if all fields were masked, with self and other considered equal only if both were fully masked. """ omask = getmask(other) smask = self.mask mask = mask_or(smask, omask, copy=True) odata = getdata(other) if mask.dtype.names is not None: # only == and != are reasonably defined for structured dtypes, # so give up early for all other comparisons: if compare not in (operator.eq, operator.ne): return NotImplemented # For possibly masked structured arrays we need to be careful, # since the standard structured array comparison will use all # fields, masked or not. To avoid masked fields influencing the # outcome, we set all masked fields in self to other, so they'll # count as equal. To prepare, we ensure we have the right shape. broadcast_shape = np.broadcast(self, odata).shape sbroadcast = np.broadcast_to(self, broadcast_shape, subok=True) sbroadcast._mask = mask sdata = sbroadcast.filled(odata) # Now take care of the mask; the merged mask should have an item # masked if all fields were masked (in one and/or other). mask = (mask == np.ones((), mask.dtype)) else: # For regular arrays, just use the data as they come. sdata = self.data check = compare(sdata, odata) if isinstance(check, (np.bool_, bool)): return masked if mask else check if mask is not nomask and compare in (operator.eq, operator.ne): # Adjust elements that were masked, which should be treated # as equal if masked in both, unequal if masked in one. # Note that this works automatically for structured arrays too. # Ignore this for operations other than `==` and `!=` check = np.where(mask, compare(smask, omask), check) if mask.shape != check.shape: # Guarantee consistency of the shape, making a copy since the # the mask may need to get written to later. mask = np.broadcast_to(mask, check.shape).copy() check = check.view(type(self)) check._update_from(self) check._mask = mask # Cast fill value to bool_ if needed. If it cannot be cast, the # default boolean fill value is used. if check._fill_value is not None: try: fill = _check_fill_value(check._fill_value, np.bool_) except (TypeError, ValueError): fill = _check_fill_value(None, np.bool_) check._fill_value = fill return check def __eq__(self, other): """Check whether other equals self elementwise. When either of the elements is masked, the result is masked as well, but the underlying boolean data are still set, with self and other considered equal if both are masked, and unequal otherwise. For structured arrays, all fields are combined, with masked values ignored. The result is masked if all fields were masked, with self and other considered equal only if both were fully masked. """ return self._comparison(other, operator.eq) def __ne__(self, other): """Check whether other does not equal self elementwise. When either of the elements is masked, the result is masked as well, but the underlying boolean data are still set, with self and other considered equal if both are masked, and unequal otherwise. For structured arrays, all fields are combined, with masked values ignored. The result is masked if all fields were masked, with self and other considered equal only if both were fully masked. """ return self._comparison(other, operator.ne) # All other comparisons: def __le__(self, other): return self._comparison(other, operator.le) def __lt__(self, other): return self._comparison(other, operator.lt) def __ge__(self, other): return self._comparison(other, operator.ge) def __gt__(self, other): return self._comparison(other, operator.gt) def __add__(self, other): """ Add self to other, and return a new masked array. """ if self._delegate_binop(other): return NotImplemented return add(self, other) def __radd__(self, other): """ Add other to self, and return a new masked array. """ # In analogy with __rsub__ and __rdiv__, use original order: # we get here from `other + self`. return add(other, self) def __sub__(self, other): """ Subtract other from self, and return a new masked array. """ if self._delegate_binop(other): return NotImplemented return subtract(self, other) def __rsub__(self, other): """ Subtract self from other, and return a new masked array. """ return subtract(other, self) def __mul__(self, other): "Multiply self by other, and return a new masked array." if self._delegate_binop(other): return NotImplemented return multiply(self, other) def __rmul__(self, other): """ Multiply other by self, and return a new masked array. """ # In analogy with __rsub__ and __rdiv__, use original order: # we get here from `other * self`. return multiply(other, self) def __div__(self, other): """ Divide other into self, and return a new masked array. """ if self._delegate_binop(other): return NotImplemented return divide(self, other) def __truediv__(self, other): """ Divide other into self, and return a new masked array. """ if self._delegate_binop(other): return NotImplemented return true_divide(self, other) def __rtruediv__(self, other): """ Divide self into other, and return a new masked array. """ return true_divide(other, self) def __floordiv__(self, other): """ Divide other into self, and return a new masked array. """ if self._delegate_binop(other): return NotImplemented return floor_divide(self, other) def __rfloordiv__(self, other): """ Divide self into other, and return a new masked array. """ return floor_divide(other, self) def __pow__(self, other): """ Raise self to the power other, masking the potential NaNs/Infs """ if self._delegate_binop(other): return NotImplemented return power(self, other) def __rpow__(self, other): """ Raise other to the power self, masking the potential NaNs/Infs """ return power(other, self) def __iadd__(self, other): """ Add other to self in-place. """ m = getmask(other) if self._mask is nomask: if m is not nomask and m.any(): self._mask = make_mask_none(self.shape, self.dtype) self._mask += m else: if m is not nomask: self._mask += m other_data = getdata(other) other_data = np.where(self._mask, other_data.dtype.type(0), other_data) self._data.__iadd__(other_data) return self def __isub__(self, other): """ Subtract other from self in-place. """ m = getmask(other) if self._mask is nomask: if m is not nomask and m.any(): self._mask = make_mask_none(self.shape, self.dtype) self._mask += m elif m is not nomask: self._mask += m other_data = getdata(other) other_data = np.where(self._mask, other_data.dtype.type(0), other_data) self._data.__isub__(other_data) return self def __imul__(self, other): """ Multiply self by other in-place. """ m = getmask(other) if self._mask is nomask: if m is not nomask and m.any(): self._mask = make_mask_none(self.shape, self.dtype) self._mask += m elif m is not nomask: self._mask += m other_data = getdata(other) other_data = np.where(self._mask, other_data.dtype.type(1), other_data) self._data.__imul__(other_data) return self def __idiv__(self, other): """ Divide self by other in-place. """ other_data = getdata(other) dom_mask = _DomainSafeDivide().__call__(self._data, other_data) other_mask = getmask(other) new_mask = mask_or(other_mask, dom_mask) # The following 4 lines control the domain filling if dom_mask.any(): (_, fval) = ufunc_fills[np.divide] other_data = np.where( dom_mask, other_data.dtype.type(fval), other_data) self._mask |= new_mask other_data = np.where(self._mask, other_data.dtype.type(1), other_data) self._data.__idiv__(other_data) return self def __ifloordiv__(self, other): """ Floor divide self by other in-place. """ other_data = getdata(other) dom_mask = _DomainSafeDivide().__call__(self._data, other_data) other_mask = getmask(other) new_mask = mask_or(other_mask, dom_mask) # The following 3 lines control the domain filling if dom_mask.any(): (_, fval) = ufunc_fills[np.floor_divide] other_data = np.where( dom_mask, other_data.dtype.type(fval), other_data) self._mask |= new_mask other_data = np.where(self._mask, other_data.dtype.type(1), other_data) self._data.__ifloordiv__(other_data) return self def __itruediv__(self, other): """ True divide self by other in-place. """ other_data = getdata(other) dom_mask = _DomainSafeDivide().__call__(self._data, other_data) other_mask = getmask(other) new_mask = mask_or(other_mask, dom_mask) # The following 3 lines control the domain filling if dom_mask.any(): (_, fval) = ufunc_fills[np.true_divide] other_data = np.where( dom_mask, other_data.dtype.type(fval), other_data) self._mask |= new_mask other_data = np.where(self._mask, other_data.dtype.type(1), other_data) self._data.__itruediv__(other_data) return self def __ipow__(self, other): """ Raise self to the power other, in place. """ other_data = getdata(other) other_data = np.where(self._mask, other_data.dtype.type(1), other_data) other_mask = getmask(other) with np.errstate(divide='ignore', invalid='ignore'): self._data.__ipow__(other_data) invalid = np.logical_not(np.isfinite(self._data)) if invalid.any(): if self._mask is not nomask: self._mask |= invalid else: self._mask = invalid np.copyto(self._data, self.fill_value, where=invalid) new_mask = mask_or(other_mask, invalid) self._mask = mask_or(self._mask, new_mask) return self def __float__(self): """ Convert to float. """ if self.size > 1: raise TypeError("Only length-1 arrays can be converted " "to Python scalars") elif self._mask: warnings.warn("Warning: converting a masked element to nan.", stacklevel=2) return np.nan return float(self.item()) def __int__(self): """ Convert to int. """ if self.size > 1: raise TypeError("Only length-1 arrays can be converted " "to Python scalars") elif self._mask: raise MaskError('Cannot convert masked element to a Python int.') return int(self.item()) def imag(self): """ The imaginary part of the masked array. This property is a view on the imaginary part of this `MaskedArray`. See Also -------- real Examples -------- >>> x = np.ma.array([1+1.j, -2j, 3.45+1.6j], mask=[False, True, False]) >>> x.imag masked_array(data=[1.0, --, 1.6], mask=[False, True, False], fill_value=1e+20) """ result = self._data.imag.view(type(self)) result.__setmask__(self._mask) return result # kept for compatibility get_imag = imag.fget def real(self): """ The real part of the masked array. This property is a view on the real part of this `MaskedArray`. See Also -------- imag Examples -------- >>> x = np.ma.array([1+1.j, -2j, 3.45+1.6j], mask=[False, True, False]) >>> x.real masked_array(data=[1.0, --, 3.45], mask=[False, True, False], fill_value=1e+20) """ result = self._data.real.view(type(self)) result.__setmask__(self._mask) return result # kept for compatibility get_real = real.fget def count(self, axis=None, keepdims=np._NoValue): """ Count the non-masked elements of the array along the given axis. Parameters ---------- axis : None or int or tuple of ints, optional Axis or axes along which the count is performed. The default, None, performs the count over all the dimensions of the input array. `axis` may be negative, in which case it counts from the last to the first axis. .. versionadded:: 1.10.0 If this is a tuple of ints, the count is performed on multiple axes, instead of a single axis or all the axes as before. keepdims : bool, optional If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the array. Returns ------- result : ndarray or scalar An array with the same shape as the input array, with the specified axis removed. If the array is a 0-d array, or if `axis` is None, a scalar is returned. See Also -------- ma.count_masked : Count masked elements in array or along a given axis. Examples -------- >>> import numpy.ma as ma >>> a = ma.arange(6).reshape((2, 3)) >>> a[1, :] = ma.masked >>> a masked_array( data=[[0, 1, 2], [--, --, --]], mask=[[False, False, False], [ True, True, True]], fill_value=999999) >>> a.count() 3 When the `axis` keyword is specified an array of appropriate size is returned. >>> a.count(axis=0) array([1, 1, 1]) >>> a.count(axis=1) array([3, 0]) """ kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims} m = self._mask # special case for matrices (we assume no other subclasses modify # their dimensions) if isinstance(self.data, np.matrix): if m is nomask: m = np.zeros(self.shape, dtype=np.bool_) m = m.view(type(self.data)) if m is nomask: # compare to _count_reduce_items in _methods.py if self.shape == (): if axis not in (None, 0): raise np.AxisError(axis=axis, ndim=self.ndim) return 1 elif axis is None: if kwargs.get('keepdims', False): return np.array(self.size, dtype=np.intp, ndmin=self.ndim) return self.size axes = normalize_axis_tuple(axis, self.ndim) items = 1 for ax in axes: items *= self.shape[ax] if kwargs.get('keepdims', False): out_dims = list(self.shape) for a in axes: out_dims[a] = 1 else: out_dims = [d for n, d in enumerate(self.shape) if n not in axes] # make sure to return a 0-d array if axis is supplied return np.full(out_dims, items, dtype=np.intp) # take care of the masked singleton if self is masked: return 0 return (~m).sum(axis=axis, dtype=np.intp, **kwargs) def ravel(self, order='C'): """ Returns a 1D version of self, as a view. Parameters ---------- order : {'C', 'F', 'A', 'K'}, optional The elements of `a` are read using this index order. 'C' means to index the elements in C-like order, with the last axis index changing fastest, back to the first axis index changing slowest. 'F' means to index the elements in Fortran-like index order, with the first index changing fastest, and the last index changing slowest. Note that the 'C' and 'F' options take no account of the memory layout of the underlying array, and only refer to the order of axis indexing. 'A' means to read the elements in Fortran-like index order if `m` is Fortran *contiguous* in memory, C-like order otherwise. 'K' means to read the elements in the order they occur in memory, except for reversing the data when strides are negative. By default, 'C' index order is used. Returns ------- MaskedArray Output view is of shape ``(self.size,)`` (or ``(np.ma.product(self.shape),)``). Examples -------- >>> x = np.ma.array([[1,2,3],[4,5,6],[7,8,9]], mask=[0] + [1,0]*4) >>> x masked_array( data=[[1, --, 3], [--, 5, --], [7, --, 9]], mask=[[False, True, False], [ True, False, True], [False, True, False]], fill_value=999999) >>> x.ravel() masked_array(data=[1, --, 3, --, 5, --, 7, --, 9], mask=[False, True, False, True, False, True, False, True, False], fill_value=999999) """ r = ndarray.ravel(self._data, order=order).view(type(self)) r._update_from(self) if self._mask is not nomask: r._mask = ndarray.ravel(self._mask, order=order).reshape(r.shape) else: r._mask = nomask return r def reshape(self, *s, **kwargs): """ Give a new shape to the array without changing its data. Returns a masked array containing the same data, but with a new shape. The result is a view on the original array; if this is not possible, a ValueError is raised. Parameters ---------- shape : int or tuple of ints The new shape should be compatible with the original shape. If an integer is supplied, then the result will be a 1-D array of that length. order : {'C', 'F'}, optional Determines whether the array data should be viewed as in C (row-major) or FORTRAN (column-major) order. Returns ------- reshaped_array : array A new view on the array. See Also -------- reshape : Equivalent function in the masked array module. numpy.ndarray.reshape : Equivalent method on ndarray object. numpy.reshape : Equivalent function in the NumPy module. Notes ----- The reshaping operation cannot guarantee that a copy will not be made, to modify the shape in place, use ``a.shape = s`` Examples -------- >>> x = np.ma.array([[1,2],[3,4]], mask=[1,0,0,1]) >>> x masked_array( data=[[--, 2], [3, --]], mask=[[ True, False], [False, True]], fill_value=999999) >>> x = x.reshape((4,1)) >>> x masked_array( data=[[--], [2], [3], [--]], mask=[[ True], [False], [False], [ True]], fill_value=999999) """ kwargs.update(order=kwargs.get('order', 'C')) result = self._data.reshape(*s, **kwargs).view(type(self)) result._update_from(self) mask = self._mask if mask is not nomask: result._mask = mask.reshape(*s, **kwargs) return result def resize(self, newshape, refcheck=True, order=False): """ .. warning:: This method does nothing, except raise a ValueError exception. A masked array does not own its data and therefore cannot safely be resized in place. Use the `numpy.ma.resize` function instead. This method is difficult to implement safely and may be deprecated in future releases of NumPy. """ # Note : the 'order' keyword looks broken, let's just drop it errmsg = "A masked array does not own its data "\ "and therefore cannot be resized.\n" \ "Use the numpy.ma.resize function instead." raise ValueError(errmsg) def put(self, indices, values, mode='raise'): """ Set storage-indexed locations to corresponding values. Sets self._data.flat[n] = values[n] for each n in indices. If `values` is shorter than `indices` then it will repeat. If `values` has some masked values, the initial mask is updated in consequence, else the corresponding values are unmasked. Parameters ---------- indices : 1-D array_like Target indices, interpreted as integers. values : array_like Values to place in self._data copy at target indices. mode : {'raise', 'wrap', 'clip'}, optional Specifies how out-of-bounds indices will behave. 'raise' : raise an error. 'wrap' : wrap around. 'clip' : clip to the range. Notes ----- `values` can be a scalar or length 1 array. Examples -------- >>> x = np.ma.array([[1,2,3],[4,5,6],[7,8,9]], mask=[0] + [1,0]*4) >>> x masked_array( data=[[1, --, 3], [--, 5, --], [7, --, 9]], mask=[[False, True, False], [ True, False, True], [False, True, False]], fill_value=999999) >>> x.put([0,4,8],[10,20,30]) >>> x masked_array( data=[[10, --, 3], [--, 20, --], [7, --, 30]], mask=[[False, True, False], [ True, False, True], [False, True, False]], fill_value=999999) >>> x.put(4,999) >>> x masked_array( data=[[10, --, 3], [--, 999, --], [7, --, 30]], mask=[[False, True, False], [ True, False, True], [False, True, False]], fill_value=999999) """ # Hard mask: Get rid of the values/indices that fall on masked data if self._hardmask and self._mask is not nomask: mask = self._mask[indices] indices = narray(indices, copy=False) values = narray(values, copy=False, subok=True) values.resize(indices.shape) indices = indices[~mask] values = values[~mask] self._data.put(indices, values, mode=mode) # short circuit if neither self nor values are masked if self._mask is nomask and getmask(values) is nomask: return m = getmaskarray(self) if getmask(values) is nomask: m.put(indices, False, mode=mode) else: m.put(indices, values._mask, mode=mode) m = make_mask(m, copy=False, shrink=True) self._mask = m return def ids(self): """ Return the addresses of the data and mask areas. Parameters ---------- None Examples -------- >>> x = np.ma.array([1, 2, 3], mask=[0, 1, 1]) >>> x.ids() (166670640, 166659832) # may vary If the array has no mask, the address of `nomask` is returned. This address is typically not close to the data in memory: >>> x = np.ma.array([1, 2, 3]) >>> x.ids() (166691080, 3083169284) # may vary """ if self._mask is nomask: return (self.ctypes.data, id(nomask)) return (self.ctypes.data, self._mask.ctypes.data) def iscontiguous(self): """ Return a boolean indicating whether the data is contiguous. Parameters ---------- None Examples -------- >>> x = np.ma.array([1, 2, 3]) >>> x.iscontiguous() True `iscontiguous` returns one of the flags of the masked array: >>> x.flags C_CONTIGUOUS : True F_CONTIGUOUS : True OWNDATA : False WRITEABLE : True ALIGNED : True WRITEBACKIFCOPY : False """ return self.flags['CONTIGUOUS'] def all(self, axis=None, out=None, keepdims=np._NoValue): """ Returns True if all elements evaluate to True. The output array is masked where all the values along the given axis are masked: if the output would have been a scalar and that all the values are masked, then the output is `masked`. Refer to `numpy.all` for full documentation. See Also -------- numpy.ndarray.all : corresponding function for ndarrays numpy.all : equivalent function Examples -------- >>> np.ma.array([1,2,3]).all() True >>> a = np.ma.array([1,2,3], mask=True) >>> (a.all() is np.ma.masked) True """ kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims} mask = _check_mask_axis(self._mask, axis, **kwargs) if out is None: d = self.filled(True).all(axis=axis, **kwargs).view(type(self)) if d.ndim: d.__setmask__(mask) elif mask: return masked return d self.filled(True).all(axis=axis, out=out, **kwargs) if isinstance(out, MaskedArray): if out.ndim or mask: out.__setmask__(mask) return out def any(self, axis=None, out=None, keepdims=np._NoValue): """ Returns True if any of the elements of `a` evaluate to True. Masked values are considered as False during computation. Refer to `numpy.any` for full documentation. See Also -------- numpy.ndarray.any : corresponding function for ndarrays numpy.any : equivalent function """ kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims} mask = _check_mask_axis(self._mask, axis, **kwargs) if out is None: d = self.filled(False).any(axis=axis, **kwargs).view(type(self)) if d.ndim: d.__setmask__(mask) elif mask: d = masked return d self.filled(False).any(axis=axis, out=out, **kwargs) if isinstance(out, MaskedArray): if out.ndim or mask: out.__setmask__(mask) return out def nonzero(self): """ Return the indices of unmasked elements that are not zero. Returns a tuple of arrays, one for each dimension, containing the indices of the non-zero elements in that dimension. The corresponding non-zero values can be obtained with:: a[a.nonzero()] To group the indices by element, rather than dimension, use instead:: np.transpose(a.nonzero()) The result of this is always a 2d array, with a row for each non-zero element. Parameters ---------- None Returns ------- tuple_of_arrays : tuple Indices of elements that are non-zero. See Also -------- numpy.nonzero : Function operating on ndarrays. flatnonzero : Return indices that are non-zero in the flattened version of the input array. numpy.ndarray.nonzero : Equivalent ndarray method. count_nonzero : Counts the number of non-zero elements in the input array. Examples -------- >>> import numpy.ma as ma >>> x = ma.array(np.eye(3)) >>> x masked_array( data=[[1., 0., 0.], [0., 1., 0.], [0., 0., 1.]], mask=False, fill_value=1e+20) >>> x.nonzero() (array([0, 1, 2]), array([0, 1, 2])) Masked elements are ignored. >>> x[1, 1] = ma.masked >>> x masked_array( data=[[1.0, 0.0, 0.0], [0.0, --, 0.0], [0.0, 0.0, 1.0]], mask=[[False, False, False], [False, True, False], [False, False, False]], fill_value=1e+20) >>> x.nonzero() (array([0, 2]), array([0, 2])) Indices can also be grouped by element. >>> np.transpose(x.nonzero()) array([[0, 0], [2, 2]]) A common use for ``nonzero`` is to find the indices of an array, where a condition is True. Given an array `a`, the condition `a` > 3 is a boolean array and since False is interpreted as 0, ma.nonzero(a > 3) yields the indices of the `a` where the condition is true. >>> a = ma.array([[1,2,3],[4,5,6],[7,8,9]]) >>> a > 3 masked_array( data=[[False, False, False], [ True, True, True], [ True, True, True]], mask=False, fill_value=True) >>> ma.nonzero(a > 3) (array([1, 1, 1, 2, 2, 2]), array([0, 1, 2, 0, 1, 2])) The ``nonzero`` method of the condition array can also be called. >>> (a > 3).nonzero() (array([1, 1, 1, 2, 2, 2]), array([0, 1, 2, 0, 1, 2])) """ return narray(self.filled(0), copy=False).nonzero() def trace(self, offset=0, axis1=0, axis2=1, dtype=None, out=None): """ (this docstring should be overwritten) """ #!!!: implement out + test! m = self._mask if m is nomask: result = super().trace(offset=offset, axis1=axis1, axis2=axis2, out=out) return result.astype(dtype) else: D = self.diagonal(offset=offset, axis1=axis1, axis2=axis2) return D.astype(dtype).filled(0).sum(axis=-1, out=out) trace.__doc__ = ndarray.trace.__doc__ def dot(self, b, out=None, strict=False): """ a.dot(b, out=None) Masked dot product of two arrays. Note that `out` and `strict` are located in different positions than in `ma.dot`. In order to maintain compatibility with the functional version, it is recommended that the optional arguments be treated as keyword only. At some point that may be mandatory. .. versionadded:: 1.10.0 Parameters ---------- b : masked_array_like Inputs array. out : masked_array, optional Output argument. This must have the exact kind that would be returned if it was not used. In particular, it must have the right type, must be C-contiguous, and its dtype must be the dtype that would be returned for `ma.dot(a,b)`. This is a performance feature. Therefore, if these conditions are not met, an exception is raised, instead of attempting to be flexible. strict : bool, optional Whether masked data are propagated (True) or set to 0 (False) for the computation. Default is False. Propagating the mask means that if a masked value appears in a row or column, the whole row or column is considered masked. .. versionadded:: 1.10.2 See Also -------- numpy.ma.dot : equivalent function """ return dot(self, b, out=out, strict=strict) def sum(self, axis=None, dtype=None, out=None, keepdims=np._NoValue): """ Return the sum of the array elements over the given axis. Masked elements are set to 0 internally. Refer to `numpy.sum` for full documentation. See Also -------- numpy.ndarray.sum : corresponding function for ndarrays numpy.sum : equivalent function Examples -------- >>> x = np.ma.array([[1,2,3],[4,5,6],[7,8,9]], mask=[0] + [1,0]*4) >>> x masked_array( data=[[1, --, 3], [--, 5, --], [7, --, 9]], mask=[[False, True, False], [ True, False, True], [False, True, False]], fill_value=999999) >>> x.sum() 25 >>> x.sum(axis=1) masked_array(data=[4, 5, 16], mask=[False, False, False], fill_value=999999) >>> x.sum(axis=0) masked_array(data=[8, 5, 12], mask=[False, False, False], fill_value=999999) >>> print(type(x.sum(axis=0, dtype=np.int64)[0])) <class 'numpy.int64'> """ kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims} _mask = self._mask newmask = _check_mask_axis(_mask, axis, **kwargs) # No explicit output if out is None: result = self.filled(0).sum(axis, dtype=dtype, **kwargs) rndim = getattr(result, 'ndim', 0) if rndim: result = result.view(type(self)) result.__setmask__(newmask) elif newmask: result = masked return result # Explicit output result = self.filled(0).sum(axis, dtype=dtype, out=out, **kwargs) if isinstance(out, MaskedArray): outmask = getmask(out) if outmask is nomask: outmask = out._mask = make_mask_none(out.shape) outmask.flat = newmask return out def cumsum(self, axis=None, dtype=None, out=None): """ Return the cumulative sum of the array elements over the given axis. Masked values are set to 0 internally during the computation. However, their position is saved, and the result will be masked at the same locations. Refer to `numpy.cumsum` for full documentation. Notes ----- The mask is lost if `out` is not a valid :class:`ma.MaskedArray` ! Arithmetic is modular when using integer types, and no error is raised on overflow. See Also -------- numpy.ndarray.cumsum : corresponding function for ndarrays numpy.cumsum : equivalent function Examples -------- >>> marr = np.ma.array(np.arange(10), mask=[0,0,0,1,1,1,0,0,0,0]) >>> marr.cumsum() masked_array(data=[0, 1, 3, --, --, --, 9, 16, 24, 33], mask=[False, False, False, True, True, True, False, False, False, False], fill_value=999999) """ result = self.filled(0).cumsum(axis=axis, dtype=dtype, out=out) if out is not None: if isinstance(out, MaskedArray): out.__setmask__(self.mask) return out result = result.view(type(self)) result.__setmask__(self._mask) return result def prod(self, axis=None, dtype=None, out=None, keepdims=np._NoValue): """ Return the product of the array elements over the given axis. Masked elements are set to 1 internally for computation. Refer to `numpy.prod` for full documentation. Notes ----- Arithmetic is modular when using integer types, and no error is raised on overflow. See Also -------- numpy.ndarray.prod : corresponding function for ndarrays numpy.prod : equivalent function """ kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims} _mask = self._mask newmask = _check_mask_axis(_mask, axis, **kwargs) # No explicit output if out is None: result = self.filled(1).prod(axis, dtype=dtype, **kwargs) rndim = getattr(result, 'ndim', 0) if rndim: result = result.view(type(self)) result.__setmask__(newmask) elif newmask: result = masked return result # Explicit output result = self.filled(1).prod(axis, dtype=dtype, out=out, **kwargs) if isinstance(out, MaskedArray): outmask = getmask(out) if outmask is nomask: outmask = out._mask = make_mask_none(out.shape) outmask.flat = newmask return out product = prod def cumprod(self, axis=None, dtype=None, out=None): """ Return the cumulative product of the array elements over the given axis. Masked values are set to 1 internally during the computation. However, their position is saved, and the result will be masked at the same locations. Refer to `numpy.cumprod` for full documentation. Notes ----- The mask is lost if `out` is not a valid MaskedArray ! Arithmetic is modular when using integer types, and no error is raised on overflow. See Also -------- numpy.ndarray.cumprod : corresponding function for ndarrays numpy.cumprod : equivalent function """ result = self.filled(1).cumprod(axis=axis, dtype=dtype, out=out) if out is not None: if isinstance(out, MaskedArray): out.__setmask__(self._mask) return out result = result.view(type(self)) result.__setmask__(self._mask) return result def mean(self, axis=None, dtype=None, out=None, keepdims=np._NoValue): """ Returns the average of the array elements along given axis. Masked entries are ignored, and result elements which are not finite will be masked. Refer to `numpy.mean` for full documentation. See Also -------- numpy.ndarray.mean : corresponding function for ndarrays numpy.mean : Equivalent function numpy.ma.average : Weighted average. Examples -------- >>> a = np.ma.array([1,2,3], mask=[False, False, True]) >>> a masked_array(data=[1, 2, --], mask=[False, False, True], fill_value=999999) >>> a.mean() 1.5 """ kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims} if self._mask is nomask: result = super().mean(axis=axis, dtype=dtype, **kwargs)[()] else: is_float16_result = False if dtype is None: if issubclass(self.dtype.type, (ntypes.integer, ntypes.bool_)): dtype = mu.dtype('f8') elif issubclass(self.dtype.type, ntypes.float16): dtype = mu.dtype('f4') is_float16_result = True dsum = self.sum(axis=axis, dtype=dtype, **kwargs) cnt = self.count(axis=axis, **kwargs) if cnt.shape == () and (cnt == 0): result = masked elif is_float16_result: result = self.dtype.type(dsum * 1. / cnt) else: result = dsum * 1. / cnt if out is not None: out.flat = result if isinstance(out, MaskedArray): outmask = getmask(out) if outmask is nomask: outmask = out._mask = make_mask_none(out.shape) outmask.flat = getmask(result) return out return result def anom(self, axis=None, dtype=None): """ Compute the anomalies (deviations from the arithmetic mean) along the given axis. Returns an array of anomalies, with the same shape as the input and where the arithmetic mean is computed along the given axis. Parameters ---------- axis : int, optional Axis over which the anomalies are taken. The default is to use the mean of the flattened array as reference. dtype : dtype, optional Type to use in computing the variance. For arrays of integer type the default is float32; for arrays of float types it is the same as the array type. See Also -------- mean : Compute the mean of the array. Examples -------- >>> a = np.ma.array([1,2,3]) >>> a.anom() masked_array(data=[-1., 0., 1.], mask=False, fill_value=1e+20) """ m = self.mean(axis, dtype) if not axis: return self - m else: return self - expand_dims(m, axis) def var(self, axis=None, dtype=None, out=None, ddof=0, keepdims=np._NoValue): """ Returns the variance of the array elements along given axis. Masked entries are ignored, and result elements which are not finite will be masked. Refer to `numpy.var` for full documentation. See Also -------- numpy.ndarray.var : corresponding function for ndarrays numpy.var : Equivalent function """ kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims} # Easy case: nomask, business as usual if self._mask is nomask: ret = super().var(axis=axis, dtype=dtype, out=out, ddof=ddof, **kwargs)[()] if out is not None: if isinstance(out, MaskedArray): out.__setmask__(nomask) return out return ret # Some data are masked, yay! cnt = self.count(axis=axis, **kwargs) - ddof danom = self - self.mean(axis, dtype, keepdims=True) if iscomplexobj(self): danom = umath.absolute(danom) ** 2 else: danom *= danom dvar = divide(danom.sum(axis, **kwargs), cnt).view(type(self)) # Apply the mask if it's not a scalar if dvar.ndim: dvar._mask = mask_or(self._mask.all(axis, **kwargs), (cnt <= 0)) dvar._update_from(self) elif getmask(dvar): # Make sure that masked is returned when the scalar is masked. dvar = masked if out is not None: if isinstance(out, MaskedArray): out.flat = 0 out.__setmask__(True) elif out.dtype.kind in 'biu': errmsg = "Masked data information would be lost in one or "\ "more location." raise MaskError(errmsg) else: out.flat = np.nan return out # In case with have an explicit output if out is not None: # Set the data out.flat = dvar # Set the mask if needed if isinstance(out, MaskedArray): out.__setmask__(dvar.mask) return out return dvar var.__doc__ = np.var.__doc__ def std(self, axis=None, dtype=None, out=None, ddof=0, keepdims=np._NoValue): """ Returns the standard deviation of the array elements along given axis. Masked entries are ignored. Refer to `numpy.std` for full documentation. See Also -------- numpy.ndarray.std : corresponding function for ndarrays numpy.std : Equivalent function """ kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims} dvar = self.var(axis, dtype, out, ddof, **kwargs) if dvar is not masked: if out is not None: np.power(out, 0.5, out=out, casting='unsafe') return out dvar = sqrt(dvar) return dvar def round(self, decimals=0, out=None): """ Return each element rounded to the given number of decimals. Refer to `numpy.around` for full documentation. See Also -------- numpy.ndarray.round : corresponding function for ndarrays numpy.around : equivalent function """ result = self._data.round(decimals=decimals, out=out).view(type(self)) if result.ndim > 0: result._mask = self._mask result._update_from(self) elif self._mask: # Return masked when the scalar is masked result = masked # No explicit output: we're done if out is None: return result if isinstance(out, MaskedArray): out.__setmask__(self._mask) return out def argsort(self, axis=np._NoValue, kind=None, order=None, endwith=True, fill_value=None): """ Return an ndarray of indices that sort the array along the specified axis. Masked values are filled beforehand to `fill_value`. Parameters ---------- axis : int, optional Axis along which to sort. If None, the default, the flattened array is used. .. versionchanged:: 1.13.0 Previously, the default was documented to be -1, but that was in error. At some future date, the default will change to -1, as originally intended. Until then, the axis should be given explicitly when ``arr.ndim > 1``, to avoid a FutureWarning. kind : {'quicksort', 'mergesort', 'heapsort', 'stable'}, optional The sorting algorithm used. order : list, optional When `a` is an array with fields defined, this argument specifies which fields to compare first, second, etc. Not all fields need be specified. endwith : {True, False}, optional Whether missing values (if any) should be treated as the largest values (True) or the smallest values (False) When the array contains unmasked values at the same extremes of the datatype, the ordering of these values and the masked values is undefined. fill_value : scalar or None, optional Value used internally for the masked values. If ``fill_value`` is not None, it supersedes ``endwith``. Returns ------- index_array : ndarray, int Array of indices that sort `a` along the specified axis. In other words, ``a[index_array]`` yields a sorted `a`. See Also -------- ma.MaskedArray.sort : Describes sorting algorithms used. lexsort : Indirect stable sort with multiple keys. numpy.ndarray.sort : Inplace sort. Notes ----- See `sort` for notes on the different sorting algorithms. Examples -------- >>> a = np.ma.array([3,2,1], mask=[False, False, True]) >>> a masked_array(data=[3, 2, --], mask=[False, False, True], fill_value=999999) >>> a.argsort() array([1, 0, 2]) """ # 2017-04-11, Numpy 1.13.0, gh-8701: warn on axis default if axis is np._NoValue: axis = _deprecate_argsort_axis(self) if fill_value is None: if endwith: # nan > inf if np.issubdtype(self.dtype, np.floating): fill_value = np.nan else: fill_value = minimum_fill_value(self) else: fill_value = maximum_fill_value(self) filled = self.filled(fill_value) return filled.argsort(axis=axis, kind=kind, order=order) def argmin(self, axis=None, fill_value=None, out=None, *, keepdims=np._NoValue): """ Return array of indices to the minimum values along the given axis. Parameters ---------- axis : {None, integer} If None, the index is into the flattened array, otherwise along the specified axis fill_value : scalar or None, optional Value used to fill in the masked values. If None, the output of minimum_fill_value(self._data) is used instead. out : {None, array}, optional Array into which the result can be placed. Its type is preserved and it must be of the right shape to hold the output. Returns ------- ndarray or scalar If multi-dimension input, returns a new ndarray of indices to the minimum values along the given axis. Otherwise, returns a scalar of index to the minimum values along the given axis. Examples -------- >>> x = np.ma.array(np.arange(4), mask=[1,1,0,0]) >>> x.shape = (2,2) >>> x masked_array( data=[[--, --], [2, 3]], mask=[[ True, True], [False, False]], fill_value=999999) >>> x.argmin(axis=0, fill_value=-1) array([0, 0]) >>> x.argmin(axis=0, fill_value=9) array([1, 1]) """ if fill_value is None: fill_value = minimum_fill_value(self) d = self.filled(fill_value).view(ndarray) keepdims = False if keepdims is np._NoValue else bool(keepdims) return d.argmin(axis, out=out, keepdims=keepdims) def argmax(self, axis=None, fill_value=None, out=None, *, keepdims=np._NoValue): """ Returns array of indices of the maximum values along the given axis. Masked values are treated as if they had the value fill_value. Parameters ---------- axis : {None, integer} If None, the index is into the flattened array, otherwise along the specified axis fill_value : scalar or None, optional Value used to fill in the masked values. If None, the output of maximum_fill_value(self._data) is used instead. out : {None, array}, optional Array into which the result can be placed. Its type is preserved and it must be of the right shape to hold the output. Returns ------- index_array : {integer_array} Examples -------- >>> a = np.arange(6).reshape(2,3) >>> a.argmax() 5 >>> a.argmax(0) array([1, 1, 1]) >>> a.argmax(1) array([2, 2]) """ if fill_value is None: fill_value = maximum_fill_value(self._data) d = self.filled(fill_value).view(ndarray) keepdims = False if keepdims is np._NoValue else bool(keepdims) return d.argmax(axis, out=out, keepdims=keepdims) def sort(self, axis=-1, kind=None, order=None, endwith=True, fill_value=None): """ Sort the array, in-place Parameters ---------- a : array_like Array to be sorted. axis : int, optional Axis along which to sort. If None, the array is flattened before sorting. The default is -1, which sorts along the last axis. kind : {'quicksort', 'mergesort', 'heapsort', 'stable'}, optional The sorting algorithm used. order : list, optional When `a` is a structured array, this argument specifies which fields to compare first, second, and so on. This list does not need to include all of the fields. endwith : {True, False}, optional Whether missing values (if any) should be treated as the largest values (True) or the smallest values (False) When the array contains unmasked values sorting at the same extremes of the datatype, the ordering of these values and the masked values is undefined. fill_value : scalar or None, optional Value used internally for the masked values. If ``fill_value`` is not None, it supersedes ``endwith``. Returns ------- sorted_array : ndarray Array of the same type and shape as `a`. See Also -------- numpy.ndarray.sort : Method to sort an array in-place. argsort : Indirect sort. lexsort : Indirect stable sort on multiple keys. searchsorted : Find elements in a sorted array. Notes ----- See ``sort`` for notes on the different sorting algorithms. Examples -------- >>> a = np.ma.array([1, 2, 5, 4, 3],mask=[0, 1, 0, 1, 0]) >>> # Default >>> a.sort() >>> a masked_array(data=[1, 3, 5, --, --], mask=[False, False, False, True, True], fill_value=999999) >>> a = np.ma.array([1, 2, 5, 4, 3],mask=[0, 1, 0, 1, 0]) >>> # Put missing values in the front >>> a.sort(endwith=False) >>> a masked_array(data=[--, --, 1, 3, 5], mask=[ True, True, False, False, False], fill_value=999999) >>> a = np.ma.array([1, 2, 5, 4, 3],mask=[0, 1, 0, 1, 0]) >>> # fill_value takes over endwith >>> a.sort(endwith=False, fill_value=3) >>> a masked_array(data=[1, --, --, 3, 5], mask=[False, True, True, False, False], fill_value=999999) """ if self._mask is nomask: ndarray.sort(self, axis=axis, kind=kind, order=order) return if self is masked: return sidx = self.argsort(axis=axis, kind=kind, order=order, fill_value=fill_value, endwith=endwith) self[...] = np.take_along_axis(self, sidx, axis=axis) def min(self, axis=None, out=None, fill_value=None, keepdims=np._NoValue): """ Return the minimum along a given axis. Parameters ---------- axis : None or int or tuple of ints, optional Axis along which to operate. By default, ``axis`` is None and the flattened input is used. .. versionadded:: 1.7.0 If this is a tuple of ints, the minimum is selected over multiple axes, instead of a single axis or all the axes as before. out : array_like, optional Alternative output array in which to place the result. Must be of the same shape and buffer length as the expected output. fill_value : scalar or None, optional Value used to fill in the masked values. If None, use the output of `minimum_fill_value`. keepdims : bool, optional If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the array. Returns ------- amin : array_like New array holding the result. If ``out`` was specified, ``out`` is returned. See Also -------- ma.minimum_fill_value Returns the minimum filling value for a given datatype. Examples -------- >>> import numpy.ma as ma >>> x = [[1., -2., 3.], [0.2, -0.7, 0.1]] >>> mask = [[1, 1, 0], [0, 0, 1]] >>> masked_x = ma.masked_array(x, mask) >>> masked_x masked_array( data=[[--, --, 3.0], [0.2, -0.7, --]], mask=[[ True, True, False], [False, False, True]], fill_value=1e+20) >>> ma.min(masked_x) -0.7 >>> ma.min(masked_x, axis=-1) masked_array(data=[3.0, -0.7], mask=[False, False], fill_value=1e+20) >>> ma.min(masked_x, axis=0, keepdims=True) masked_array(data=[[0.2, -0.7, 3.0]], mask=[[False, False, False]], fill_value=1e+20) >>> mask = [[1, 1, 1,], [1, 1, 1]] >>> masked_x = ma.masked_array(x, mask) >>> ma.min(masked_x, axis=0) masked_array(data=[--, --, --], mask=[ True, True, True], fill_value=1e+20, dtype=float64) """ kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims} _mask = self._mask newmask = _check_mask_axis(_mask, axis, **kwargs) if fill_value is None: fill_value = minimum_fill_value(self) # No explicit output if out is None: result = self.filled(fill_value).min( axis=axis, out=out, **kwargs).view(type(self)) if result.ndim: # Set the mask result.__setmask__(newmask) # Get rid of Infs if newmask.ndim: np.copyto(result, result.fill_value, where=newmask) elif newmask: result = masked return result # Explicit output result = self.filled(fill_value).min(axis=axis, out=out, **kwargs) if isinstance(out, MaskedArray): outmask = getmask(out) if outmask is nomask: outmask = out._mask = make_mask_none(out.shape) outmask.flat = newmask else: if out.dtype.kind in 'biu': errmsg = "Masked data information would be lost in one or more"\ " location." raise MaskError(errmsg) np.copyto(out, np.nan, where=newmask) return out def max(self, axis=None, out=None, fill_value=None, keepdims=np._NoValue): """ Return the maximum along a given axis. Parameters ---------- axis : None or int or tuple of ints, optional Axis along which to operate. By default, ``axis`` is None and the flattened input is used. .. versionadded:: 1.7.0 If this is a tuple of ints, the maximum is selected over multiple axes, instead of a single axis or all the axes as before. out : array_like, optional Alternative output array in which to place the result. Must be of the same shape and buffer length as the expected output. fill_value : scalar or None, optional Value used to fill in the masked values. If None, use the output of maximum_fill_value(). keepdims : bool, optional If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the array. Returns ------- amax : array_like New array holding the result. If ``out`` was specified, ``out`` is returned. See Also -------- ma.maximum_fill_value Returns the maximum filling value for a given datatype. Examples -------- >>> import numpy.ma as ma >>> x = [[-1., 2.5], [4., -2.], [3., 0.]] >>> mask = [[0, 0], [1, 0], [1, 0]] >>> masked_x = ma.masked_array(x, mask) >>> masked_x masked_array( data=[[-1.0, 2.5], [--, -2.0], [--, 0.0]], mask=[[False, False], [ True, False], [ True, False]], fill_value=1e+20) >>> ma.max(masked_x) 2.5 >>> ma.max(masked_x, axis=0) masked_array(data=[-1.0, 2.5], mask=[False, False], fill_value=1e+20) >>> ma.max(masked_x, axis=1, keepdims=True) masked_array( data=[[2.5], [-2.0], [0.0]], mask=[[False], [False], [False]], fill_value=1e+20) >>> mask = [[1, 1], [1, 1], [1, 1]] >>> masked_x = ma.masked_array(x, mask) >>> ma.max(masked_x, axis=1) masked_array(data=[--, --, --], mask=[ True, True, True], fill_value=1e+20, dtype=float64) """ kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims} _mask = self._mask newmask = _check_mask_axis(_mask, axis, **kwargs) if fill_value is None: fill_value = maximum_fill_value(self) # No explicit output if out is None: result = self.filled(fill_value).max( axis=axis, out=out, **kwargs).view(type(self)) if result.ndim: # Set the mask result.__setmask__(newmask) # Get rid of Infs if newmask.ndim: np.copyto(result, result.fill_value, where=newmask) elif newmask: result = masked return result # Explicit output result = self.filled(fill_value).max(axis=axis, out=out, **kwargs) if isinstance(out, MaskedArray): outmask = getmask(out) if outmask is nomask: outmask = out._mask = make_mask_none(out.shape) outmask.flat = newmask else: if out.dtype.kind in 'biu': errmsg = "Masked data information would be lost in one or more"\ " location." raise MaskError(errmsg) np.copyto(out, np.nan, where=newmask) return out def ptp(self, axis=None, out=None, fill_value=None, keepdims=False): """ Return (maximum - minimum) along the given dimension (i.e. peak-to-peak value). .. warning:: `ptp` preserves the data type of the array. This means the return value for an input of signed integers with n bits (e.g. `np.int8`, `np.int16`, etc) is also a signed integer with n bits. In that case, peak-to-peak values greater than ``2**(n-1)-1`` will be returned as negative values. An example with a work-around is shown below. Parameters ---------- axis : {None, int}, optional Axis along which to find the peaks. If None (default) the flattened array is used. out : {None, array_like}, optional Alternative output array in which to place the result. It must have the same shape and buffer length as the expected output but the type will be cast if necessary. fill_value : scalar or None, optional Value used to fill in the masked values. keepdims : bool, optional If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the array. Returns ------- ptp : ndarray. A new array holding the result, unless ``out`` was specified, in which case a reference to ``out`` is returned. Examples -------- >>> x = np.ma.MaskedArray([[4, 9, 2, 10], ... [6, 9, 7, 12]]) >>> x.ptp(axis=1) masked_array(data=[8, 6], mask=False, fill_value=999999) >>> x.ptp(axis=0) masked_array(data=[2, 0, 5, 2], mask=False, fill_value=999999) >>> x.ptp() 10 This example shows that a negative value can be returned when the input is an array of signed integers. >>> y = np.ma.MaskedArray([[1, 127], ... [0, 127], ... [-1, 127], ... [-2, 127]], dtype=np.int8) >>> y.ptp(axis=1) masked_array(data=[ 126, 127, -128, -127], mask=False, fill_value=999999, dtype=int8) A work-around is to use the `view()` method to view the result as unsigned integers with the same bit width: >>> y.ptp(axis=1).view(np.uint8) masked_array(data=[126, 127, 128, 129], mask=False, fill_value=999999, dtype=uint8) """ if out is None: result = self.max(axis=axis, fill_value=fill_value, keepdims=keepdims) result -= self.min(axis=axis, fill_value=fill_value, keepdims=keepdims) return result out.flat = self.max(axis=axis, out=out, fill_value=fill_value, keepdims=keepdims) min_value = self.min(axis=axis, fill_value=fill_value, keepdims=keepdims) np.subtract(out, min_value, out=out, casting='unsafe') return out def partition(self, *args, **kwargs): warnings.warn("Warning: 'partition' will ignore the 'mask' " f"of the {self.__class__.__name__}.", stacklevel=2) return super().partition(*args, **kwargs) def argpartition(self, *args, **kwargs): warnings.warn("Warning: 'argpartition' will ignore the 'mask' " f"of the {self.__class__.__name__}.", stacklevel=2) return super().argpartition(*args, **kwargs) def take(self, indices, axis=None, out=None, mode='raise'): """ """ (_data, _mask) = (self._data, self._mask) cls = type(self) # Make sure the indices are not masked maskindices = getmask(indices) if maskindices is not nomask: indices = indices.filled(0) # Get the data, promoting scalars to 0d arrays with [...] so that # .view works correctly if out is None: out = _data.take(indices, axis=axis, mode=mode)[...].view(cls) else: np.take(_data, indices, axis=axis, mode=mode, out=out) # Get the mask if isinstance(out, MaskedArray): if _mask is nomask: outmask = maskindices else: outmask = _mask.take(indices, axis=axis, mode=mode) outmask |= maskindices out.__setmask__(outmask) # demote 0d arrays back to scalars, for consistency with ndarray.take return out[()] # Array methods copy = _arraymethod('copy') diagonal = _arraymethod('diagonal') flatten = _arraymethod('flatten') repeat = _arraymethod('repeat') squeeze = _arraymethod('squeeze') swapaxes = _arraymethod('swapaxes') T = property(fget=lambda self: self.transpose()) transpose = _arraymethod('transpose') def tolist(self, fill_value=None): """ Return the data portion of the masked array as a hierarchical Python list. Data items are converted to the nearest compatible Python type. Masked values are converted to `fill_value`. If `fill_value` is None, the corresponding entries in the output list will be ``None``. Parameters ---------- fill_value : scalar, optional The value to use for invalid entries. Default is None. Returns ------- result : list The Python list representation of the masked array. Examples -------- >>> x = np.ma.array([[1,2,3], [4,5,6], [7,8,9]], mask=[0] + [1,0]*4) >>> x.tolist() [[1, None, 3], [None, 5, None], [7, None, 9]] >>> x.tolist(-999) [[1, -999, 3], [-999, 5, -999], [7, -999, 9]] """ _mask = self._mask # No mask ? Just return .data.tolist ? if _mask is nomask: return self._data.tolist() # Explicit fill_value: fill the array and get the list if fill_value is not None: return self.filled(fill_value).tolist() # Structured array. names = self.dtype.names if names: result = self._data.astype([(_, object) for _ in names]) for n in names: result[n][_mask[n]] = None return result.tolist() # Standard arrays. if _mask is nomask: return [None] # Set temps to save time when dealing w/ marrays. inishape = self.shape result = np.array(self._data.ravel(), dtype=object) result[_mask.ravel()] = None result.shape = inishape return result.tolist() def tostring(self, fill_value=None, order='C'): r""" A compatibility alias for `tobytes`, with exactly the same behavior. Despite its name, it returns `bytes` not `str`\ s. .. deprecated:: 1.19.0 """ # 2020-03-30, Numpy 1.19.0 warnings.warn( "tostring() is deprecated. Use tobytes() instead.", DeprecationWarning, stacklevel=2) return self.tobytes(fill_value, order=order) def tobytes(self, fill_value=None, order='C'): """ Return the array data as a string containing the raw bytes in the array. The array is filled with a fill value before the string conversion. .. versionadded:: 1.9.0 Parameters ---------- fill_value : scalar, optional Value used to fill in the masked values. Default is None, in which case `MaskedArray.fill_value` is used. order : {'C','F','A'}, optional Order of the data item in the copy. Default is 'C'. - 'C' -- C order (row major). - 'F' -- Fortran order (column major). - 'A' -- Any, current order of array. - None -- Same as 'A'. See Also -------- numpy.ndarray.tobytes tolist, tofile Notes ----- As for `ndarray.tobytes`, information about the shape, dtype, etc., but also about `fill_value`, will be lost. Examples -------- >>> x = np.ma.array(np.array([[1, 2], [3, 4]]), mask=[[0, 1], [1, 0]]) >>> x.tobytes() b'\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00?B\\x0f\\x00\\x00\\x00\\x00\\x00?B\\x0f\\x00\\x00\\x00\\x00\\x00\\x04\\x00\\x00\\x00\\x00\\x00\\x00\\x00' """ return self.filled(fill_value).tobytes(order=order) def tofile(self, fid, sep="", format="%s"): """ Save a masked array to a file in binary format. .. warning:: This function is not implemented yet. Raises ------ NotImplementedError When `tofile` is called. """ raise NotImplementedError("MaskedArray.tofile() not implemented yet.") def toflex(self): """ Transforms a masked array into a flexible-type array. The flexible type array that is returned will have two fields: * the ``_data`` field stores the ``_data`` part of the array. * the ``_mask`` field stores the ``_mask`` part of the array. Parameters ---------- None Returns ------- record : ndarray A new flexible-type `ndarray` with two fields: the first element containing a value, the second element containing the corresponding mask boolean. The returned record shape matches self.shape. Notes ----- A side-effect of transforming a masked array into a flexible `ndarray` is that meta information (``fill_value``, ...) will be lost. Examples -------- >>> x = np.ma.array([[1,2,3],[4,5,6],[7,8,9]], mask=[0] + [1,0]*4) >>> x masked_array( data=[[1, --, 3], [--, 5, --], [7, --, 9]], mask=[[False, True, False], [ True, False, True], [False, True, False]], fill_value=999999) >>> x.toflex() array([[(1, False), (2, True), (3, False)], [(4, True), (5, False), (6, True)], [(7, False), (8, True), (9, False)]], dtype=[('_data', '<i8'), ('_mask', '?')]) """ # Get the basic dtype. ddtype = self.dtype # Make sure we have a mask _mask = self._mask if _mask is None: _mask = make_mask_none(self.shape, ddtype) # And get its dtype mdtype = self._mask.dtype record = np.ndarray(shape=self.shape, dtype=[('_data', ddtype), ('_mask', mdtype)]) record['_data'] = self._data record['_mask'] = self._mask return record torecords = toflex # Pickling def __getstate__(self): """Return the internal state of the masked array, for pickling purposes. """ cf = 'CF'[self.flags.fnc] data_state = super().__reduce__()[2] return data_state + (getmaskarray(self).tobytes(cf), self._fill_value) def __setstate__(self, state): """Restore the internal state of the masked array, for pickling purposes. ``state`` is typically the output of the ``__getstate__`` output, and is a 5-tuple: - class name - a tuple giving the shape of the data - a typecode for the data - a binary string for the data - a binary string for the mask. """ (_, shp, typ, isf, raw, msk, flv) = state super().__setstate__((shp, typ, isf, raw)) self._mask.__setstate__((shp, make_mask_descr(typ), isf, msk)) self.fill_value = flv def __reduce__(self): """Return a 3-tuple for pickling a MaskedArray. """ return (_mareconstruct, (self.__class__, self._baseclass, (0,), 'b',), self.__getstate__()) def __deepcopy__(self, memo=None): from copy import deepcopy copied = MaskedArray.__new__(type(self), self, copy=True) if memo is None: memo = {} memo[id(self)] = copied for (k, v) in self.__dict__.items(): copied.__dict__[k] = deepcopy(v, memo) return copied masked = masked_singleton = MaskedConstant() any = _frommethod('any') def ndim(obj): """ maskedarray version of the numpy function. """ return np.ndim(getdata(obj)) ndim.__doc__ = np.ndim.__doc__ def where(condition, x=_NoValue, y=_NoValue): """ Return a masked array with elements from `x` or `y`, depending on condition. .. note:: When only `condition` is provided, this function is identical to `nonzero`. The rest of this documentation covers only the case where all three arguments are provided. Parameters ---------- condition : array_like, bool Where True, yield `x`, otherwise yield `y`. x, y : array_like, optional Values from which to choose. `x`, `y` and `condition` need to be broadcastable to some shape. Returns ------- out : MaskedArray An masked array with `masked` elements where the condition is masked, elements from `x` where `condition` is True, and elements from `y` elsewhere. See Also -------- numpy.where : Equivalent function in the top-level NumPy module. nonzero : The function that is called when x and y are omitted Examples -------- >>> x = np.ma.array(np.arange(9.).reshape(3, 3), mask=[[0, 1, 0], ... [1, 0, 1], ... [0, 1, 0]]) >>> x masked_array( data=[[0.0, --, 2.0], [--, 4.0, --], [6.0, --, 8.0]], mask=[[False, True, False], [ True, False, True], [False, True, False]], fill_value=1e+20) >>> np.ma.where(x > 5, x, -3.1416) masked_array( data=[[-3.1416, --, -3.1416], [--, -3.1416, --], [6.0, --, 8.0]], mask=[[False, True, False], [ True, False, True], [False, True, False]], fill_value=1e+20) """ # handle the single-argument case missing = (x is _NoValue, y is _NoValue).count(True) if missing == 1: raise ValueError("Must provide both 'x' and 'y' or neither.") if missing == 2: return nonzero(condition) # we only care if the condition is true - false or masked pick y cf = filled(condition, False) xd = getdata(x) yd = getdata(y) # we need the full arrays here for correct final dimensions cm = getmaskarray(condition) xm = getmaskarray(x) ym = getmaskarray(y) # deal with the fact that masked.dtype == float64, but we don't actually # want to treat it as that. if x is masked and y is not masked: xd = np.zeros((), dtype=yd.dtype) xm = np.ones((), dtype=ym.dtype) elif y is masked and x is not masked: yd = np.zeros((), dtype=xd.dtype) ym = np.ones((), dtype=xm.dtype) data = np.where(cf, xd, yd) mask = np.where(cf, xm, ym) mask = np.where(cm, np.ones((), dtype=mask.dtype), mask) # collapse the mask, for backwards compatibility mask = _shrink_mask(mask) return masked_array(data, mask=mask) The provided code snippet includes necessary dependencies for implementing the `power` function. Write a Python function `def power(a, b, third=None)` to solve the following problem: Returns element-wise base array raised to power from second array. This is the masked array version of `numpy.power`. For details see `numpy.power`. See Also -------- numpy.power Notes ----- The *out* argument to `numpy.power` is not supported, `third` has to be None. Examples -------- >>> import numpy.ma as ma >>> x = [11.2, -3.973, 0.801, -1.41] >>> mask = [0, 0, 0, 1] >>> masked_x = ma.masked_array(x, mask) >>> masked_x masked_array(data=[11.2, -3.973, 0.801, --], mask=[False, False, False, True], fill_value=1e+20) >>> ma.power(masked_x, 2) masked_array(data=[125.43999999999998, 15.784728999999999, 0.6416010000000001, --], mask=[False, False, False, True], fill_value=1e+20) >>> y = [-0.5, 2, 0, 17] >>> masked_y = ma.masked_array(y, mask) >>> masked_y masked_array(data=[-0.5, 2.0, 0.0, --], mask=[False, False, False, True], fill_value=1e+20) >>> ma.power(masked_x, masked_y) masked_array(data=[0.29880715233359845, 15.784728999999999, 1.0, --], mask=[False, False, False, True], fill_value=1e+20) Here is the function: def power(a, b, third=None): """ Returns element-wise base array raised to power from second array. This is the masked array version of `numpy.power`. For details see `numpy.power`. See Also -------- numpy.power Notes ----- The *out* argument to `numpy.power` is not supported, `third` has to be None. Examples -------- >>> import numpy.ma as ma >>> x = [11.2, -3.973, 0.801, -1.41] >>> mask = [0, 0, 0, 1] >>> masked_x = ma.masked_array(x, mask) >>> masked_x masked_array(data=[11.2, -3.973, 0.801, --], mask=[False, False, False, True], fill_value=1e+20) >>> ma.power(masked_x, 2) masked_array(data=[125.43999999999998, 15.784728999999999, 0.6416010000000001, --], mask=[False, False, False, True], fill_value=1e+20) >>> y = [-0.5, 2, 0, 17] >>> masked_y = ma.masked_array(y, mask) >>> masked_y masked_array(data=[-0.5, 2.0, 0.0, --], mask=[False, False, False, True], fill_value=1e+20) >>> ma.power(masked_x, masked_y) masked_array(data=[0.29880715233359845, 15.784728999999999, 1.0, --], mask=[False, False, False, True], fill_value=1e+20) """ if third is not None: raise MaskError("3-argument power not supported.") # Get the masks ma = getmask(a) mb = getmask(b) m = mask_or(ma, mb) # Get the rawdata fa = getdata(a) fb = getdata(b) # Get the type of the result (so that we preserve subclasses) if isinstance(a, MaskedArray): basetype = type(a) else: basetype = MaskedArray # Get the result and view it as a (subclass of) MaskedArray with np.errstate(divide='ignore', invalid='ignore'): result = np.where(m, fa, umath.power(fa, fb)).view(basetype) result._update_from(a) # Find where we're in trouble w/ NaNs and Infs invalid = np.logical_not(np.isfinite(result.view(ndarray))) # Add the initial mask if m is not nomask: if not result.ndim: return masked result._mask = np.logical_or(m, invalid) # Fix the invalid parts if invalid.any(): if not result.ndim: return masked elif result._mask is nomask: result._mask = invalid result._data[invalid] = result.fill_value return result
Returns element-wise base array raised to power from second array. This is the masked array version of `numpy.power`. For details see `numpy.power`. See Also -------- numpy.power Notes ----- The *out* argument to `numpy.power` is not supported, `third` has to be None. Examples -------- >>> import numpy.ma as ma >>> x = [11.2, -3.973, 0.801, -1.41] >>> mask = [0, 0, 0, 1] >>> masked_x = ma.masked_array(x, mask) >>> masked_x masked_array(data=[11.2, -3.973, 0.801, --], mask=[False, False, False, True], fill_value=1e+20) >>> ma.power(masked_x, 2) masked_array(data=[125.43999999999998, 15.784728999999999, 0.6416010000000001, --], mask=[False, False, False, True], fill_value=1e+20) >>> y = [-0.5, 2, 0, 17] >>> masked_y = ma.masked_array(y, mask) >>> masked_y masked_array(data=[-0.5, 2.0, 0.0, --], mask=[False, False, False, True], fill_value=1e+20) >>> ma.power(masked_x, masked_y) masked_array(data=[0.29880715233359845, 15.784728999999999, 1.0, --], mask=[False, False, False, True], fill_value=1e+20)
170,114
import builtins import inspect import operator import warnings import textwrap import re from functools import reduce import numpy as np import numpy.core.umath as umath import numpy.core.numerictypes as ntypes from numpy.core import multiarray as mu from numpy import ndarray, amax, amin, iscomplexobj, bool_, _NoValue from numpy import array as narray from numpy.lib.function_base import angle from numpy.compat import ( getargspec, formatargspec, long, unicode, bytes ) from numpy import expand_dims from numpy.core.numeric import normalize_axis_tuple nomask = MaskType(0) def filled(a, fill_value=None): """ Return input as an array with masked data replaced by a fill value. If `a` is not a `MaskedArray`, `a` itself is returned. If `a` is a `MaskedArray` and `fill_value` is None, `fill_value` is set to ``a.fill_value``. Parameters ---------- a : MaskedArray or array_like An input object. fill_value : array_like, optional. Can be scalar or non-scalar. If non-scalar, the resulting filled array should be broadcastable over input array. Default is None. Returns ------- a : ndarray The filled array. See Also -------- compressed Examples -------- >>> x = np.ma.array(np.arange(9).reshape(3, 3), mask=[[1, 0, 0], ... [1, 0, 0], ... [0, 0, 0]]) >>> x.filled() array([[999999, 1, 2], [999999, 4, 5], [ 6, 7, 8]]) >>> x.filled(fill_value=333) array([[333, 1, 2], [333, 4, 5], [ 6, 7, 8]]) >>> x.filled(fill_value=np.arange(3)) array([[0, 1, 2], [0, 4, 5], [6, 7, 8]]) """ if hasattr(a, 'filled'): return a.filled(fill_value) elif isinstance(a, ndarray): # Should we check for contiguity ? and a.flags['CONTIGUOUS']: return a elif isinstance(a, dict): return np.array(a, 'O') else: return np.array(a) def getmask(a): """ Return the mask of a masked array, or nomask. Return the mask of `a` as an ndarray if `a` is a `MaskedArray` and the mask is not `nomask`, else return `nomask`. To guarantee a full array of booleans of the same shape as a, use `getmaskarray`. Parameters ---------- a : array_like Input `MaskedArray` for which the mask is required. See Also -------- getdata : Return the data of a masked array as an ndarray. getmaskarray : Return the mask of a masked array, or full array of False. Examples -------- >>> import numpy.ma as ma >>> a = ma.masked_equal([[1,2],[3,4]], 2) >>> a masked_array( data=[[1, --], [3, 4]], mask=[[False, True], [False, False]], fill_value=2) >>> ma.getmask(a) array([[False, True], [False, False]]) Equivalently use the `MaskedArray` `mask` attribute. >>> a.mask array([[False, True], [False, False]]) Result when mask == `nomask` >>> b = ma.masked_array([[1,2],[3,4]]) >>> b masked_array( data=[[1, 2], [3, 4]], mask=False, fill_value=999999) >>> ma.nomask False >>> ma.getmask(b) == ma.nomask True >>> b.mask == ma.nomask True """ return getattr(a, '_mask', nomask) masked_array = MaskedArray The provided code snippet includes necessary dependencies for implementing the `left_shift` function. Write a Python function `def left_shift(a, n)` to solve the following problem: Shift the bits of an integer to the left. This is the masked array version of `numpy.left_shift`, for details see that function. See Also -------- numpy.left_shift Here is the function: def left_shift(a, n): """ Shift the bits of an integer to the left. This is the masked array version of `numpy.left_shift`, for details see that function. See Also -------- numpy.left_shift """ m = getmask(a) if m is nomask: d = umath.left_shift(filled(a), n) return masked_array(d) else: d = umath.left_shift(filled(a, 0), n) return masked_array(d, mask=m)
Shift the bits of an integer to the left. This is the masked array version of `numpy.left_shift`, for details see that function. See Also -------- numpy.left_shift